mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(marketplace-deployment): emulate AWS Marketplace Deployment API (#3341)
This commit is contained in:
1 parent
debf9fb0dc
commit
48d2928061
12 files changed
+688
-1
No files matched your search
@@ -297,6 +297,11 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>marketplaceentitlement</artifactId>
|
||||
</dependency>
|
||||
<!-- AWS Marketplace Deployment client -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>marketplacedeployment</artifactId>
|
||||
</dependency>
|
||||
<!-- IAM Access Analyzer client -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
|
||||
@@ -44,6 +44,7 @@ import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClie
|
||||
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
|
||||
import software.amazon.awssdk.services.marketplaceentitlement.MarketplaceEntitlementClient;
|
||||
import software.amazon.awssdk.services.verifiedpermissions.VerifiedPermissionsClient;
|
||||
import software.amazon.awssdk.services.marketplacedeployment.MarketplaceDeploymentClient;
|
||||
import software.amazon.awssdk.services.inspector2.Inspector2Client;
|
||||
import software.amazon.awssdk.services.securityhub.SecurityHubClient;
|
||||
import software.amazon.awssdk.services.detective.DetectiveClient;
|
||||
@@ -455,6 +456,14 @@ public final class TestFixtures {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static MarketplaceDeploymentClient marketplaceDeploymentClient() {
|
||||
return MarketplaceDeploymentClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static DetectiveClient detectiveClient(String accountId) {
|
||||
return DetectiveClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.marketplacedeployment.MarketplaceDeploymentClient;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class MarketplaceDeploymentTest {
|
||||
|
||||
@Test
|
||||
void usesAwsSdkWireContract() {
|
||||
try (MarketplaceDeploymentClient client = TestFixtures.marketplaceDeploymentClient()) {
|
||||
var response = client.putDeploymentParameter(r -> r
|
||||
.catalog("AWSMarketplace")
|
||||
.productId("prod-sdk-compat")
|
||||
.agreementId("agr-sdk-compat")
|
||||
.deploymentParameter(p -> p.name("ApiKey").secretString("local-secret"))
|
||||
.tags(java.util.Map.of("suite", "sdk-compat")));
|
||||
assertNotNull(response.deploymentParameterId());
|
||||
assertNotNull(response.resourceArn());
|
||||
assertEquals("sdk-compat", response.tags().get("suite"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,7 @@ Floci emulates AWS Marketplace APIs under the shared `aws-marketplace` SigV4 sig
|
||||
| `SendAgreementPaymentRequest` | Sends an agreement payment request |
|
||||
| `UpdatePurchaseOrders` | Updates purchase orders for an agreement |
|
||||
| `GetEntitlements` | - |
|
||||
| `PutDeploymentParameter` | Creates or updates an AWS Marketplace deployment parameter |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
## Marketplace Catalog
|
||||
@@ -68,6 +69,12 @@ Agreement request acceptance persists the resulting agreement and exposes it thr
|
||||
AWS exposes this service as read-only: `GetEntitlements` is the only public operation. Floci therefore does not add a non-AWS mutation endpoint. Entitlement records are loaded from the shared `StorageFactory` backend (`marketplace-entitlements.json` in persistent mode), so tests and local environments can pre-seed AWS-shaped entitlement state while preserving account isolation.
|
||||
|
||||
|
||||
## Marketplace Deployment
|
||||
|
||||
Deployment parameters and idempotency records are persisted through `StorageFactory` and isolated by AWS account.
|
||||
|
||||
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
@@ -52,6 +52,7 @@ 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 io.github.hectorvent.floci.services.marketplace.MarketplaceDeploymentController;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -657,7 +658,7 @@ public class ResolvedServiceCatalog {
|
||||
"marketplace", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON, ServiceProtocol.JSON, ServiceProtocol.CBOR),
|
||||
Set.of("AWSMPCommerceService_v20200301.", "AWSMPEntitlementService."), Set.of("aws-marketplace"), Set.of("AWS Marketplace Entitlement Service"),
|
||||
Set.of(MarketplaceCatalogController.class))
|
||||
Set.of(MarketplaceCatalogController.class, MarketplaceDeploymentController.class))
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
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.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class MarketplaceDeploymentController {
|
||||
private final MarketplaceDeploymentService service;
|
||||
private final ObjectReader strictReader;
|
||||
private final RequestContext requestContext;
|
||||
|
||||
@Inject
|
||||
public MarketplaceDeploymentController(MarketplaceDeploymentService service, ObjectMapper mapper,
|
||||
RequestContext requestContext) {
|
||||
this.service = service;
|
||||
this.strictReader = mapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
this.requestContext = requestContext;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/catalogs/{catalog}/products/{productId}/deployment-parameters")
|
||||
public Response putDeploymentParameter(@PathParam("catalog") String catalog,
|
||||
@PathParam("productId") String productId,
|
||||
String body) {
|
||||
return Response.ok(service.putDeploymentParameter(
|
||||
catalog, productId, parse(body), region(), accountId())).build();
|
||||
}
|
||||
|
||||
private JsonNode parse(String body) {
|
||||
try {
|
||||
JsonNode request = strictReader.readTree(body == null || body.isBlank() ? "{}" : body);
|
||||
if (request == null || !request.isObject()) {
|
||||
throw validation("Request body must be a JSON object.");
|
||||
}
|
||||
return request;
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw validation("Request body is not valid JSON.");
|
||||
}
|
||||
}
|
||||
|
||||
private String region() {
|
||||
return requestContext.getRegion() == null ? "us-east-1" : requestContext.getRegion();
|
||||
}
|
||||
|
||||
private String accountId() {
|
||||
return requestContext.getAccountId() == null ? "000000000000" : requestContext.getAccountId();
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
}
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
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.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.MarketplaceDeploymentParameter;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class MarketplaceDeploymentService implements Resettable {
|
||||
private static final String CATALOG = "AWSMarketplace";
|
||||
private static final Pattern PRODUCT_ID = Pattern.compile("[A-Za-z0-9_/-]{1,64}");
|
||||
private static final Pattern AGREEMENT_ID = Pattern.compile("[A-Za-z0-9_/-]{1,64}");
|
||||
private static final Pattern CLIENT_TOKEN = Pattern.compile("[a-zA-Z0-9/_+=.:@-]{32,64}");
|
||||
private static final Pattern PARAMETER_NAME = Pattern.compile("[a-zA-Z0-9/_+=.@-]{1,400}");
|
||||
private static final Pattern TAG_KEY = Pattern.compile("[a-zA-Z0-9/_+=.:@-]{1,128}");
|
||||
private static final Pattern TAG_VALUE = Pattern.compile("[a-zA-Z0-9/_+=.:@-]{1,256}");
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
private final AccountAwareStorageBackend<JsonNode> parameters;
|
||||
private final AccountAwareStorageBackend<JsonNode> idempotency;
|
||||
|
||||
@Inject
|
||||
public MarketplaceDeploymentService(StorageFactory factory, ObjectMapper mapper) {
|
||||
this(mapper,
|
||||
factory.create("marketplace", "marketplace-deployment-parameters.json", type()),
|
||||
factory.create("marketplace", "marketplace-deployment-idempotency.json", type()));
|
||||
}
|
||||
|
||||
MarketplaceDeploymentService(ObjectMapper mapper,
|
||||
AccountAwareStorageBackend<JsonNode> parameters,
|
||||
AccountAwareStorageBackend<JsonNode> idempotency) {
|
||||
this.mapper = mapper;
|
||||
this.parameters = parameters;
|
||||
this.idempotency = idempotency;
|
||||
}
|
||||
|
||||
private static TypeReference<Map<String, JsonNode>> type() {
|
||||
return new TypeReference<>() {};
|
||||
}
|
||||
|
||||
public synchronized ObjectNode putDeploymentParameter(String catalog, String productId,
|
||||
JsonNode request, String region, String accountId) {
|
||||
validateRegion(region);
|
||||
validateCatalog(catalog);
|
||||
if (productId == null || !PRODUCT_ID.matcher(productId).matches()) {
|
||||
throw validation("productId must match [A-Za-z0-9_/-]+ and be at most 64 characters.");
|
||||
}
|
||||
String agreementId = requireText(request, "agreementId", 1, 64);
|
||||
if (!AGREEMENT_ID.matcher(agreementId).matches()) {
|
||||
throw validation("agreementId contains unsupported characters.");
|
||||
}
|
||||
JsonNode input = request.get("deploymentParameter");
|
||||
if (input == null || !input.isObject()) {
|
||||
throw validation("deploymentParameter is required.");
|
||||
}
|
||||
String name = requireText(input, "name", 1, 400);
|
||||
if (!PARAMETER_NAME.matcher(name).matches()) {
|
||||
throw validation("deploymentParameter.name contains unsupported characters.");
|
||||
}
|
||||
String secret = requireText(input, "secretString", 1, 15000);
|
||||
String clientToken = optionalText(request, "clientToken");
|
||||
if (clientToken != null && !CLIENT_TOKEN.matcher(clientToken).matches()) {
|
||||
throw validation("clientToken must be 32 to 64 characters and match the AWS Marketplace token pattern.");
|
||||
}
|
||||
Instant expiration = parseExpiration(request.get("expirationDate"));
|
||||
Map<String, String> requestedTags = parseTags(request.get("tags"));
|
||||
MarketplaceDeploymentParameter parameter = new MarketplaceDeploymentParameter(
|
||||
catalog, productId, agreementId, name, secret, expiration, requestedTags);
|
||||
|
||||
String logicalKey = parameter.catalog() + "/" + parameter.productId() + "/"
|
||||
+ parameter.agreementId() + "/" + parameter.name();
|
||||
if (clientToken != null) {
|
||||
JsonNode replay = idempotency.get(clientToken).orElse(null);
|
||||
if (replay != null) {
|
||||
if (!logicalKey.equals(replay.path("logicalKey").asText())
|
||||
|| !replay.path("request").equals(request)) {
|
||||
throw new AwsException("ConflictException",
|
||||
"clientToken was already used with different request parameters.", 409);
|
||||
}
|
||||
ObjectNode current = parameters.get(logicalKey)
|
||||
.filter(JsonNode::isObject)
|
||||
.map(value -> (ObjectNode) value.deepCopy())
|
||||
.orElse(null);
|
||||
String replayId = replay.path("response").path("deploymentParameterId").asText();
|
||||
if (current != null && !isExpired(current)
|
||||
&& replayId.equals(current.path("deploymentParameterId").asText())) {
|
||||
return response((ObjectNode) replay.path("response").deepCopy());
|
||||
}
|
||||
if (current != null && isExpired(current)) {
|
||||
parameters.delete(logicalKey);
|
||||
}
|
||||
idempotency.delete(clientToken);
|
||||
}
|
||||
}
|
||||
|
||||
ObjectNode existing = parameters.get(logicalKey)
|
||||
.filter(JsonNode::isObject)
|
||||
.map(value -> (ObjectNode) value.deepCopy())
|
||||
.orElse(null);
|
||||
if (existing != null && isExpired(existing)) {
|
||||
parameters.delete(logicalKey);
|
||||
existing = null;
|
||||
}
|
||||
boolean create = existing == null;
|
||||
ObjectNode record = create ? mapper.createObjectNode() : existing;
|
||||
String id = create ? "dp-" + compactId() : record.path("deploymentParameterId").asText();
|
||||
String arn = create
|
||||
? "arn:aws:aws-marketplace:" + region + ":" + accountId
|
||||
+ ":DeploymentParameter:catalogs/" + catalog + "/products/" + productId + "/" + id
|
||||
: record.path("resourceArn").asText();
|
||||
|
||||
record.put("catalog", parameter.catalog());
|
||||
record.put("productId", parameter.productId());
|
||||
record.put("agreementId", parameter.agreementId());
|
||||
record.put("deploymentParameterId", id);
|
||||
record.put("resourceArn", arn);
|
||||
record.put("name", parameter.name());
|
||||
record.put("secretString", parameter.secretString());
|
||||
record.put("updatedAt", Instant.now().toString());
|
||||
if (parameter.expirationDate() != null) {
|
||||
record.put("expirationDate", parameter.expirationDate().toString());
|
||||
} else {
|
||||
record.remove("expirationDate");
|
||||
}
|
||||
if (create) {
|
||||
record.set("tags", tagsNode(parameter.tags()));
|
||||
record.put("createdAt", Instant.now().toString());
|
||||
}
|
||||
parameters.put(logicalKey, record);
|
||||
|
||||
ObjectNode output = response(record);
|
||||
if (clientToken != null) {
|
||||
ObjectNode replay = mapper.createObjectNode();
|
||||
replay.put("logicalKey", logicalKey);
|
||||
replay.set("request", request.deepCopy());
|
||||
replay.set("response", output.deepCopy());
|
||||
idempotency.put(clientToken, replay);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public ObjectNode listTagsForResource(String resourceArn, String region) {
|
||||
validateRegion(region);
|
||||
ObjectNode record = requireByArn(resourceArn);
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
response.set("tags", record.path("tags").deepCopy());
|
||||
return response;
|
||||
}
|
||||
|
||||
public synchronized void tagResource(String resourceArn, JsonNode request, String region) {
|
||||
validateRegion(region);
|
||||
ObjectNode record = requireByArn(resourceArn);
|
||||
Map<String, String> merged = tagsMap(record.path("tags"));
|
||||
merged.putAll(parseTags(request.get("tags")));
|
||||
if (merged.size() > 50) {
|
||||
throw validation("A deployment parameter can have at most 50 tags.");
|
||||
}
|
||||
record.set("tags", tagsNode(merged));
|
||||
saveRecord(record);
|
||||
}
|
||||
|
||||
public synchronized void untagResource(String resourceArn, java.util.List<String> tagKeys, String region) {
|
||||
validateRegion(region);
|
||||
ObjectNode record = requireByArn(resourceArn);
|
||||
if (tagKeys == null || tagKeys.isEmpty()) {
|
||||
throw validation("tagKeys is required.");
|
||||
}
|
||||
Map<String, String> existing = tagsMap(record.path("tags"));
|
||||
for (String key : tagKeys) {
|
||||
if (key == null || key.isBlank()) {
|
||||
throw validation("tagKeys entries must be non-empty strings.");
|
||||
}
|
||||
existing.remove(key);
|
||||
}
|
||||
record.set("tags", tagsNode(existing));
|
||||
saveRecord(record);
|
||||
}
|
||||
|
||||
private ObjectNode requireByArn(String resourceArn) {
|
||||
if (resourceArn == null || resourceArn.isBlank()) {
|
||||
throw validation("resourceArn is required.");
|
||||
}
|
||||
for (JsonNode value : parameters.scan(key -> true)) {
|
||||
if (resourceArn.equals(value.path("resourceArn").asText())) {
|
||||
ObjectNode record = (ObjectNode) value.deepCopy();
|
||||
if (isExpired(record)) {
|
||||
throw notFound(resourceArn);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
}
|
||||
throw notFound(resourceArn);
|
||||
}
|
||||
|
||||
private void saveRecord(ObjectNode record) {
|
||||
String key = record.path("catalog").asText() + "/" + record.path("productId").asText()
|
||||
+ "/" + record.path("agreementId").asText() + "/" + record.path("name").asText();
|
||||
record.put("updatedAt", Instant.now().toString());
|
||||
parameters.put(key, record);
|
||||
}
|
||||
|
||||
private boolean isExpired(JsonNode record) {
|
||||
String value = record.path("expirationDate").asText(null);
|
||||
return value != null && Instant.parse(value).isBefore(Instant.now());
|
||||
}
|
||||
|
||||
private ObjectNode response(ObjectNode record) {
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
out.put("agreementId", record.path("agreementId").asText());
|
||||
out.put("deploymentParameterId", record.path("deploymentParameterId").asText());
|
||||
out.put("resourceArn", record.path("resourceArn").asText());
|
||||
out.set("tags", record.path("tags").deepCopy());
|
||||
return out;
|
||||
}
|
||||
|
||||
private Map<String, String> parseTags(JsonNode value) {
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
if (value == null || value.isNull()) {
|
||||
return result;
|
||||
}
|
||||
if (!value.isObject()) {
|
||||
throw validation("tags must be an object.");
|
||||
}
|
||||
if (value.size() > 50) {
|
||||
throw validation("tags can contain at most 50 entries.");
|
||||
}
|
||||
value.fields().forEachRemaining(entry -> {
|
||||
if (!TAG_KEY.matcher(entry.getKey()).matches()) {
|
||||
throw validation("Tag key contains unsupported characters or length.");
|
||||
}
|
||||
if (!entry.getValue().isTextual() || !TAG_VALUE.matcher(entry.getValue().asText()).matches()) {
|
||||
throw validation("Tag value contains unsupported characters or length.");
|
||||
}
|
||||
result.put(entry.getKey(), entry.getValue().asText());
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private ObjectNode tagsNode(Map<String, String> values) {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
values.forEach(node::put);
|
||||
return node;
|
||||
}
|
||||
|
||||
private static Map<String, String> tagsMap(JsonNode node) {
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
if (node != null && node.isObject()) {
|
||||
node.fields().forEachRemaining(entry -> result.put(entry.getKey(), entry.getValue().asText()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Instant parseExpiration(JsonNode value) {
|
||||
if (value == null || value.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (value.isNumber()) {
|
||||
double seconds = value.asDouble();
|
||||
long millis = Math.round(seconds * 1000.0d);
|
||||
return Instant.ofEpochMilli(millis);
|
||||
}
|
||||
if (value.isTextual()) {
|
||||
try {
|
||||
return Instant.parse(value.asText());
|
||||
} catch (DateTimeParseException e) {
|
||||
throw validation("expirationDate must be a valid timestamp.");
|
||||
}
|
||||
}
|
||||
throw validation("expirationDate must be a valid timestamp.");
|
||||
}
|
||||
|
||||
private static String requireText(JsonNode node, String field, int min, int max) {
|
||||
String value = optionalText(node, field);
|
||||
if (value == null) {
|
||||
throw validation(field + " is required.");
|
||||
}
|
||||
if (value.length() < min || value.length() > max) {
|
||||
throw validation(field + " must be between " + min + " and " + max + " characters.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String optionalText(JsonNode node, String field) {
|
||||
JsonNode value = node == null ? null : node.get(field);
|
||||
if (value == null || value.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!value.isTextual() || value.asText().isBlank()) {
|
||||
throw validation(field + " must be a non-empty string.");
|
||||
}
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
private static void validateRegion(String region) {
|
||||
if (region != null && !region.isBlank() && !"us-east-1".equals(region)) {
|
||||
throw validation("AWS Marketplace Deployment Service is available only in us-east-1.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateCatalog(String catalog) {
|
||||
if (!CATALOG.equals(catalog)) {
|
||||
throw validation("catalog must be AWSMarketplace.");
|
||||
}
|
||||
}
|
||||
|
||||
private static String compactId() {
|
||||
return UUID.randomUUID().toString().replace("-", "").substring(0, 20);
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException notFound(String resourceArn) {
|
||||
return new AwsException("ResourceNotFoundException",
|
||||
"Deployment parameter " + resourceArn + " was not found.", 404);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
parameters.clear();
|
||||
idempotency.clear();
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.services.marketplace;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.TagHandler;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Routes AWS Marketplace Deployment's shared /tags/{resourceArn} endpoints. */
|
||||
@ApplicationScoped
|
||||
public class MarketplaceDeploymentTagHandler implements TagHandler {
|
||||
|
||||
private final MarketplaceDeploymentService service;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public MarketplaceDeploymentTagHandler(MarketplaceDeploymentService service, ObjectMapper mapper) {
|
||||
this.service = service;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serviceKey() {
|
||||
return "aws-marketplace";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictTagValidation() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> listTags(String region, String arn) {
|
||||
JsonNode tags = service.listTagsForResource(arn, region).path("tags");
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
tags.fields().forEachRemaining(entry -> result.put(entry.getKey(), entry.getValue().asText()));
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tagResource(String region, String arn, Map<String, String> tags) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
ObjectNode tagNode = request.putObject("tags");
|
||||
tags.forEach(tagNode::put);
|
||||
service.tagResource(arn, request, region);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void untagResource(String region, String arn, List<String> tagKeys) {
|
||||
service.untagResource(arn, tagKeys, region);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package io.github.hectorvent.floci.services.marketplace.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
/** Immutable deployment parameter identity used for local AWS-compatible state. */
|
||||
public record MarketplaceDeploymentParameter(
|
||||
String catalog,
|
||||
String productId,
|
||||
String agreementId,
|
||||
String name,
|
||||
String secretString,
|
||||
Instant expirationDate,
|
||||
Map<String, String> tags) {
|
||||
public MarketplaceDeploymentParameter {
|
||||
tags = tags == null ? Map.of() : Map.copyOf(tags);
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
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.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class MarketplaceDeploymentIntegrationTest {
|
||||
@BeforeAll static void configure() { RestAssuredJsonUtils.configureAwsContentTypes(); }
|
||||
|
||||
@Test
|
||||
void putDeploymentParameterCreatesStableResourceAndTags() {
|
||||
String body = "{\"agreementId\":\"agr-local\",\"clientToken\":\"12345678901234567890123456789012\","
|
||||
+ "\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"local-secret\"},"
|
||||
+ "\"tags\":{\"env\":\"test\"}}";
|
||||
var response = given().contentType("application/json").header("Authorization", auth()).body(body)
|
||||
.post("/catalogs/AWSMarketplace/products/prod-local/deployment-parameters")
|
||||
.then().statusCode(200).body("deploymentParameterId", notNullValue())
|
||||
.body("tags.env", equalTo("test")).extract().response();
|
||||
String arn = response.path("resourceArn");
|
||||
given().urlEncodingEnabled(false).header("Authorization", auth()).get("/tags/" + encode(arn)).then().statusCode(200)
|
||||
.body("tags.env", equalTo("test"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putDeploymentParameterUpdatesByNameButKeepsCreateTags() {
|
||||
String first = "{\"agreementId\":\"agr-update\",\"deploymentParameter\":{\"name\":\"ExternalId\",\"secretString\":\"one\"},\"tags\":{\"owner\":\"first\"}}";
|
||||
String id = given().contentType("application/json").header("Authorization", auth()).body(first)
|
||||
.post("/catalogs/AWSMarketplace/products/prod-update/deployment-parameters")
|
||||
.then().statusCode(200).extract().path("deploymentParameterId");
|
||||
String second = "{\"agreementId\":\"agr-update\",\"deploymentParameter\":{\"name\":\"ExternalId\",\"secretString\":\"two\"},\"tags\":{\"owner\":\"ignored\"}}";
|
||||
given().contentType("application/json").header("Authorization", auth()).body(second)
|
||||
.post("/catalogs/AWSMarketplace/products/prod-update/deployment-parameters")
|
||||
.then().statusCode(200).body("deploymentParameterId", equalTo(id)).body("tags.owner", equalTo("first"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putDeploymentParameterRejectsIdentifiersOutsideAwsPatterns() {
|
||||
String invalidAgreement = "{\"agreementId\":\"bad agreement\",\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"secret\"}}";
|
||||
given().contentType("application/json").header("Authorization", auth()).body(invalidAgreement)
|
||||
.post("/catalogs/AWSMarketplace/products/prod-local/deployment-parameters")
|
||||
.then().statusCode(400);
|
||||
|
||||
String invalidToken = "{\"agreementId\":\"agr-local\",\"clientToken\":\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\","
|
||||
+ "\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"secret\"}}";
|
||||
given().contentType("application/json").header("Authorization", auth()).body(invalidToken)
|
||||
.post("/catalogs/AWSMarketplace/products/prod-local/deployment-parameters")
|
||||
.then().statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putDeploymentParameterRejectsUnsupportedRegion() {
|
||||
String body = "{\"agreementId\":\"agr-local\",\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"secret\"}}";
|
||||
given().contentType("application/json").header("Authorization", auth("us-west-2")).body(body)
|
||||
.post("/catalogs/AWSMarketplace/products/prod-local/deployment-parameters")
|
||||
.then().statusCode(400);
|
||||
}
|
||||
|
||||
private static String encode(String value) {
|
||||
return java.net.URLEncoder.encode(value, java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String auth() {
|
||||
return auth("us-east-1");
|
||||
}
|
||||
|
||||
private static String auth(String region) {
|
||||
return "AWS4-HMAC-SHA256 Credential=000000000000/20260908/" + region
|
||||
+ "/aws-marketplace/aws4_request";
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package io.github.hectorvent.floci.services.marketplace;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
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 java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class MarketplaceDeploymentServiceTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private AccountAwareStorageBackend<JsonNode> parameters;
|
||||
private MarketplaceDeploymentService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
parameters = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
service = new MarketplaceDeploymentService(
|
||||
mapper, parameters, AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientTokenRejectsChangedPayload() throws Exception {
|
||||
String token = "12345678901234567890123456789012";
|
||||
JsonNode first = mapper.readTree("{\"agreementId\":\"agr-1\",\"clientToken\":\"" + token
|
||||
+ "\",\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"one\"}}");
|
||||
JsonNode changed = mapper.readTree("{\"agreementId\":\"agr-1\",\"clientToken\":\"" + token
|
||||
+ "\",\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"two\"}}");
|
||||
service.putDeploymentParameter("AWSMarketplace", "prod-1", first, "us-east-1", "000000000000");
|
||||
assertThrows(AwsException.class, () -> service.putDeploymentParameter(
|
||||
"AWSMarketplace", "prod-1", changed, "us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredParameterGetsNewIdentity() throws Exception {
|
||||
JsonNode expired = mapper.readTree("{\"agreementId\":\"agr-1\",\"expirationDate\":"
|
||||
+ (Instant.now().minusSeconds(60).toEpochMilli() / 1000.0)
|
||||
+ ",\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"one\"}}");
|
||||
String oldId = service.putDeploymentParameter("AWSMarketplace", "prod-1", expired,
|
||||
"us-east-1", "000000000000").path("deploymentParameterId").asText();
|
||||
JsonNode fresh = mapper.readTree("{\"agreementId\":\"agr-1\",\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"two\"}}");
|
||||
String newId = service.putDeploymentParameter("AWSMarketplace", "prod-1", fresh,
|
||||
"us-east-1", "000000000000").path("deploymentParameterId").asText();
|
||||
assertNotEquals(oldId, newId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredParameterInvalidatesCachedClientTokenReplay() throws Exception {
|
||||
String token = "12345678901234567890123456789012";
|
||||
JsonNode request = mapper.readTree("{\"agreementId\":\"agr-1\",\"clientToken\":\"" + token
|
||||
+ "\",\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"one\"}}");
|
||||
String oldId = service.putDeploymentParameter("AWSMarketplace", "prod-1", request,
|
||||
"us-east-1", "000000000000").path("deploymentParameterId").asText();
|
||||
|
||||
String key = "AWSMarketplace/prod-1/agr-1/ApiKey";
|
||||
ObjectNode stored = (ObjectNode) parameters.get(key).orElseThrow().deepCopy();
|
||||
stored.put("expirationDate", Instant.now().minusSeconds(60).toString());
|
||||
parameters.put(key, stored);
|
||||
|
||||
String newId = service.putDeploymentParameter("AWSMarketplace", "prod-1", request,
|
||||
"us-east-1", "000000000000").path("deploymentParameterId").asText();
|
||||
|
||||
assertNotEquals(oldId, newId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagOperationsRejectWrongRegion() throws Exception {
|
||||
JsonNode request = mapper.readTree("{\"agreementId\":\"agr-1\",\"deploymentParameter\":{\"name\":\"ApiKey\",\"secretString\":\"one\"}}");
|
||||
String arn = service.putDeploymentParameter("AWSMarketplace", "prod-1", request,
|
||||
"us-east-1", "000000000000").path("resourceArn").asText();
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.listTagsForResource(arn, "us-west-2"));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,7 @@ services:
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogController.java, mode: rest }
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceAgreementService.java, mode: switch }
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceEntitlementController.java, mode: switch }
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDeploymentController.java, mode: rest }
|
||||
exclude_actions:
|
||||
- AgreementType
|
||||
- Status
|
||||
|
||||
Reference in new issue
Block a user