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:
Mario Toffia authored and GitHub committed 2026-11-05 04:43:20 -04:00
1 parent cf25c9f6db
commit a19b296f06
13 files changed
+845 -96

No files matched your search

+2 -2
View File
@@ -43,8 +43,8 @@ changing credentials already issued.
| `ValidateTemplate` | Refuses a body that is no template (see [Template format](#template-format)) and a template holding a `null` value (see [Null values](#null-values)); otherwise returns success without validating further |
| `ListStacks` | List stacks by status |
| `ListExports` | - |
| `SetStackPolicy` | Accepted; no-op (stub — stack policies are not enforced) |
| `GetStackPolicy` | Accepted; returns an empty policy (stub) |
| `SetStackPolicy` | Store a stack policy given as `StackPolicyBody` or `StackPolicyURL`; only its structure is checked, and the policy is not enforced. `CreateStack` stores its policy and `UpdateStack` applies its policy once the update completes |
| `GetStackPolicy` | Return the stored stack policy as submitted, including for a deleted stack by stack id |
| `DescribeStackResource` | Get a specific stack resource |
| `DescribeOrganizationsAccess` | - |
| `ActivateOrganizationsAccess` | - |
@@ -65,8 +65,8 @@ public class CloudFormationQueryHandler {
case "ValidateTemplate" -> validateTemplate(params);
case "ListStacks" -> listStacks(params, region);
case "ListExports" -> listExports(params, region);
case "SetStackPolicy" -> Response.ok(emptyResult("SetStackPolicyResponse")).build();
case "GetStackPolicy" -> Response.ok(emptyResult("GetStackPolicyResponse")).build();
case "SetStackPolicy" -> setStackPolicy(params, region);
case "GetStackPolicy" -> getStackPolicy(params, region);
case "DescribeStackResource" -> describeStackResource(params, region);
case "DescribeOrganizationsAccess" -> describeOrganizationsAccess();
case "ActivateOrganizationsAccess" -> activateOrganizationsAccess();
@@ -117,11 +117,13 @@ public class CloudFormationQueryHandler {
Map<String, String> parameters = extractParameters(params);
List<String> capabilities = extractList(params, "Capabilities.member.");
Map<String, String> tags = extractTags(params);
String stackPolicy = cfnService.resolveStackPolicy(params.getFirst("StackPolicyBody"),
params.getFirst("StackPolicyURL"), " to be applied after stack creation");
boolean terminationProtection = Boolean.parseBoolean(params.getFirst("EnableTerminationProtection"));
ChangeSet initial = cfnService.createChangeSetForCreateStack(stackName, "initial-create",
templateBody, templateUrl, parameters, capabilities, tags, region,
terminationProtection);
terminationProtection, stackPolicy);
try {
cfnService.executeChangeSet(initial.getStackId(), initial.getChangeSetId(), region);
} catch (AwsException e) {
@@ -154,13 +156,15 @@ public class CloudFormationQueryHandler {
extractParameters(params, cfnService.currentParameters(stackName, region));
List<String> capabilities = extractList(params, "Capabilities.member.");
Map<String, String> tags = extractTags(params);
String stackPolicy = cfnService.resolveStackPolicy(params.getFirst("StackPolicyBody"),
params.getFirst("StackPolicyURL"), " to be applied after stack update");
String changeSetName = "update-" + UUID.randomUUID().toString().substring(0, 8);
ChangeSet cs = usePreviousTemplate
? cfnService.createChangeSetFromPreviousTemplate(stackName, changeSetName,
parameters, capabilities, tags, region)
: cfnService.createChangeSet(stackName, changeSetName,
"UPDATE", templateBody, templateUrl, parameters, capabilities, tags, region);
parameters, capabilities, tags, region, stackPolicy)
: cfnService.createChangeSetForUpdateStack(stackName, changeSetName,
templateBody, templateUrl, parameters, capabilities, tags, region, stackPolicy);
// An update that submits what the stack already has is refused, and leaves no change set
// behind, as UpdateStack does on AWS.
if (CloudFormationService.NO_CHANGES_REASON.equals(cs.getStatusReason())) {
@@ -241,6 +245,35 @@ public class CloudFormationQueryHandler {
}
}
// ── SetStackPolicy / GetStackPolicy ─────────────────────────────────────────
private Response setStackPolicy(MultivaluedMap<String, String> params, String region) {
try {
cfnService.setStackPolicy(params.getFirst("StackName"), params.getFirst("StackPolicyBody"),
params.getFirst("StackPolicyURL"), region);
return Response.ok(emptyResult("SetStackPolicyResponse")).type("text/xml").build();
} catch (AwsException e) {
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
private Response getStackPolicy(MultivaluedMap<String, String> params, String region) {
try {
String policy = cfnService.getStackPolicy(params.getFirst("StackName"), region);
String xml = new XmlBuilder()
.start("GetStackPolicyResponse", CF_NS)
.start("GetStackPolicyResult")
.elem("StackPolicyBody", policy)
.end("GetStackPolicyResult")
.raw(AwsQueryResponse.responseMetadata())
.end("GetStackPolicyResponse")
.build();
return Response.ok(xml).type("text/xml").build();
} catch (AwsException e) {
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
// ── CreateChangeSet ───────────────────────────────────────────────────────
private Response createChangeSet(MultivaluedMap<String, String> params, String region) {
@@ -264,7 +297,7 @@ public class CloudFormationQueryHandler {
// internally, may attach a CREATE change set to a stack still in REVIEW_IN_PROGRESS.
ChangeSet cs = usePreviousTemplate
? cfnService.createChangeSetFromPreviousTemplate(stackName, changeSetName,
parameters, capabilities, tags, region)
parameters, capabilities, tags, region, null)
: cfnService.createChangeSetForRequest(stackName, changeSetName, changeSetType,
templateBody, templateUrl, parameters, capabilities, tags, region);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -43,6 +44,7 @@ import org.jboss.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
@@ -253,6 +255,126 @@ public class CloudFormationService implements ResourceProvider {
});
}
// ── Stack policy ──────────────────────────────────────────────────────────
/**
* Stores a stack's policy (CloudFormation {@code SetStackPolicy}). The checks run in AWS's order:
* the stack's name, the policy source, the stack, the stack's state, then the policy itself.
*/
public void setStackPolicy(String stackName, String body, String url, String region) {
validateStackName(stackName);
if (isNullOrEmpty(body) && isNullOrEmpty(url)) {
// AWS's own spelling.
throw new AwsException("ValidationError", "Ether StackPolicyURL or StackPolicyBody must be specified.", 400);
}
rejectBothPolicySources(body, url);
Stack stack = stackForPolicy(stackName, region);
refuseStackPolicyIn(stack);
String policy = resolveStackPolicy(body, url, "");
// Reading a StackPolicyURL takes time, so the state is checked again under the lock an
// update or delete claims.
stacks.compute(stackKey(ownerAccount(stack), stack.getStackName(), stack.getRegion()), (key, live) -> {
refuseStackPolicyIn(stack);
if (live != stack) {
throw new AwsException("ValidationError", CONTINUE_STACK_MISSING.formatted(stackName), 400);
}
stack.setStackPolicyBody(policy);
// Persisted under the lock, so a delete that completes next cannot be undone by this write.
persistStack(stack);
return live;
});
}
private static void refuseStackPolicyIn(Stack stack) {
String status = stack.getStatus();
if (refusesUpdate(status) || "DELETE_COMPLETE".equals(status)) {
throw new AwsException("ValidationError",
"SetStackPolicy cannot be called when stack is in the " + status + " state", 400);
}
}
/** The stack's policy as it was submitted, or null when it has none. A deleted stack keeps it. */
public String getStackPolicy(String stackName, String region) {
validateStackName(stackName);
return stackForPolicy(stackName, region).getStackPolicyBody();
}
/**
* The policy a request supplies as {@code StackPolicyBody} or, read from S3, as
* {@code StackPolicyURL}, or null when it supplies neither. {@code appliedWhen} completes AWS's
* message for a policy that is not one. The check is structural: Floci stores a policy but does
* not enforce it.
*/
public String resolveStackPolicy(String body, String url, String appliedWhen) {
rejectBothPolicySources(body, url);
if (isNullOrEmpty(body) && isNullOrEmpty(url)) {
return null;
}
String policy = isNullOrEmpty(url) ? body : fetchTemplateFromS3(url);
if (!isStackPolicy(policy)) {
throw new AwsException("ValidationError",
"Error validating stack policy" + appliedWhen + ": Invalid stack policy", 400);
}
return policy;
}
private static void rejectBothPolicySources(String body, String url) {
if (!isNullOrEmpty(body) && !isNullOrEmpty(url)) {
throw new AwsException("ValidationError", "You cannot specify both StackPolicyURL and StackPolicyBody", 400);
}
}
private Stack stackForPolicy(String stackName, String region) {
Stack stack = resolveStackForDescribe(stackName, region);
if (stack == null) {
throw new AwsException("ValidationError", CONTINUE_STACK_MISSING.formatted(stackName), 400);
}
return stack;
}
/**
* A JSON object that is empty or has a {@code Statement}: one statement object or a non-empty
* array of them, each with an Allow or Deny {@code Effect} and not both {@code Action} and
* {@code NotAction}. These are the shapes AWS refuses as "Invalid stack policy".
*/
private boolean isStackPolicy(String policy) {
JsonNode root;
try {
root = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(policy);
} catch (IOException e) {
return false;
}
if (root == null || !root.isObject()) {
return false;
}
if (root.isEmpty()) {
return true;
}
JsonNode statements = root.path("Statement");
if (statements.isObject()) {
return isPolicyStatement(statements);
}
if (!statements.isArray() || statements.isEmpty()) {
return false;
}
for (JsonNode statement : statements) {
if (!isPolicyStatement(statement)) {
return false;
}
}
return true;
}
private static boolean isPolicyStatement(JsonNode statement) {
String effect = statement.path("Effect").asText();
return ("Allow".equalsIgnoreCase(effect) || "Deny".equalsIgnoreCase(effect))
&& !(statement.has("Action") && statement.has("NotAction"));
}
private static boolean isNullOrEmpty(String value) {
return value == null || value.isEmpty();
}
// ── DescribeStacks ────────────────────────────────────────────────────────
public List<Stack> describeStacks(String stackName, String region) {
@@ -356,7 +478,8 @@ public class CloudFormationService implements ResourceProvider {
public ChangeSet createChangeSetFromPreviousTemplate(String stackName, String changeSetName,
Map<String, String> parameters,
List<String> capabilities,
Map<String, String> tags, String region) {
Map<String, String> tags, String region,
String stackPolicy) {
ChangeSet created = null;
while (created == null) {
Stack stack = resolveStack(stackName, region);
@@ -366,7 +489,7 @@ public class CloudFormationService implements ResourceProvider {
}
String previousTemplate = previousTemplateOf(stack);
created = createChangeSet(stackName, changeSetName, "UPDATE", previousTemplate, null,
parameters, capabilities, tags, region, currentAccount(), false, true, false);
parameters, capabilities, tags, region, currentAccount(), false, true, false, stackPolicy);
}
return created;
}
@@ -384,17 +507,26 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
parameters, capabilities, tags, region, regionResolver.getAccountId(), false, false, false);
parameters, capabilities, tags, region, regionResolver.getAccountId(), false, false, false, null);
}
public ChangeSet createChangeSetForCreateStack(String stackName, String changeSetName,
String templateBody, String templateUrl,
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region,
boolean enableTerminationProtection) {
boolean enableTerminationProtection, String stackPolicy) {
return createChangeSet(stackName, changeSetName, "CREATE", templateBody, templateUrl,
parameters, capabilities, tags, region, regionResolver.getAccountId(), false, false,
enableTerminationProtection);
enableTerminationProtection, stackPolicy);
}
public ChangeSet createChangeSetForUpdateStack(String stackName, String changeSetName,
String templateBody, String templateUrl,
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region, String stackPolicy) {
return createChangeSet(stackName, changeSetName, "UPDATE", templateBody, templateUrl,
parameters, capabilities, tags, region, regionResolver.getAccountId(), false, false, false,
stackPolicy);
}
/**
@@ -418,7 +550,7 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
parameters, capabilities, tags, region, regionResolver.getAccountId(), true, false, false);
parameters, capabilities, tags, region, regionResolver.getAccountId(), true, false, false, null);
}
/**
@@ -436,7 +568,7 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region, String accountId) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
parameters, capabilities, tags, region, accountId, false, false, false);
parameters, capabilities, tags, region, accountId, false, false, false, null);
}
private ChangeSet createChangeSet(String stackName, String changeSetName, String changeSetType,
@@ -444,7 +576,7 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region, String accountId,
boolean attachToReviewInProgressStack, boolean fromPreviousTemplate,
boolean enableTerminationProtection) {
boolean enableTerminationProtection, String stackPolicy) {
String resolvedTemplate = resolveTemplate(templateBody, templateUrl);
requireValidTemplate(resolvedTemplate);
boolean isCreateType = "CREATE".equalsIgnoreCase(changeSetType);
@@ -589,11 +721,14 @@ public class CloudFormationService implements ResourceProvider {
cs.setParameters(parameters);
cs.setCapabilities(capabilities);
cs.setTags(tags);
cs.setStackPolicyBody(stackPolicy);
// A new stack policy alone is still an update.
boolean newPolicy = stackPolicy != null && !stackPolicy.equals(target.getStackPolicyBody());
if (samTransformFailureReason != null) {
cs.setStatus("FAILED");
cs.setExecutionStatus("UNAVAILABLE");
cs.setStatusReason(samTransformFailureReason);
} else if (unchanged[0]) {
} else if (unchanged[0] && !newPolicy) {
cs.setStatus("FAILED");
cs.setExecutionStatus("UNAVAILABLE");
cs.setStatusReason(NO_CHANGES_REASON);
@@ -1226,7 +1361,8 @@ public class CloudFormationService implements ResourceProvider {
private record StackMutationSnapshot(String status, Instant lastUpdatedTime,
List<StackEvent> events,
Map<String, ChangeSet> changeSets,
Map<ChangeSet, ChangeSetState> changeSetStates) {}
Map<ChangeSet, ChangeSetState> changeSetStates,
String stackPolicyBody) {}
// compute() holds the stack's per-key lock for the whole claim, so only one racing execution can win.
private Future<?> claimAndSubmitExecution(String stackNameOrArn, String changeSetName, String region,
@@ -1273,6 +1409,9 @@ public class CloudFormationService implements ResourceProvider {
}
}
}
if (isCreate && cs.getStackPolicyBody() != null) {
existing.setStackPolicyBody(cs.getStackPolicyBody());
}
existing.setStatus(isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS");
existing.setLastUpdatedTime(now());
addEvent(existing, existing.getStackName(), existing.getStackId(),
@@ -1315,7 +1454,8 @@ public class CloudFormationService implements ResourceProvider {
return submitOperation(() -> RequestScopes.runAs(accountId, region, () -> {
try {
executeTemplate(stack, templateBody, params, cs.getTags(), claimed.isCreate(), region, accountId);
executeTemplate(stack, templateBody, params, cs.getTags(), claimed.isCreate(), region, accountId,
cs.getStackPolicyBody());
String status = stack.getStatus();
cs.setExecutionStatus(status != null && (status.contains("ROLLBACK") || status.endsWith("_FAILED"))
? "EXECUTE_FAILED" : "EXECUTE_COMPLETE");
@@ -1563,6 +1703,26 @@ public class CloudFormationService implements ResourceProvider {
* {@code ValidationError}, with AWS's texts. A skip has no length limit.
*/
private static void validateContinueUpdateRollback(String stackNameOrArn, List<String> resourcesToSkip) {
List<String> violations = stackNameViolations(stackNameOrArn);
if (resourcesToSkip.stream().anyMatch(skip -> !RESOURCE_TO_SKIP.matcher(skip).matches())) {
violations.add("Value '" + resourcesToSkip + "' at 'resourcesToSkip' failed to satisfy constraint:"
+ " Member must satisfy constraint: [Member must satisfy regular expression pattern: "
+ RESOURCE_TO_SKIP.pattern() + "]");
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationError(violations);
}
}
/** Refuses a {@code StackName} AWS's model refuses, before anything else in the request is checked. */
private static void validateStackName(String stackNameOrArn) {
List<String> violations = stackNameViolations(stackNameOrArn);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationError(violations);
}
}
private static List<String> stackNameViolations(String stackNameOrArn) {
List<String> violations = new ArrayList<>();
if (stackNameOrArn == null) {
violations.add(SmithyValidationErrors.notNull("stackName"));
@@ -1576,14 +1736,7 @@ public class CloudFormationService implements ResourceProvider {
+ " Member must satisfy regular expression pattern: " + STACK_NAME.pattern());
}
}
if (resourcesToSkip.stream().anyMatch(skip -> !RESOURCE_TO_SKIP.matcher(skip).matches())) {
violations.add("Value '" + resourcesToSkip + "' at 'resourcesToSkip' failed to satisfy constraint:"
+ " Member must satisfy constraint: [Member must satisfy regular expression pattern: "
+ RESOURCE_TO_SKIP.pattern() + "]");
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationError(violations);
}
return violations;
}
private StackMutationSnapshot snapshot(Stack stack) {
@@ -1592,7 +1745,7 @@ public class CloudFormationService implements ResourceProvider {
states.put(changeSet, new ChangeSetState(changeSet.getStatus(), changeSet.getExecutionStatus()));
}
return new StackMutationSnapshot(stack.getStatus(), stack.getLastUpdatedTime(),
stack.eventsSnapshot(), stack.changeSetsSnapshot(), states);
stack.eventsSnapshot(), stack.changeSetsSnapshot(), states, stack.getStackPolicyBody());
}
private void restore(Stack stack, StackMutationSnapshot snapshot) {
@@ -1601,6 +1754,7 @@ public class CloudFormationService implements ResourceProvider {
}
stack.setStatus(snapshot.status());
stack.setLastUpdatedTime(snapshot.lastUpdatedTime());
stack.setStackPolicyBody(snapshot.stackPolicyBody());
stack.setEvents(new ArrayList<>(snapshot.events()));
stack.setChangeSets(new LinkedHashMap<>(snapshot.changeSets()));
snapshot.changeSetStates().forEach((changeSet, state) -> {
@@ -2073,7 +2227,7 @@ public class CloudFormationService implements ResourceProvider {
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
Map<String, String> tags,
boolean isCreate, String region, String accountId) {
boolean isCreate, String region, String accountId, String stackPolicy) {
Map<String, String> previousTags = stack.tagsSnapshot();
Map<String, String> operationTags = tags == null ? previousTags : new LinkedHashMap<>(tags);
boolean stackTagsChanged = !operationTags.equals(previousTags);
@@ -2432,6 +2586,9 @@ public class CloudFormationService implements ResourceProvider {
if (!isCreate) {
updateCommitted = true;
if (stackPolicy != null) {
stack.setStackPolicyBody(stackPolicy);
}
stack.replaceTags(operationTags);
stack.getResources().values().forEach(resource -> resource.getAttributes()
.remove(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR));
@@ -4474,7 +4631,7 @@ public class CloudFormationService implements ResourceProvider {
savedChildDeployment(childStack, region, accountId).toString());
}
executeTemplate(childStack, childTemplate, childParams, childTags, childCreate, region, accountId);
executeTemplate(childStack, childTemplate, childParams, childTags, childCreate, region, accountId, null);
resource.setPhysicalId(childStack.getStackId());
resource.getAttributes().put("Arn", childStack.getStackId());
@@ -24,6 +24,9 @@ public class ChangeSet {
private Map<String, String> tags;
private String changeSetType; // CREATE or UPDATE
private Instant creationTime = Instant.now();
// AWS change sets carry no stack policy; this is the policy a CreateStack or UpdateStack
// applies with its change set.
private String stackPolicyBody;
public String getChangeSetId() { return changeSetId; }
public void setChangeSetId(String changeSetId) { this.changeSetId = changeSetId; }
@@ -51,4 +54,6 @@ public class ChangeSet {
public void setChangeSetType(String changeSetType) { this.changeSetType = changeSetType; }
public Instant getCreationTime() { return creationTime; }
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
public String getStackPolicyBody() { return stackPolicyBody; }
public void setStackPolicyBody(String stackPolicyBody) { this.stackPolicyBody = stackPolicyBody; }
}
@@ -72,6 +72,7 @@ public class Stack {
private Map<String, ChangeSet> changeSets = orderedMap();
private Map<String, String> tags = orderedMap();
private boolean enableTerminationProtection = false;
private volatile String stackPolicyBody;
/**
* Set when an update rollback fails, and kept until a rollback completes or the stack is
* deleted: the state from before the failed update, and the logical ids whose rollback has not
@@ -227,6 +228,8 @@ public class Stack {
}
public boolean isEnableTerminationProtection() { return enableTerminationProtection; }
public void setEnableTerminationProtection(boolean enableTerminationProtection) { this.enableTerminationProtection = enableTerminationProtection; }
public String getStackPolicyBody() { return stackPolicyBody; }
public void setStackPolicyBody(String stackPolicyBody) { this.stackPolicyBody = stackPolicyBody; }
public StackUpdateSnapshot getUpdateRollbackSnapshot() { return updateRollbackSnapshot; }
public void setUpdateRollbackSnapshot(StackUpdateSnapshot updateRollbackSnapshot) { this.updateRollbackSnapshot = updateRollbackSnapshot; }
public List<String> getUpdateRollbackResourceIds() { return updateRollbackResourceIds; }
@@ -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);
}
/**
@@ -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;
}));
@@ -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);
}
}
@@ -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);
@@ -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);
}
}
}
@@ -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
@@ -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("/");
}
}
@@ -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);
}
}
}