Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(marketplace-catalog): emulate AWS Marketplace Catalog API (#3338)

Franklin G. Mendoza50fa334dc526
diff --git a/README.md b/README.md
index 5c54561870..65be67b003 100644
--- a/README.md
+++ b/README.md
@@ -238,7 +238,7 @@ Floci supports local emulation for application services, data services, eventing
| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock Runtime, Bedrock AgentCore |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core, Amazon Connect |
-| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Control Catalog, Control Tower, Service Catalog |
+| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Control Catalog, Control Tower, Service Catalog, AWS Marketplace |
| Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 2bfd4de58f..a52548491d 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -282,6 +282,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>controlcatalog</artifactId>
</dependency>
+ <!-- AWS Marketplace Catalog client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>marketplacecatalog</artifactId>
+ </dependency>
<!-- IAM Access Analyzer client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index e8100396e4..1683c82860 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -38,6 +38,7 @@ import software.amazon.awssdk.services.identitystore.IdentitystoreClient;
import software.amazon.awssdk.services.budgets.BudgetsClient;
import software.amazon.awssdk.services.macie2.Macie2Client;
import software.amazon.awssdk.services.controlcatalog.ControlCatalogClient;
+import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.inspector2.Inspector2Client;
import software.amazon.awssdk.services.securityhub.SecurityHubClient;
import software.amazon.awssdk.services.detective.DetectiveClient;
@@ -359,6 +360,14 @@ public final class TestFixtures {
.build();
}
+ public static MarketplaceCatalogClient marketplaceCatalogClient() {
+ return MarketplaceCatalogClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static DetectiveClient detectiveClient(String accountId) {
return DetectiveClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/MarketplaceCatalogTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/MarketplaceCatalogTest.java
new file mode 100644
index 0000000000..002147a44f
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/MarketplaceCatalogTest.java
@@ -0,0 +1,17 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+class MarketplaceCatalogTest {
+
+ @Test
+ void usesAwsSdkWireContract() {
+ try (MarketplaceCatalogClient client = TestFixtures.marketplaceCatalogClient()) {
+ var response = client.listEntities(r -> r.catalog("AWSMarketplace").entityType("SaaSProduct"));
+ assertNotNull(response.entitySummaryList());
+ }
+ }
+}
diff --git a/docs/services/index.md b/docs/services/index.md
index a68e87f82b..b5d2e020d2 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -104,6 +104,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [AWS Budgets](budgets.md) | `POST /` + `X-Amz-Target: AWSBudgetServiceGateway.*` | JSON 1.1 | 26 |
| [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 12 |
| [Control Catalog](controlcatalog.md) | `/get-control`, `/list-controls` | REST JSON | 2 |
+| [AWS Marketplace](marketplace.md) | Marketplace Catalog API | REST JSON | 15 |
| [Control Tower](controltower.md) | `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/*-baseline*` | REST JSON | 15 |
| [Managed Prometheus (AMP)](managed-prometheus.md) | `/workspaces/*`, `/workspaces/*/rulegroupsnamespaces/*`, `/tags/*` | REST JSON | 13 |
| [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 |
diff --git a/docs/services/marketplace.md b/docs/services/marketplace.md
new file mode 100644
index 0000000000..87000f5605
--- /dev/null
+++ b/docs/services/marketplace.md
@@ -0,0 +1,35 @@
+# AWS Marketplace
+
+Floci emulates AWS Marketplace APIs under the shared `aws-marketplace` SigV4 signing scope.
+
+## Marketplace Catalog
+
+<!-- floci:actions:start -->
+| Action | Description |
+| --- | --- |
+| `BatchDescribeEntities` | Describes up to 20 catalog entities in one request |
+| `CancelChangeSet` | Cancels a change set while it is preparing or applying |
+| `DeleteResourcePolicy` | Deletes an entity resource policy |
+| `DescribeAssessment` | Returns an assessment and control results |
+| `DescribeChangeSet` | Returns change set status and change details |
+| `DescribeEntity` | Returns the current entity revision |
+| `GetResourcePolicy` | Returns an entity resource policy |
+| `ListAssessments` | Lists Marketplace Catalog assessments |
+| `ListChangeSets` | Lists change sets with pagination |
+| `ListEntities` | Lists catalog entities by entity type |
+| `ListTagsForResource` | Lists tags on a Marketplace Catalog resource |
+| `PutResourcePolicy` | Creates or replaces an entity resource policy |
+| `StartChangeSet` | Starts an idempotent Marketplace Catalog change set |
+| `TagResource` | Adds or replaces tags on a Marketplace Catalog resource |
+| `UntagResource` | Removes tag keys from a Marketplace Catalog resource |
+<!-- floci:actions:end -->
+
+Catalog change sets use AWS states (`PREPARING`, `APPLYING`, `SUCCEEDED`, and `CANCELLED`). Floci applies supported entity mutations locally when a change set is observed and persists entities, change sets, tags, resource policies, and assessments through `StorageFactory`, isolated by AWS account.
+
+## Configuration
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_MARKETPLACE_ENABLED` | `true` | Enable or disable AWS Marketplace emulation |
+
+See the [AWS Marketplace API Reference](https://docs.aws.amazon.com/marketplace/latest/APIReference/).
diff --git a/mkdocs.yml b/mkdocs.yml
index b9649a8e3e..7984c68d59 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -129,6 +129,7 @@ nav:
- Security Hub: services/securityhub.md
- Amazon Detective: services/detective.md
- Control Catalog: services/controlcatalog.md
+ - AWS Marketplace: services/marketplace.md
- Control Tower: services/controltower.md
- AWS Service Catalog: services/service-catalog.md
- ElastiCache: services/elasticache.md
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index d52b27158d..926d7613d6 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -744,6 +744,7 @@ public interface EmulatorConfig {
LakeFormationServiceConfig lakeformation();
EfsServiceConfig efs();
CodeGuruReviewerServiceConfig codegurureviewer();
+ MarketplaceServiceConfig marketplace();
}
interface ConnectServiceConfig {
@@ -811,6 +812,11 @@ public interface EmulatorConfig {
boolean enabled();
}
+ interface MarketplaceServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface IotServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index fb34ca119c..4b1e9e1153 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -49,6 +49,7 @@ import io.github.hectorvent.floci.services.rum.RumController;
import io.github.hectorvent.floci.services.s3vectors.S3VectorsController;
import io.github.hectorvent.floci.services.s3tables.S3TablesController;
import io.github.hectorvent.floci.services.efs.EfsController;
+import io.github.hectorvent.floci.services.marketplace.MarketplaceCatalogController;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -640,7 +641,12 @@ public class ResolvedServiceCatalog {
"codegurureviewer", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("codeguru-reviewer"), Set.of(),
- Set.of(io.github.hectorvent.floci.services.codegurureviewer.CodeGuruReviewerController.class))
+ Set.of(io.github.hectorvent.floci.services.codegurureviewer.CodeGuruReviewerController.class)),
+ descriptor("marketplace", "marketplace", config.services().marketplace().enabled(), true,
+ "marketplace", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
+ protocols(ServiceProtocol.REST_JSON),
+ Set.of(), Set.of("aws-marketplace"), Set.of(),
+ Set.of(MarketplaceCatalogController.class))
));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogController.java b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogController.java
new file mode 100644
index 0000000000..f1818bd17b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogController.java
@@ -0,0 +1,151 @@
+package io.github.hectorvent.floci.services.marketplace;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectReader;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RequestContext;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.PATCH;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class MarketplaceCatalogController {
+ private final MarketplaceService service;
+ private final ObjectReader strictReader;
+ private final RequestContext context;
+
+ @Inject
+ public MarketplaceCatalogController(MarketplaceService service, ObjectMapper mapper, RequestContext context) {
+ this.service = service;
+ this.strictReader = mapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+ this.context = context;
+ }
+
+ @POST
+ @Path("/BatchDescribeEntities")
+ public Response batchDescribeEntities(String body) {
+ return ok(service.batchDescribeEntities(parse(body), region()));
+ }
+
+ @PATCH
+ @Path("/CancelChangeSet")
+ public Response cancelChangeSet(@QueryParam("catalog") String catalog, @QueryParam("changeSetId") String id) {
+ return ok(service.cancelChangeSet(catalog, id, region()));
+ }
+
+ @DELETE
+ @Path("/DeleteResourcePolicy")
+ public Response deleteResourcePolicy(@QueryParam("resourceArn") String arn) {
+ return ok(service.deleteResourcePolicy(arn, region()));
+ }
+
+ @POST
+ @Path("/DescribeAssessment")
+ public Response describeAssessment(String body) {
+ return ok(service.describeAssessment(parse(body), region()));
+ }
+
+ @GET
+ @Path("/DescribeChangeSet")
+ public Response describeChangeSet(@QueryParam("catalog") String catalog, @QueryParam("changeSetId") String id) {
+ return ok(service.describeChangeSet(catalog, id, region()));
+ }
+
+ @GET
+ @Path("/DescribeEntity")
+ public Response describeEntity(@QueryParam("catalog") String catalog, @QueryParam("entityId") String id) {
+ return ok(service.describeEntity(catalog, id, region()));
+ }
+
+ @GET
+ @Path("/GetResourcePolicy")
+ public Response getResourcePolicy(@QueryParam("resourceArn") String arn) {
+ return ok(service.getResourcePolicy(arn, region()));
+ }
+
+ @POST
+ @Path("/ListAssessments")
+ public Response listAssessments(String body) {
+ return ok(service.listAssessments(parse(body), region()));
+ }
+
+ @POST
+ @Path("/ListChangeSets")
+ public Response listChangeSets(String body) {
+ return ok(service.listChangeSets(parse(body), region()));
+ }
+
+ @POST
+ @Path("/ListEntities")
+ public Response listEntities(String body) {
+ return ok(service.listEntities(parse(body), region()));
+ }
+
+ @POST
+ @Path("/ListTagsForResource")
+ public Response listTagsForResource(String body) {
+ return ok(service.catalogListTags(parse(body), region()));
+ }
+
+ @POST
+ @Path("/PutResourcePolicy")
+ public Response putResourcePolicy(String body) {
+ return ok(service.putResourcePolicy(parse(body), region()));
+ }
+
+ @POST
+ @Path("/StartChangeSet")
+ public Response startChangeSet(String body) {
+ return ok(service.startChangeSet(parse(body), region()));
+ }
+
+ @POST
+ @Path("/TagResource")
+ public Response tagResource(String body) {
+ return ok(service.catalogTagResource(parse(body), region()));
+ }
+
+ @POST
+ @Path("/UntagResource")
+ public Response untagResource(String body) {
+ return ok(service.catalogUntagResource(parse(body), region()));
+ }
+
+ private JsonNode parse(String body) {
+ try {
+ JsonNode value = strictReader.readTree(body == null || body.isBlank() ? "{}" : body);
+ if (value == null || !value.isObject()) {
+ throw validation("Request body must be a JSON object.");
+ }
+ return value;
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw validation("Request body is not valid JSON.");
+ }
+ }
+
+ private String region() {
+ return context.getRegion() == null ? "us-east-1" : context.getRegion();
+ }
+
+ private static Response ok(JsonNode node) {
+ return Response.ok(node).build();
+ }
+
+ private static AwsException validation(String message) {
+ return new AwsException("ValidationException", message, 422);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java
new file mode 100644
index 0000000000..62ccab9952
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java
@@ -0,0 +1,850 @@
+package io.github.hectorvent.floci.services.marketplace;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RequestContext;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.marketplace.model.MarketplaceChangeSetRequest;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+@ApplicationScoped
+public class MarketplaceService implements Resettable {
+ private static final String CATALOG = "AWSMarketplace";
+ private static final String REGION = "us-east-1";
+ private static final Pattern CLIENT_TOKEN = Pattern.compile("[!-~]{1,64}");
+ private static final Pattern CHANGE_SET_NAME = Pattern.compile("[\\w\\s+=.:@-]{1,100}");
+ private static final Set<String> SUPPORTED_CHANGE_TYPES = Set.of(
+ "AddDeliveryOptions", "AddDimension", "AddDimensions", "AddInstanceTypes", "AddRegions",
+ "AddRepositories", "AddRevisions", "AllowProductProcurement", "AssociateAudience",
+ "AssociateOffers", "AssociateSolution", "CreateBrandingSettings", "CreateExperience",
+ "CreateOffer", "CreateOfferSet", "CreateOfferUsingResaleAuthorization", "CreateProcurementPolicy",
+ "CreateProduct", "CreateReplacementOffer", "CreateReplacementOfferUsingResaleAuthorization",
+ "CreateResaleAuthorization", "CreateSolution", "DenyProductProcurement", "DisassociateAudience",
+ "DisassociateOffers", "DisassociateSolution", "ReleaseOffer", "ReleaseOfferSet", "ReleaseProduct",
+ "ReleaseResaleAuthorization", "ReleaseSolution", "RestrictDeliveryOptions", "RestrictDimension",
+ "RestrictExperience", "RestrictInstanceTypes", "RestrictRegions", "RestrictResaleAuthorization",
+ "ReviveExperience", "UpdateAvailability", "UpdateBrandingSettings", "UpdateBuyerEngagementOptions",
+ "UpdateBuyerTargetingTerms", "UpdateBuyerValidityTerms", "UpdateCustomerVerificationTerms",
+ "UpdateDeliveryOptions", "UpdateDeliveryOptionsVisibility", "UpdateDimension", "UpdateExperience",
+ "UpdateFutureRegionSupport", "UpdateInformation", "UpdateLegalTerms", "UpdateMarkup",
+ "UpdatePaymentScheduleTerms", "UpdatePricingTerms", "UpdateProcurementPolicy", "UpdateRelatedProducts",
+ "UpdateRenewalTerms", "UpdateSupportTerms", "UpdateTargeting", "UpdateValidityTerms", "UpdateVisibility");
+ private static final Logger LOG = Logger.getLogger(MarketplaceService.class);
+
+ private final ObjectMapper mapper;
+ private final AccountAwareStorageBackend<JsonNode> entities;
+ private final AccountAwareStorageBackend<JsonNode> changeSets;
+ private final AccountAwareStorageBackend<JsonNode> resourcePolicies;
+ private final AccountAwareStorageBackend<JsonNode> tags;
+ private final AccountAwareStorageBackend<JsonNode> assessments;
+ private final RequestContext requestContext;
+
+ @Inject
+ public MarketplaceService(StorageFactory factory, ObjectMapper mapper, RequestContext requestContext) {
+ this(mapper,
+ factory.create("marketplace", "marketplace-entities.json", type()),
+ factory.create("marketplace", "marketplace-change-sets.json", type()),
+ factory.create("marketplace", "marketplace-resource-policies.json", type()),
+ factory.create("marketplace", "marketplace-tags.json", type()),
+ factory.create("marketplace", "marketplace-assessments.json", type()),
+ requestContext);
+ }
+
+ MarketplaceService(ObjectMapper mapper,
+ AccountAwareStorageBackend<JsonNode> entities,
+ AccountAwareStorageBackend<JsonNode> changeSets,
+ AccountAwareStorageBackend<JsonNode> resourcePolicies,
+ AccountAwareStorageBackend<JsonNode> tags,
+ AccountAwareStorageBackend<JsonNode> assessments,
+ RequestContext requestContext) {
+ this.mapper = mapper;
+ this.entities = entities;
+ this.changeSets = changeSets;
+ this.resourcePolicies = resourcePolicies;
+ this.tags = tags;
+ this.assessments = assessments;
+ this.requestContext = requestContext;
+ }
+
+ private static TypeReference<Map<String, JsonNode>> type() {
+ return new TypeReference<>() {};
+ }
+
+ public ObjectNode batchDescribeEntities(JsonNode request, String region) {
+ validateRegion(region);
+ ArrayNode inputs = requireArray(request, "EntityRequestList");
+ if (inputs.isEmpty() || inputs.size() > 20) {
+ throw validation("EntityRequestList must contain between 1 and 20 items.");
+ }
+ completePending();
+ ObjectNode out = mapper.createObjectNode();
+ ObjectNode details = out.putObject("EntityDetails");
+ ObjectNode errors = out.putObject("Errors");
+ for (JsonNode input : inputs) {
+ String catalog = text(input, "Catalog", true);
+ String id = text(input, "EntityId", true);
+ if (!CATALOG.equals(catalog)) {
+ errors.set(id, errorDetail("ValidationException", "Catalog must be AWSMarketplace."));
+ continue;
+ }
+ JsonNode entity = entities.get(id).orElse(null);
+ if (entity == null) {
+ errors.set(id, errorDetail("ResourceNotFoundException", "Entity not found."));
+ } else {
+ details.set(id, entity.deepCopy());
+ }
+ }
+ return out;
+ }
+
+ public ObjectNode startChangeSet(JsonNode request, String region) {
+ validateRegion(region);
+ requireCatalog(text(request, "Catalog", true));
+ ArrayNode changes = requireArray(request, "ChangeSet");
+ if (changes.isEmpty() || changes.size() > 20) {
+ throw validation("ChangeSet must contain between 1 and 20 changes.");
+ }
+ String token = text(request, "ClientRequestToken", false);
+ if (token != null && !CLIENT_TOKEN.matcher(token).matches()) {
+ throw validation("ClientRequestToken must contain 1 to 64 visible ASCII characters.");
+ }
+ String name = text(request, "ChangeSetName", false);
+ if (name != null && !CHANGE_SET_NAME.matcher(name).matches()) {
+ throw validation("ChangeSetName is invalid.");
+ }
+ String intent = request.path("Intent").asText("APPLY");
+ if (!Set.of("APPLY", "VALIDATE").contains(intent)) {
+ throw validation("Intent must be APPLY or VALIDATE.");
+ }
+
+ JsonNode idempotencyPayload = request.deepCopy();
+ MarketplaceChangeSetRequest retry = new MarketplaceChangeSetRequest(token, idempotencyPayload);
+ if (token != null) {
+ for (JsonNode existing : changeSets.scan(key -> true)) {
+ if (!token.equals(existing.path("ClientRequestToken").asText(null))) {
+ continue;
+ }
+ if (!retry.matches(existing.path("_IdempotencyRequest"))) {
+ throw validation("ClientRequestToken was already used with different parameters.");
+ }
+ return ids(existing);
+ }
+ }
+
+ ArrayNode normalized = normalizeChanges(changes, region);
+ validateNoDuplicateChanges(normalized);
+ String id = "cs-" + compactId();
+ String arn = arn(region, "AWSMarketplace/ChangeSet/" + id);
+ ObjectNode cs = mapper.createObjectNode();
+ cs.put("ChangeSetId", id);
+ cs.put("ChangeSetArn", arn);
+ if (name != null) {
+ cs.put("ChangeSetName", name);
+ }
+ cs.put("Intent", intent);
+ cs.put("StartTime", Instant.now().toString());
+ cs.put("Status", "PREPARING");
+ cs.put("_Region", region);
+ cs.set("ChangeSet", normalized);
+ if (token != null) {
+ cs.put("ClientRequestToken", token);
+ cs.set("_IdempotencyRequest", idempotencyPayload);
+ }
+ changeSets.put(id, cs);
+ if (request.path("ChangeSetTags").isArray()) {
+ tags.put(arn, request.path("ChangeSetTags").deepCopy());
+ }
+ return ids(cs);
+ }
+
+ public ObjectNode cancelChangeSet(String catalog, String id, String region) {
+ validateRegion(region);
+ requireCatalog(catalog);
+ ObjectNode cs = changeSet(id);
+ ensureStoredRegion(cs, region);
+ String status = cs.path("Status").asText();
+ if (!"PREPARING".equals(status) && !"APPLYING".equals(status)) {
+ throw new AwsException("ResourceInUseException",
+ "Change set cannot be cancelled in status " + status + ".", 423);
+ }
+ cs.put("Status", "CANCELLED");
+ cs.put("EndTime", Instant.now().toString());
+ changeSets.put(id, cs);
+ return ids(cs);
+ }
+
+ public ObjectNode describeChangeSet(String catalog, String id, String region) {
+ validateRegion(region);
+ requireCatalog(catalog);
+ ObjectNode cs = changeSet(id);
+ ensureStoredRegion(cs, region);
+ if ("PREPARING".equals(cs.path("Status").asText())) {
+ applyChangeSet(cs);
+ changeSets.put(id, cs);
+ }
+ return publicChangeSet(cs);
+ }
+
+ public ObjectNode listChangeSets(JsonNode request, String region) {
+ validateRegion(region);
+ requireCatalog(text(request, "Catalog", true));
+ completePending();
+ List<JsonNode> all = new ArrayList<>(changeSets.scan(key -> true));
+ all.removeIf(cs -> !region.equals(cs.path("_Region").asText(REGION)));
+ all.removeIf(cs -> !matchesChangeSetFilters(cs, request.get("FilterList")));
+ sortChangeSets(all, request.get("Sort"));
+ return page("ChangeSetSummaryList", all.stream().map(this::changeSummary).toList(), request, 20, 1, 20);
+ }
+
+ public ObjectNode describeEntity(String catalog, String id, String region) {
+ validateRegion(region);
+ requireCatalog(catalog);
+ completePending();
+ JsonNode entity = entities.get(id).orElseThrow(() -> notFound("Entity", id));
+ return (ObjectNode) entity.deepCopy();
+ }
+
+ public ObjectNode listEntities(JsonNode request, String region) {
+ validateRegion(region);
+ requireCatalog(text(request, "Catalog", true));
+ String type = text(request, "EntityType", true);
+ String ownership = request.path("OwnershipType").asText("SELF");
+ if (!Set.of("SELF", "SHARED").contains(ownership)) {
+ throw validation("OwnershipType must be SELF or SHARED.");
+ }
+ completePending();
+ if ("SHARED".equals(ownership) || requestsSharedScope(request.get("FilterList"))) {
+ return page("EntitySummaryList", List.of(), request, 20, 1, 50);
+ }
+ if (request.hasNonNull("EntityTypeFilters")) {
+ throw validation("EntityTypeFilters are not supported by this local catalog implementation.");
+ }
+ if (request.hasNonNull("EntityTypeSort")) {
+ throw validation("EntityTypeSort is not supported by this local catalog implementation.");
+ }
+ List<JsonNode> list = new ArrayList<>(entities.scan(key -> true));
+ list.removeIf(entity -> !type.equals(baseEntityType(entity.path("EntityType").asText())));
+ list.removeIf(entity -> !matchesEntityFilters(entity, request.get("FilterList")));
+ sortEntities(list, request.get("Sort"));
+ return page("EntitySummaryList", list.stream().map(this::entitySummary).toList(), request, 20, 1, 50);
+ }
+
+ public ObjectNode catalogListTags(JsonNode request, String region) {
+ validateRegion(region);
+ String arn = text(request, "ResourceArn", true);
+ ensureResource(arn);
+ ObjectNode out = mapper.createObjectNode();
+ out.put("ResourceArn", arn);
+ out.set("Tags", tags.get(arn).map(node -> (JsonNode) node.deepCopy()).orElseGet(mapper::createArrayNode));
+ return out;
+ }
+
+ public ObjectNode catalogTagResource(JsonNode request, String region) {
+ validateRegion(region);
+ String arn = text(request, "ResourceArn", true);
+ ensureResource(arn);
+ ArrayNode incoming = requireArray(request, "Tags");
+ Map<String, String> merged = new LinkedHashMap<>();
+ tags.get(arn).ifPresent(old -> old.forEach(tag ->
+ merged.put(tag.path("Key").asText(), tag.path("Value").asText())));
+ for (JsonNode tag : incoming) {
+ merged.put(text(tag, "Key", true), text(tag, "Value", true));
+ }
+ if (merged.size() > 50) {
+ throw validation("A resource can have at most 50 tags.");
+ }
+ ArrayNode out = mapper.createArrayNode();
+ merged.forEach((key, value) -> out.addObject().put("Key", key).put("Value", value));
+ tags.put(arn, out);
+ return mapper.createObjectNode();
+ }
+
+ public ObjectNode catalogUntagResource(JsonNode request, String region) {
+ validateRegion(region);
+ String arn = text(request, "ResourceArn", true);
+ ensureResource(arn);
+ ArrayNode keys = requireArray(request, "TagKeys");
+ Set<String> remove = new HashSet<>();
+ keys.forEach(key -> remove.add(key.asText()));
+ ArrayNode out = mapper.createArrayNode();
+ tags.get(arn).ifPresent(old -> old.forEach(tag -> {
+ if (!remove.contains(tag.path("Key").asText())) {
+ out.add(tag.deepCopy());
+ }
+ }));
+ tags.put(arn, out);
+ return mapper.createObjectNode();
+ }
+
+ public ObjectNode putResourcePolicy(JsonNode request, String region) {
+ validateRegion(region);
+ String arn = text(request, "ResourceArn", true);
+ ensureResource(arn);
+ String policy = text(request, "Policy", true);
+ try {
+ mapper.readTree(policy);
+ } catch (Exception e) {
+ throw validation("Policy must be valid JSON.");
+ }
+ resourcePolicies.put(arn, mapper.getNodeFactory().textNode(policy));
+ return mapper.createObjectNode();
+ }
+
+ public ObjectNode getResourcePolicy(String arn, String region) {
+ validateRegion(region);
+ if (arn == null || arn.isBlank()) {
+ throw validation("ResourceArn is required.");
+ }
+ ensureResource(arn);
+ JsonNode policy = resourcePolicies.get(arn).orElseThrow(() -> notFound("Resource policy", arn));
+ return mapper.createObjectNode().put("Policy", policy.asText());
+ }
+
+ public ObjectNode deleteResourcePolicy(String arn, String region) {
+ validateRegion(region);
+ if (arn == null || arn.isBlank()) {
+ throw validation("ResourceArn is required.");
+ }
+ ensureResource(arn);
+ if (resourcePolicies.get(arn).isEmpty()) {
+ throw notFound("Resource policy", arn);
+ }
+ resourcePolicies.delete(arn);
+ return mapper.createObjectNode();
+ }
+
+ public ObjectNode listAssessments(JsonNode request, String region) {
+ validateRegion(region);
+ requireCatalog(text(request, "Catalog", true));
+ List<JsonNode> list = new ArrayList<>(assessments.scan(key -> true));
+ String frameworkId = text(request, "FrameworkId", false);
+ if (frameworkId != null) {
+ list.removeIf(value -> !frameworkId.equals(value.path("FrameworkId").asText()));
+ }
+ JsonNode target = request.get("AssessmentTargetFilter");
+ if (target != null && !target.isNull()) {
+ if (!target.isObject()) {
+ throw validation("AssessmentTargetFilter must be an object.");
+ }
+ String entityId = text(target, "EntityId", false);
+ String changeSetId = text(target, "ChangeSetId", false);
+ if (entityId != null && changeSetId != null) {
+ throw validation("AssessmentTargetFilter can specify only one target.");
+ }
+ if (entityId != null) {
+ list.removeIf(value -> !entityId.equals(value.path("EntityId").asText()));
+ }
+ if (changeSetId != null) {
+ list.removeIf(value -> !changeSetId.equals(value.path("ChangeSetId").asText()));
+ }
+ }
+ if (request.hasNonNull("FrameworkFilters")) {
+ JsonNode filters = request.get("FrameworkFilters");
+ if (!filters.isObject() || filters.size() != 1) {
+ throw validation("FrameworkFilters must contain exactly one framework filter.");
+ }
+ }
+ list.sort(Comparator.comparing(value -> value.path("CreatedAt").asText(), Comparator.reverseOrder()));
+ return page("AssessmentSummaryList", list.stream().map(this::assessmentSummary).toList(), request, 20, 1, 100);
+ }
+
+ public ObjectNode describeAssessment(JsonNode request, String region) {
+ validateRegion(region);
+ requireCatalog(text(request, "Catalog", true));
+ String id = text(request, "AssessmentIdentifier", true);
+ JsonNode assessment = assessments.get(id).orElse(null);
+ if (assessment == null && id.contains("/")) {
+ assessment = assessments.get(id.substring(id.lastIndexOf('/') + 1)).orElse(null);
+ }
+ if (assessment == null) {
+ throw notFound("Assessment", id);
+ }
+ ObjectNode out = (ObjectNode) assessment.deepCopy();
+ JsonNode controls = out.get("ControlEvaluations");
+ if (controls != null && controls.isArray()) {
+ ObjectNode paged = page("ControlEvaluations", toList(controls), request, 20, 1, 100);
+ out.set("ControlEvaluations", paged.path("ControlEvaluations"));
+ if (paged.has("NextToken")) {
+ out.set("NextToken", paged.get("NextToken"));
+ } else {
+ out.remove("NextToken");
+ }
+ }
+ return out;
+ }
+
+ private ArrayNode normalizeChanges(ArrayNode changes, String region) {
+ ArrayNode out = mapper.createArrayNode();
+ for (JsonNode raw : changes) {
+ if (!raw.isObject()) {
+ throw validation("Each ChangeSet entry must be an object.");
+ }
+ ObjectNode change = (ObjectNode) raw.deepCopy();
+ String changeType = text(change, "ChangeType", true);
+ if (!SUPPORTED_CHANGE_TYPES.contains(changeType)) {
+ throw validation("Unsupported ChangeType: " + changeType + ".");
+ }
+ JsonNode entity = change.get("Entity");
+ if (entity == null || !entity.isObject()) {
+ throw validation("Each change requires Entity.");
+ }
+ String type = text(entity, "Type", true);
+ String identifier = text(entity, "Identifier", false);
+ if (identifier == null || "@1".equals(identifier)) {
+ identifier = idForType(type);
+ ((ObjectNode) entity).put("Identifier", identifier);
+ }
+ change.put("EntityArn", arn(region,
+ "AWSMarketplace/" + arnEntityType(type) + "/" + identifier));
+ out.add(change);
+ }
+ return out;
+ }
+
+ private void validateNoDuplicateChanges(ArrayNode changes) {
+ Set<String> seen = new HashSet<>();
+ for (JsonNode change : changes) {
+ String key = change.path("ChangeType").asText() + "|"
+ + change.path("Entity").path("Identifier").asText();
+ if (!seen.add(key)) {
+ throw validation("A change set cannot contain the same change type for the same entity more than once.");
+ }
+ }
+ }
+
+ private void applyChangeSet(ObjectNode changeSet) {
+ changeSet.put("Status", "APPLYING");
+ if (!"VALIDATE".equals(changeSet.path("Intent").asText())) {
+ for (JsonNode change : changeSet.path("ChangeSet")) {
+ String changeType = change.path("ChangeType").asText();
+ JsonNode reference = change.path("Entity");
+ String type = reference.path("Type").asText();
+ String id = reference.path("Identifier").asText();
+ if (changeType.toLowerCase(Locale.ROOT).startsWith("delete")) {
+ entities.delete(id);
+ continue;
+ }
+ ObjectNode entity = entities.get(id)
+ .filter(JsonNode::isObject)
+ .map(node -> (ObjectNode) node.deepCopy())
+ .orElseGet(mapper::createObjectNode);
+ entity.put("EntityType", type);
+ entity.put("EntityIdentifier", id);
+ entity.put("EntityId", id);
+ entity.put("EntityArn", arn(changeSet.path("_Region").asText(REGION),
+ "AWSMarketplace/" + arnEntityType(type) + "/" + id));
+ entity.put("LastModifiedDate", Instant.now().toString());
+ JsonNode details = change.get("DetailsDocument");
+ if (details != null && !details.isNull()) {
+ entity.set("DetailsDocument", details.deepCopy());
+ }
+ JsonNode legacy = change.get("Details");
+ if (legacy != null && !legacy.isNull()) {
+ entity.put("Details", legacy.asText());
+ if (!entity.has("DetailsDocument")) {
+ try {
+ entity.set("DetailsDocument", mapper.readTree(legacy.asText()));
+ } catch (Exception parseError) {
+ LOG.debug("Legacy Marketplace Details is not JSON; preserving it as an opaque string.",
+ parseError);
+ }
+ }
+ }
+ entities.put(id, entity);
+ }
+ }
+ changeSet.put("Status", "SUCCEEDED");
+ changeSet.put("EndTime", Instant.now().toString());
+ }
+
+ private void completePending() {
+ for (String key : changeSets.keys()) {
+ JsonNode node = changeSets.get(key).orElse(null);
+ if (node instanceof ObjectNode objectNode
+ && REGION.equals(objectNode.path("_Region").asText(REGION))
+ && "PREPARING".equals(objectNode.path("Status").asText())) {
+ applyChangeSet(objectNode);
+ changeSets.put(key, objectNode);
+ }
+ }
+ }
+
+ private boolean matchesChangeSetFilters(JsonNode changeSet, JsonNode filters) {
+ if (filters == null || filters.isNull()) {
+ return true;
+ }
+ validateFilterList(filters);
+ for (JsonNode filter : filters) {
+ String name = text(filter, "Name", true);
+ ArrayNode values = requireArray(filter, "ValueList");
+ if (values.isEmpty() || values.size() > 10) {
+ throw validation("Filter ValueList must contain between 1 and 10 values.");
+ }
+ boolean match = switch (name) {
+ case "ChangeSetName" -> contains(values, changeSet.path("ChangeSetName").asText());
+ case "Status" -> contains(values, changeSet.path("Status").asText());
+ case "EntityId" -> anyChangeEntityMatches(changeSet, values);
+ case "BeforeStartTime" -> compareTime(changeSet.path("StartTime").asText(null), values, true);
+ case "AfterStartTime" -> compareTime(changeSet.path("StartTime").asText(null), values, false);
+ case "BeforeEndTime" -> compareTime(changeSet.path("EndTime").asText(null), values, true);
+ case "AfterEndTime" -> compareTime(changeSet.path("EndTime").asText(null), values, false);
+ case "Scope" -> !contains(values, "SharedWithMe");
+ default -> throw validation("Unsupported ListChangeSets filter: " + name + ".");
+ };
+ if (!match) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean matchesEntityFilters(JsonNode entity, JsonNode filters) {
+ if (filters == null || filters.isNull()) {
+ return true;
+ }
+ validateFilterList(filters);
+ for (JsonNode filter : filters) {
+ String name = text(filter, "Name", true);
+ ArrayNode values = requireArray(filter, "ValueList");
+ if (values.isEmpty() || values.size() > 10) {
+ throw validation("Filter ValueList must contain between 1 and 10 values.");
+ }
+ if ("Scope".equals(name)) {
+ if (contains(values, "SharedWithMe")) {
+ return false;
+ }
+ continue;
+ }
+ if (!"EntityId".equals(name)) {
+ throw validation("Unsupported ListEntities filter: " + name + ".");
+ }
+ if (!contains(values, entity.path("EntityId").asText())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static void validateFilterList(JsonNode filters) {
+ if (!filters.isArray() || filters.isEmpty() || filters.size() > 8) {
+ throw validation("FilterList must contain between 1 and 8 filters.");
+ }
+ }
+
+ private static boolean requestsSharedScope(JsonNode filters) {
+ if (filters == null || !filters.isArray()) {
+ return false;
+ }
+ for (JsonNode filter : filters) {
+ if ("Scope".equals(filter.path("Name").asText())) {
+ for (JsonNode value : filter.path("ValueList")) {
+ if ("SharedWithMe".equals(value.asText())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private void sortChangeSets(List<JsonNode> values, JsonNode sort) {
+ String sortBy = sort == null || sort.isNull() ? "StartTime" : sort.path("SortBy").asText("StartTime");
+ if (!Set.of("StartTime", "EndTime").contains(sortBy)) {
+ throw validation("ListChangeSets SortBy must be StartTime or EndTime.");
+ }
+ boolean ascending = sort != null && "ASCENDING".equals(sort.path("SortOrder").asText());
+ validateSortOrder(sort);
+ Comparator<JsonNode> comparator = Comparator.comparing(value -> value.path(sortBy).asText(""));
+ values.sort(ascending ? comparator : comparator.reversed());
+ }
+
+ private void sortEntities(List<JsonNode> values, JsonNode sort) {
+ String sortBy = sort == null || sort.isNull() ? "LastModifiedDate" : sort.path("SortBy").asText("LastModifiedDate");
+ if (!Set.of("LastModifiedDate", "EntityId").contains(sortBy)) {
+ throw validation("ListEntities SortBy must be LastModifiedDate or EntityId.");
+ }
+ boolean ascending = sort != null && "ASCENDING".equals(sort.path("SortOrder").asText());
+ validateSortOrder(sort);
+ Comparator<JsonNode> comparator = Comparator.comparing(value -> value.path(sortBy).asText(""));
+ values.sort(ascending ? comparator : comparator.reversed());
+ }
+
+ private static void validateSortOrder(JsonNode sort) {
+ if (sort == null || sort.isNull() || !sort.hasNonNull("SortOrder")) {
+ return;
+ }
+ String order = sort.path("SortOrder").asText();
+ if (!Set.of("ASCENDING", "DESCENDING").contains(order)) {
+ throw validation("SortOrder must be ASCENDING or DESCENDING.");
+ }
+ }
+
+ private static boolean anyChangeEntityMatches(JsonNode changeSet, ArrayNode values) {
+ for (JsonNode change : changeSet.path("ChangeSet")) {
+ if (contains(values, change.path("Entity").path("Identifier").asText())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean contains(ArrayNode values, String actual) {
+ for (JsonNode value : values) {
+ if (value.isTextual() && value.asText().equals(actual)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean compareTime(String actualValue, ArrayNode values, boolean before) {
+ if (actualValue == null) {
+ return false;
+ }
+ Instant actual;
+ try {
+ actual = Instant.parse(actualValue);
+ } catch (DateTimeParseException e) {
+ return false;
+ }
+ for (JsonNode value : values) {
+ try {
+ Instant boundary = Instant.parse(value.asText());
+ if (before ? actual.isBefore(boundary) : actual.isAfter(boundary)) {
+ return true;
+ }
+ } catch (DateTimeParseException e) {
+ throw validation("Time filters must use ISO-8601 timestamps.");
+ }
+ }
+ return false;
+ }
+
+ private ObjectNode publicChangeSet(JsonNode changeSet) {
+ ObjectNode copy = (ObjectNode) changeSet.deepCopy();
+ copy.remove(List.of("ClientRequestToken", "_IdempotencyRequest", "_Region"));
+ return copy;
+ }
+
+ private ObjectNode ids(JsonNode changeSet) {
+ return mapper.createObjectNode()
+ .put("ChangeSetId", changeSet.path("ChangeSetId").asText())
+ .put("ChangeSetArn", changeSet.path("ChangeSetArn").asText());
+ }
+
+ private ObjectNode changeSet(String id) {
+ if (id == null || id.isBlank()) {
+ throw validation("ChangeSetId is required.");
+ }
+ JsonNode node = changeSets.get(id).orElseThrow(() -> notFound("Change set", id));
+ if (!node.isObject()) {
+ throw new AwsException("InternalServiceException", "Stored change set is invalid.", 500);
+ }
+ return (ObjectNode) node.deepCopy();
+ }
+
+ private JsonNode changeSummary(JsonNode changeSet) {
+ ObjectNode out = mapper.createObjectNode();
+ for (String field : List.of("ChangeSetId", "ChangeSetArn", "ChangeSetName", "StartTime", "EndTime", "Status")) {
+ if (changeSet.has(field)) {
+ out.set(field, changeSet.get(field));
+ }
+ }
+ ArrayNode entityIds = out.putArray("EntityIdList");
+ Set<String> unique = new java.util.LinkedHashSet<>();
+ changeSet.path("ChangeSet").forEach(change -> unique.add(change.path("Entity").path("Identifier").asText()));
+ unique.forEach(entityIds::add);
+ return out;
+ }
+
+ private JsonNode entitySummary(JsonNode entity) {
+ ObjectNode out = mapper.createObjectNode();
+ out.put("Name", entityName(entity));
+ out.put("EntityType", baseEntityType(entity.path("EntityType").asText()));
+ out.put("EntityId", entity.path("EntityId").asText());
+ out.put("EntityArn", entity.path("EntityArn").asText());
+ out.put("LastModifiedDate", entity.path("LastModifiedDate").asText());
+ return out;
+ }
+
+ private static String entityName(JsonNode entity) {
+ JsonNode details = entity.path("DetailsDocument");
+ for (String field : List.of("ProductTitle", "OfferName", "OfferSetName", "Name", "Title")) {
+ if (details.hasNonNull(field) && !details.path(field).asText().isBlank()) {
+ return details.path(field).asText();
+ }
+ }
+ return entity.path("EntityIdentifier").asText();
+ }
+
+ private JsonNode assessmentSummary(JsonNode assessment) {
+ ObjectNode out = mapper.createObjectNode();
+ for (String field : List.of("AssessmentArn", "AssessmentId", "FrameworkId",
+ "AssessmentResult", "CreatedAt", "ExpiresAt")) {
+ if (assessment.has(field)) {
+ out.set(field, assessment.get(field));
+ }
+ }
+ return out;
+ }
+
+ private ObjectNode page(String name, List<JsonNode> values, JsonNode request,
+ int defaultSize, int min, int max) {
+ int size = request.path("MaxResults").isInt() ? request.path("MaxResults").asInt() : defaultSize;
+ if (size < min || size > max) {
+ throw validation("MaxResults is out of range.");
+ }
+ int offset = decodeToken(request.path("NextToken").asText(null));
+ if (offset > values.size()) {
+ throw validation("NextToken is invalid.");
+ }
+ int end = Math.min(values.size(), offset + size);
+ ObjectNode out = mapper.createObjectNode();
+ ArrayNode array = out.putArray(name);
+ values.subList(offset, end).forEach(value -> array.add(value.deepCopy()));
+ if (end < values.size()) {
+ out.put("NextToken", Integer.toString(end));
+ }
+ return out;
+ }
+
+ private static int decodeToken(String token) {
+ if (token == null || token.isBlank()) {
+ return 0;
+ }
+ try {
+ int value = Integer.parseInt(token);
+ if (value < 0) {
+ throw new NumberFormatException();
+ }
+ return value;
+ } catch (NumberFormatException e) {
+ throw validation("NextToken is invalid.");
+ }
+ }
+
+ private ObjectNode errorDetail(String code, String message) {
+ return mapper.createObjectNode().put("ErrorCode", code).put("ErrorMessage", message);
+ }
+
+ private void ensureResource(String arn) {
+ boolean exists = entities.scan(key -> true).stream()
+ .anyMatch(entity -> arn.equals(entity.path("EntityArn").asText()))
+ || changeSets.scan(key -> true).stream()
+ .anyMatch(changeSet -> arn.equals(changeSet.path("ChangeSetArn").asText()));
+ if (!exists) {
+ throw notFound("Resource", arn);
+ }
+ }
+
+ private static ArrayNode requireArray(JsonNode node, String field) {
+ JsonNode value = node == null ? null : node.get(field);
+ if (value == null || !value.isArray()) {
+ throw validation(field + " is required and must be an array.");
+ }
+ return (ArrayNode) value;
+ }
+
+ private static String text(JsonNode node, String field, boolean required) {
+ JsonNode value = node == null ? null : node.get(field);
+ if (value == null || value.isNull() || !value.isTextual() || value.asText().isBlank()) {
+ if (required) {
+ throw validation(field + " is required.");
+ }
+ return null;
+ }
+ return value.asText();
+ }
+
+ private static void requireCatalog(String catalog) {
+ if (catalog == null || catalog.isBlank()) {
+ throw validation("Catalog is required.");
+ }
+ if (!CATALOG.equals(catalog)) {
+ throw validation("Catalog must be AWSMarketplace.");
+ }
+ }
+
+ private static void validateRegion(String region) {
+ if (!REGION.equals(region)) {
+ throw validation("AWS Marketplace Catalog API is available only in us-east-1.");
+ }
+ }
+
+ private static void ensureStoredRegion(JsonNode changeSet, String region) {
+ if (!region.equals(changeSet.path("_Region").asText(REGION))) {
+ throw notFound("Change set", changeSet.path("ChangeSetId").asText());
+ }
+ }
+
+ private static String baseEntityType(String type) {
+ int version = type.indexOf('@');
+ return version < 0 ? type : type.substring(0, version);
+ }
+
+ private static String idForType(String type) {
+ String prefix = type.toLowerCase(Locale.ROOT).contains("offer") ? "offer-" : "prod-";
+ return prefix + compactId();
+ }
+
+ private static String arnEntityType(String type) {
+ return baseEntityType(type);
+ }
+
+ private static String compactId() {
+ return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
+ }
+
+ private String arn(String region, String resource) {
+ return "arn:aws:aws-marketplace:" + region + ":" + accountId() + ":" + resource;
+ }
+
+ private String accountId() {
+ return requestContext == null || requestContext.getAccountId() == null
+ ? "000000000000" : requestContext.getAccountId();
+ }
+
+ private static List<JsonNode> toList(JsonNode array) {
+ List<JsonNode> values = new ArrayList<>();
+ array.forEach(values::add);
+ return values;
+ }
+
+ private static AwsException validation(String message) {
+ return new AwsException("ValidationException", message, 422);
+ }
+
+ private static AwsException notFound(String kind, String id) {
+ return new AwsException("ResourceNotFoundException", kind + " " + id + " was not found.", 404);
+ }
+
+ @Override
+ public void clear() {
+ entities.clear();
+ changeSets.clear();
+ resourcePolicies.clear();
+ tags.clear();
+ assessments.clear();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/marketplace/model/MarketplaceChangeSetRequest.java b/src/main/java/io/github/hectorvent/floci/services/marketplace/model/MarketplaceChangeSetRequest.java
new file mode 100644
index 0000000000..258bcc6c30
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/marketplace/model/MarketplaceChangeSetRequest.java
@@ -0,0 +1,14 @@
+package io.github.hectorvent.floci.services.marketplace.model;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+/** Immutable snapshot used to validate StartChangeSet idempotent retries. */
+public record MarketplaceChangeSetRequest(String clientRequestToken, JsonNode payload) {
+ public MarketplaceChangeSetRequest {
+ payload = payload == null ? null : payload.deepCopy();
+ }
+
+ public boolean matches(JsonNode other) {
+ return payload != null && payload.equals(other);
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 819f3deb86..640e80ca7d 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -707,3 +707,5 @@ floci:
enabled: true
codegurureviewer:
enabled: true
+ marketplace:
+ enabled: true
diff --git a/src/test/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogControllerIntegrationTest.java
new file mode 100644
index 0000000000..ef7acc1931
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogControllerIntegrationTest.java
@@ -0,0 +1,88 @@
+package io.github.hectorvent.floci.services.marketplace;
+
+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.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
+
+@QuarkusTest
+class MarketplaceCatalogControllerIntegrationTest {
+ @BeforeAll
+ static void configure() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void changeSetCreatesAndDescribesEntity() {
+ String body = "{\"Catalog\":\"AWSMarketplace\",\"ChangeSet\":[{\"ChangeType\":\"CreateProduct\",\"Entity\":{\"Type\":\"[email protected]\",\"Identifier\":\"@1\"},\"DetailsDocument\":{\"ProductTitle\":\"Local product\"}}]}";
+ String id = given().contentType("application/json").header("Authorization", auth())
+ .body(body).post("/StartChangeSet").then().statusCode(200)
+ .body("ChangeSetId", notNullValue())
+ .body("ChangeSetArn", containsString(":000000000000:AWSMarketplace/ChangeSet/"))
+ .extract().path("ChangeSetId");
+ var described = given().header("Authorization", auth())
+ .get("/DescribeChangeSet?catalog=AWSMarketplace&changeSetId=" + id)
+ .then().statusCode(200).body("Status", equalTo("SUCCEEDED")).extract().response();
+ String entityId = described.path("ChangeSet[0].Entity.Identifier");
+ given().header("Authorization", auth())
+ .get("/DescribeEntity?catalog=AWSMarketplace&entityId=" + entityId)
+ .then().statusCode(200)
+ .body("EntityIdentifier", equalTo(entityId))
+ .body("EntityArn", containsString(":000000000000:AWSMarketplace/SaaSProduct/"))
+ .body("DetailsDocument.ProductTitle", equalTo("Local product"));
+ }
+
+ @Test
+ void cancelAndValidationMatchAwsErrorShapes() {
+ String id = given().contentType("application/json").header("Authorization", auth())
+ .body("{\"Catalog\":\"AWSMarketplace\",\"ChangeSet\":[{\"ChangeType\":\"CreateOffer\",\"Entity\":{\"Type\":\"[email protected]\",\"Identifier\":\"@1\"},\"DetailsDocument\":{}}]}")
+ .post("/StartChangeSet").then().statusCode(200).extract().path("ChangeSetId");
+ given().header("Authorization", auth())
+ .patch("/CancelChangeSet?catalog=AWSMarketplace&changeSetId=" + id)
+ .then().statusCode(200).body("ChangeSetId", equalTo(id));
+ given().contentType("application/json").header("Authorization", auth()).body("{}")
+ .post("/ListEntities").then().statusCode(422)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void rejectsUnsupportedChangeTypeBeforeMutatingCatalogState() {
+ given().contentType("application/json").header("Authorization", auth())
+ .body("{\"Catalog\":\"AWSMarketplace\",\"ChangeSet\":[{\"ChangeType\":\"CreatProduct\",\"Entity\":{\"Type\":\"[email protected]\"},\"DetailsDocument\":{}}]}")
+ .post("/StartChangeSet").then().statusCode(422)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void tagsAndPoliciesPersistOnEntity() {
+ String cs = given().contentType("application/json").header("Authorization", auth())
+ .body("{\"Catalog\":\"AWSMarketplace\",\"ChangeSet\":[{\"ChangeType\":\"CreateProduct\",\"Entity\":{\"Type\":\"[email protected]\",\"Identifier\":\"@1\"},\"DetailsDocument\":{}}]}")
+ .post("/StartChangeSet").then().statusCode(200).extract().path("ChangeSetId");
+ var response = given().header("Authorization", auth())
+ .get("/DescribeChangeSet?catalog=AWSMarketplace&changeSetId=" + cs)
+ .then().extract().response();
+ String arn = response.path("ChangeSet[0].EntityArn");
+ given().contentType("application/json").header("Authorization", auth())
+ .body("{\"ResourceArn\":\"" + arn + "\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"test\"}]}")
+ .post("/TagResource").then().statusCode(200);
+ given().contentType("application/json").header("Authorization", auth())
+ .body("{\"ResourceArn\":\"" + arn + "\"}")
+ .post("/ListTagsForResource").then().statusCode(200)
+ .body("Tags[0].Key", equalTo("env"));
+ given().contentType("application/json").header("Authorization", auth())
+ .body("{\"ResourceArn\":\"" + arn + "\",\"Policy\":\"{\\\"Version\\\":\\\"2012-10-17\\\"}\"}")
+ .post("/PutResourcePolicy").then().statusCode(200);
+ given().header("Authorization", auth())
+ .get("/GetResourcePolicy?resourceArn=" + arn).then().statusCode(200)
+ .body("Policy", containsString("2012-10-17"));
+ }
+
+ private static String auth() {
+ return "AWS4-HMAC-SHA256 Credential=000000000000/20260908/us-east-1/aws-marketplace/aws4_request";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/marketplace/MarketplaceServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/marketplace/MarketplaceServiceTest.java
new file mode 100644
index 0000000000..def79bc71a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/marketplace/MarketplaceServiceTest.java
@@ -0,0 +1,102 @@
+package io.github.hectorvent.floci.services.marketplace;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class MarketplaceServiceTest {
+ private final ObjectMapper mapper = new ObjectMapper();
+ private MarketplaceService service;
+
+ @BeforeEach
+ void setUp() {
+ service = new MarketplaceService(
+ mapper,
+ AccountAwareStorageBackend.inMemory("000000000000"),
+ AccountAwareStorageBackend.inMemory("000000000000"),
+ AccountAwareStorageBackend.inMemory("000000000000"),
+ AccountAwareStorageBackend.inMemory("000000000000"),
+ AccountAwareStorageBackend.inMemory("000000000000"),
+ null);
+ }
+
+ @Test
+ void startChangeSetRejectsUnsupportedRegion() throws Exception {
+ JsonNode request = mapper.readTree("""
+ {"Catalog":"AWSMarketplace","ChangeSet":[{"ChangeType":"CreateProduct",
+ "Entity":{"Type":"[email protected]","Identifier":"@1"},"DetailsDocument":{}}]}
+ """);
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.startChangeSet(request, "us-west-2"));
+ assertEquals("ValidationException", error.getErrorCode());
+ }
+
+ @Test
+ void idempotentRetryRequiresSameParameters() throws Exception {
+ JsonNode first = mapper.readTree("""
+ {"Catalog":"AWSMarketplace","ClientRequestToken":"token-1",
+ "ChangeSet":[{"ChangeType":"CreateProduct","Entity":{"Type":"[email protected]","Identifier":"@1"},
+ "DetailsDocument":{"ProductTitle":"first"}}]}
+ """);
+ JsonNode different = mapper.readTree("""
+ {"Catalog":"AWSMarketplace","ClientRequestToken":"token-1",
+ "ChangeSet":[{"ChangeType":"CreateProduct","Entity":{"Type":"[email protected]","Identifier":"@1"},
+ "DetailsDocument":{"ProductTitle":"different"}}]}
+ """);
+ String firstId = service.startChangeSet(first, "us-east-1").path("ChangeSetId").asText();
+ assertEquals(firstId, service.startChangeSet(first, "us-east-1").path("ChangeSetId").asText());
+ assertThrows(AwsException.class, () -> service.startChangeSet(different, "us-east-1"));
+ }
+
+ @Test
+ void listEntitiesAppliesIdFilterAndAwsDefaultSort() throws Exception {
+ String first = createProduct("Zeta");
+ String second = createProduct("Alpha");
+ JsonNode filtered = mapper.readTree("""
+ {"Catalog":"AWSMarketplace","EntityType":"SaaSProduct",
+ "FilterList":[{"Name":"EntityId","ValueList":["%s"]}]}
+ """.formatted(first));
+ JsonNode response = service.listEntities(filtered, "us-east-1");
+ assertEquals(1, response.path("EntitySummaryList").size());
+ assertEquals(first, response.path("EntitySummaryList").get(0).path("EntityId").asText());
+ assertNotEquals(first, second);
+ }
+
+ @Test
+ void listChangeSetsAppliesStatusFilter() throws Exception {
+ createProduct("One");
+ JsonNode request = mapper.readTree("""
+ {"Catalog":"AWSMarketplace","FilterList":[{"Name":"Status","ValueList":["SUCCEEDED"]}]}
+ """);
+ JsonNode response = service.listChangeSets(request, "us-east-1");
+ assertTrue(response.path("ChangeSetSummaryList").size() >= 1);
+ assertEquals("SUCCEEDED", response.path("ChangeSetSummaryList").get(0).path("Status").asText());
+ }
+
+ @Test
+ void malformedChangeSetEntryReturnsValidationException() throws Exception {
+ JsonNode request = mapper.readTree("{\"Catalog\":\"AWSMarketplace\",\"ChangeSet\":[\"bad\"]}");
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.startChangeSet(request, "us-east-1"));
+ assertEquals("ValidationException", error.getErrorCode());
+ }
+
+ private String createProduct(String title) throws Exception {
+ JsonNode request = mapper.readTree("""
+ {"Catalog":"AWSMarketplace","ChangeSet":[{"ChangeType":"CreateProduct",
+ "Entity":{"Type":"[email protected]","Identifier":"@1"},
+ "DetailsDocument":{"ProductTitle":"%s"}}]}
+ """.formatted(title));
+ String changeSetId = service.startChangeSet(request, "us-east-1").path("ChangeSetId").asText();
+ return service.describeChangeSet("AWSMarketplace", changeSetId, "us-east-1")
+ .path("ChangeSet").get(0).path("Entity").path("Identifier").asText();
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index ec1602ce13..4a4bf678d8 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -439,3 +439,5 @@ floci:
enabled: true
codegurureviewer:
enabled: true
+ marketplace:
+ enabled: true
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index b6474707e7..c764da98c9 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -81,6 +81,10 @@ services:
- TagResourceByBody
- TagResourcePut
- UntagResourceByQuery
+ - service: marketplace
+ doc: docs/services/marketplace.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogController.java, mode: rest }
- service: comprehend
doc: docs/services/comprehend.md
sources: