mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): store stack policies and return them (#7552)
* fix(cloudformation): store stack policies and return them * test(cloudformation): remove the stack policy test bucket after use * fix(cloudformation): apply a stack policy with its stack operation UpdateStack now stores its policy when the update commits, before UPDATE_COMPLETE is published, and CreateStack when execution starts. A policy-only update no longer leaves its change set FAILED. SetStackPolicy checks the stack state again under the stack lock after reading a StackPolicyURL. * fix(cloudformation): apply a creation policy when the create is claimed * fix(cloudformation): keep a rejected policy-only update executable * fix(cloudformation): assign a stack policy when its change set is created * test(cloudformation): stop the stack policy test's executor * test(cloudformation): round-trip stack policies through persistent storage * test(cloudformation): build the stack policy requests on CfnRequests * test(cloudformation): construct CloudFormationService through one shared fixture * fix(cloudformation): refuse a missing or malformed StackName in the stack policy actions SetStackPolicy and GetStackPolicy looked a missing StackName up as the stack named "null". Both now validate StackName first, as AWS does, with the checks ContinueUpdateRollback already applies.
This commit is contained in:
1 parent
cf25c9f6db
commit
a19b296f06
13 files changed
+845
-96
No files matched your search
+1
-15
@@ -2,9 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.appconfig.AppConfigService;
|
||||
import io.github.hectorvent.floci.services.appconfig.model.Application;
|
||||
@@ -13,17 +11,13 @@ import io.github.hectorvent.floci.services.appconfig.model.DeploymentSummary;
|
||||
import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersion;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppConfigCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -33,10 +27,8 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doCallRealMethod;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -64,13 +56,7 @@ class CloudFormationAppConfigLifecycleTest {
|
||||
appConfig = spy(new AppConfigService(storage, null));
|
||||
CfnResourceDispatcher dispatcher = new CfnResourceDispatcher(MAPPER,
|
||||
new CloudFormationResourceRegistry(List.of(new AppConfigCfnProvisioner(appConfig))), null, null);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
cfn = new CloudFormationService(dispatcher, mock(S3Service.class), mock(SsmService.class),
|
||||
mock(GetStackOutputRoleAuthorizer.class), new CfnDynamicReferences(null, null, MAPPER), MAPPER,
|
||||
config, regionResolver, Clock.systemUTC(), new InMemoryStorageFactory(ACCOUNT));
|
||||
cfn = CloudFormationServiceFixture.create(dispatcher);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ class CloudFormationCreateStackIdentityIntegrationTest {
|
||||
"000000000000");
|
||||
deleted.get(5, TimeUnit.SECONDS);
|
||||
replacement.set(original.createChangeSetForCreateStack(stackName, "initial-create",
|
||||
TEMPLATE, null, null, List.of(), null, "us-east-1", false));
|
||||
TEMPLATE, null, null, List.of(), null, "us-east-1", false, invocation.getArgument(9)));
|
||||
assertNotEquals(initial.getStackId(), replacement.get().getStackId());
|
||||
return initial;
|
||||
}));
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** A real {@link CloudFormationService} over in-memory storage, shared by the tests that need one. */
|
||||
public final class CloudFormationServiceFixture {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private CloudFormationServiceFixture() {
|
||||
}
|
||||
|
||||
public static CloudFormationService create(CfnResourceDispatcher dispatcher) {
|
||||
return create(dispatcher, mock(S3Service.class), Clock.systemUTC(), new InMemoryStorageFactory(ACCOUNT));
|
||||
}
|
||||
|
||||
public static CloudFormationService create(CfnResourceDispatcher dispatcher, S3Service s3Service, Clock clock,
|
||||
StorageFactory storageFactory) {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
return new CloudFormationService(dispatcher, s3Service, mock(SsmService.class),
|
||||
mock(GetStackOutputRoleAuthorizer.class), new CfnDynamicReferences(null, null, objectMapper),
|
||||
objectMapper, config, regionResolver, clock, storageFactory);
|
||||
}
|
||||
}
|
||||
+55
-1
@@ -6,9 +6,12 @@ import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
import io.github.hectorvent.floci.testing.CfnStackWaits;
|
||||
import io.quarkus.arc.ClientProxy;
|
||||
import io.quarkus.test.junit.QuarkusMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.path.xml.element.Node;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -32,6 +35,7 @@ import java.util.stream.Collectors;
|
||||
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.withSettings;
|
||||
@@ -85,6 +89,8 @@ class CloudFormationServiceRestoreIntegrationTest {
|
||||
void rejectedExecutionRestoresStackAndChangeSetState() throws Exception {
|
||||
String targetStack = uniqueStackName("target");
|
||||
createChangeSet(targetStack);
|
||||
String policy = "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"Update:*\",\"Principal\":\"*\",\"Resource\":\"*\"}]}";
|
||||
service.describeChangeSet(targetStack, "initial", REGION).setStackPolicyBody(policy);
|
||||
|
||||
List<Future<?>> runningOperations = fillExecutor();
|
||||
try {
|
||||
@@ -94,6 +100,7 @@ class CloudFormationServiceRestoreIntegrationTest {
|
||||
|
||||
Stack restored = service.describeStacks(targetStack, REGION).getFirst();
|
||||
assertEquals("REVIEW_IN_PROGRESS", restored.getStatus());
|
||||
assertNull(restored.getStackPolicyBody());
|
||||
ChangeSet restoredChangeSet = service.describeChangeSet(targetStack, "initial", REGION);
|
||||
assertEquals("CREATE_COMPLETE", restoredChangeSet.getStatus());
|
||||
assertEquals("AVAILABLE", restoredChangeSet.getExecutionStatus());
|
||||
@@ -104,6 +111,7 @@ class CloudFormationServiceRestoreIntegrationTest {
|
||||
Future<?> retry = service.executeChangeSet(targetStack, "initial", REGION);
|
||||
retry.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
assertEquals("CREATE_COMPLETE", service.describeStacks(targetStack, REGION).getFirst().getStatus());
|
||||
assertEquals(policy, service.describeStacks(targetStack, REGION).getFirst().getStackPolicyBody());
|
||||
assertEquals("EXECUTE_COMPLETE",
|
||||
service.describeChangeSet(targetStack, "initial", REGION).getExecutionStatus());
|
||||
}
|
||||
@@ -154,11 +162,57 @@ class CloudFormationServiceRestoreIntegrationTest {
|
||||
.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedPolicyOnlyUpdateCanBeExecutedOnceCapacityReturns() throws Exception {
|
||||
// Outside STACK_PREFIX, so its own create and update are not held by the blocking provisioner.
|
||||
String targetStack = "restore-policy-target-" + System.nanoTime();
|
||||
cfn("CreateStack", targetStack).formParam("TemplateBody", TEMPLATE)
|
||||
.when().post("/").then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(targetStack, "CREATE_COMPLETE");
|
||||
String policy = "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"Update:*\",\"Principal\":\"*\",\"Resource\":\"*\"}]}";
|
||||
|
||||
String updateChangeSet;
|
||||
List<Future<?>> runningOperations = fillExecutor();
|
||||
try {
|
||||
Response rejected = cfn("UpdateStack", targetStack)
|
||||
.formParam("UsePreviousTemplate", "true")
|
||||
.formParam("StackPolicyBody", policy)
|
||||
.when().post("/");
|
||||
assertEquals(400, rejected.statusCode(), rejected.asString());
|
||||
assertTrue(rejected.asString().contains("LimitExceededException"), rejected.asString());
|
||||
|
||||
String listed = cfn("ListChangeSets", targetStack).when().post("/")
|
||||
.then().statusCode(200).extract().asString();
|
||||
List<Node> updates = XmlPath.from(listed)
|
||||
.getList("**.findAll { it.name() == 'member' }", Node.class).stream()
|
||||
.filter(summary -> summary.getNode("ChangeSetName").value().startsWith("update-"))
|
||||
.toList();
|
||||
assertEquals(1, updates.size(), listed);
|
||||
Node restored = updates.getFirst();
|
||||
updateChangeSet = restored.getNode("ChangeSetName").value();
|
||||
assertEquals("AVAILABLE", restored.getNode("ExecutionStatus").value(), listed);
|
||||
assertEquals("CREATE_COMPLETE", restored.getNode("Status").value(), listed);
|
||||
} finally {
|
||||
release(runningOperations);
|
||||
}
|
||||
|
||||
cfn("ExecuteChangeSet", targetStack).formParam("ChangeSetName", updateChangeSet)
|
||||
.when().post("/").then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(targetStack, "UPDATE_COMPLETE");
|
||||
String applied = cfn("GetStackPolicy", targetStack).when().post("/")
|
||||
.then().statusCode(200).extract().xmlPath()
|
||||
.getString("GetStackPolicyResponse.GetStackPolicyResult.StackPolicyBody");
|
||||
assertEquals(policy, applied);
|
||||
|
||||
service.deleteStack(targetStack, REGION, regionResolver.getAccountId())
|
||||
.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedCreateCleanupDoesNotUnprotectAnExecutingStack() throws Exception {
|
||||
String targetStack = uniqueStackName("executing");
|
||||
ChangeSet initial = service.createChangeSetForCreateStack(targetStack, "initial-create",
|
||||
TEMPLATE, null, Map.of(), List.of(), Map.of(), REGION, true);
|
||||
TEMPLATE, null, Map.of(), List.of(), Map.of(), REGION, true, null);
|
||||
Future<?> execution = service.executeChangeSet(targetStack, "initial-create", REGION);
|
||||
try {
|
||||
service.clearProtectionAfterRejectedCreate(targetStack, initial, REGION);
|
||||
|
||||
+6
-48
@@ -1,20 +1,14 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackUpdateSnapshot;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
|
||||
@@ -28,7 +22,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCle
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.WafV2CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
@@ -58,7 +52,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.CALLS_REAL_METHODS;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_DEFAULTS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
@@ -383,23 +376,9 @@ class CloudFormationServiceRollbackTest {
|
||||
.thenAnswer(invocation -> routing.takesParentPhysicalId(invocation.getArgument(0)));
|
||||
when(provisioner.idPrefixCanNameParent(any()))
|
||||
.thenAnswer(invocation -> routing.idPrefixCanNameParent(invocation.getArgument(0)));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
|
||||
templateStore = mock(S3Service.class);
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
service = new CloudFormationService(
|
||||
provisioner,
|
||||
templateStore,
|
||||
mock(SsmService.class),
|
||||
mock(GetStackOutputRoleAuthorizer.class),
|
||||
mock(CfnDynamicReferences.class),
|
||||
new ObjectMapper(),
|
||||
config,
|
||||
resolver,
|
||||
Clock.systemUTC(),
|
||||
new InMemoryStorageFactory());
|
||||
service = CloudFormationServiceFixture.create(provisioner, templateStore, Clock.systemUTC(),
|
||||
new InMemoryStorageFactory(ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1032,11 +1011,7 @@ class CloudFormationServiceRollbackTest {
|
||||
resource.getAttributes().remove("rollbackSnapshot");
|
||||
return null;
|
||||
}).when(cleanupDispatcher).delete(resource, REGION);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
CloudFormationService deleteService = new CloudFormationService(cleanupDispatcher, mock(S3Service.class),
|
||||
mock(SsmService.class), mock(GetStackOutputRoleAuthorizer.class), mock(CfnDynamicReferences.class), new ObjectMapper(),
|
||||
config, mock(RegionResolver.class), Clock.systemUTC(), new InMemoryStorageFactory());
|
||||
CloudFormationService deleteService = CloudFormationServiceFixture.create(cleanupDispatcher);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> deleteService.deleteStackResources(stack, REGION, ACCOUNT));
|
||||
assertEquals("DELETE_FAILED", stack.getStatus());
|
||||
@@ -2276,13 +2251,8 @@ class CloudFormationServiceRollbackTest {
|
||||
|
||||
/** A service over the shared provisioner that reads the time from {@code clock}. */
|
||||
private CloudFormationService serviceReading(Clock clock) {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
return new CloudFormationService(provisioner, mock(S3Service.class), mock(SsmService.class),
|
||||
mock(GetStackOutputRoleAuthorizer.class), mock(CfnDynamicReferences.class), new ObjectMapper(), config,
|
||||
regionResolver, clock, new InMemoryStorageFactory());
|
||||
return CloudFormationServiceFixture.create(provisioner, mock(S3Service.class), clock,
|
||||
new InMemoryStorageFactory(ACCOUNT));
|
||||
}
|
||||
|
||||
/** The stack as {@code PersistentStorage} writes it and reads it back. */
|
||||
@@ -2320,16 +2290,4 @@ class CloudFormationServiceRollbackTest {
|
||||
return Instant.now();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class InMemoryStorageFactory extends StorageFactory {
|
||||
private InMemoryStorageFactory() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -28,6 +28,10 @@ class CloudFormationStackPersistenceTest {
|
||||
Path tempDir;
|
||||
|
||||
private static final String KEY = "000000000000/my-stack:us-east-1";
|
||||
private static final String STACK_POLICY =
|
||||
"{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"Update:*\",\"Principal\":\"*\",\"Resource\":\"*\"}]}";
|
||||
private static final String PENDING_POLICY =
|
||||
"{\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"Update:*\",\"Principal\":\"*\",\"Resource\":\"*\"}]}";
|
||||
|
||||
@Test
|
||||
void stackGraphPersistsAcrossInstances() {
|
||||
@@ -43,6 +47,7 @@ class CloudFormationStackPersistenceTest {
|
||||
stack.getOutputs().put("BucketArn", "arn:aws:s3:::my-bucket");
|
||||
stack.getExports().put("MyExport", "exported-value");
|
||||
stack.getTags().put("team", "platform");
|
||||
stack.setStackPolicyBody(STACK_POLICY);
|
||||
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("MyBucket");
|
||||
@@ -62,6 +67,7 @@ class CloudFormationStackPersistenceTest {
|
||||
changeSet.setChangeSetName("initial-create");
|
||||
changeSet.setStackName("my-stack");
|
||||
changeSet.setStatus("CREATE_COMPLETE");
|
||||
changeSet.setStackPolicyBody(PENDING_POLICY);
|
||||
stack.getChangeSets().put("initial-create", changeSet);
|
||||
|
||||
PersistentStorage<String, Stack> writer = new PersistentStorage<>(
|
||||
@@ -86,6 +92,7 @@ class CloudFormationStackPersistenceTest {
|
||||
assertEquals("arn:aws:s3:::my-bucket", loaded.getOutputs().get("BucketArn"));
|
||||
assertEquals("exported-value", loaded.getExports().get("MyExport"));
|
||||
assertEquals("platform", loaded.getTags().get("team"));
|
||||
assertEquals(STACK_POLICY, loaded.getStackPolicyBody());
|
||||
|
||||
StackResource loadedResource = loaded.getResources().get("MyBucket");
|
||||
assertNotNull(loadedResource, "Nested stack resources must round-trip");
|
||||
@@ -98,6 +105,7 @@ class CloudFormationStackPersistenceTest {
|
||||
assertEquals("CREATE_COMPLETE", loaded.getEvents().get(0).getResourceStatus());
|
||||
assertTrue(loaded.getChangeSets().containsKey("initial-create"));
|
||||
assertEquals("CREATE_COMPLETE", loaded.getChangeSets().get("initial-create").getStatus());
|
||||
assertEquals(PENDING_POLICY, loaded.getChangeSets().get("initial-create").getStackPolicyBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.testing.CfnRequests;
|
||||
import io.github.hectorvent.floci.testing.CfnStackWaits;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
/**
|
||||
* SetStackPolicy, GetStackPolicy, and the stack policy CreateStack and UpdateStack carry, as
|
||||
* measured on CloudFormation (eu-west-1). Floci stores the policy and checks its structure; it
|
||||
* does not enforce it during updates.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationStackPolicyIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
|
||||
private static final String TEMPLATE = "{\"Resources\":{\"P\":{\"Type\":\"AWS::SSM::Parameter\","
|
||||
+ "\"Properties\":{\"Type\":\"String\",\"Value\":\"v\"}}}}";
|
||||
private static final String UPDATED_TEMPLATE = TEMPLATE.replace("\"v\"", "\"v2\"");
|
||||
// SSM refuses a comma in a tag key, so this template fails to create and fails to update.
|
||||
private static final String FAILING_TEMPLATE = TEMPLATE.replace("\"Value\":\"v\"",
|
||||
"\"Value\":\"v3\",\"Tags\":{\"a,b\":\"x\"}");
|
||||
private static final String POLICY = "{\n \"Statement\" : [ {\"Effect\":\"Deny\",\"Action\":\"Update:*\","
|
||||
+ "\"Principal\":\"*\",\"Resource\":\"*\"} ]\n}";
|
||||
private static final String OTHER_POLICY = "{\"Statement\":{\"Effect\":\"allow\",\"NotAction\":\"Update:Delete\","
|
||||
+ "\"Principal\":\"*\",\"Resource\":\"*\"}}";
|
||||
private static final String INVALID = "Error validating stack policy: Invalid stack policy";
|
||||
|
||||
@Test
|
||||
void setStoresThePolicyVerbatimAndGetReturnsItByNameAndByArn() {
|
||||
String stackName = createdStack();
|
||||
String stackId = stackId(stackName);
|
||||
try {
|
||||
policyOf(stackName).then().statusCode(200)
|
||||
.body(containsString("<GetStackPolicyResult"))
|
||||
.body(not(containsString("StackPolicyBody")));
|
||||
|
||||
cfn("SetStackPolicy", stackName, "StackPolicyBody", POLICY).then().statusCode(200)
|
||||
.body(containsString("<SetStackPolicyResponse"))
|
||||
.body(not(containsString("SetStackPolicyResult")));
|
||||
assertEquals(POLICY, storedPolicy(stackName));
|
||||
assertEquals(POLICY, storedPolicy(stackId));
|
||||
|
||||
cfn("SetStackPolicy", stackId, "StackPolicyBody", OTHER_POLICY).then().statusCode(200);
|
||||
assertEquals(OTHER_POLICY, storedPolicy(stackName));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void setRequiresExactlyOnePolicySourceBeforeLookingTheStackUp() {
|
||||
cfn("SetStackPolicy", "never-created").then().statusCode(400)
|
||||
.body(containsString("<Code>ValidationError</Code>"))
|
||||
.body(containsString("<Message>Ether StackPolicyURL or StackPolicyBody must be specified.</Message>"));
|
||||
cfn("SetStackPolicy", "never-created", "StackPolicyBody", POLICY,
|
||||
"StackPolicyURL", "https://s3.amazonaws.com/b/k").then().statusCode(400)
|
||||
.body(containsString("<Message>You cannot specify both StackPolicyURL and StackPolicyBody</Message>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAndGetOnAMissingStackReportIt() {
|
||||
cfn("SetStackPolicy", "never-created", "StackPolicyBody", "nope").then().statusCode(400)
|
||||
.body(containsString("<Code>ValidationError</Code>"))
|
||||
.body(containsString("<Message>Stack: never-created does not exist</Message>"));
|
||||
policyOf("never-created").then().statusCode(400)
|
||||
.body(containsString("<Message>Stack: never-created does not exist</Message>"));
|
||||
}
|
||||
|
||||
/** Before the policy source, so a request without a name never reaches a stack named "null". */
|
||||
@Test
|
||||
void aMissingOrMalformedStackNameIsRefusedFirst() {
|
||||
String missing = "1 validation error detected: Value null at 'stackName' failed to satisfy constraint:"
|
||||
+ " Member must not be null";
|
||||
assertEquals(missing, validationError(cfn("SetStackPolicy", null)));
|
||||
assertEquals(missing, validationError(policyOf(null)));
|
||||
assertEquals("2 validation errors detected: Value '' at 'stackName' failed to satisfy constraint:"
|
||||
+ " Member must have length greater than or equal to 1; Value '' at 'stackName' failed"
|
||||
+ " to satisfy constraint: Member must satisfy regular expression pattern:"
|
||||
+ " [a-zA-Z][-a-zA-Z0-9]*|arn:[-a-zA-Z0-9:/._+]*",
|
||||
validationError(policyOf("")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"nope",
|
||||
"[]",
|
||||
" ",
|
||||
"null",
|
||||
"{\"Foo\":1}",
|
||||
"{\"Version\":\"2012-10-17\"}",
|
||||
"{\"Statement\":null}",
|
||||
"{\"Statement\":[]}",
|
||||
"{\"Statement\":\"x\"}",
|
||||
"{\"Statement\":[{}]}",
|
||||
"{\"Statement\":[\"x\"]}",
|
||||
"{\"Statement\":[{\"Effect\":\"Maybe\"}]}",
|
||||
"{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"Update:*\",\"NotAction\":\"Update:Delete\"}]}",
|
||||
"{\"Statement\":{\"Effect\":\"Allow\"}} junk"
|
||||
})
|
||||
void setRejectsAPolicyThatIsNotAPolicy(String policy) {
|
||||
String stackName = createdStack();
|
||||
try {
|
||||
cfn("SetStackPolicy", stackName, "StackPolicyBody", policy).then().statusCode(400)
|
||||
.body(containsString("<Code>ValidationError</Code>"))
|
||||
.body(containsString("<Message>" + INVALID + "</Message>"));
|
||||
policyOf(stackName).then().statusCode(200).body(not(containsString("StackPolicyBody")));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{}",
|
||||
"{\"Statement\":{\"Effect\":\"allow\"}}",
|
||||
"{\"Statement\":[{\"Effect\":\"Deny\",\"Action\":[\"Update:Replace\",\"Update:Delete\"]}]}"
|
||||
})
|
||||
void setAcceptsAStructurallyValidPolicy(String policy) {
|
||||
String stackName = createdStack();
|
||||
try {
|
||||
cfn("SetStackPolicy", stackName, "StackPolicyBody", policy).then().statusCode(200);
|
||||
assertEquals(policy, storedPolicy(stackName));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void setReadsAPolicyUrlFromS3() {
|
||||
String stackName = createdStack();
|
||||
String bucket = "cfn-stack-policy-" + Long.toString(System.nanoTime(), 36);
|
||||
try {
|
||||
given().when().put("/" + bucket).then().statusCode(200);
|
||||
given().contentType("application/json").body(POLICY).when().put("/" + bucket + "/policy.json")
|
||||
.then().statusCode(200);
|
||||
cfn("SetStackPolicy", stackName,
|
||||
"StackPolicyURL", "https://s3.us-east-1.amazonaws.com/" + bucket + "/policy.json")
|
||||
.then().statusCode(200);
|
||||
assertEquals(POLICY, storedPolicy(stackName));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
given().when().delete("/" + bucket + "/policy.json");
|
||||
given().when().delete("/" + bucket);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void setIsRefusedOnAStackThatFailedToCreate() {
|
||||
String stackName = uniqueName();
|
||||
cfn("CreateStack", stackName, "TemplateBody", FAILING_TEMPLATE).then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackName, "ROLLBACK_COMPLETE", CFN_AUTH);
|
||||
try {
|
||||
cfn("SetStackPolicy", stackName, "StackPolicyBody", "nope").then().statusCode(400)
|
||||
.body(containsString("<Message>SetStackPolicy cannot be called when stack is in the"
|
||||
+ " ROLLBACK_COMPLETE state</Message>"));
|
||||
policyOf(stackName).then().statusCode(200).body(not(containsString("StackPolicyBody")));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeletedStackKeepsItsPolicyByArnAndRefusesANewOne() {
|
||||
String stackName = createdStack();
|
||||
String stackId = stackId(stackName);
|
||||
cfn("SetStackPolicy", stackName, "StackPolicyBody", POLICY).then().statusCode(200);
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
|
||||
assertEquals(POLICY, storedPolicy(stackId));
|
||||
policyOf(stackName).then().statusCode(400)
|
||||
.body(containsString("<Message>Stack: " + stackName + " does not exist</Message>"));
|
||||
cfn("SetStackPolicy", stackId, "StackPolicyBody", OTHER_POLICY).then().statusCode(400)
|
||||
.body(containsString("<Message>SetStackPolicy cannot be called when stack is in the"
|
||||
+ " DELETE_COMPLETE state</Message>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackStoresItsPolicy() {
|
||||
String stackName = uniqueName();
|
||||
cfn("CreateStack", stackName, "TemplateBody", TEMPLATE, "StackPolicyBody", POLICY)
|
||||
.then().statusCode(200);
|
||||
try {
|
||||
assertEquals(POLICY, storedPolicy(stackName));
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE", CFN_AUTH);
|
||||
assertEquals(POLICY, storedPolicy(stackName));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackRefusesAnInvalidPolicyWithoutCreatingTheStack() {
|
||||
String stackName = uniqueName();
|
||||
cfn("CreateStack", stackName, "TemplateBody", TEMPLATE, "StackPolicyBody", "{\"Statement\":[]}")
|
||||
.then().statusCode(400)
|
||||
.body(containsString("<Code>ValidationError</Code>"))
|
||||
.body(containsString("<Message>Error validating stack policy to be applied after stack creation:"
|
||||
+ " Invalid stack policy</Message>"));
|
||||
cfn("CreateStack", stackName, "TemplateBody", TEMPLATE, "StackPolicyBody", POLICY,
|
||||
"StackPolicyURL", "https://s3.amazonaws.com/b/k").then().statusCode(400)
|
||||
.body(containsString("<Message>You cannot specify both StackPolicyURL and StackPolicyBody</Message>"));
|
||||
cfn("DescribeStacks", stackName).then().statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackAppliesItsPolicyOnceTheUpdateCompletes() {
|
||||
String stackName = createdStack();
|
||||
try {
|
||||
cfn("UpdateStack", stackName, "TemplateBody", UPDATED_TEMPLATE, "StackPolicyBody", POLICY)
|
||||
.then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH);
|
||||
assertEquals(POLICY, storedPolicy(stackName));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedUpdateKeepsThePreviousPolicy() {
|
||||
String stackName = createdStack();
|
||||
try {
|
||||
cfn("SetStackPolicy", stackName, "StackPolicyBody", POLICY).then().statusCode(200);
|
||||
cfn("UpdateStack", stackName, "TemplateBody", FAILING_TEMPLATE, "StackPolicyBody", OTHER_POLICY)
|
||||
.then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE", CFN_AUTH);
|
||||
assertEquals(POLICY, storedPolicy(stackName));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewPolicyAloneIsAnUpdateButTheSamePolicyIsNot() {
|
||||
String stackName = createdStack();
|
||||
try {
|
||||
int resourceEvents = resourceEvents(stackName);
|
||||
assertNotEquals(0, resourceEvents);
|
||||
cfn("UpdateStack", stackName, "UsePreviousTemplate", "true", "StackPolicyBody", POLICY)
|
||||
.then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH);
|
||||
assertEquals(POLICY, storedPolicy(stackName));
|
||||
assertEquals(resourceEvents, resourceEvents(stackName));
|
||||
cfn("ListChangeSets", stackName).then().statusCode(200)
|
||||
.body(not(containsString("<Status>FAILED</Status>")))
|
||||
.body(containsString("<ExecutionStatus>EXECUTE_COMPLETE</ExecutionStatus>"));
|
||||
|
||||
cfn("UpdateStack", stackName, "UsePreviousTemplate", "true", "StackPolicyBody", POLICY)
|
||||
.then().statusCode(400)
|
||||
.body(containsString("<Message>No updates are to be performed.</Message>"));
|
||||
cfn("UpdateStack", stackName, "UsePreviousTemplate", "true",
|
||||
"StackPolicyDuringUpdateBody", OTHER_POLICY).then().statusCode(400)
|
||||
.body(containsString("<Message>No updates are to be performed.</Message>"));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackRefusesAnInvalidPolicy() {
|
||||
String stackName = createdStack();
|
||||
try {
|
||||
cfn("UpdateStack", stackName, "TemplateBody", UPDATED_TEMPLATE, "StackPolicyBody", "nope")
|
||||
.then().statusCode(400)
|
||||
.body(containsString("<Message>Error validating stack policy to be applied after stack update:"
|
||||
+ " Invalid stack policy</Message>"));
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE", CFN_AUTH);
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
private static String uniqueName() {
|
||||
return "stack-policy-" + Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
private static String createdStack() {
|
||||
String stackName = uniqueName();
|
||||
cfn("CreateStack", stackName, "TemplateBody", TEMPLATE).then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE", CFN_AUTH);
|
||||
return stackName;
|
||||
}
|
||||
|
||||
private static String stackId(String stackName) {
|
||||
return cfn("DescribeStacks", stackName).then().statusCode(200).extract().xmlPath()
|
||||
.getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackId");
|
||||
}
|
||||
|
||||
private static Response policyOf(String stackName) {
|
||||
return cfn("GetStackPolicy", stackName);
|
||||
}
|
||||
|
||||
private static String storedPolicy(String stackName) {
|
||||
Response response = policyOf(stackName);
|
||||
response.then().statusCode(200);
|
||||
return response.xmlPath().getString("GetStackPolicyResponse.GetStackPolicyResult.StackPolicyBody");
|
||||
}
|
||||
|
||||
private static String validationError(Response response) {
|
||||
return response.then().statusCode(400).body(containsString("<Code>ValidationError</Code>"))
|
||||
.extract().xmlPath().getString("ErrorResponse.Error.Message");
|
||||
}
|
||||
|
||||
/** How many events the stack's one resource has, so a policy-only update can be shown not to touch it. */
|
||||
private static int resourceEvents(String stackName) {
|
||||
return cfn("DescribeStackEvents", stackName).then().statusCode(200).extract().xmlPath()
|
||||
.getList("DescribeStackEventsResponse.DescribeStackEventsResult.StackEvents.member"
|
||||
+ ".findAll { it.LogicalResourceId == 'P' }").size();
|
||||
}
|
||||
|
||||
private static Response cfn(String action, String stackName, String... params) {
|
||||
RequestSpecification request = CfnRequests.cfn(action, stackName).header("Authorization", CFN_AUTH);
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
request = request.formParam(params[i], params[i + 1]);
|
||||
}
|
||||
return request.when().post("/");
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Covers that a create, an update and SetStackPolicy store a stack policy only alongside a stack state that allows it. */
|
||||
class CloudFormationStackPolicyServiceTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String TEMPLATE = "{\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}";
|
||||
private static final String UPDATED_TEMPLATE =
|
||||
"{\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"},\"Topic\":{\"Type\":\"AWS::SNS::Topic\"}}}";
|
||||
private static final String POLICY =
|
||||
"{\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"Update:*\",\"Principal\":\"*\",\"Resource\":\"*\"}]}";
|
||||
|
||||
private CfnResourceDispatcher provisioner;
|
||||
private S3Service templateStore;
|
||||
private RecordingStackStore stackStore;
|
||||
private CloudFormationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
provisioner = mock(CfnResourceDispatcher.class);
|
||||
when(provisioner.provision(anyString(), anyString(), any(), any(), anyString(), anyString(), anyString(),
|
||||
any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId(invocation.getArgument(0));
|
||||
resource.setResourceType(invocation.getArgument(1));
|
||||
resource.setPhysicalId(invocation.getArgument(0) + "-id");
|
||||
resource.setStatus("CREATE_COMPLETE");
|
||||
return resource;
|
||||
});
|
||||
templateStore = mock(S3Service.class);
|
||||
stackStore = new RecordingStackStore();
|
||||
service = CloudFormationServiceFixture.create(provisioner, templateStore, Clock.systemUTC(),
|
||||
new InMemoryStorageFactory(ACCOUNT).withStore("cloudformation-stacks.json", stackStore));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopService() {
|
||||
service.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createChangeSet_storesItsStackPolicyBeforeCreateInProgressIsPersisted() throws Exception {
|
||||
ChangeSet changeSet = service.createChangeSet("policy-create", "create", "CREATE", TEMPLATE, null,
|
||||
Map.of(), List.of(), Map.of(), REGION, ACCOUNT);
|
||||
changeSet.setStackPolicyBody(POLICY);
|
||||
|
||||
service.executeChangeSet("policy-create", "create", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
|
||||
|
||||
List<PersistedStack> inProgress = stackStore.puts.stream()
|
||||
.filter(put -> "CREATE_IN_PROGRESS".equals(put.status()))
|
||||
.toList();
|
||||
assertFalse(inProgress.isEmpty());
|
||||
assertTrue(inProgress.stream().allMatch(put -> POLICY.equals(put.stackPolicyBody())), inProgress::toString);
|
||||
assertEquals(POLICY, service.describeStacks("policy-create", REGION, ACCOUNT).getFirst().getStackPolicyBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateChangeSet_storesItsStackPolicyBeforeUpdateCompleteIsPersisted() throws Exception {
|
||||
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
createStack("policy-update");
|
||||
ChangeSet changeSet = service.createChangeSet("policy-update", "update", "UPDATE", UPDATED_TEMPLATE, null,
|
||||
Map.of(), List.of(), Map.of(), REGION, ACCOUNT);
|
||||
changeSet.setStackPolicyBody(POLICY);
|
||||
|
||||
service.executeChangeSet("policy-update", "update", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
|
||||
|
||||
List<PersistedStack> completed = stackStore.puts.stream()
|
||||
.filter(put -> "UPDATE_COMPLETE".equals(put.status()))
|
||||
.toList();
|
||||
assertFalse(completed.isEmpty());
|
||||
assertTrue(completed.stream().allMatch(put -> POLICY.equals(put.stackPolicyBody())), completed::toString);
|
||||
assertEquals(POLICY, service.describeStacks("policy-update", REGION, ACCOUNT).getFirst().getStackPolicyBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackChangeSetCarriesItsPolicyWhenItIsCreated() {
|
||||
ChangeSet changeSet = service.createChangeSetForCreateStack("policy-initial", "initial-create", TEMPLATE,
|
||||
null, Map.of(), List.of(), Map.of(), REGION, false, POLICY);
|
||||
|
||||
assertEquals(POLICY, changeSet.getStackPolicyBody());
|
||||
assertEquals(POLICY,
|
||||
service.describeChangeSet("policy-initial", "initial-create", REGION).getStackPolicyBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackChangeSetWithOnlyANewPolicyIsExecutable() throws Exception {
|
||||
createStack("policy-only");
|
||||
|
||||
ChangeSet newPolicy = service.createChangeSetForUpdateStack("policy-only", "new-policy", TEMPLATE, null,
|
||||
Map.of(), List.of(), Map.of(), REGION, POLICY);
|
||||
|
||||
assertEquals("CREATE_COMPLETE", newPolicy.getStatus());
|
||||
assertEquals("AVAILABLE", newPolicy.getExecutionStatus());
|
||||
assertNull(newPolicy.getStatusReason());
|
||||
assertEquals(POLICY, newPolicy.getStackPolicyBody());
|
||||
|
||||
service.setStackPolicy("policy-only", POLICY, null, REGION);
|
||||
ChangeSet samePolicy = service.createChangeSetForUpdateStack("policy-only", "same-policy", TEMPLATE, null,
|
||||
Map.of(), List.of(), Map.of(), REGION, POLICY);
|
||||
|
||||
assertEquals("FAILED", samePolicy.getStatus());
|
||||
assertEquals(CloudFormationService.NO_CHANGES_REASON, samePolicy.getStatusReason());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setStackPolicy_refusesAStackAnUpdateClaimedWhileItsPolicyWasRead() throws Exception {
|
||||
createStack("policy-race");
|
||||
Stack stack = service.describeStacks("policy-race", REGION, ACCOUNT).getFirst();
|
||||
when(templateStore.getObject("policies", "policy.json")).thenAnswer(invocation -> {
|
||||
stack.setStatus("UPDATE_IN_PROGRESS");
|
||||
return new S3Object("policies", "policy.json", POLICY.getBytes(StandardCharsets.UTF_8),
|
||||
"application/json");
|
||||
});
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.setStackPolicy(
|
||||
"policy-race", null, "http://localhost/policies/policy.json", REGION));
|
||||
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertEquals("SetStackPolicy cannot be called when stack is in the UPDATE_IN_PROGRESS state",
|
||||
error.getMessage());
|
||||
assertNull(stack.getStackPolicyBody());
|
||||
}
|
||||
|
||||
private void createStack(String stackName) throws Exception {
|
||||
service.createChangeSet(stackName, "create", "CREATE", TEMPLATE, null,
|
||||
Map.of(), List.of(), Map.of(), REGION, ACCOUNT);
|
||||
service.executeChangeSet(stackName, "create", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
|
||||
assertEquals("CREATE_COMPLETE", service.describeStacks(stackName, REGION, ACCOUNT).getFirst().getStatus());
|
||||
}
|
||||
|
||||
private record PersistedStack(String status, String stackPolicyBody) {}
|
||||
|
||||
private static final class RecordingStackStore extends InMemoryStorage<String, Stack> {
|
||||
private final List<PersistedStack> puts = new CopyOnWriteArrayList<>();
|
||||
|
||||
@Override
|
||||
public void put(String key, Stack value) {
|
||||
puts.add(new PersistedStack(value.getStatus(), value.getStackPolicyBody()));
|
||||
super.put(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user