mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): scope stack state by account (#3185)
* fix(cloudformation): scope stack state by account * fix(cloudformation): attribute ownerless stacks to default account * fix(cloudformation): avoid foreign stack existence leaks
This commit is contained in:
1 parent
b713c4b0d9
commit
0cff3156ec
4 files changed
+306
-70
No files matched your search
+151
-67
@@ -58,7 +58,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
private final ConcurrentHashMap<String, Stack> stacks = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, DeletedStackEntry> deletedStacks = new ConcurrentHashMap<>();
|
||||
// Global exports registry: region:exportName -> exportValue
|
||||
// Account-scoped exports registry: account:region:exportName -> exportValue
|
||||
private final ConcurrentHashMap<String, String> exports = new ConcurrentHashMap<>();
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool();
|
||||
|
||||
@@ -73,12 +73,11 @@ public class CloudFormationService implements ResourceProvider {
|
||||
private final Clock clock;
|
||||
|
||||
// Persisted state so stacks survive a restart (criteria #10, #11). The in-memory maps above are
|
||||
// the live working copy; these backends are write-through + loaded on startup. CloudFormation is
|
||||
// account-blind (keyed by stack+region), so everything is stored under one fixed account
|
||||
// namespace for thread-consistent access from both request and background executor threads.
|
||||
// the live working copy; these backends are write-through + loaded on startup. Legacy records
|
||||
// without an account owner are attributed to the configured default account by the storage layer.
|
||||
private final AccountAwareStorageBackend<Stack> stackBackend;
|
||||
private final AccountAwareStorageBackend<String> exportBackend;
|
||||
private final String storageAccount;
|
||||
|
||||
|
||||
@Inject
|
||||
public CloudFormationService(CloudFormationResourceProvisioner provisioner, S3Service s3Service,
|
||||
@@ -94,7 +93,6 @@ public class CloudFormationService implements ResourceProvider {
|
||||
this.samTransformProcessor = new SamTransformProcessor(objectMapper);
|
||||
this.awsIncludeProcessor = new AwsIncludeProcessor(objectMapper, s3Service);
|
||||
this.clock = clock;
|
||||
this.storageAccount = config.defaultAccountId();
|
||||
this.stackBackend = storageFactory.create(
|
||||
"cloudformation", "cloudformation-stacks.json", new TypeReference<Map<String, Stack>>() {});
|
||||
this.exportBackend = storageFactory.create(
|
||||
@@ -103,12 +101,15 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
@PostConstruct
|
||||
void loadPersistedState() {
|
||||
for (Stack stack : stackBackend.scanForAccount(storageAccount, k -> true)) {
|
||||
stacks.put(key(stack.getStackName(), stack.getRegion()), stack);
|
||||
for (var entry : stackBackend.scanAllAccountEntries(k -> true)) {
|
||||
Stack stack = entry.value();
|
||||
if (stack.getAccountId() == null) {
|
||||
stack.setAccountId(entry.accountId());
|
||||
}
|
||||
stacks.put(stackKey(stack.getAccountId(), stack.getStackName(), stack.getRegion()), stack);
|
||||
}
|
||||
for (String exportKey : exportBackend.keysForAccount(storageAccount)) {
|
||||
exportBackend.getForAccount(storageAccount, exportKey)
|
||||
.ifPresent(value -> exports.put(exportKey, value));
|
||||
for (var entry : exportBackend.scanAllAccountEntries(k -> true)) {
|
||||
exports.put(accountExportKey(entry.accountId(), entry.key()), entry.value());
|
||||
}
|
||||
if (!stacks.isEmpty() || !exports.isEmpty()) {
|
||||
LOG.infov("Loaded {0} CloudFormation stack(s) and {1} export(s) from storage",
|
||||
@@ -122,11 +123,24 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private void persistStack(Stack stack) {
|
||||
stackBackend.putForAccount(storageAccount, key(stack.getStackName(), stack.getRegion()), stack);
|
||||
String accountId = ownerAccount(stack);
|
||||
stack.setAccountId(accountId);
|
||||
stackBackend.putForAccount(accountId, stackStorageKey(stack.getStackName(), stack.getRegion()), stack);
|
||||
}
|
||||
|
||||
private void unpersistStack(String stackName, String region) {
|
||||
stackBackend.deleteForAccount(storageAccount, key(stackName, region));
|
||||
private void unpersistStack(String accountId, String stackName, String region) {
|
||||
stackBackend.deleteForAccount(accountId, stackStorageKey(stackName, region));
|
||||
}
|
||||
|
||||
private String ownerAccount(Stack stack) {
|
||||
// Persisted stacks are assigned their storage partition's account during startup. The
|
||||
// default is only a compatibility attribution for transient ownerless fixtures created
|
||||
// directly by callers of the service.
|
||||
return stack.getAccountId() != null ? stack.getAccountId() : config.defaultAccountId();
|
||||
}
|
||||
|
||||
private String currentAccount() {
|
||||
return regionResolver.getAccountId();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -143,8 +157,12 @@ public class CloudFormationService implements ResourceProvider {
|
||||
// ── DescribeStacks ────────────────────────────────────────────────────────
|
||||
|
||||
public List<Stack> describeStacks(String stackName, String region) {
|
||||
return describeStacks(stackName, region, currentAccount());
|
||||
}
|
||||
|
||||
public List<Stack> describeStacks(String stackName, String region, String accountId) {
|
||||
if (stackName != null && !stackName.isBlank()) {
|
||||
Stack stack = resolveStackForDescribe(stackName, region);
|
||||
Stack stack = resolveStackForDescribe(stackName, region, accountId);
|
||||
if (stack == null) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Stack with id " + stackName + " does not exist", 400);
|
||||
@@ -152,7 +170,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return List.of(stack);
|
||||
}
|
||||
return stacks.values().stream()
|
||||
.filter(s -> region.equals(s.getRegion()))
|
||||
.filter(s -> accountId.equals(ownerAccount(s)) && region.equals(s.getRegion()))
|
||||
.sorted(Comparator.comparing(Stack::getCreationTime))
|
||||
.toList();
|
||||
}
|
||||
@@ -173,7 +191,11 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* StackSet deployment uses this to decide what to do with an instance before it acts on it.
|
||||
*/
|
||||
String stackStatus(String stackName, String region) {
|
||||
Stack stack = resolveStack(stackName, region);
|
||||
return stackStatus(stackName, region, currentAccount());
|
||||
}
|
||||
|
||||
String stackStatus(String stackName, String region, String accountId) {
|
||||
Stack stack = resolveStack(stackName, region, accountId);
|
||||
return stack != null ? stack.getStatus() : null;
|
||||
}
|
||||
|
||||
@@ -304,10 +326,14 @@ public class CloudFormationService implements ResourceProvider {
|
||||
// remapping function does short, non-blocking work.
|
||||
boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
|
||||
ChangeSet[] created = new ChangeSet[1];
|
||||
Stack stack = stacks.compute(key(stackName, region), (k, existing) -> {
|
||||
Stack stack = stacks.compute(stackKey(accountId, stackName, region), (k, existing) -> {
|
||||
Stack target;
|
||||
if (existing == null) {
|
||||
target = newStack(stackName, region);
|
||||
if (!isCreateType) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Stack with id " + stackName + " does not exist", 400);
|
||||
}
|
||||
target = newStack(stackName, region, accountId);
|
||||
if (tags != null) target.getTags().putAll(tags);
|
||||
// A CREATE change set puts a brand-new stack into REVIEW_IN_PROGRESS. Record the
|
||||
// matching stack-level event (as AWS and LocalStack do) so DescribeStackEvents is
|
||||
@@ -337,7 +363,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
|
||||
cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, accountId, "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
|
||||
cs.setChangeSetName(changeSetName);
|
||||
cs.setStackName(stackName);
|
||||
cs.setStackId(target.getStackId());
|
||||
@@ -406,7 +432,8 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
public ChangeSet describeChangeSet(String stackName, String changeSetName, String region) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName(changeSetName));
|
||||
ChangeSet cs = stack.getChangeSets().get(
|
||||
resolveChangeSetName(changeSetName, region, currentAccount()));
|
||||
if (cs == null) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetName + "] does not exist", 400);
|
||||
@@ -589,8 +616,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* that failure surfaces on those paths, and floci must still expose it there.
|
||||
*/
|
||||
public Future<?> executeChangeSetForRequest(String stackName, String changeSetName, String region) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName(changeSetName));
|
||||
Stack stack = getStackOrThrow(stackName, region, regionResolver.getAccountId());
|
||||
ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName(
|
||||
changeSetName, region, regionResolver.getAccountId()));
|
||||
if (cs == null) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetName + "] does not exist", 400);
|
||||
@@ -617,8 +645,8 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* when that change set failed, for example from a failed SAM transform.
|
||||
*/
|
||||
public Future<?> executeChangeSet(String stackName, String changeSetName, String region, String accountId) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName(changeSetName));
|
||||
Stack stack = getStackOrThrow(stackName, region, accountId);
|
||||
ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName(changeSetName, region, accountId));
|
||||
if (cs == null) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetName + "] does not exist", 400);
|
||||
@@ -674,7 +702,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
public void deleteChangeSet(String stackName, String changeSetName, String region) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
String name = resolveChangeSetName(changeSetName);
|
||||
String name = resolveChangeSetName(changeSetName, region, currentAccount());
|
||||
ChangeSet cs = stack.getChangeSets().get(name);
|
||||
if (cs == null) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
@@ -701,8 +729,20 @@ public class CloudFormationService implements ResourceProvider {
|
||||
*/
|
||||
public Future<?> deleteStack(String stackName, String region, String accountId) {
|
||||
purgeExpiredDeletedStacks();
|
||||
Stack stack = resolveStack(stackName, region);
|
||||
Stack stack = resolveStack(stackName, region, accountId);
|
||||
if (stack == null) {
|
||||
if (stackName != null && stackName.startsWith("arn:")) {
|
||||
try {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(stackName);
|
||||
if (!accountId.equals(arn.accountId()) || !region.equals(arn.region())) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Stack with id " + stackName + " does not exist", 400);
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Stack with id " + stackName + " does not exist", 400);
|
||||
}
|
||||
}
|
||||
return CompletableFuture.completedFuture(null); // Already gone — no-op
|
||||
}
|
||||
if (stack.isEnableTerminationProtection()) {
|
||||
@@ -913,8 +953,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
// ── ListStacks ────────────────────────────────────────────────────────────
|
||||
|
||||
public List<Stack> listStacks(String region) {
|
||||
String accountId = currentAccount();
|
||||
return stacks.values().stream()
|
||||
.filter(s -> region.equals(s.getRegion()))
|
||||
.filter(s -> accountId.equals(ownerAccount(s)) && region.equals(s.getRegion()))
|
||||
.sorted(Comparator.comparing(Stack::getCreationTime))
|
||||
.toList();
|
||||
}
|
||||
@@ -923,8 +964,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
public Map<String, ExportEntry> listExports(String region) {
|
||||
Map<String, ExportEntry> result = new LinkedHashMap<>();
|
||||
String accountId = currentAccount();
|
||||
for (Stack stack : stacks.values()) {
|
||||
if (!region.equals(stack.getRegion())) {
|
||||
if (!accountId.equals(ownerAccount(stack)) || !region.equals(stack.getRegion())) {
|
||||
continue;
|
||||
}
|
||||
for (var entry : stack.getExports().entrySet()) {
|
||||
@@ -939,16 +981,21 @@ public class CloudFormationService implements ResourceProvider {
|
||||
// ── Private ───────────────────────────────────────────────────────────────
|
||||
|
||||
private void removeStackExports(Stack stack, String region) {
|
||||
String accountId = ownerAccount(stack);
|
||||
for (String exportName : stack.getExports().keySet()) {
|
||||
String exportKey = exportKey(region, exportName);
|
||||
exports.remove(exportKey);
|
||||
exportBackend.deleteForAccount(storageAccount, exportKey);
|
||||
String logicalKey = exportKey(region, exportName);
|
||||
exports.remove(accountExportKey(accountId, logicalKey));
|
||||
exportBackend.deleteForAccount(accountId, logicalKey);
|
||||
}
|
||||
}
|
||||
|
||||
private String exportKey(String region, String exportName) {
|
||||
return region + ":" + exportName;
|
||||
}
|
||||
private String accountExportKey(String accountId, String logicalKey) {
|
||||
return accountId + ":" + logicalKey;
|
||||
}
|
||||
|
||||
|
||||
private void validateExportNameAvailable(String region, String exportName,
|
||||
Map<String, String> oldExports,
|
||||
@@ -957,7 +1004,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
throw new AwsException("ValidationError",
|
||||
"Export with name " + exportName + " is already defined by this stack", 400);
|
||||
}
|
||||
if (!oldExports.containsKey(exportName) && exports.containsKey(exportKey(region, exportName))) {
|
||||
if (!oldExports.containsKey(exportName) && exports.containsKey(accountExportKey(currentAccount(), region + ":" + exportName))) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Export with name " + exportName + " is already exported by another stack", 400);
|
||||
}
|
||||
@@ -1088,7 +1135,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine(
|
||||
accountId, region, stack.getStackName(),
|
||||
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
|
||||
name -> exports.get(exportKey(region, name)));
|
||||
name -> exports.get(accountExportKey(accountId, exportKey(region, name))));
|
||||
|
||||
StackResource resource = stack.getResources().get(logicalId);
|
||||
StackResource previousResource = resource;
|
||||
@@ -1186,7 +1233,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
CloudFormationTemplateEngine finalEngine = new CloudFormationTemplateEngine(
|
||||
accountId, region, stack.getStackName(),
|
||||
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
|
||||
name -> exports.get(exportKey(region, name)));
|
||||
name -> exports.get(accountExportKey(accountId, exportKey(region, name))));
|
||||
|
||||
// Resolve outputs before mutating stack/global export state, so failed updates do not
|
||||
// leave stale or partially registered exports behind.
|
||||
@@ -1220,9 +1267,10 @@ public class CloudFormationService implements ResourceProvider {
|
||||
stack.getOutputExportNames().clear();
|
||||
stack.getOutputExportNames().putAll(newOutputExportNames);
|
||||
newExports.forEach((exportName, value) -> {
|
||||
String exportKey = exportKey(region, exportName);
|
||||
String logicalKey = region + ":" + exportName;
|
||||
String exportKey = accountExportKey(accountId, logicalKey);
|
||||
exports.put(exportKey, value);
|
||||
exportBackend.putForAccount(storageAccount, exportKey, value);
|
||||
exportBackend.putForAccount(accountId, logicalKey, value);
|
||||
LOG.infov("Registered export {0} = {1} from stack {2}",
|
||||
exportName, value, stack.getStackName());
|
||||
});
|
||||
@@ -1596,10 +1644,11 @@ public class CloudFormationService implements ResourceProvider {
|
||||
Stack stack, String region, StackUpdateSnapshot previousState) {
|
||||
RuntimeException storageFailure = null;
|
||||
for (String exportName : new ArrayList<>(stack.getExports().keySet())) {
|
||||
String key = exportKey(region, exportName);
|
||||
String logicalKey = exportKey(region, exportName);
|
||||
String key = accountExportKey(ownerAccount(stack), logicalKey);
|
||||
exports.remove(key);
|
||||
try {
|
||||
exportBackend.deleteForAccount(storageAccount, key);
|
||||
exportBackend.deleteForAccount(ownerAccount(stack), logicalKey);
|
||||
} catch (RuntimeException e) {
|
||||
storageFailure = appendFailure(storageFailure, e);
|
||||
}
|
||||
@@ -1613,10 +1662,11 @@ public class CloudFormationService implements ResourceProvider {
|
||||
stack.getOutputExportNames().putAll(previousState.outputExportNames());
|
||||
|
||||
for (Map.Entry<String, String> entry : previousState.exports().entrySet()) {
|
||||
String key = exportKey(region, entry.getKey());
|
||||
String logicalKey = exportKey(region, entry.getKey());
|
||||
String key = accountExportKey(ownerAccount(stack), logicalKey);
|
||||
exports.put(key, entry.getValue());
|
||||
try {
|
||||
exportBackend.putForAccount(storageAccount, key, entry.getValue());
|
||||
exportBackend.putForAccount(ownerAccount(stack), logicalKey, entry.getValue());
|
||||
} catch (RuntimeException e) {
|
||||
storageFailure = appendFailure(storageFailure, e);
|
||||
}
|
||||
@@ -1888,8 +1938,8 @@ public class CloudFormationService implements ResourceProvider {
|
||||
addEvent(stack, stack.getStackName(), stack.getStackId(),
|
||||
"AWS::CloudFormation::Stack", "DELETE_COMPLETE", null);
|
||||
removeStackExports(stack, region);
|
||||
stacks.remove(key(stack.getStackName(), region));
|
||||
unpersistStack(stack.getStackName(), region);
|
||||
stacks.remove(stackKey(ownerAccount(stack), stack.getStackName(), region));
|
||||
unpersistStack(ownerAccount(stack), stack.getStackName(), region);
|
||||
deletedStacks.put(stack.getStackId(), new DeletedStackEntry(
|
||||
stack,
|
||||
now().plusSeconds(config.services().cloudformation().deletedStackRetentionSeconds())));
|
||||
@@ -2182,9 +2232,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
String childTemplate = fetchTemplateFromS3(templateUrl);
|
||||
String childStackName = parentStack.getStackName() + "-" + logicalId;
|
||||
|
||||
Stack childStack = newStack(childStackName, region);
|
||||
Stack childStack = newStack(childStackName, region, accountId);
|
||||
childStack.setStatus("CREATE_IN_PROGRESS");
|
||||
stacks.put(key(childStackName, region), childStack);
|
||||
stacks.put(stackKey(accountId, childStackName, region), childStack);
|
||||
|
||||
Map<String, String> childParams = new LinkedHashMap<>();
|
||||
if (props != null && props.has("Parameters") && props.get("Parameters").isObject()) {
|
||||
@@ -2208,12 +2258,14 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return resource;
|
||||
}
|
||||
|
||||
private Stack newStack(String stackName, String region) {
|
||||
|
||||
private Stack newStack(String stackName, String region, String accountId) {
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName(stackName);
|
||||
stack.setRegion(region);
|
||||
stack.setAccountId(accountId);
|
||||
stack.setStatus("REVIEW_IN_PROGRESS");
|
||||
String stackId = AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "stack/" + stackName + "/" + UUID.randomUUID()).toString();
|
||||
String stackId = AwsArnUtils.Arn.of("cloudformation", region, accountId, "stack/" + stackName + "/" + UUID.randomUUID()).toString();
|
||||
stack.setStackId(stackId);
|
||||
stack.setCreationTime(now());
|
||||
return stack;
|
||||
@@ -2233,7 +2285,11 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private Stack getStackOrThrow(String stackNameOrArn, String region) {
|
||||
Stack stack = resolveStack(stackNameOrArn, region);
|
||||
return getStackOrThrow(stackNameOrArn, region, currentAccount());
|
||||
}
|
||||
|
||||
private Stack getStackOrThrow(String stackNameOrArn, String region, String accountId) {
|
||||
Stack stack = resolveStack(stackNameOrArn, region, accountId);
|
||||
if (stack == null) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Stack with id " + stackNameOrArn + " does not exist", 400);
|
||||
@@ -2242,7 +2298,11 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private Stack resolveStackForDescribe(String stackNameOrArn, String region) {
|
||||
Stack stack = resolveStack(stackNameOrArn, region);
|
||||
return resolveStackForDescribe(stackNameOrArn, region, currentAccount());
|
||||
}
|
||||
|
||||
private Stack resolveStackForDescribe(String stackNameOrArn, String region, String accountId) {
|
||||
Stack stack = resolveStack(stackNameOrArn, region, accountId);
|
||||
if (stack != null) {
|
||||
return stack;
|
||||
}
|
||||
@@ -2253,7 +2313,8 @@ public class CloudFormationService implements ResourceProvider {
|
||||
deletedStacks.remove(stackNameOrArn, deleted);
|
||||
return null;
|
||||
}
|
||||
if (region.equals(deleted.stack().getRegion())) {
|
||||
if (accountId.equals(ownerAccount(deleted.stack()))
|
||||
&& region.equals(deleted.stack().getRegion())) {
|
||||
return deleted.stack();
|
||||
}
|
||||
}
|
||||
@@ -2281,20 +2342,27 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* The AWS CLI passes the full ARN (arn:aws:cloudformation:…:changeSet/<name>/<uuid>)
|
||||
* when referencing a changeset by the ID returned from CreateChangeSet.
|
||||
*/
|
||||
private String resolveChangeSetName(String changeSetNameOrArn) {
|
||||
if (changeSetNameOrArn != null && changeSetNameOrArn.startsWith("arn:")) {
|
||||
// arn:aws:cloudformation:<region>:<account>:changeSet/<name>/<uuid>
|
||||
try {
|
||||
String resource = AwsArnUtils.parse(changeSetNameOrArn).resource();
|
||||
String[] parts = resource.split("/");
|
||||
if (parts.length >= 2) {
|
||||
return parts[1];
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
// fall through to return as-is
|
||||
}
|
||||
private String resolveChangeSetName(String changeSetNameOrArn, String region, String accountId) {
|
||||
if (changeSetNameOrArn == null || !changeSetNameOrArn.startsWith("arn:")) {
|
||||
return changeSetNameOrArn;
|
||||
}
|
||||
return changeSetNameOrArn;
|
||||
try {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(changeSetNameOrArn);
|
||||
if (!accountId.equals(arn.accountId()) || !region.equals(arn.region())) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Change set " + changeSetNameOrArn + " does not belong to this account or region", 400);
|
||||
}
|
||||
String resource = arn.resource();
|
||||
String[] parts = resource.split("/");
|
||||
if (parts.length >= 2 && "changeSet".equals(parts[0])) {
|
||||
return parts[1];
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Invalid change set ARN: " + changeSetNameOrArn, 400);
|
||||
}
|
||||
throw new AwsException("ValidationError",
|
||||
"Invalid change set ARN: " + changeSetNameOrArn, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2303,24 +2371,36 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* Falls back to a linear scan matching on stackId for robustness.
|
||||
*/
|
||||
private Stack resolveStack(String stackNameOrArn, String region) {
|
||||
return resolveStack(stackNameOrArn, region, currentAccount());
|
||||
}
|
||||
|
||||
private Stack resolveStack(String stackNameOrArn, String region, String accountId) {
|
||||
// Try direct name lookup first (fast path)
|
||||
Stack stack = stacks.get(key(stackNameOrArn, region));
|
||||
Stack stack = stacks.get(stackKey(accountId, stackNameOrArn, region));
|
||||
if (stack != null) {
|
||||
return stack;
|
||||
}
|
||||
|
||||
// If input looks like an ARN, extract the stack name and retry
|
||||
if (stackNameOrArn != null && stackNameOrArn.startsWith("arn:")) {
|
||||
try {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(stackNameOrArn);
|
||||
if (!accountId.equals(arn.accountId()) || !region.equals(arn.region())) {
|
||||
return null;
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
String extractedName = extractStackNameFromArn(stackNameOrArn);
|
||||
if (extractedName != null) {
|
||||
stack = stacks.get(key(extractedName, region));
|
||||
stack = stacks.get(stackKey(accountId, extractedName, region));
|
||||
if (stack != null) {
|
||||
return stack;
|
||||
}
|
||||
}
|
||||
// Fallback: scan by stackId in case the ARN format is unexpected
|
||||
for (Stack s : stacks.values()) {
|
||||
if (stackNameOrArn.equals(s.getStackId())) {
|
||||
if (accountId.equals(ownerAccount(s)) && stackNameOrArn.equals(s.getStackId())) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
@@ -2540,10 +2620,14 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private static String key(String stackName, String region) {
|
||||
private static String stackStorageKey(String stackName, String region) {
|
||||
return region + ":" + stackName;
|
||||
}
|
||||
|
||||
private static String stackKey(String accountId, String stackName, String region) {
|
||||
return accountId + ":" + region + ":" + stackName;
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
|
||||
+4
-3
@@ -232,7 +232,8 @@ public class StackSetService {
|
||||
// INOPERABLE, updates the rest, and reports the operation FAILED. Deploying into it
|
||||
// anyway would raise the refusal out of here and fail the whole UpdateStackSet call
|
||||
// with a 400, updating no instance at all.
|
||||
String stackStatus = cfnService.stackStatus(inst.getStackName(), inst.getRegion());
|
||||
String stackStatus = cfnService.stackStatus(
|
||||
inst.getStackName(), inst.getRegion(), inst.getAccount());
|
||||
if (CloudFormationService.refusesUpdate(stackStatus)) {
|
||||
inst.setStatus("INOPERABLE");
|
||||
inst.setDetailedStatus("FAILED");
|
||||
@@ -639,7 +640,7 @@ public class StackSetService {
|
||||
inst.setRegion(region);
|
||||
inst.setStackName(stackName);
|
||||
inst.setStackId(resolveStackId(stackName, region, account));
|
||||
List<Stack> stacks = cfnService.describeStacks(stackName, region);
|
||||
List<Stack> stacks = cfnService.describeStacks(stackName, region, account);
|
||||
String stackStatus = stacks.isEmpty() ? null : stacks.get(0).getStatus();
|
||||
// Only a clean create/update is a success. A failed resource rolls the stack back, so its
|
||||
// terminal status is ROLLBACK_COMPLETE (not *_FAILED) — treat anything that is not COMPLETE
|
||||
@@ -655,7 +656,7 @@ public class StackSetService {
|
||||
}
|
||||
|
||||
private String resolveStackId(String stackName, String region, String account) {
|
||||
List<Stack> stacks = cfnService.describeStacks(stackName, region);
|
||||
List<Stack> stacks = cfnService.describeStacks(stackName, region, account);
|
||||
if (!stacks.isEmpty() && stacks.get(0).getStackId() != null) {
|
||||
return stacks.get(0).getStackId();
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import java.util.*;
|
||||
public class Stack {
|
||||
private String stackId;
|
||||
private String stackName;
|
||||
/** AWS account that owns this stack; absent only on legacy records. */
|
||||
private String accountId;
|
||||
private String region;
|
||||
private String status = "CREATE_IN_PROGRESS";
|
||||
private String statusReason;
|
||||
@@ -38,6 +40,8 @@ public class Stack {
|
||||
public void setStackId(String stackId) { this.stackId = stackId; }
|
||||
public String getStackName() { return stackName; }
|
||||
public void setStackName(String stackName) { this.stackName = stackName; }
|
||||
public String getAccountId() { return accountId; }
|
||||
public void setAccountId(String accountId) { this.accountId = accountId; }
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
public String getStatus() { return status; }
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationAccountOwnershipIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT_1 = "000000000001";
|
||||
private static final String ACCOUNT_2 = "000000000002";
|
||||
private static final String US_EAST_1 = "us-east-1";
|
||||
private static final String EU_WEST_1 = "eu-west-1";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameStackNameIsIsolatedByAccount() {
|
||||
createStack(ACCOUNT_1, US_EAST_1, "cfn-account-isolated-stack");
|
||||
createStack(ACCOUNT_2, US_EAST_1, "cfn-account-isolated-stack");
|
||||
|
||||
describeStack(ACCOUNT_1, US_EAST_1, "cfn-account-isolated-stack")
|
||||
.statusCode(200).body(containsString(ACCOUNT_1));
|
||||
describeStack(ACCOUNT_2, US_EAST_1, "cfn-account-isolated-stack")
|
||||
.statusCode(200).body(containsString(ACCOUNT_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameStackNameIsIsolatedByRegion() {
|
||||
createStack(ACCOUNT_1, US_EAST_1, "cfn-region-isolated-stack");
|
||||
createStack(ACCOUNT_1, EU_WEST_1, "cfn-region-isolated-stack");
|
||||
|
||||
describeStack(ACCOUNT_1, US_EAST_1, "cfn-region-isolated-stack")
|
||||
.statusCode(200).body(containsString(US_EAST_1));
|
||||
describeStack(ACCOUNT_1, EU_WEST_1, "cfn-region-isolated-stack")
|
||||
.statusCode(200).body(containsString(EU_WEST_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameExportNameIsIsolatedByAccount() {
|
||||
createExportingStack(ACCOUNT_1, US_EAST_1, "cfn-export-account-one");
|
||||
createExportingStack(ACCOUNT_2, US_EAST_1, "cfn-export-account-two");
|
||||
|
||||
listExports(ACCOUNT_1, US_EAST_1).statusCode(200)
|
||||
.body(containsString("cfn-shared-export"))
|
||||
.body(containsString(ACCOUNT_1))
|
||||
.body(not(containsString(ACCOUNT_2)));
|
||||
listExports(ACCOUNT_2, US_EAST_1).statusCode(200)
|
||||
.body(containsString("cfn-shared-export"))
|
||||
.body(containsString(ACCOUNT_2))
|
||||
.body(not(containsString(ACCOUNT_1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossAccountReadAndUpdateDoNotChangeOwnerStack() {
|
||||
String ownerArn = createStack(ACCOUNT_1, US_EAST_1, "cfn-cross-account-mutation",
|
||||
"{\"Resources\":{\"Original\":{\"Type\":\"AWS::S3::Bucket\"}}}");
|
||||
|
||||
describeStack(ACCOUNT_2, US_EAST_1, "cfn-cross-account-mutation")
|
||||
.statusCode(400)
|
||||
.body(containsString("does not exist"));
|
||||
given().header("Authorization", auth(ACCOUNT_2, US_EAST_1))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", "cfn-cross-account-mutation")
|
||||
.formParam("TemplateBody", "{\"Resources\":{\"Changed\":{\"Type\":\"AWS::S3::Bucket\"}}}")
|
||||
.when().post("/").then().statusCode(400);
|
||||
given().header("Authorization", auth(ACCOUNT_2, US_EAST_1))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", "cfn-cross-account-mutation")
|
||||
.when().post("/").then().statusCode(200);
|
||||
given().header("Authorization", auth(ACCOUNT_2, US_EAST_1))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", ownerArn)
|
||||
.when().post("/").then().statusCode(400);
|
||||
describeStackResources(ACCOUNT_1, US_EAST_1, "cfn-cross-account-mutation")
|
||||
.statusCode(200)
|
||||
.body(containsString("Original"))
|
||||
.body(not(containsString("Changed")));
|
||||
}
|
||||
|
||||
private static String createStack(String account, String region, String name) {
|
||||
return createStack(account, region, name, "{\"Resources\":{}}");
|
||||
}
|
||||
|
||||
private static String createStack(String account, String region, String name, String template) {
|
||||
String body = given().header("Authorization", auth(account, region))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", name)
|
||||
.formParam("TemplateBody", template)
|
||||
.when().post("/").then().statusCode(200).extract().body().asString();
|
||||
return body.replaceFirst("(?s).*<StackId>([^<]+)</StackId>.*", "$1");
|
||||
}
|
||||
|
||||
private static void createExportingStack(String account, String region, String name) {
|
||||
String template = "{\"Outputs\":{\"Exported\":{\"Value\":\"" + account
|
||||
+ "\",\"Export\":{\"Name\":\"cfn-shared-export\"}}}}";
|
||||
given().header("Authorization", auth(account, region))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", name)
|
||||
.formParam("TemplateBody", template)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static io.restassured.response.ValidatableResponse describeStack(
|
||||
String account, String region, String name) {
|
||||
return given().header("Authorization", auth(account, region))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", name)
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
private static io.restassured.response.ValidatableResponse describeStackResources(
|
||||
String account, String region, String name) {
|
||||
return given().header("Authorization", auth(account, region))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackResources")
|
||||
.formParam("StackName", name)
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
private static io.restassured.response.ValidatableResponse listExports(String account, String region) {
|
||||
return given().header("Authorization", auth(account, region))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "ListExports")
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
private static String auth(String account, String region) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account
|
||||
+ "/20260907/" + region + "/cloudformation/aws4_request,"
|
||||
+ " SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user