fix(servicecatalog): keep portfolios, products and their resources in their Region (#8717)

* fix(servicecatalog): keep portfolios, products and their resources in their Region
* refactor(servicecatalog): use partitionForRegion in copyProduct and ServiceCatalogRequests in the tests
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-17 09:15:05 -04:00
1 parent be34135e5b
commit e8735be43b
4 files changed
+257 -23

No files matched your search

+9 -1
View File
@@ -116,7 +116,15 @@ Floci lazily creates the managed **AWS Control Tower Account Factory Portfolio**
Account Factory product the first time `ListPortfolios`, `ListAcceptedPortfolioShares`,
`SearchProducts` or `ProvisionProduct` is called. `SearchProductsAsAdmin` does not trigger
this, so the Account Factory product is absent from the admin view until one of those
operations has run.
operations has run in a Region. Each Region of an account gets a catalog of its own, as
Floci's Control Tower seeds a landing zone in each; provisioning the Account Factory product in
a second Region reuses the Organizations account whose `AccountEmail` matches.
Every other resource is Regional too: portfolios, products, TagOptions, service actions,
constraints, plans and provisioned products are listed and reached only in the Region they
were created in. `CopyProduct` copies a product of any Region of the request's partition into
the Region the request is sent to.
`ProvisionProduct` resolves the product named by `ProductId` or `ProductName` and rejects one the catalog does not hold with `ResourceNotFoundException`; a request naming neither is rejected with `InvalidParametersException`. A supplied `ProvisioningArtifactId` or `ProvisioningArtifactName` must belong to that product, and when neither is supplied the product's first artifact is used.
When the resolved product is the Account Factory product, `ProvisionProduct` creates a real Organizations member account through the Organizations service — reusing an existing account when `AccountEmail` already matches one — moves it under the OU named by the `ManagedOrganizationalUnit` provisioning parameter, and persists an `AVAILABLE` provisioned product of type `CONTROL_TOWER_ACCOUNT`. Organizational-unit display labels such as `Infrastructure (ou-...)` are resolved to their underlying OU IDs. Any other product persists an `AVAILABLE` provisioned product of type `CFN_STACK` and never touches Organizations.
@@ -8,8 +8,12 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.EpochSeconds;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
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.core.storage.StorageOperations;
import io.floci.aws.services.iam.PassedRoleLookup;
import io.floci.aws.services.organizations.OrganizationsService;
import io.floci.aws.services.organizations.model.CreateAccountStatus;
@@ -47,25 +51,32 @@ public class ServiceCatalogService implements PassedRoleLookup {
private final StorageBackend<String, ObjectNode> associationStore;
private final StorageBackend<String, ObjectNode> shareStore;
private final StorageBackend<String, ObjectNode> provisionedProductStore;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final OrganizationsService organizationsService;
private final Clock clock;
/**
* Every resource this service stores is Regional, as on AWS, so each store is the request's Region's view
* ({@link RegionScopedStorage}); one stored before, without a Region, is the default Region's.
*/
@Inject
public ServiceCatalogService(StorageFactory storageFactory, ObjectMapper objectMapper,
OrganizationsService organizationsService, Clock clock) {
this.portfolioStore = storageFactory.create("servicecatalog", "servicecatalog-portfolios.json",
new TypeReference<Map<String, ObjectNode>>() {});
this.productStore = storageFactory.create("servicecatalog", "servicecatalog-products.json",
new TypeReference<Map<String, ObjectNode>>() {});
this.tagOptionStore = storageFactory.create("servicecatalog", "servicecatalog-tag-options.json",
new TypeReference<Map<String, ObjectNode>>() {});
this.associationStore = storageFactory.create("servicecatalog", "servicecatalog-associations.json",
new TypeReference<Map<String, ObjectNode>>() {});
this.shareStore = storageFactory.create("servicecatalog", "servicecatalog-shares.json",
new TypeReference<Map<String, ObjectNode>>() {});
this.provisionedProductStore = storageFactory.create("servicecatalog", "servicecatalog-provisioned-products.json",
new TypeReference<Map<String, ObjectNode>>() {});
OrganizationsService organizationsService, Clock clock,
RegionResolver regionResolver) {
this.portfolioStore = new RegionScopedStorage<>(storageFactory, regionResolver, "servicecatalog",
"servicecatalog-portfolios.json", new TypeReference<Map<String, ObjectNode>>() {});
this.productStore = new RegionScopedStorage<>(storageFactory, regionResolver, "servicecatalog",
"servicecatalog-products.json", new TypeReference<Map<String, ObjectNode>>() {});
this.tagOptionStore = new RegionScopedStorage<>(storageFactory, regionResolver, "servicecatalog",
"servicecatalog-tag-options.json", new TypeReference<Map<String, ObjectNode>>() {});
this.associationStore = new RegionScopedStorage<>(storageFactory, regionResolver, "servicecatalog",
"servicecatalog-associations.json", new TypeReference<Map<String, ObjectNode>>() {});
this.shareStore = new RegionScopedStorage<>(storageFactory, regionResolver, "servicecatalog",
"servicecatalog-shares.json", new TypeReference<Map<String, ObjectNode>>() {});
this.provisionedProductStore = new RegionScopedStorage<>(storageFactory, regionResolver, "servicecatalog",
"servicecatalog-provisioned-products.json", new TypeReference<Map<String, ObjectNode>>() {});
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.organizationsService = organizationsService;
this.clock = clock;
@@ -103,6 +114,10 @@ public class ServiceCatalogService implements PassedRoleLookup {
return portfolioStore.scan(key -> true).stream().map(ObjectNode::deepCopy).toList();
}
/**
* Seeds the Control Tower Account Factory catalog in the request's Region, the first time that Region asks for
* it. Each Region gets its own, under the same ids, as {@code ControlTowerService} seeds a landing zone in each.
*/
private void ensureControlTowerCatalog(String region, String accountId) {
boolean exists = portfolioStore.scan(key -> true).stream()
.anyMatch(portfolio -> CONTROL_TOWER_PORTFOLIO_NAME.equals(text(portfolio, "DisplayName"))
@@ -432,10 +447,8 @@ public class ServiceCatalogService implements PassedRoleLookup {
throw inUse("product", productId, "it is associated with a portfolio");
}
productStore.delete(productId);
associationStore.keys().stream()
.filter(key -> associationStore.get(key)
.map(value -> productMatches(value.path("ProductId").asText(), product)).orElse(false))
.toList().forEach(associationStore::delete);
StorageOperations.deleteMatchingAtomically(associationStore,
value -> productMatches(value.path("ProductId").asText(), product));
}
public ObjectNode createTagOption(JsonNode request) {
@@ -469,10 +482,7 @@ public class ServiceCatalogService implements PassedRoleLookup {
public void deleteTagOption(String id) {
require(tagOptionStore, id, "TagOption");
tagOptionStore.delete(id);
associationStore.keys().stream()
.filter(key -> associationStore.get(key)
.map(value -> id.equals(text(value, "TagOptionId"))).orElse(false))
.toList().forEach(associationStore::delete);
StorageOperations.deleteMatchingAtomically(associationStore, value -> id.equals(text(value, "TagOptionId")));
}
public String associateProduct(String portfolioId, String productId) {
@@ -701,10 +711,26 @@ public class ServiceCatalogService implements PassedRoleLookup {
.toList();
}
/**
* Copies a product into the request's Region. The source may be of another Region of the request's partition,
* the one its ARN names, as on AWS, so it is read there. One of another partition is not found.
*/
public String copyProduct(JsonNode request, String region, String accountId) {
String sourceArn = requireText(request, "SourceProductArn");
String sourceId = sourceArn.substring(sourceArn.lastIndexOf('/') + 1);
ObjectNode source = requireProduct(sourceId);
String sourceRegion = region;
if (AwsArnUtils.isArn(sourceArn)) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(sourceArn);
String partition = regionResolver.getPartition();
if (AwsArnUtils.isForeignPartition(arn, partition)
|| !arn.region().isEmpty() && !regionResolver.partitionForRegion(arn.region()).equals(partition)) {
throw notFound("product", sourceId);
}
if (!arn.region().isEmpty()) {
sourceRegion = arn.region();
}
}
ObjectNode source = RequestScopes.callAs(null, sourceRegion, () -> requireProduct(sourceId));
String newId = id("prod");
ObjectNode product = source.deepCopy();
product.put("Id", newId);
@@ -0,0 +1,174 @@
package io.floci.aws.services.servicecatalog;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.ServiceCatalogRequests;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
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.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
/**
* Service Catalog's resources are Regional, as on AWS: a portfolio, product, TagOption, service action,
* constraint or provisioned product is listed and reached only in the Region it was created in, and each Region seeds
* a Control Tower Account Factory catalog of its own. Each test works in an account of its own.
*/
@QuarkusTest
class ServiceCatalogRegionScopingIntegrationTest {
private static final AtomicLong ACCOUNTS = new AtomicLong(732100000000L);
private static final String HOME = "eu-west-1";
private static final String OTHER = "eu-central-1";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private String account;
@BeforeAll
static void configureAwsJson() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void accountOfItsOwn() {
account = Long.toString(ACCOUNTS.incrementAndGet());
}
@Test
void eachResourceIsListedAndReachedOnlyInTheRegionItWasCreatedIn() {
String portfolio = call(HOME, "CreatePortfolio", "{\"DisplayName\":\"apps\",\"ProviderName\":\"floci\"}")
.statusCode(200).extract().path("PortfolioDetail.Id");
cleanup.register(() -> call(HOME, "DeletePortfolio", byId(portfolio)));
String product = createProduct(HOME);
String tagOption = call(HOME, "CreateTagOption", "{\"Key\":\"team\",\"Value\":\"data\"}")
.statusCode(200).extract().path("TagOptionDetail.Id");
cleanup.register(() -> call(HOME, "DeleteTagOption", byId(tagOption)));
String action = call(HOME, "CreateServiceAction", "{\"Name\":\"restart\",\"DefinitionType\":"
+ "\"SSM_AUTOMATION\",\"Definition\":{\"Name\":\"AWS-RestartEC2Instance\"},\"IdempotencyToken\":\"t1\"}")
.statusCode(200).extract().path("ServiceActionDetail.ServiceActionSummary.Id");
cleanup.register(() -> call(HOME, "DeleteServiceAction", byId(action)));
String constraint = call(HOME, "CreateConstraint", "{\"PortfolioId\":\"" + portfolio + "\",\"ProductId\":\""
+ product + "\",\"Parameters\":\"{}\",\"Type\":\"LAUNCH\",\"IdempotencyToken\":\"t2\"}")
.statusCode(200).extract().path("ConstraintDetail.ConstraintId");
cleanup.register(() -> call(HOME, "DeleteConstraint", byId(constraint)));
String provisioned = call(HOME, "ProvisionProduct", "{\"ProductId\":\"" + product
+ "\",\"ProvisionedProductName\":\"app-1\"}")
.statusCode(200).extract().path("RecordDetail.ProvisionedProductId");
cleanup.register(() -> call(HOME, "TerminateProvisionedProduct", "{\"ProvisionedProductId\":\""
+ provisioned + "\",\"TerminateToken\":\"t4\"}"));
call(OTHER, "ListPortfolios", "{}").statusCode(200).body("PortfolioDetails.Id", not(hasItem(portfolio)));
notFound(call(OTHER, "DescribePortfolio", byId(portfolio)));
notFound(call(OTHER, "DeletePortfolio", byId(portfolio)));
call(OTHER, "SearchProductsAsAdmin", "{}").statusCode(200)
.body("ProductViewDetails.ProductViewSummary.ProductId", not(hasItem(product)));
notFound(call(OTHER, "DescribeProductAsAdmin", byId(product)));
call(OTHER, "ListTagOptions", "{}").statusCode(200).body("TagOptionDetails.Id", not(hasItem(tagOption)));
notFound(call(OTHER, "DescribeTagOption", byId(tagOption)));
call(OTHER, "ListServiceActions", "{}").statusCode(200).body("ServiceActionSummaries.Id", not(hasItem(action)));
notFound(call(OTHER, "UpdateServiceAction", "{\"Id\":\"" + action + "\",\"Name\":\"renamed\"}"));
notFound(call(OTHER, "DescribeConstraint", byId(constraint)));
call(OTHER, "SearchProvisionedProducts", "{}").statusCode(200)
.body("ProvisionedProducts.Id", not(hasItem(provisioned)));
notFound(call(OTHER, "DescribeProvisionedProduct", byId(provisioned)));
call(HOME, "ListPortfolios", "{}").statusCode(200).body("PortfolioDetails.Id", hasItem(portfolio));
call(HOME, "DescribePortfolio", byId(portfolio)).statusCode(200);
call(HOME, "SearchProductsAsAdmin", "{}").statusCode(200)
.body("ProductViewDetails.ProductViewSummary.ProductId", hasItem(product));
call(HOME, "DescribeProductAsAdmin", byId(product)).statusCode(200);
call(HOME, "ListTagOptions", "{}").statusCode(200).body("TagOptionDetails.Id", hasItem(tagOption));
call(HOME, "ListServiceActions", "{}").statusCode(200).body("ServiceActionSummaries.Id", hasItem(action));
call(HOME, "DescribeConstraint", byId(constraint)).statusCode(200);
call(HOME, "DescribeProvisionedProduct", byId(provisioned)).statusCode(200)
.body("ProvisionedProductDetail.Arn", startsWith("arn:aws:servicecatalog:" + HOME + ":"));
}
/** CopyProduct copies a product of another Region, the one its ARN names, into the request's Region. */
@Test
void aProductOfAnotherRegionIsCopiedIntoTheRequestsRegion() {
String source = createProduct(HOME);
String sourceArn = call(HOME, "DescribeProductAsAdmin", byId(source)).statusCode(200)
.extract().path("ProductViewDetail.ProductViewSummary.ARN");
String token = call(OTHER, "CopyProduct", "{\"SourceProductArn\":\"" + sourceArn
+ "\",\"TargetProductName\":\"copied\",\"IdempotencyToken\":\"t3\"}")
.statusCode(200).extract().path("CopyProductToken");
String copy = call(OTHER, "DescribeCopyProductStatus", "{\"CopyProductToken\":\"" + token + "\"}")
.statusCode(200).body("CopyProductStatus", equalTo("SUCCEEDED")).extract().path("TargetProductId");
cleanup.register(() -> call(OTHER, "DeleteProduct", byId(copy)));
call(OTHER, "DescribeProductAsAdmin", byId(copy)).statusCode(200)
.body("ProductViewDetail.ProductViewSummary.Name", equalTo("copied"))
.body("ProductViewDetail.ProductViewSummary.ARN", startsWith("arn:aws:catalog:" + OTHER + ":"));
notFound(call(HOME, "DescribeProductAsAdmin", byId(copy)));
}
/**
* A product of another partition isn't copied, though that partition holds one under the ARN's id: neither by an
* ARN of that partition, nor by one of the request's partition naming that partition's Region.
*/
@Test
void aProductOfAnotherPartitionIsNotFound() {
String source = createProduct("cn-north-1");
notFound(call(OTHER, "CopyProduct", "{\"SourceProductArn\":\"arn:aws-cn:catalog:cn-north-1:" + account
+ ":product/" + source + "\",\"IdempotencyToken\":\"t5\"}"));
notFound(call(OTHER, "CopyProduct", "{\"SourceProductArn\":\"arn:aws:catalog:cn-north-1:" + account
+ ":product/" + source + "\",\"IdempotencyToken\":\"t6\"}"));
}
/**
* The Control Tower Account Factory catalog Floci seeds is each Region's own, as Floci's Control Tower seeds a
* landing zone in each: the portfolio a Region lists is of that Region, and deleting one leaves the other's.
*/
@Test
void eachRegionSeedsAnAccountFactoryCatalogOfItsOwn() {
for (String region : List.of(HOME, OTHER)) {
call(region, "ListPortfolios", "{}").statusCode(200)
.body("PortfolioDetails.Id", hasItem(ServiceCatalogService.CONTROL_TOWER_PORTFOLIO_ID));
call(region, "DescribePortfolio", byId(ServiceCatalogService.CONTROL_TOWER_PORTFOLIO_ID)).statusCode(200)
.body("PortfolioDetail.ARN", startsWith("arn:aws:catalog:" + region + ":"));
}
call(HOME, "DisassociateProductFromPortfolio", "{\"PortfolioId\":\""
+ ServiceCatalogService.CONTROL_TOWER_PORTFOLIO_ID + "\",\"ProductId\":\""
+ ServiceCatalogService.CONTROL_TOWER_PRODUCT_ID + "\"}").statusCode(200);
call(HOME, "DeletePortfolio", byId(ServiceCatalogService.CONTROL_TOWER_PORTFOLIO_ID)).statusCode(200);
call(OTHER, "DescribePortfolio", byId(ServiceCatalogService.CONTROL_TOWER_PORTFOLIO_ID)).statusCode(200)
.body("PortfolioDetail.ARN", startsWith("arn:aws:catalog:" + OTHER + ":"));
}
/** A product created in {@code region}, deleted after the test. */
private String createProduct(String region) {
String product = call(region, "CreateProduct", "{\"Name\":\"app\",\"Owner\":\"floci\","
+ "\"ProvisioningArtifactParameters\":[{\"Name\":\"v1\"}]}")
.statusCode(200).extract().path("ProductViewDetail.ProductViewSummary.ProductId");
cleanup.register(() -> call(region, "DeleteProduct", byId(product)));
return product;
}
private static String byId(String id) {
return "{\"Id\":\"" + id + "\"}";
}
private static void notFound(ValidatableResponse response) {
response.statusCode(400).body("__type", equalTo("ResourceNotFoundException"));
}
private ValidatableResponse call(String region, String action, String body) {
return ServiceCatalogRequests.call(action, account, region, body);
}
}
@@ -0,0 +1,26 @@
package io.floci.aws.testing;
import io.restassured.response.ValidatableResponse;
import static io.restassured.RestAssured.given;
/**
* Service Catalog JSON calls signed for an account and a Region, over the test's RestAssured port. The caller
* registers the AWS JSON content types first ({@link RestAssuredJsonUtils#configureAwsContentTypes}).
*/
public final class ServiceCatalogRequests {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private ServiceCatalogRequests() {}
/** {@code AWS242ServiceCatalogService.<action>} with {@code body}, signed for {@code account} in {@code region}. */
public static ValidatableResponse call(String action, String account, String region, String body) {
return given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWS242ServiceCatalogService." + action)
.header("Authorization", EnforcementFixtures.auth(account, "20260918", region, "servicecatalog"))
.body(body)
.when().post("/")
.then();
}
}