mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): keep stack sets with their instances and operations in their Region (#8987)
This commit is contained in:
1 parent
c2721ca938
commit
573cb9e9b7
12 files changed
+657
-50
No files matched your search
@@ -80,7 +80,7 @@ not checked: no member of those requests gives them.
|
||||
|
||||
StackSets support both `SELF_MANAGED` and the Cloud Launchpad `SERVICE_MANAGED` workflow. `ActivateOrganizationsAccess` requires an Organizations management account with all features enabled and enables trusted access for `stacksets.cloudformation.amazonaws.com`. Service-managed organizational-unit deployment targets are resolved from the caller's actual Organizations state rather than converted into synthetic account IDs. Targeting an OU includes eligible accounts directly in that OU and in all descendant OUs, while excluding the organization management account, matching AWS StackSets targeting semantics. `DescribeStackSet` returns the stack set's ARN as `StackSetARN`, its `Tags` and, for a service-managed stack set, the root and OU ids its instances were created for as `OrganizationalUnitIds`.
|
||||
|
||||
With `AutoDeployment` enabled, a service-managed stack set follows its organization. An account created in, invited into or moved under a targeted root or OU gets an instance in every Region of the targets that now cover it, and an account moved out of every target or removed from the organization loses its instances; their stacks stay when `RetainStacksOnAccountRemoval` is set. Account placement changes are reconciled asynchronously, so Organizations calls do not wait for deployments and deployment failures do not undo completed account changes. A second `CreateStackInstances` for a target already recorded adds its Regions to the earlier ones. Automatic creates and deletes are recorded in `ListStackSetOperations` and `DescribeStackSetOperation`, with their timestamps and success or failure status. An account move that needs no instance changes records no operation. A returning account uses a distinct backing-stack name when its previous name remains occupied; the retained stack is not reassociated.
|
||||
With `AutoDeployment` enabled, a service-managed stack set follows its organization. An account created in, invited into or moved under a targeted root or OU gets an instance in every Region of the targets that now cover it, and an account moved out of every target or removed from the organization loses its instances; their stacks stay when `RetainStacksOnAccountRemoval` is set. Account placement changes are reconciled asynchronously, each stack set in its own Region whatever Region the Organizations call was sent to, so Organizations calls do not wait for deployments and deployment failures do not undo completed account changes. A second `CreateStackInstances` for a target already recorded adds its Regions to the earlier ones. Automatic creates and deletes are recorded in `ListStackSetOperations` and `DescribeStackSetOperation`, with their timestamps and success or failure status. An account move that needs no instance changes records no operation. A returning account uses a distinct backing-stack name when its previous name remains occupied; the retained stack is not reassociated.
|
||||
|
||||
A template can declare `AWS::CloudFormation::StackSet` with required `StackSetName` and `PermissionModel` properties. Missing or blank values fail resource creation. Floci creates the stack set and an instance in every account, or account under every root and OU, and Region of its `StackInstancesGroup`. An update applies the template, parameters and settings to every instance, deploys to the targets and Regions the template adds, and removes the instances of a target it drops or of a Region it drops from a target it keeps; deleting the resource deletes every instance and then the stack set. `Ref` and `Fn::GetAtt StackSetId` return the stack set id. Resource updates require that original id; deleting a resource whose original id is gone succeeds. Changing `StackSetName` or `PermissionModel` replaces the resource. `UpdateReplacePolicy: Retain` preserves the displaced set; replacement rollback restores the previous identity and removes the replacement. In-place rollback restores the saved configuration, deployment targets and instances. A failed restore keeps its snapshot for `ContinueUpdateRollback`. `AdministrationRoleARN`, `ExecutionRoleName`, `OperationPreferences`, `CallAs` and `ParameterOverrides` are not applied.
|
||||
|
||||
@@ -1380,6 +1380,13 @@ each instance's resources into that target account's namespace — so a queue na
|
||||
into accounts `222222222222` and `333333333333` exists independently in each. The stack set, its
|
||||
instances, and its operation history are recorded in the administration (caller) account.
|
||||
|
||||
A stack set is Regional, as on AWS: it is listed, described, updated and deleted only in the Region
|
||||
it was created in, its administrator Region, and so are its instances, operations and automatic
|
||||
deployment targets, while its instances deploy stacks in the Regions they name. The same name can be
|
||||
used for another stack set in another Region. Trusted access with Organizations
|
||||
(`ActivateOrganizationsAccess`) is the organization's and holds in every Region. A stack set stored
|
||||
before Floci kept them per Region is the default Region's.
|
||||
|
||||
`DeleteStackInstances` removes instances and their resources, unless `RetainStacks=true`, which
|
||||
detaches the instances from the stack set but leaves their underlying stacks and resources in place.
|
||||
A stack set must be empty before `DeleteStackSet`.
|
||||
|
||||
@@ -53,6 +53,18 @@ public final class RegionScopedStorage<V> implements StorageBackend<String, V> {
|
||||
.or(() -> regionlessHere(key) ? delegate.get(key) : Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* The value {@code region}'s view holds under {@code key} in {@code accountId}, whatever the request's account and
|
||||
* Region, read in place as {@link AccountAwareStorageBackend#readInAccount} reads it: for a lookup that must leave
|
||||
* the store as it is, as IAM's reads of the tags of the resource an ARN names must. A regionless key is read for
|
||||
* the default Region only, as {@link #get} reads it there.
|
||||
*/
|
||||
public Optional<V> readInAccount(String accountId, String region, String key) {
|
||||
return AccountAwareStorageBackend.readInAccount(delegate, accountId, prefix(region) + key)
|
||||
.or(() -> regionlessIn(region, key)
|
||||
? AccountAwareStorageBackend.readInAccount(delegate, accountId, key) : Optional.empty());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String key) {
|
||||
if (regionlessHere(key)) {
|
||||
@@ -72,6 +84,24 @@ public final class RegionScopedStorage<V> implements StorageBackend<String, V> {
|
||||
return values;
|
||||
}
|
||||
|
||||
/** A value of {@link #scanEveryRegion}: the Region whose view holds it, and its key there. */
|
||||
public record RegionEntry<V>(String region, String key, V value) {}
|
||||
|
||||
/**
|
||||
* The request's account's values of every Region, each with the Region whose view holds it, a regionless key's
|
||||
* being the default Region's: for a worker that acts on every Region's resources, each in its own Region.
|
||||
*/
|
||||
public List<RegionEntry<V>> scanEveryRegion() {
|
||||
List<RegionEntry<V>> entries = new ArrayList<>();
|
||||
for (String stored : delegate.keys()) {
|
||||
boolean prefixed = regionPrefixed(stored);
|
||||
String region = prefixed ? stored.substring(0, stored.indexOf('/')) : regions.getDefaultRegion();
|
||||
String key = prefixed ? stored.substring(region.length() + 1) : stored;
|
||||
delegate.get(stored).ifPresent(value -> entries.add(new RegionEntry<>(region, key, value)));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> keys() {
|
||||
String prefix = prefix();
|
||||
@@ -128,19 +158,28 @@ public final class RegionScopedStorage<V> implements StorageBackend<String, V> {
|
||||
}
|
||||
|
||||
private String prefix() {
|
||||
return regions.getRegion() + "/";
|
||||
return prefix(regions.getRegion());
|
||||
}
|
||||
|
||||
private static String prefix(String region) {
|
||||
return region + "/";
|
||||
}
|
||||
|
||||
private boolean defaultRegion() {
|
||||
return regions.getRegion().equals(regions.getDefaultRegion());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code key} may also be stored regionless, as it was before this view, and is read here that way:
|
||||
* only in the default Region, and only when it doesn't start with a Region, as a stored key of this view does.
|
||||
*/
|
||||
private boolean regionlessHere(String key) {
|
||||
return key != null && defaultRegion() && !regionPrefixed(key);
|
||||
return regionlessIn(regions.getRegion(), key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code key} may also be stored regionless, as it was before this view, and is read that way in
|
||||
* {@code region}: only in the default Region, and only when it doesn't start with a Region, as a stored key of this
|
||||
* view does.
|
||||
*/
|
||||
private boolean regionlessIn(String region, String key) {
|
||||
return key != null && region.equals(regions.getDefaultRegion()) && !regionPrefixed(key);
|
||||
}
|
||||
|
||||
/** Whether {@code key} starts with a Region and a slash, as every key this view stores does. */
|
||||
|
||||
@@ -7,7 +7,7 @@ import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.RegionScopedStorage;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.cloudformation.model.ChangeSet;
|
||||
@@ -53,11 +53,15 @@ import java.util.regex.Pattern;
|
||||
* <p>A StackSet holds a template and configuration; {@code CreateStackInstances} drives the existing
|
||||
* single-stack engine ({@link CloudFormationService}) once per target {@code (account, region)},
|
||||
* provisioning the resources into each target account's namespace. The StackSet, instance and
|
||||
* operation records themselves live in the administration (caller) account's namespace.
|
||||
* operation records themselves live in the administration (caller) account's namespace, in the Region the stack
|
||||
* set was created in: a stack set is Regional, listed and reached only there, as on AWS, and so are its instances,
|
||||
* operations and automatic deployment targets. Trusted access with Organizations is the organization's, in every
|
||||
* Region.
|
||||
*
|
||||
* <p>A service-managed stack set with automatic deployment follows the accounts of the organization: an
|
||||
* account created in, invited into or moved under one of its targets gets an instance in every Region
|
||||
* that target was given, and one no target covers any more loses its instances.
|
||||
* that target was given, and one no target covers any more loses its instances. That runs in each stack set's own
|
||||
* Region, whatever Region the Organizations call was sent to.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class StackSetService implements PassedRoleLookup, AccountPlacementListener {
|
||||
@@ -75,7 +79,7 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
|
||||
private static final Pattern REGION_PATTERN = Pattern.compile("[A-Za-z0-9-]{1,128}");
|
||||
|
||||
private final CloudFormationService cfnService;
|
||||
private final StorageBackend<String, StackSet> stackSets;
|
||||
private final RegionScopedStorage<StackSet> stackSets;
|
||||
private final StorageBackend<String, StackInstance> instances;
|
||||
private final StorageBackend<String, StackSetOperation> operations;
|
||||
private final StorageBackend<String, String> organizationsAccess;
|
||||
@@ -98,19 +102,25 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
|
||||
this(cfnService, storageFactory, null, new RegionResolver("us-east-1", "000000000000")); // partition-literal: test-shaped constructor default
|
||||
}
|
||||
|
||||
/**
|
||||
* A stack set is Regional, as on AWS, so the stores of stack sets, instances, operations and automatic deployment
|
||||
* targets are the request's Region's view ({@link RegionScopedStorage}); a record stored before, without a
|
||||
* Region, is the default Region's. Trusted access with Organizations is the organization's, so its store is not.
|
||||
*/
|
||||
@Inject
|
||||
public StackSetService(CloudFormationService cfnService, StorageFactory storageFactory,
|
||||
OrganizationsService organizationsService, RegionResolver regionResolver) {
|
||||
this.cfnService = cfnService;
|
||||
this.stackSets = storageFactory.create("cloudformation", "cloudformation-stacksets.json",
|
||||
new TypeReference<Map<String, StackSet>>() {});
|
||||
this.instances = storageFactory.create("cloudformation", "cloudformation-stackset-instances.json",
|
||||
new TypeReference<Map<String, StackInstance>>() {});
|
||||
this.operations = storageFactory.create("cloudformation", "cloudformation-stackset-operations.json",
|
||||
new TypeReference<Map<String, StackSetOperation>>() {});
|
||||
this.stackSets = new RegionScopedStorage<>(storageFactory, regionResolver, "cloudformation",
|
||||
"cloudformation-stacksets.json", new TypeReference<Map<String, StackSet>>() {});
|
||||
this.instances = new RegionScopedStorage<>(storageFactory, regionResolver, "cloudformation",
|
||||
"cloudformation-stackset-instances.json", new TypeReference<Map<String, StackInstance>>() {});
|
||||
this.operations = new RegionScopedStorage<>(storageFactory, regionResolver, "cloudformation",
|
||||
"cloudformation-stackset-operations.json", new TypeReference<Map<String, StackSetOperation>>() {});
|
||||
this.organizationsAccess = storageFactory.create("cloudformation", "cloudformation-organizations-access.json",
|
||||
new TypeReference<Map<String, String>>() {});
|
||||
this.autoDeploymentTargets = storageFactory.create("cloudformation", "cloudformation-stackset-auto-targets.json",
|
||||
this.autoDeploymentTargets = new RegionScopedStorage<>(storageFactory, regionResolver, "cloudformation",
|
||||
"cloudformation-stackset-auto-targets.json",
|
||||
new TypeReference<Map<String, StackSetAutoDeploymentTarget>>() {});
|
||||
this.organizationsService = organizationsService;
|
||||
this.regionResolver = regionResolver;
|
||||
@@ -225,9 +235,9 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the stack set stored under {@code arn} in the account the ARN names, a pre-multi-account one of the
|
||||
* default account read in place, by key, which IAM gives a resource-tag condition; empty when there is none. Reads
|
||||
* only, matching the stack set's id, {@code <name>:<id>}, on the ARN.
|
||||
* The tags of the stack set stored under {@code arn} in the account and Region the ARN names, a pre-multi-account
|
||||
* one of the default account read in place, by key, which IAM gives a resource-tag condition; empty when there is
|
||||
* none. Reads only, matching the stack set's id, {@code <name>:<id>}, on the ARN.
|
||||
*/
|
||||
public Map<String, String> storedTags(String arn) {
|
||||
if (!AwsArnUtils.isArnFor(arn, "cloudformation")) {
|
||||
@@ -240,11 +250,8 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
|
||||
return Map.of();
|
||||
}
|
||||
String name = id.substring(0, id.indexOf(':'));
|
||||
String account = parsed.accountId();
|
||||
Optional<StackSet> stored = stackSets instanceof AccountAwareStorageBackend<StackSet> aware
|
||||
? aware.getForAccount(account, name).or(() -> aware.getLegacyForAccount(account, name))
|
||||
: stackSets.get(name);
|
||||
return stored.filter(stackSet -> id.equals(stackSet.getStackSetId()))
|
||||
return stackSets.readInAccount(parsed.accountId(), parsed.region(), name)
|
||||
.filter(stackSet -> id.equals(stackSet.getStackSetId()))
|
||||
.<Map<String, String>>map(stackSet -> Map.copyOf(stackSet.getTags()))
|
||||
.orElse(Map.of());
|
||||
}
|
||||
@@ -524,20 +531,42 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
|
||||
() -> reconcileAccountPlacement(managementAccountId, accountId)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deploys to or removes from {@code accountId} the instances of every automatically deploying stack set of the
|
||||
* management account, in every Region, each in its own Region, where its instances and operations are.
|
||||
*/
|
||||
private synchronized void reconcileAccountPlacement(String managementAccountId, String accountId) {
|
||||
Set<String> ancestors = ancestorsOf(managementAccountId, accountId);
|
||||
for (StackSet stackSet : stackSets.scan(key -> true)) {
|
||||
if ("SERVICE_MANAGED".equals(stackSet.getPermissionModel()) && stackSet.isAutoDeploymentEnabled()) {
|
||||
for (RegionScopedStorage.RegionEntry<StackSet> entry : stackSets.scanEveryRegion()) {
|
||||
StackSet stackSet = entry.value();
|
||||
String region = administratorRegion(entry);
|
||||
if (region != null
|
||||
&& "SERVICE_MANAGED".equals(stackSet.getPermissionModel()) && stackSet.isAutoDeploymentEnabled()) {
|
||||
try {
|
||||
autoDeploy(stackSet, accountId, ancestors);
|
||||
RequestScopes.runAs(managementAccountId, region, () -> autoDeploy(stackSet, accountId, ancestors));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Automatic deployment failed for StackSet {0}, account {1}",
|
||||
stackSet.getStackSetName(), accountId);
|
||||
LOG.warnv(e, "Automatic deployment failed for StackSet {0} in {1}, account {2}",
|
||||
stackSet.getStackSetName(), region, accountId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Region a stored stack set is reached in, null for a key that isn't one of its own. A stack set of a Region no
|
||||
* partition publishes, kept with {@code allow-unknown-regions}, reads as the default Region's key
|
||||
* {@code <Region>/<name>}; a name holds no slash, so that key is the one the store wrote in that Region.
|
||||
*/
|
||||
private static String administratorRegion(RegionScopedStorage.RegionEntry<StackSet> entry) {
|
||||
String name = entry.value().getStackSetName();
|
||||
if (entry.key().equals(name)) {
|
||||
return entry.region();
|
||||
}
|
||||
String suffix = "/" + name;
|
||||
return entry.key().endsWith(suffix) && entry.key().length() > suffix.length()
|
||||
? entry.key().substring(0, entry.key().length() - suffix.length()) : null;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void stopAccountPlacementExecutor() {
|
||||
accountPlacementExecutor.shutdownNow();
|
||||
@@ -998,10 +1027,11 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
|
||||
}
|
||||
}
|
||||
|
||||
/** The stack set of that name in the request's Region; another Region's is not found, as one that doesn't exist. */
|
||||
private StackSet getStackSetOrThrow(String name) {
|
||||
return stackSets.get(name)
|
||||
.orElseThrow(() -> new AwsException("StackSetNotFoundException",
|
||||
"StackSet [" + name + "] not found", 404));
|
||||
"StackSet " + name + " not found", 404));
|
||||
}
|
||||
|
||||
private static String instanceStackName(String stackSetName, String account) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.core.storage;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.testing.StorageFactories;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
@@ -136,11 +137,69 @@ class RegionScopedStorageTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A scan of every Region gives each of the request's account's values with the Region whose view holds it and its
|
||||
* key there, a regionless one the default Region's, whatever the request's Region, and no other account's.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"memory", "persistent", "hybrid", "wal"})
|
||||
void aScanOfEveryRegionGivesEachValueTheRegionHoldingIt(String mode) {
|
||||
StorageFactory factory = StorageFactories.open(directory, mode, "000000000000");
|
||||
try {
|
||||
AccountAwareStorageBackend<String> legacy = factory.create(
|
||||
"appconfig", "records.json", new TypeReference<>() {});
|
||||
legacy.put("older", "regionless");
|
||||
legacy.putForAccount("111111111111", "us-west-2/app", "another-account");
|
||||
store(factory, "us-west-2").put("app", "west");
|
||||
store(factory, "eu-west-1").put("app", "eu");
|
||||
store(factory, "eu-west-1").put("my-cd-1/plan", "eu-plan");
|
||||
|
||||
assertEquals(Set.of(
|
||||
new RegionScopedStorage.RegionEntry<>("us-east-1", "older", "regionless"),
|
||||
new RegionScopedStorage.RegionEntry<>("us-west-2", "app", "west"),
|
||||
new RegionScopedStorage.RegionEntry<>("eu-west-1", "app", "eu"),
|
||||
new RegionScopedStorage.RegionEntry<>("eu-west-1", "my-cd-1/plan", "eu-plan")),
|
||||
Set.copyOf(store(factory, "us-west-2").scanEveryRegion()));
|
||||
} finally {
|
||||
factory.shutdownAll();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A read in an account and Region, as IAM reads the tags of the resource an ARN names, whatever the request's: it
|
||||
* finds what that Region's view holds in that account, a regionless key only for the default Region and a key
|
||||
* stored before accounts only for the default account, and moves nothing.
|
||||
*/
|
||||
@Test
|
||||
void aReadInAnAccountAndRegionFindsItsKeyInPlace() {
|
||||
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
|
||||
RegionScopedStorage<String> east = new RegionScopedStorage<>(
|
||||
new AccountAwareStorageBackend<>(raw, null, "000000000000"), regions("us-east-1"));
|
||||
raw.put("111111111111/us-west-2/app", "west");
|
||||
raw.put("111111111111/older", "regionless");
|
||||
raw.put("oldest", "before-accounts");
|
||||
|
||||
assertEquals(Optional.of("west"), east.readInAccount("111111111111", "us-west-2", "app"));
|
||||
assertEquals(Optional.empty(), east.readInAccount("111111111111", "us-east-1", "app"));
|
||||
assertEquals(Optional.empty(), east.readInAccount("222222222222", "us-west-2", "app"));
|
||||
assertEquals(Optional.of("regionless"), east.readInAccount("111111111111", "us-east-1", "older"));
|
||||
assertEquals(Optional.empty(), east.readInAccount("111111111111", "us-west-2", "older"));
|
||||
assertEquals(Optional.of("before-accounts"), east.readInAccount("000000000000", "us-east-1", "oldest"));
|
||||
assertEquals(Optional.empty(), east.readInAccount("111111111111", "us-east-1", "oldest"));
|
||||
assertEquals(Set.of("111111111111/us-west-2/app", "111111111111/older", "oldest"), raw.keys());
|
||||
}
|
||||
|
||||
private static RegionScopedStorage<String> store(StorageFactory factory, String region) {
|
||||
return new RegionScopedStorage<>(factory, regions(region), "appconfig", "records.json",
|
||||
new TypeReference<>() {});
|
||||
}
|
||||
|
||||
/** A resolver whose request is in {@code region}, {@code us-east-1} being the default Region. */
|
||||
private static RegionResolver regions(String region) {
|
||||
RegionResolver regions = mock(RegionResolver.class);
|
||||
when(regions.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regions.getRegion()).thenReturn(region);
|
||||
return new RegionScopedStorage<>(factory, regions, "appconfig", "records.json", new TypeReference<>() {});
|
||||
return regions;
|
||||
}
|
||||
|
||||
}
|
||||
+5
-10
@@ -6,6 +6,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.StackSetErrors.assertNotFound;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
@@ -540,14 +541,11 @@ class CloudFormationStackSetsIntegrationTest {
|
||||
String queue = "errq-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
// Describe a non-existent stack set → StackSetNotFoundException.
|
||||
given()
|
||||
assertNotFound(given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackSet")
|
||||
.formParam("StackSetName", "does-not-exist-" + setName)
|
||||
.header("Authorization", auth(ADMIN, "cloudformation"))
|
||||
.when().post("/")
|
||||
.then().statusCode(404)
|
||||
.body(containsString("StackSetNotFoundException"));
|
||||
.header("Authorization", auth(ADMIN, "cloudformation")), "does-not-exist-" + setName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
@@ -919,14 +917,11 @@ class CloudFormationStackSetsIntegrationTest {
|
||||
.body(containsString("<Code>ValidationError</Code>"))
|
||||
.body(containsString("<Message>Parameters: [Suffix] must have values</Message>"));
|
||||
|
||||
given()
|
||||
assertNotFound(given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackSet")
|
||||
.formParam("StackSetName", setName)
|
||||
.header("Authorization", auth(ADMIN, "cloudformation"))
|
||||
.when().post("/")
|
||||
.then().statusCode(404)
|
||||
.body(containsString("StackSetNotFoundException"));
|
||||
.header("Authorization", auth(ADMIN, "cloudformation")), setName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.cloudformation.model.StackInstance;
|
||||
import io.floci.aws.services.cloudformation.model.StackSet;
|
||||
import io.floci.aws.services.cloudformation.model.StackSetAutoDeploymentTarget;
|
||||
import io.floci.aws.services.cloudformation.model.StackSetOperation;
|
||||
import io.floci.aws.services.organizations.OrganizationsService;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.floci.aws.testing.StackSetErrors.assertNotFound;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* A stack set stored before stack sets were kept per Region, with its instance, operation and automatic deployment
|
||||
* target, recorded no Region: it is the default Region's, listed and reached there and not in another Region, where
|
||||
* its name is free. The stores are account stores, as in production.
|
||||
*/
|
||||
class StackSetLegacyRecordsTest {
|
||||
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String DEFAULT_REGION = "us-east-1";
|
||||
private static final String OTHER_REGION = "eu-west-1";
|
||||
private static final String SET = "stored-before";
|
||||
private static final String ID = SET + ":5f0c3a52-8d4e-4c41-9b7a-2f1e6d0a9c11";
|
||||
private static final String TARGET_ACCOUNT = "210987654321";
|
||||
private static final String OU = "ou-abcd-abcdefgh";
|
||||
|
||||
private final RequestRegion regions = new RequestRegion();
|
||||
private StackSetService service;
|
||||
|
||||
@BeforeEach
|
||||
void storeRecordsWithoutARegion() {
|
||||
InMemoryStorageFactory storage = new InMemoryStorageFactory(ACCOUNT);
|
||||
StackSet stackSet = new StackSet();
|
||||
stackSet.setStackSetName(SET);
|
||||
stackSet.setStackSetId(ID);
|
||||
stackSet.setTemplateBody("{\"Resources\":{}}");
|
||||
stackSet.setPermissionModel("SERVICE_MANAGED");
|
||||
stackSet.setTags(Map.of("team", "red"));
|
||||
storage.create("cloudformation", "cloudformation-stacksets.json",
|
||||
new TypeReference<Map<String, StackSet>>() {}).put(SET, stackSet);
|
||||
StackInstance instance = new StackInstance();
|
||||
instance.setStackSetId(ID);
|
||||
instance.setStackSetName(SET);
|
||||
instance.setAccount(TARGET_ACCOUNT);
|
||||
instance.setRegion("eu-central-1");
|
||||
storage.create("cloudformation", "cloudformation-stackset-instances.json",
|
||||
new TypeReference<Map<String, StackInstance>>() {})
|
||||
.put(SET + ":" + TARGET_ACCOUNT + ":eu-central-1", instance);
|
||||
storage.create("cloudformation", "cloudformation-stackset-operations.json",
|
||||
new TypeReference<Map<String, StackSetOperation>>() {})
|
||||
.put(SET + ":op-1", new StackSetOperation("op-1", SET, "CREATE"));
|
||||
storage.create("cloudformation", "cloudformation-stackset-auto-targets.json",
|
||||
new TypeReference<Map<String, StackSetAutoDeploymentTarget>>() {})
|
||||
.put(SET + "::" + OU, new StackSetAutoDeploymentTarget(SET, OU, List.of("eu-central-1")));
|
||||
service = new StackSetService(mock(CloudFormationService.class), storage, mock(OrganizationsService.class),
|
||||
regions);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStackSetStoredBeforeIsListedAndReachedInTheDefaultRegionOnly() {
|
||||
assertEquals(ID, service.describeStackSet(SET).getStackSetId());
|
||||
assertEquals(List.of(SET), service.listStackSets().stream().map(StackSet::getStackSetName).toList());
|
||||
assertEquals(List.of(TARGET_ACCOUNT + "/eu-central-1"), service.listStackInstances(SET, null, null).stream()
|
||||
.map(instance -> instance.getAccount() + "/" + instance.getRegion()).toList());
|
||||
assertEquals("CREATE", service.describeStackSetOperation(SET, "op-1").getAction());
|
||||
assertEquals(List.of(OU), service.organizationalUnitIds(SET));
|
||||
assertEquals(Map.of("team", "red"), service.storedTags(arn(DEFAULT_REGION)));
|
||||
|
||||
regions.region = OTHER_REGION;
|
||||
|
||||
assertNotFound(() -> service.describeStackSet(SET), SET);
|
||||
assertEquals(List.of(), service.listStackSets());
|
||||
assertNotFound(() -> service.listStackInstances(SET, null, null), SET);
|
||||
assertNotFound(() -> service.describeStackSetOperation(SET, "op-1"), SET);
|
||||
assertEquals(Map.of(), service.storedTags(arn(OTHER_REGION)));
|
||||
|
||||
StackSet created = service.createStackSet(SET, "{\"Resources\":{}}", null, null, null, null);
|
||||
assertNotEquals(ID, created.getStackSetId());
|
||||
regions.region = DEFAULT_REGION;
|
||||
assertEquals(ID, service.describeStackSet(SET).getStackSetId());
|
||||
}
|
||||
|
||||
private static String arn(String region) {
|
||||
return "arn:aws:cloudformation:" + region + ":" + ACCOUNT + ":stackset/" + ID;
|
||||
}
|
||||
|
||||
/** A resolver whose request is in the Region a test sets, {@code us-east-1} being the default Region. */
|
||||
private static final class RequestRegion extends RegionResolver {
|
||||
private volatile String region = DEFAULT_REGION;
|
||||
|
||||
RequestRegion() {
|
||||
super(DEFAULT_REGION, ACCOUNT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRegion() {
|
||||
return region;
|
||||
}
|
||||
}
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.cloudformation.model.StackSet;
|
||||
import io.floci.aws.services.cloudformation.model.StackSetAutoDeploymentTarget;
|
||||
import io.floci.aws.testing.CfnRequests;
|
||||
import io.floci.aws.testing.OrganizationsFixture;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.floci.aws.testing.StackSetErrors.assertNotFound;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
/**
|
||||
* A stack set is Regional, as on AWS: it is listed, described, changed and deleted only in the Region it was created
|
||||
* in, its administrator Region, and so are its instances and operations, while its instances deploy stacks in the
|
||||
* Regions they name. Its name can be used again in another Region, and automatic deployment runs in its Region,
|
||||
* whatever Region the Organizations call was sent to, the default Region for one stored before, without a Region, and
|
||||
* the stack set's own for one of a Region no partition publishes, served with {@code allow-unknown-regions} (from
|
||||
* {@link SidecarContainersProfile}). Each test works in an account of its own.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
class StackSetRegionScopingIntegrationTest {
|
||||
|
||||
private static final AtomicLong ACCOUNTS = new AtomicLong(732200000000L);
|
||||
private static final String HOME = "eu-west-1";
|
||||
private static final String OTHER = "eu-central-1";
|
||||
/** The deployment's default Region, where the Organizations calls are sent unless a test sends one elsewhere. */
|
||||
private static final String DEFAULT_REGION = "us-east-1";
|
||||
/** A Region no partition publishes, served with {@code allow-unknown-regions}. */
|
||||
private static final String UNKNOWN = "polygondwanaland-west-1";
|
||||
private static final String OU_TARGET = "DeploymentTargets.OrganizationalUnitIds.member.1";
|
||||
private static final String INSTANCES = "ListStackInstancesResponse.ListStackInstancesResult.Summaries.member";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Inject
|
||||
StorageFactory storageFactory;
|
||||
|
||||
private final OrganizationsFixture organizations = new OrganizationsFixture();
|
||||
private String account;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void accountOfItsOwn() {
|
||||
account = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
}
|
||||
|
||||
/**
|
||||
* A stack set of {@code eu-west-1} with an instance in {@code eu-central-1} is neither listed nor reached from
|
||||
* {@code eu-central-1}, where its instance's stack is: not described, changed, deployed or deleted there, nor are
|
||||
* its instances and operations.
|
||||
*/
|
||||
@Test
|
||||
void aStackSetIsListedAndReachedOnlyInTheRegionItWasCreatedIn() {
|
||||
String stackSet = "regional";
|
||||
createStackSet(HOME, stackSet, "regional-q").statusCode(200);
|
||||
String operation = cfn(HOME, "CreateStackInstances")
|
||||
.formParam("StackSetName", stackSet)
|
||||
.formParam("Accounts.member.1", account)
|
||||
.formParam("Regions.member.1", OTHER)
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("CreateStackInstancesResponse.CreateStackInstancesResult.OperationId");
|
||||
cleanup.register(() -> deleteWithInstances(HOME, stackSet, "Accounts.member.1", account));
|
||||
|
||||
assertEquals(List.of(), stackSetNames(OTHER));
|
||||
assertNotFound(cfn(OTHER, "DescribeStackSet").formParam("StackSetName", stackSet), stackSet);
|
||||
assertNotFound(cfn(OTHER, "ListStackInstances").formParam("StackSetName", stackSet), stackSet);
|
||||
assertNotFound(cfn(OTHER, "DescribeStackInstance").formParam("StackSetName", stackSet)
|
||||
.formParam("StackInstanceAccount", account).formParam("StackInstanceRegion", OTHER), stackSet);
|
||||
assertNotFound(cfn(OTHER, "ListStackSetOperations").formParam("StackSetName", stackSet), stackSet);
|
||||
assertNotFound(cfn(OTHER, "DescribeStackSetOperation").formParam("StackSetName", stackSet)
|
||||
.formParam("OperationId", operation), stackSet);
|
||||
assertNotFound(cfn(OTHER, "UpdateStackSet").formParam("StackSetName", stackSet)
|
||||
.formParam("UsePreviousTemplate", "true"), stackSet);
|
||||
assertNotFound(cfn(OTHER, "CreateStackInstances").formParam("StackSetName", stackSet)
|
||||
.formParam("Accounts.member.1", account).formParam("Regions.member.1", HOME), stackSet);
|
||||
assertNotFound(cfn(OTHER, "DeleteStackInstances").formParam("StackSetName", stackSet)
|
||||
.formParam("Accounts.member.1", account).formParam("Regions.member.1", OTHER)
|
||||
.formParam("RetainStacks", "false"), stackSet);
|
||||
assertNotFound(cfn(OTHER, "DeleteStackSet").formParam("StackSetName", stackSet), stackSet);
|
||||
|
||||
assertEquals(List.of(stackSet), stackSetNames(HOME));
|
||||
cfn(HOME, "DescribeStackSet").formParam("StackSetName", stackSet).post("/").then().statusCode(200)
|
||||
.body("DescribeStackSetResponse.DescribeStackSetResult.StackSet.StackSetARN",
|
||||
startsWith("arn:aws:cloudformation:" + HOME + ":" + account + ":stackset/" + stackSet + ":"));
|
||||
cfn(HOME, "DescribeStackSetOperation").formParam("StackSetName", stackSet).formParam("OperationId", operation)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("DescribeStackSetOperationResponse.DescribeStackSetOperationResult.StackSetOperation.Status",
|
||||
equalTo("SUCCEEDED"));
|
||||
cfn(HOME, "ListStackInstances").formParam("StackSetName", stackSet).post("/").then().statusCode(200)
|
||||
.body("ListStackInstancesResponse.ListStackInstancesResult.Summaries.member.Region", equalTo(OTHER))
|
||||
.body("ListStackInstancesResponse.ListStackInstancesResult.Summaries.member.StackId",
|
||||
startsWith("arn:aws:cloudformation:" + OTHER + ":" + account + ":stack/StackSet-" + stackSet));
|
||||
queueUrl(account, OTHER, "regional-q").statusCode(200)
|
||||
.body("GetQueueUrlResponse.GetQueueUrlResult.QueueUrl", endsWith("/" + account + "/regional-q"));
|
||||
}
|
||||
|
||||
/** A name is unique in its Region: each Region holds a stack set of its own under it, and deletes only its own. */
|
||||
@Test
|
||||
void aStackSetNameCanBeUsedAgainInAnotherRegion() {
|
||||
String stackSet = "shared";
|
||||
String home = createStackSet(HOME, stackSet, "shared-home-q").statusCode(200)
|
||||
.extract().path("CreateStackSetResponse.CreateStackSetResult.StackSetId");
|
||||
cleanup.register(() -> cfn(HOME, "DeleteStackSet").formParam("StackSetName", stackSet).post("/"));
|
||||
String other = createStackSet(OTHER, stackSet, "shared-other-q").statusCode(200)
|
||||
.extract().path("CreateStackSetResponse.CreateStackSetResult.StackSetId");
|
||||
cleanup.register(() -> cfn(OTHER, "DeleteStackSet").formParam("StackSetName", stackSet).post("/"));
|
||||
assertNotEquals(home, other);
|
||||
|
||||
createStackSet(HOME, stackSet, "shared-again-q").statusCode(409)
|
||||
.body("ErrorResponse.Error.Code", equalTo("NameAlreadyExistsException"));
|
||||
cfn(OTHER, "DeleteStackSet").formParam("StackSetName", stackSet).post("/").then().statusCode(200);
|
||||
|
||||
assertNotFound(cfn(OTHER, "DescribeStackSet").formParam("StackSetName", stackSet), stackSet);
|
||||
cfn(HOME, "DescribeStackSet").formParam("StackSetName", stackSet).post("/").then().statusCode(200)
|
||||
.body("DescribeStackSetResponse.DescribeStackSetResult.StackSet.StackSetId", equalTo(home));
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatic deployment runs in each stack set's Region: an account moved, by an Organizations call sent to
|
||||
* {@code us-east-1}, under the target of two service-managed stack sets of one name, one of {@code eu-west-1}
|
||||
* and one of {@code eu-central-1}, gets each one's instance, each automatic operation is its stack set's, in its
|
||||
* Region, and {@code us-east-1} holds no such stack set.
|
||||
*/
|
||||
@Test
|
||||
void automaticDeploymentRunsInEachStackSetsRegion() {
|
||||
cleanup.register(organizations::cleanup);
|
||||
String root = organizations.createWithTrustedAccess(account);
|
||||
String target = organizations.createOu(account, root, "RegionalTarget");
|
||||
String stackSet = "regional-auto";
|
||||
for (String region : List.of(HOME, OTHER)) {
|
||||
cfn(region, "CreateStackSet")
|
||||
.formParam("StackSetName", stackSet)
|
||||
.formParam("TemplateBody", queueTemplate(region + "-auto-q"))
|
||||
.formParam("PermissionModel", "SERVICE_MANAGED")
|
||||
.formParam("AutoDeployment.Enabled", "true")
|
||||
.formParam("AutoDeployment.RetainStacksOnAccountRemoval", "false")
|
||||
.post("/").then().statusCode(200);
|
||||
cfn(region, "CreateStackInstances")
|
||||
.formParam("StackSetName", stackSet)
|
||||
.formParam(OU_TARGET, target)
|
||||
.formParam("Regions.member.1", OTHER)
|
||||
.post("/").then().statusCode(200);
|
||||
cleanup.register(() -> deleteWithInstances(region, stackSet, OU_TARGET, target));
|
||||
}
|
||||
|
||||
String member = organizations.createAccount(account, "regional-auto-" + account + "@example.com",
|
||||
"RegionalAuto");
|
||||
organizations.moveAccount(account, member, root, target);
|
||||
|
||||
for (String region : List.of(HOME, OTHER)) {
|
||||
awaitInstance(region, stackSet, member);
|
||||
queueUrl(member, OTHER, region + "-auto-q").statusCode(200);
|
||||
assertEquals(List.of("CREATE", "CREATE"), operationActions(region, stackSet));
|
||||
}
|
||||
assertEquals(List.of(), stackSetNames(DEFAULT_REGION));
|
||||
assertNotFound(cfn(DEFAULT_REGION, "ListStackSetOperations").formParam("StackSetName", stackSet), stackSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* An automatically deploying stack set stored before, without a Region, is the default Region's: an account moved
|
||||
* under its target by an Organizations call sent to {@code eu-west-1} gets its instance, its automatic operation is
|
||||
* recorded in {@code us-east-1}, and {@code eu-west-1} holds no such stack set.
|
||||
*/
|
||||
@Test
|
||||
void aStackSetStoredBeforeDeploysAutomaticallyInTheDefaultRegion() {
|
||||
cleanup.register(organizations::cleanup);
|
||||
String root = organizations.createWithTrustedAccess(account);
|
||||
String target = organizations.createOu(account, root, "StoredBeforeTarget");
|
||||
String stackSet = "stored-before";
|
||||
StackSet stored = new StackSet();
|
||||
stored.setStackSetName(stackSet);
|
||||
stored.setStackSetId(stackSet + ":" + UUID.randomUUID());
|
||||
stored.setTemplateBody(queueTemplate("stored-before-q"));
|
||||
stored.setPermissionModel("SERVICE_MANAGED");
|
||||
stored.setAutoDeploymentEnabled(true);
|
||||
storageFactory.create("cloudformation", "cloudformation-stacksets.json",
|
||||
new TypeReference<Map<String, StackSet>>() {}).putForAccount(account, stackSet, stored);
|
||||
storageFactory.create("cloudformation", "cloudformation-stackset-auto-targets.json",
|
||||
new TypeReference<Map<String, StackSetAutoDeploymentTarget>>() {})
|
||||
.putForAccount(account, stackSet + "::" + target,
|
||||
new StackSetAutoDeploymentTarget(stackSet, target, List.of(OTHER)));
|
||||
cleanup.register(() -> deleteWithInstances(DEFAULT_REGION, stackSet, OU_TARGET, target));
|
||||
|
||||
String member = organizations.createAccount(account, "stored-before-" + account + "@example.com",
|
||||
"StoredBefore");
|
||||
organizations.moveAccount(account, HOME, member, root, target);
|
||||
|
||||
awaitInstance(DEFAULT_REGION, stackSet, member);
|
||||
queueUrl(member, OTHER, "stored-before-q").statusCode(200);
|
||||
assertEquals(List.of("CREATE"), operationActions(DEFAULT_REGION, stackSet));
|
||||
assertEquals(List.of(), stackSetNames(HOME));
|
||||
}
|
||||
|
||||
/**
|
||||
* A stack set of a Region no partition publishes deploys automatically in that Region: an account moved under its
|
||||
* target, by an Organizations call sent to {@code us-east-1}, gets its instance, and its automatic operation is
|
||||
* recorded there.
|
||||
*/
|
||||
@Test
|
||||
void aStackSetOfAnUnknownRegionDeploysAutomaticallyThere() {
|
||||
cleanup.register(organizations::cleanup);
|
||||
String root = organizations.createWithTrustedAccess(account);
|
||||
String target = organizations.createOu(account, root, "UnknownRegionTarget");
|
||||
String stackSet = "unknown-region-auto";
|
||||
cfn(UNKNOWN, "CreateStackSet")
|
||||
.formParam("StackSetName", stackSet)
|
||||
.formParam("TemplateBody", queueTemplate("unknown-region-auto-q"))
|
||||
.formParam("PermissionModel", "SERVICE_MANAGED")
|
||||
.formParam("AutoDeployment.Enabled", "true")
|
||||
.formParam("AutoDeployment.RetainStacksOnAccountRemoval", "false")
|
||||
.post("/").then().statusCode(200);
|
||||
cfn(UNKNOWN, "CreateStackInstances")
|
||||
.formParam("StackSetName", stackSet)
|
||||
.formParam(OU_TARGET, target)
|
||||
.formParam("Regions.member.1", OTHER)
|
||||
.post("/").then().statusCode(200);
|
||||
cleanup.register(() -> deleteWithInstances(UNKNOWN, stackSet, OU_TARGET, target));
|
||||
|
||||
String member = organizations.createAccount(account, "unknown-region-" + account + "@example.com",
|
||||
"UnknownRegion");
|
||||
organizations.moveAccount(account, member, root, target);
|
||||
|
||||
awaitInstance(UNKNOWN, stackSet, member);
|
||||
queueUrl(member, OTHER, "unknown-region-auto-q").statusCode(200);
|
||||
assertEquals(List.of("CREATE", "CREATE"), operationActions(UNKNOWN, stackSet));
|
||||
}
|
||||
|
||||
private ValidatableResponse createStackSet(String region, String stackSet, String queue) {
|
||||
return cfn(region, "CreateStackSet")
|
||||
.formParam("StackSetName", stackSet)
|
||||
.formParam("TemplateBody", queueTemplate(queue))
|
||||
.post("/").then();
|
||||
}
|
||||
|
||||
/** The names {@code ListStackSets} lists in {@code region}. */
|
||||
private List<String> stackSetNames(String region) {
|
||||
return cfn(region, "ListStackSets").post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getList("ListStackSetsResponse.ListStackSetsResult.Summaries.member.StackSetName", String.class);
|
||||
}
|
||||
|
||||
/** The actions of the operations {@code ListStackSetOperations} lists for the {@code region} stack set. */
|
||||
private List<String> operationActions(String region, String stackSet) {
|
||||
return cfn(region, "ListStackSetOperations").formParam("StackSetName", stackSet)
|
||||
.post("/").then().statusCode(200).extract().xmlPath().getList(
|
||||
"ListStackSetOperationsResponse.ListStackSetOperationsResult.Summaries.member.Action",
|
||||
String.class);
|
||||
}
|
||||
|
||||
/** Waits until the {@code region} stack set has a successful instance in {@code member}'s {@code eu-central-1}. */
|
||||
private void awaitInstance(String region, String stackSet, String member) {
|
||||
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() ->
|
||||
cfn(region, "ListStackInstances").formParam("StackSetName", stackSet)
|
||||
.formParam("StackInstanceAccount", member)
|
||||
.post("/").then().statusCode(200)
|
||||
.body(INSTANCES + ".Region", equalTo(OTHER))
|
||||
.body(INSTANCES + ".StackInstanceStatus.DetailedStatus", equalTo("SUCCEEDED")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the {@code region} stack set's instances in {@code eu-central-1} of the account or the root or OU
|
||||
* {@code target} names, as the request member {@code targetMember}, with their stacks, then the stack set.
|
||||
*/
|
||||
private void deleteWithInstances(String region, String stackSet, String targetMember, String target) {
|
||||
cfn(region, "DeleteStackInstances").formParam("StackSetName", stackSet)
|
||||
.formParam(targetMember, target).formParam("Regions.member.1", OTHER)
|
||||
.formParam("RetainStacks", "false").post("/");
|
||||
cfn(region, "DeleteStackSet").formParam("StackSetName", stackSet).post("/");
|
||||
}
|
||||
|
||||
private RequestSpecification cfn(String region, String action) {
|
||||
return CfnRequests.cfn(action, null).header("Authorization", auth(account, region, "cloudformation"));
|
||||
}
|
||||
|
||||
private static ValidatableResponse queueUrl(String owner, String region, String queue) {
|
||||
return given().header("Authorization", auth(owner, region, "sqs"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "GetQueueUrl")
|
||||
.formParam("QueueName", queue)
|
||||
.post("/").then();
|
||||
}
|
||||
|
||||
private static String queueTemplate(String queue) {
|
||||
return "{\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\",\"Properties\":{\"QueueName\":\""
|
||||
+ queue + "\"}}}}";
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -17,6 +17,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static io.floci.aws.testing.StackSetErrors.assertNotFound;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -120,8 +121,7 @@ class StackSetServiceDeleteFailureTest {
|
||||
service.deleteStackSetWithInstances(SET);
|
||||
service.deleteStackSetWithInstances(SET);
|
||||
|
||||
AwsException missing = assertThrows(AwsException.class, () -> service.describeStackSet(SET));
|
||||
assertEquals("StackSetNotFoundException", missing.getErrorCode());
|
||||
assertNotFound(() -> service.describeStackSet(SET), SET);
|
||||
}
|
||||
|
||||
private static final class InMemoryStorageFactory extends StorageFactory {
|
||||
|
||||
@@ -51,8 +51,13 @@ public final class OrganizationsFixture {
|
||||
}
|
||||
|
||||
public void moveAccount(String owner, String account, String source, String destination) {
|
||||
request(owner, "MoveAccount", "{\"AccountId\":\"" + account + "\",\"SourceParentId\":\"" + source
|
||||
+ "\",\"DestinationParentId\":\"" + destination + "\"}")
|
||||
moveAccount(owner, "us-east-1", account, source, destination);
|
||||
}
|
||||
|
||||
/** As above; the call signed for {@code region}. */
|
||||
public void moveAccount(String owner, String region, String account, String source, String destination) {
|
||||
OrganizationsRequests.request(owner, region, "MoveAccount", "{\"AccountId\":\"" + account
|
||||
+ "\",\"SourceParentId\":\"" + source + "\",\"DestinationParentId\":\"" + destination + "\"}")
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,8 +18,13 @@ public final class OrganizationsRequests {
|
||||
|
||||
/** One call, named by its action, carrying {@code body} as its payload. */
|
||||
public static RequestSpecification request(String accountId, String action, String body) {
|
||||
return request(accountId, "us-east-1", action, body);
|
||||
}
|
||||
|
||||
/** As above; signed for {@code region}, as a client configured for that Region signs it. */
|
||||
public static RequestSpecification request(String accountId, String region, String action, String body) {
|
||||
return given()
|
||||
.header("Authorization", EnforcementFixtures.auth(accountId, "organizations"))
|
||||
.header("Authorization", EnforcementFixtures.auth(accountId, region, "organizations"))
|
||||
.header("X-Amz-Target", TARGET_PREFIX + action)
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body);
|
||||
|
||||
@@ -74,8 +74,8 @@ import java.util.Map;
|
||||
* outside the subset Floci evaluates. {@code IotTopicRuleSqlStrictIntegrationTest} relies on
|
||||
* it.</li>
|
||||
* <li>{@code floci.partitions.allow-unknown-regions=true} gives a region label no partition
|
||||
* publishes a namespace of its own. {@code PartitionUnknownRegionAllowedIntegrationTest} and
|
||||
* {@code ColonRegionRejectionIntegrationTest} rely on it.</li>
|
||||
* publishes a namespace of its own. {@code PartitionUnknownRegionAllowedIntegrationTest},
|
||||
* {@code ColonRegionRejectionIntegrationTest} and {@code StackSetRegionScopingIntegrationTest} rely on it.</li>
|
||||
* <li>{@code floci.services.ec2instanceconnect.enabled=false} turns EC2 Instance Connect off.
|
||||
* {@code InstanceConnectEnablementIntegrationTest} relies on it.</li>
|
||||
* <li>{@code floci.storage.services.rekognition.mode=persistent} keeps Rekognition collections on
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* What CloudFormation answers for a stack set that isn't there: {@code StackSetNotFoundException}, "StackSet NAME not
|
||||
* found", HTTP 404, a {@code Sender} error (measured, eu-west-1 and eu-central-1, 2026-11-17).
|
||||
*/
|
||||
public final class StackSetErrors {
|
||||
|
||||
private StackSetErrors() {
|
||||
}
|
||||
|
||||
/** Asserts that {@code call} throws that answer for {@code stackSet}. */
|
||||
public static void assertNotFound(Executable call, String stackSet) {
|
||||
AwsException missing = assertThrows(AwsException.class, call);
|
||||
assertEquals("StackSetNotFoundException", missing.getErrorCode());
|
||||
assertEquals(message(stackSet), missing.getMessage());
|
||||
assertEquals(404, missing.getHttpStatus());
|
||||
}
|
||||
|
||||
/** Sends {@code request}, a CloudFormation Query request, and asserts it gets that answer for {@code stackSet}. */
|
||||
public static void assertNotFound(RequestSpecification request, String stackSet) {
|
||||
request.post("/").then().statusCode(404)
|
||||
.body("ErrorResponse.Error.Type", equalTo("Sender"))
|
||||
.body("ErrorResponse.Error.Code", equalTo("StackSetNotFoundException"))
|
||||
.body("ErrorResponse.Error.Message", equalTo(message(stackSet)));
|
||||
}
|
||||
|
||||
private static String message(String stackSet) {
|
||||
return "StackSet " + stackSet + " not found";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user