Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cloudhsmv2): implement CloudHSM v2 service (#1776)

NAMAN JAIN1cc97d57c10d
diff --git a/.dockerignore b/.dockerignore
index 01493fb126..214c23b370 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -11,3 +11,5 @@
!target/lib/*
!target/quarkus-app/*
!native/**
+!.mvn/**
+!mvnw
diff --git a/README.md b/README.md
index b3579ab3eb..00bb04db07 100644
--- a/README.md
+++ b/README.md
@@ -226,7 +226,7 @@ Floci supports local emulation for application services, data services, eventing
| Data, analytics, and AI | Athena, Glue, EMR, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Bedrock Runtime |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core |
-| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API |
+| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, CloudHSM v2 |
| Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Backup and config | 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 ac5fafaa2e..50858c1c9e 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -208,6 +208,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>eventbridge</artifactId>
</dependency>
+ <!-- CloudHSM v2 client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>cloudhsmv2</artifactId>
+ </dependency>
<!-- Cloud Map (servicediscovery) client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
@@ -428,6 +433,12 @@
<version>3.25.3</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.bouncycastle</groupId>
+ <artifactId>bcpkix-jdk18on</artifactId>
+ <version>1.84</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
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 ff668516d8..6cd406fa73 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
@@ -4,6 +4,7 @@ import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
+import software.amazon.awssdk.services.cloudhsmv2.CloudHsmV2Client;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudtrail.CloudTrailClient;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
@@ -248,6 +249,14 @@ public final class TestFixtures {
// AWS Client Factories
// ============================================
+ public static CloudHsmV2Client cloudHsmV2Client() {
+ return CloudHsmV2Client.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static SsmClient ssmClient() {
return SsmClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudHsmV2Test.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudHsmV2Test.java
new file mode 100644
index 0000000000..8b039ffe37
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudHsmV2Test.java
@@ -0,0 +1,183 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.cloudhsmv2.CloudHsmV2Client;
+import software.amazon.awssdk.services.cloudhsmv2.model.*;
+
+import java.util.List;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.util.io.pem.PemObject;
+import org.bouncycastle.util.io.pem.PemWriter;
+
+import java.io.StringWriter;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+public class CloudHsmV2Test {
+
+ private final CloudHsmV2Client client = TestFixtures.cloudHsmV2Client();
+
+ @Test
+ public void testFullLifecycle() {
+ // 1. Create Cluster
+ CreateClusterResponse createClusterResponse = client.createCluster(r -> r
+ .hsmType("hsm1.medium")
+ .subnetIds("subnet-1", "subnet-2")
+ .mode(ClusterMode.FIPS)
+ .networkType(NetworkType.IPV4)
+ .backupRetentionPolicy(b -> b.type("DAYS").value("30"))
+ );
+
+ Cluster cluster = createClusterResponse.cluster();
+ assertThat(cluster.clusterId()).startsWith("cluster-");
+ assertThat(cluster.hsmType()).isEqualTo("hsm1.medium");
+ assertThat(cluster.stateAsString()).isEqualTo("UNINITIALIZED");
+ assertThat(cluster.certificates().clusterCsr()).isNotBlank();
+
+ String clusterId = cluster.clusterId();
+
+ // 2. Initialize Cluster
+ DescribeClustersResponse initDescribe = client.describeClusters(r -> r
+ .filters(java.util.Map.of("clusterIds", List.of(clusterId))));
+ String csr = initDescribe.clusters().get(0).certificates().clusterCsr();
+ String[] certs;
+ try { certs = generateCerts(csr); } catch (Exception e) { throw new RuntimeException(e); }
+ String signedCert = certs[0];
+ String trustAnchor = certs[1];
+
+ InitializeClusterResponse initResp = client.initializeCluster(r -> r
+ .clusterId(clusterId)
+ .signedCert(signedCert)
+ .trustAnchor(trustAnchor)
+ );
+
+ assertThat(initResp.stateAsString()).isEqualTo("INITIALIZED");
+
+ // 3. Create HSM
+ CreateHsmResponse hsmResp = client.createHsm(r -> r
+ .clusterId(clusterId)
+ .availabilityZone("us-east-1a")
+ .ipAddress("10.0.1.5")
+ );
+
+ Hsm hsm = hsmResp.hsm();
+ assertThat(hsm.hsmId()).startsWith("hsm-");
+ assertThat(hsm.stateAsString()).isEqualTo("ACTIVE");
+
+ String hsmId = hsm.hsmId();
+
+ // 4. Describe Clusters
+ DescribeClustersResponse descClusters = client.describeClusters(r -> r
+ .filters(java.util.Map.of("clusterIds", List.of(clusterId)))
+ );
+ assertThat(descClusters.clusters()).hasSize(1);
+ assertThat(descClusters.clusters().get(0).stateAsString()).isEqualTo("ACTIVE");
+
+ // 5. Describe Backups (auto-created on CreateHsm/CreateCluster)
+ DescribeBackupsResponse descBackups = client.describeBackups(r -> r
+ .filters(java.util.Map.of("clusterIds", List.of(clusterId)))
+ );
+ assertThat(descBackups.backups()).isNotEmpty();
+ String backupId = descBackups.backups().get(0).backupId();
+
+ // 6. Delete HSM
+ DeleteHsmResponse delHsm = client.deleteHsm(r -> r
+ .clusterId(clusterId)
+ .hsmId(hsmId)
+ );
+ assertThat(delHsm.hsmId()).isEqualTo(hsmId);
+
+ // 7. Delete Cluster
+ DeleteClusterResponse delCluster = client.deleteCluster(r -> r
+ .clusterId(clusterId)
+ );
+ assertThat(delCluster.cluster().stateAsString()).isEqualTo("DELETE_IN_PROGRESS");
+
+ // 8. Delete Backup
+ DeleteBackupResponse delBackup = client.deleteBackup(r -> r
+ .backupId(backupId)
+ );
+ assertThat(delBackup.backup().backupStateAsString()).isEqualTo("PENDING_DELETION");
+ }
+
+ @Test
+ public void testDeleteHsmSelectors() {
+ CreateClusterResponse createClusterResponse = client.createCluster(r -> r
+ .hsmType("hsm1.medium")
+ .subnetIds("subnet-1", "subnet-2")
+ );
+ String clusterId = createClusterResponse.cluster().clusterId();
+ DescribeClustersResponse initDescribe = client.describeClusters(r -> r
+ .filters(java.util.Map.of("clusterIds", List.of(clusterId))));
+ String csr = initDescribe.clusters().get(0).certificates().clusterCsr();
+ String[] certs;
+ try { certs = generateCerts(csr); } catch (Exception e) { throw new RuntimeException(e); }
+ String signedCert = certs[0];
+ String trustAnchor = certs[1];
+
+ client.initializeCluster(r -> r.clusterId(clusterId).signedCert(signedCert).trustAnchor(trustAnchor));
+
+ Hsm hsm = client.createHsm(r -> r.clusterId(clusterId).availabilityZone("us-east-1b")).hsm();
+
+ // Test exactly one selector rule
+ assertThatThrownBy(() -> client.deleteHsm(r -> r
+ .clusterId(clusterId)
+ .hsmId(hsm.hsmId())
+ .eniId(hsm.eniId())
+ )).hasMessageContaining("Exactly one of HsmId, EniId, or EniIp must be specified");
+
+ // Test successful delete with EniId
+ DeleteHsmResponse delResp = client.deleteHsm(r -> r
+ .clusterId(clusterId)
+ .eniId(hsm.eniId())
+ );
+ assertThat(delResp.hsmId()).isEqualTo(hsm.hsmId());
+ }
+
+ private String[] generateCerts(String csrPem) throws Exception {
+ java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
+ java.security.KeyPairGenerator keyGen = java.security.KeyPairGenerator.getInstance("RSA", "BC");
+ keyGen.initialize(2048, new java.security.SecureRandom());
+ java.security.KeyPair caKeyPair = keyGen.generateKeyPair();
+ org.bouncycastle.asn1.x500.X500Name caName = new org.bouncycastle.asn1.x500.X500Name("CN=Floci Test CA");
+ long now = System.currentTimeMillis();
+ java.util.Date startDate = new java.util.Date(now);
+ java.util.Date endDate = new java.util.Date(now + 365L * 24 * 3600 * 1000);
+ java.math.BigInteger serial = java.math.BigInteger.valueOf(now);
+ org.bouncycastle.cert.X509v3CertificateBuilder caBuilder = new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder(
+ caName, serial, startDate, endDate, caName, caKeyPair.getPublic());
+ org.bouncycastle.operator.ContentSigner caSigner = new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256WithRSA")
+ .setProvider("BC").build(caKeyPair.getPrivate());
+ org.bouncycastle.cert.X509CertificateHolder caHolder = caBuilder.build(caSigner);
+ java.io.StringWriter caSw = new java.io.StringWriter();
+ try (org.bouncycastle.openssl.jcajce.JcaPEMWriter pw = new org.bouncycastle.openssl.jcajce.JcaPEMWriter(caSw)) {
+ pw.writeObject(caHolder);
+ }
+ String trustAnchor = caSw.toString();
+ org.bouncycastle.pkcs.PKCS10CertificationRequest csr;
+ try (org.bouncycastle.openssl.PEMParser parser = new org.bouncycastle.openssl.PEMParser(new java.io.StringReader(csrPem))) {
+ csr = (org.bouncycastle.pkcs.PKCS10CertificationRequest) parser.readObject();
+ }
+ java.security.PublicKey csrPublicKey = new org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter().setProvider("BC").getPublicKey(csr.getSubjectPublicKeyInfo());
+ org.bouncycastle.cert.X509v3CertificateBuilder certBuilder = new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder(
+ caName, serial.add(java.math.BigInteger.ONE), startDate, endDate, csr.getSubject(), csrPublicKey);
+ org.bouncycastle.cert.X509CertificateHolder certHolder = certBuilder.build(caSigner);
+ java.io.StringWriter certSw = new java.io.StringWriter();
+ try (org.bouncycastle.openssl.jcajce.JcaPEMWriter pw = new org.bouncycastle.openssl.jcajce.JcaPEMWriter(certSw)) {
+ pw.writeObject(certHolder);
+ }
+ String signedCert = certSw.toString();
+ return new String[]{signedCert, trustAnchor};
+ }
+}
diff --git a/docs/services/cloudhsmv2.md b/docs/services/cloudhsmv2.md
new file mode 100644
index 0000000000..d56bc37af6
--- /dev/null
+++ b/docs/services/cloudhsmv2.md
@@ -0,0 +1,29 @@
+# CloudHSM v2
+
+**Protocol:** JSON 1.1 (`X-Amz-Target: BaldrApiService.*`)
+**Endpoint:** `POST http://localhost:4566/`
+
+## Supported Actions
+
+<!-- floci:actions:start -->
+| Action | Description |
+| --- | --- |
+| `CreateCluster` | Creates a new AWS CloudHSM cluster. |
+| `DescribeClusters` | Gets information about AWS CloudHSM clusters. |
+| `DeleteCluster` | Deletes the specified AWS CloudHSM cluster. |
+| `ModifyCluster` | Modifies AWS CloudHSM cluster. |
+| `InitializeCluster` | Claims an AWS CloudHSM cluster. |
+| `CreateHsm` | Creates a new hardware security module (HSM) in the specified AWS CloudHSM cluster. |
+| `DeleteHsm` | Deletes the specified HSM. |
+| `DescribeBackups` | Gets information about backups of AWS CloudHSM clusters. |
+| `DeleteBackup` | Deletes a specified AWS CloudHSM backup. |
+| `RestoreBackup` | Restores a specified AWS CloudHSM backup. |
+| `ModifyBackupAttributes` | Modifies attributes for AWS CloudHSM backup. |
+| `CopyBackupToRegion` | Copies a specified AWS CloudHSM cluster backup to a different region. |
+| `PutResourcePolicy` | Creates or updates a resource policy for an AWS CloudHSM cluster or backup. |
+| `GetResourcePolicy` | Retrieves the resource policy for an AWS CloudHSM cluster or backup. |
+| `DeleteResourcePolicy` | Deletes a resource policy for an AWS CloudHSM cluster or backup. |
+| `TagResource` | Adds or overwrites tags on the specified AWS CloudHSM cluster or backup. |
+| `UntagResource` | Removes the specified tag or tags from the specified AWS CloudHSM cluster or backup. |
+| `ListTags` | Gets a list of tags for the specified AWS CloudHSM cluster or backup. |
+<!-- floci:actions:end -->
diff --git a/docs/services/index.md b/docs/services/index.md
index 508ffc9812..5244f9e8dc 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -26,6 +26,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 |
| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 43 |
| [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 34 |
+| [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 |
| [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 24 |
| [Managed Service for Apache Flink](kinesisanalytics.md) | `POST /` + `X-Amz-Target: KinesisAnalytics_20180523.*` | JSON 1.1 | 7 |
| [Secrets Manager](secrets-manager.md) | `POST /` + `X-Amz-Target: secretsmanager.*` | JSON 1.1 | 16 |
diff --git a/mkdocs.yml b/mkdocs.yml
index ada249a0ba..f54402bbf5 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -88,6 +88,7 @@ nav:
- API Gateway: services/api-gateway.md
- Cognito: services/cognito.md
- KMS: services/kms.md
+ - CloudHSM v2: services/cloudhsmv2.md
- Kinesis: services/kinesis.md
- Managed Service for Apache Flink: services/kinesisanalytics.md
- Secrets Manager: services/secrets-manager.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 8b4580ea04..43fd50f421 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -608,6 +608,7 @@ public interface EmulatorConfig {
S3TablesServiceConfig s3tables();
IotServiceConfig iot();
IotDataServiceConfig iotdata();
+ CloudHsmV2ServiceConfig cloudhsmv2();
RumServiceConfig rum();
}
@@ -1157,6 +1158,11 @@ public interface EmulatorConfig {
int validationWaitSeconds();
}
+ interface CloudHsmV2ServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface AthenaServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
index 598f0fb018..4f0e470f52 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
import io.github.hectorvent.floci.services.athena.AthenaJsonHandler;
+import io.github.hectorvent.floci.services.cloudhsmv2.CloudHsmV2JsonHandler;
import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler;
import io.github.hectorvent.floci.services.codedeploy.CodeDeployJsonHandler;
import io.github.hectorvent.floci.services.codepipeline.CodePipelineJsonHandler;
@@ -103,6 +104,7 @@ public class AwsJson11Controller {
private final LightsailJsonHandler lightsailJsonHandler;
private final CloudControlJsonHandler cloudControlJsonHandler;
private final ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler;
+ private final CloudHsmV2JsonHandler cloudHsmV2JsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -138,7 +140,8 @@ public class AwsJson11Controller {
CloudTrailJsonHandler cloudTrailJsonHandler,
LightsailJsonHandler lightsailJsonHandler,
CloudControlJsonHandler cloudControlJsonHandler,
- ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler) {
+ ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler,
+ CloudHsmV2JsonHandler cloudHsmV2JsonHandler){
this.objectMapper = objectMapper;
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.catalog = catalog;
@@ -179,6 +182,7 @@ public class AwsJson11Controller {
this.lightsailJsonHandler = lightsailJsonHandler;
this.cloudControlJsonHandler = cloudControlJsonHandler;
this.applicationAutoScalingJsonHandler = applicationAutoScalingJsonHandler;
+ this.cloudHsmV2JsonHandler = cloudHsmV2JsonHandler;
}
@POST
@@ -250,6 +254,7 @@ public class AwsJson11Controller {
case "application-autoscaling" -> applicationAutoScalingJsonHandler.handle(action, request, region);
case "lightsail" -> lightsailJsonHandler.handle(action, request, region);
case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region);
+ case "cloudhsmv2" -> cloudHsmV2JsonHandler.handle(action, request, region);
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
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 08a6888a50..9025f34749 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
@@ -453,6 +453,10 @@ public class ResolvedServiceCatalog {
"iot", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("iotdata"), Set.of(), Set.of(IotDataController.class)),
+ descriptor("cloudhsmv2", "cloudhsmv2", config.services().cloudhsmv2().enabled(), true,
+ "cloudhsmv2", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
+ protocols(ServiceProtocol.JSON),
+ Set.of("BaldrApiService."), Set.of("cloudhsm"), Set.of(), Set.of()),
descriptor("rum", "rum", config.services().rum().enabled(), true,
"rum", storageMode(config.storage().services().rum().mode(), config.storage().mode()),
config.storage().services().rum().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java
new file mode 100644
index 0000000000..f7dfcef482
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java
@@ -0,0 +1,606 @@
+package io.github.hectorvent.floci.services.cloudhsmv2;
+
+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.AwsErrorResponse;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.Certificates;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.Cluster;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.Hsm;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.Backup;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.BackupRetentionPolicy;
+import java.util.stream.Collectors;
+
+
+/**
+ * CloudHSM v2 JSON 1.1 handler. Dispatched from
+ * {@link io.github.hectorvent.floci.core.common.AwsJson11Controller}
+ * under the {@code BaldrApiService.} target prefix.
+ */
+@ApplicationScoped
+public class CloudHsmV2JsonHandler {
+
+ private static final Logger LOG = Logger.getLogger(CloudHsmV2JsonHandler.class);
+
+ private final CloudHsmV2Service service;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public CloudHsmV2JsonHandler(CloudHsmV2Service service, ObjectMapper objectMapper) {
+ this.service = service;
+ this.objectMapper = objectMapper;
+ }
+
+ public Response handle(String action, JsonNode request, String region) {
+ LOG.debugv("CloudHSM v2 action: {0}", action);
+ try {
+ return switch (action) {
+ case "CreateCluster" -> handleCreateCluster(request, region);
+ case "DescribeClusters" -> handleDescribeClusters(request, region);
+ case "DeleteCluster" -> handleDeleteCluster(request, region);
+ case "ModifyCluster" -> handleModifyCluster(request, region);
+ case "InitializeCluster" -> handleInitializeCluster(request, region);
+ case "CreateHsm" -> handleCreateHsm(request, region);
+ case "DeleteHsm" -> handleDeleteHsm(request, region);
+ case "DescribeBackups" -> handleDescribeBackups(request, region);
+ case "DeleteBackup" -> handleDeleteBackup(request, region);
+ case "RestoreBackup" -> handleRestoreBackup(request, region);
+ case "ModifyBackupAttributes" -> handleModifyBackupAttributes(request, region);
+ case "CopyBackupToRegion" -> handleCopyBackupToRegion(request, region);
+ case "PutResourcePolicy" -> handlePutResourcePolicy(request, region);
+ case "GetResourcePolicy" -> handleGetResourcePolicy(request, region);
+ case "DeleteResourcePolicy" -> handleDeleteResourcePolicy(request, region);
+ case "TagResource" -> handleTagResource(request, region);
+ case "UntagResource" -> handleUntagResource(request, region);
+ case "ListTags" -> handleListTags(request, region);
+ default -> Response.status(400)
+ .entity(new AwsErrorResponse("UnknownOperationException",
+ "Operation " + action + " is not supported."))
+ .build();
+ };
+ } catch (AwsException e) {
+ return io.github.hectorvent.floci.core.common.JsonErrorResponseUtils.createErrorResponse(e);
+ } catch (Exception e) {
+ LOG.errorf(e, "CloudHSM v2 error processing action %s", action);
+ return io.github.hectorvent.floci.core.common.JsonErrorResponseUtils.createErrorResponse(e);
+ }
+ }
+
+ // ──────────────────────────── Action Handlers ────────────────────────────
+
+ private Response handleCreateCluster(JsonNode request, String region) {
+ String hsmType = text(request, "HsmType");
+ List<String> SubnetIds = parseStringList(request.path("SubnetIds"));
+ String sourceBackupId = text(request, "SourceBackupId");
+ Map<String, String> tags = parseTagList(request.path("TagList"));
+ String mode = text(request, "Mode");
+ String networkType = text(request, "NetworkType");
+ BackupRetentionPolicy backupRetentionPolicy = null;
+ if (!request.path("BackupRetentionPolicy").isMissingNode()) {
+ JsonNode brpNode = request.path("BackupRetentionPolicy");
+ backupRetentionPolicy = new BackupRetentionPolicy(brpNode.path("Type").asText(null), brpNode.path("Value").asText(null));
+ }
+
+ Cluster cluster = service.createCluster(hsmType, SubnetIds, sourceBackupId, tags, mode, networkType, backupRetentionPolicy, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Cluster", clusterNode(cluster, region));
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeClusters(JsonNode request, String region) {
+ JsonNode filters = request.path("Filters");
+ List<String> clusterIds = null;
+ List<String> states = null;
+ List<String> vpcIds = null;
+ if (!filters.isMissingNode() && !filters.isNull()) {
+ clusterIds = parseStringList(filters.path("clusterIds"));
+ states = parseStringList(filters.path("states"));
+ vpcIds = parseStringList(filters.path("vpcIds"));
+ }
+
+ Collection<Cluster> clusters = service.describeClusters(clusterIds, states, vpcIds, region);
+
+ int maxResults = parseMaxResults(request, 25);
+ int start = parseNextToken(request);
+
+ List<Cluster> list = new ArrayList<>(clusters);
+ int end = Math.min(start + maxResults, list.size());
+ List<Cluster> page = start < list.size() ? list.subList(start, end) : List.of();
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("Clusters");
+ for (Cluster c : page) {
+ arr.add(clusterNode(c, region));
+ }
+ if (end < list.size()) {
+ response.put("NextToken", String.valueOf(end));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleDeleteCluster(JsonNode request, String region) {
+ String clusterId = text(request, "ClusterId");
+ Cluster cluster = service.deleteCluster(clusterId, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Cluster", clusterNode(cluster, region));
+ return Response.ok(response).build();
+ }
+
+ private Response handleInitializeCluster(JsonNode request, String region) {
+ String clusterId = text(request, "ClusterId");
+ String signedCert = decodeBlob(text(request, "SignedCert"));
+ String trustAnchor = decodeBlob(text(request, "TrustAnchor"));
+
+ Cluster cluster = service.initializeCluster(clusterId, signedCert, trustAnchor, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("State", cluster.getState().wireValue());
+ if (cluster.getStateMessage() != null) {
+ response.put("StateMessage", cluster.getStateMessage());
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleCreateHsm(JsonNode request, String region) {
+ String clusterId = text(request, "ClusterId");
+ String az = text(request, "AvailabilityZone");
+ String ipAddress = text(request, "IpAddress");
+
+ Hsm hsm = service.createHsm(clusterId, az, ipAddress, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Hsm", hsmNode(hsm));
+ return Response.ok(response).build();
+ }
+
+ private Response handleDeleteHsm(JsonNode request, String region) {
+ String clusterId = text(request, "ClusterId");
+ String hsmId = text(request, "HsmId");
+ String eniId = text(request, "EniId");
+ String eniIp = text(request, "EniIp");
+
+ Hsm hsm = service.deleteHsm(clusterId, hsmId, eniId, eniIp, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("HsmId", hsm.getHsmId());
+ return Response.ok(response).build();
+ }
+
+ private Response handleTagResource(JsonNode request, String region) {
+ String resourceId = text(request, "ResourceId");
+ Map<String, String> tags = parseTagList(request.path("TagList"));
+ service.tagResource(resourceId, tags, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleUntagResource(JsonNode request, String region) {
+ String resourceId = text(request, "ResourceId");
+ List<String> tagKeys = parseStringList(request.path("TagKeyList"));
+ service.untagResource(resourceId, tagKeys != null ? tagKeys : List.of(), region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleListTags(JsonNode request, String region) {
+ String resourceId = text(request, "ResourceId");
+ Map<String, String> tags = service.listTags(resourceId, region);
+
+ int maxResults = parseMaxResults(request, 100);
+ int start = parseNextToken(request);
+
+ List<Map.Entry<String, String>> list = new ArrayList<>(tags.entrySet());
+ int end = Math.min(start + maxResults, list.size());
+ List<Map.Entry<String, String>> page = start < list.size() ? list.subList(start, end) : List.of();
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("TagList");
+ for (Map.Entry<String, String> tagEntry : page) {
+ ObjectNode tag = objectMapper.createObjectNode();
+ tag.put("Key", tagEntry.getKey());
+ tag.put("Value", tagEntry.getValue());
+ arr.add(tag);
+ }
+ if (end < list.size()) {
+ response.put("NextToken", String.valueOf(end));
+ }
+ return Response.ok(response).build();
+ }
+
+ private ObjectNode clusterNode(Cluster cluster , String region) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("ClusterId", cluster.getClusterId());
+ node.put("State", cluster.getState().wireValue());
+ if (cluster.getStateMessage() != null) {
+ node.put("StateMessage", cluster.getStateMessage());
+ }
+ node.put("HsmType", cluster.getHsmType());
+ if (cluster.getVpcId() != null) {
+ node.put("VpcId", cluster.getVpcId());
+ }
+ if (cluster.getSourceBackupId() != null) {
+ node.put("SourceBackupId", cluster.getSourceBackupId());
+ }
+ if (cluster.getSecurityGroup() != null) {
+ node.put("SecurityGroup", cluster.getSecurityGroup());
+ }
+ if (cluster.getCreateTimestamp() != null) {
+ node.put("CreateTimestamp", cluster.getCreateTimestamp().toEpochMilli() / 1000.0);
+ }
+ if (cluster.getBackupPolicy() != null) {
+ node.put("BackupPolicy", cluster.getBackupPolicy());
+ }
+ if (cluster.getMode() != null) {
+ node.put("Mode", cluster.getMode());
+ }
+ if (cluster.getNetworkType() != null) {
+ node.put("NetworkType", cluster.getNetworkType());
+ }
+ if (cluster.getBackupRetentionPolicy() != null) {
+ ObjectNode brp = objectMapper.createObjectNode();
+ brp.put("Type", cluster.getBackupRetentionPolicy().getType());
+ brp.put("Value", cluster.getBackupRetentionPolicy().getValue());
+ node.set("BackupRetentionPolicy", brp);
+ }
+
+ // SubnetMapping
+ if (cluster.getSubnetMapping() != null && !cluster.getSubnetMapping().isEmpty()) {
+ ObjectNode subnetNode = objectMapper.createObjectNode();
+ cluster.getSubnetMapping().forEach(subnetNode::put);
+ node.set("SubnetMapping", subnetNode);
+ }
+
+ // Certificates
+ Certificates certs = cluster.getCertificates();
+ if (certs != null) {
+ ObjectNode certsNode = objectMapper.createObjectNode();
+ if (certs.getClusterCsr() != null) {
+ certsNode.put("ClusterCsr", certs.getClusterCsr());
+ }
+ if (certs.getHsmCertificate() != null) {
+ certsNode.put("HsmCertificate", certs.getHsmCertificate());
+ }
+ if (certs.getAwsHardwareCertificate() != null) {
+ certsNode.put("AwsHardwareCertificate", certs.getAwsHardwareCertificate());
+ }
+ if (certs.getManufacturerHardwareCertificate() != null) {
+ certsNode.put("ManufacturerHardwareCertificate", certs.getManufacturerHardwareCertificate());
+ }
+ if (certs.getClusterCertificate() != null) {
+ certsNode.put("ClusterCertificate", certs.getClusterCertificate());
+ }
+ node.set("Certificates", certsNode);
+ }
+
+ // HSMs
+ ArrayNode hsmsArr = node.putArray("Hsms");
+ for (Hsm hsm : cluster.getHsms()) {
+ hsmsArr.add(hsmNode(hsm));
+ }
+
+ // Tags
+ if (cluster.getTagList() != null && !cluster.getTagList().isEmpty()) {
+ ArrayNode tagsArr = node.putArray("TagList");
+ cluster.getTagList().forEach((k, v) -> {
+ ObjectNode tag = objectMapper.createObjectNode();
+ tag.put("Key", k);
+ tag.put("Value", v);
+ tagsArr.add(tag);
+ });
+ }
+
+ return node;
+ }
+
+ private ObjectNode hsmNode(Hsm hsm) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("HsmId", hsm.getHsmId());
+ if (hsm.getAvailabilityZone() != null) {
+ node.put("AvailabilityZone", hsm.getAvailabilityZone());
+ }
+ if (hsm.getClusterId() != null) {
+ node.put("ClusterId", hsm.getClusterId());
+ }
+ if (hsm.getSubnetId() != null) {
+ node.put("SubnetId", hsm.getSubnetId());
+ }
+ if (hsm.getEniId() != null) {
+ node.put("EniId", hsm.getEniId());
+ }
+ if (hsm.getEniIp() != null) {
+ node.put("EniIp", hsm.getEniIp());
+ }
+ if (hsm.getEniIpV6() != null) {
+ node.put("EniIpV6", hsm.getEniIpV6());
+ }
+ if (hsm.getHsmType() != null) {
+ node.put("HsmType", hsm.getHsmType());
+ }
+ if (hsm.getState() != null) {
+ node.put("State", hsm.getState());
+ }
+ if (hsm.getStateMessage() != null) {
+ node.put("StateMessage", hsm.getStateMessage());
+ }
+ return node;
+ }
+
+
+ private Response handleModifyCluster(JsonNode request, String region) {
+ String clusterId = text(request, "ClusterId");
+ String hsmType = text(request, "HsmType");
+ BackupRetentionPolicy backupRetentionPolicy = null;
+ if (!request.path("BackupRetentionPolicy").isMissingNode()) {
+ JsonNode brpNode = request.path("BackupRetentionPolicy");
+ backupRetentionPolicy = new BackupRetentionPolicy(brpNode.path("Type").asText(null), brpNode.path("Value").asText(null));
+ }
+
+ Cluster cluster = service.modifyCluster(clusterId, hsmType, backupRetentionPolicy, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Cluster", clusterNode(cluster, region));
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeBackups(JsonNode request, String region) {
+ JsonNode filters = request.path("Filters");
+ List<String> backupIds = null;
+ List<String> clusterIds = null;
+ List<String> states = null;
+ List<String> sourceBackupIds = null;
+ List<String> neverExpires = null;
+ if (!filters.isMissingNode() && !filters.isNull()) {
+ backupIds = parseStringList(filters.path("backupIds"));
+ clusterIds = parseStringList(filters.path("clusterIds"));
+ states = parseStringList(filters.path("states"));
+ sourceBackupIds = parseStringList(filters.path("sourceBackupIds"));
+ neverExpires = parseStringList(filters.path("neverExpires"));
+ }
+
+ Boolean shared = request.path("Shared").isMissingNode() ? null : request.path("Shared").asBoolean();
+ Boolean sortAscending = request.path("SortAscending").isMissingNode() ? null : request.path("SortAscending").asBoolean();
+
+ Collection<Backup> backups = service.describeBackups(backupIds, clusterIds, states, sourceBackupIds, neverExpires, shared, sortAscending, region);
+
+ int maxResults = parseMaxResults(request, 50);
+ int start = parseNextToken(request);
+
+ List<Backup> list = new ArrayList<>(backups);
+ int end = Math.min(start + maxResults, list.size());
+ List<Backup> page = start < list.size() ? list.subList(start, end) : List.of();
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("Backups");
+ for (Backup b : page) {
+ arr.add(backupNode(b, region));
+ }
+ if (end < list.size()) {
+ response.put("NextToken", String.valueOf(end));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleDeleteBackup(JsonNode request, String region) {
+ String backupId = text(request, "BackupId");
+ Backup backup = service.deleteBackup(backupId, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Backup", backupNode(backup, region));
+ return Response.ok(response).build();
+ }
+
+ private Response handleRestoreBackup(JsonNode request, String region) {
+ String backupId = text(request, "BackupId");
+ Backup backup = service.restoreBackup(backupId, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Backup", backupNode(backup, region));
+ return Response.ok(response).build();
+ }
+
+ private Response handleModifyBackupAttributes(JsonNode request, String region) {
+ String backupId = text(request, "BackupId");
+ String neverExpires = text(request, "NeverExpires");
+ Backup backup = service.modifyBackupAttributes(backupId, neverExpires, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Backup", backupNode(backup, region));
+ return Response.ok(response).build();
+ }
+
+ private Response handleCopyBackupToRegion(JsonNode request, String region) {
+ String destRegion = text(request, "DestinationRegion");
+ if (destRegion == null || destRegion.isBlank()) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "DestinationRegion is required when copying a backup.", 400);
+ }
+ String backupId = text(request, "BackupId");
+ Backup backup = service.copyBackupToRegion(destRegion, backupId, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ ObjectNode destBackup = objectMapper.createObjectNode();
+ destBackup.put("CreateTimestamp", backup.getCreateTimestamp().toEpochMilli() / 1000.0);
+ destBackup.put("SourceBackup", backup.getSourceBackup());
+ destBackup.put("SourceCluster", backup.getSourceCluster());
+ destBackup.put("SourceRegion", backup.getSourceRegion());
+ response.set("DestinationBackup", destBackup);
+ return Response.ok(response).build();
+ }
+
+ private Response handlePutResourcePolicy(JsonNode request, String region) {
+ String resourceArn = text(request, "ResourceArn");
+ String policy = text(request, "Policy");
+ service.putResourcePolicy(resourceArn, policy, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("ResourceArn", resourceArn);
+ response.put("Policy", policy);
+ return Response.ok(response).build();
+ }
+
+ private Response handleGetResourcePolicy(JsonNode request, String region) {
+ String resourceArn = text(request, "ResourceArn");
+ String policy = service.getResourcePolicy(resourceArn, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("Policy", policy);
+ return Response.ok(response).build();
+ }
+
+ private Response handleDeleteResourcePolicy(JsonNode request, String region) {
+ String resourceArn = text(request, "ResourceArn");
+ String oldPolicy = service.deleteResourcePolicy(resourceArn, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("ResourceArn", resourceArn);
+ if (oldPolicy != null) {
+ response.put("Policy", oldPolicy);
+ }
+ return Response.ok(response).build();
+ }
+
+ private ObjectNode backupNode(Backup backup, String region) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("BackupId", backup.getBackupId());
+ String arnRegion = region != null ? region : "us-east-1";
+ node.put("BackupArn", "arn:aws:cloudhsm:" + arnRegion + ":000000000000:backup/" + backup.getBackupId());
+ node.put("BackupState", backup.getBackupState());
+ node.put("ClusterId", backup.getClusterId());
+ if (backup.getHsmType() != null) {
+ node.put("HsmType", backup.getHsmType());
+ }
+ if (backup.getCreateTimestamp() != null) {
+ node.put("CreateTimestamp", backup.getCreateTimestamp().toEpochMilli() / 1000.0);
+ }
+ if (backup.getDeleteTimestamp() != null) {
+ node.put("DeleteTimestamp", backup.getDeleteTimestamp().toEpochMilli() / 1000.0);
+ }
+ if (backup.getCopyTimestamp() != null) {
+ node.put("CopyTimestamp", backup.getCopyTimestamp().toEpochMilli() / 1000.0);
+ }
+ if (backup.getNeverExpires() != null) {
+ node.put("NeverExpires", "True".equalsIgnoreCase(backup.getNeverExpires()));
+ }
+ if (backup.getSourceRegion() != null) {
+ node.put("SourceRegion", backup.getSourceRegion());
+ }
+ if (backup.getSourceBackup() != null) {
+ node.put("SourceBackup", backup.getSourceBackup());
+ }
+ if (backup.getSourceCluster() != null) {
+ node.put("SourceCluster", backup.getSourceCluster());
+ }
+ if (backup.getMode() != null) {
+ node.put("Mode", backup.getMode());
+ }
+ if (backup.getTagList() != null && !backup.getTagList().isEmpty()) {
+ ArrayNode tagList = node.putArray("TagList");
+ for (Map.Entry<String, String> tagEntry : backup.getTagList().entrySet()) {
+ ObjectNode tag = objectMapper.createObjectNode();
+ tag.put("Key", tagEntry.getKey());
+ tag.put("Value", tagEntry.getValue());
+ tagList.add(tag);
+ }
+ }
+ return node;
+ }
+
+ // ──────────────────────────── Parsing Helpers ────────────────────────────
+
+ private String text(JsonNode request, String field) {
+ JsonNode node = request.path(field);
+ return node.isMissingNode() || node.isNull() ? null : node.asText(null);
+ }
+
+ private int parseMaxResults(JsonNode request, int maxAllowed) {
+ if (request.path("MaxResults").isMissingNode() || request.path("MaxResults").isNull()) {
+ return maxAllowed;
+ }
+ try {
+ int max = Integer.parseInt(request.path("MaxResults").asText());
+ if (max <= 0 || max > maxAllowed) {
+ throw new AwsException("CloudHsmInvalidRequestException", "MaxResults must be between 1 and " + maxAllowed + ".", 400);
+ }
+ return max;
+ } catch (NumberFormatException e) {
+ throw new AwsException("CloudHsmInvalidRequestException", "MaxResults must be a valid integer.", 400);
+ }
+ }
+
+ private int parseNextToken(JsonNode request) {
+ String token = text(request, "NextToken");
+ if (token == null) {
+ return 0;
+ }
+ try {
+ int val = Integer.parseInt(token);
+ if (val < 0) {
+ throw new AwsException("CloudHsmInvalidRequestException", "NextToken is invalid.", 400);
+ }
+ return val;
+ } catch (NumberFormatException e) {
+ throw new AwsException("CloudHsmInvalidRequestException", "NextToken is invalid.", 400);
+ }
+ }
+
+ private List<String> parseStringList(JsonNode node) {
+ if (node == null || !node.isArray()) {
+ return null;
+ }
+ List<String> list = new ArrayList<>();
+ node.forEach(n -> {
+ String val = n.asText(null);
+ if (val != null) {
+ list.add(val);
+ }
+ });
+ return list.isEmpty() ? null : list;
+ }
+
+ private Map<String, String> parseStringMap(JsonNode node) {
+ if (node == null || node.isMissingNode() || node.isNull()) {
+ return null;
+ }
+ Map<String, String> map = new LinkedHashMap<>();
+ var fields = node.fields();
+ while (fields.hasNext()) {
+ var entry = fields.next();
+ map.put(entry.getKey(), entry.getValue().asText());
+ }
+ return map.isEmpty() ? null : map;
+ }
+
+ private Map<String, String> parseTagList(JsonNode tagsNode) {
+ if (tagsNode == null || !tagsNode.isArray()) {
+ return null;
+ }
+ Map<String, String> tags = new LinkedHashMap<>();
+ for (JsonNode tag : tagsNode) {
+ String key = tag.path("Key").asText(null);
+ if (key != null) {
+ tags.put(key, tag.path("Value").asText(null));
+ }
+ }
+ return tags.isEmpty() ? null : tags;
+ }
+
+ /**
+ * Decodes a base64-encoded blob field. AWS SDKs send binary fields as
+ * base64-encoded strings. If the value is already in PEM format, it is returned as-is.
+ */
+ private String decodeBlob(String value) {
+ if (value == null || value.startsWith("-----")) {
+ return value;
+ }
+ try {
+ return new String(Base64.getDecoder().decode(value), java.nio.charset.StandardCharsets.UTF_8);
+ } catch (IllegalArgumentException e) {
+ return value;
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java
new file mode 100644
index 0000000000..ca644c371c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java
@@ -0,0 +1,794 @@
+package io.github.hectorvent.floci.services.cloudhsmv2;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.Certificates;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.Cluster;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.ClusterState;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.Hsm;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+
+import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
+import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.openssl.PEMParser;
+import org.jboss.logging.Logger;
+
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.Backup;
+import io.github.hectorvent.floci.services.cloudhsmv2.model.BackupRetentionPolicy;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.time.temporal.ChronoUnit;
+import java.util.stream.Collectors;
+import java.time.Instant;
+import java.util.*;
+
+import io.github.hectorvent.floci.services.ec2.Ec2Service;
+import io.github.hectorvent.floci.services.ec2.model.Subnet;
+
+/**
+ * CloudHSM v2 service implementation for the local emulator.
+ *
+ * <p>Provides cluster initialization and lifecycle management operations
+ * compatible with the AWS CloudHSM v2 API. Clusters follow a strict lifecycle:
+ * {@code CREATE_IN_PROGRESS → UNINITIALIZED → INITIALIZED → ACTIVE}.
+ *
+ * @see <a href="https://docs.aws.amazon.com/cloudhsm/latest/APIReference/Welcome.html">AWS CloudHSM v2 API Reference</a>
+ */
+@ApplicationScoped
+public class CloudHsmV2Service {
+
+ private static final Logger LOG = Logger.getLogger(CloudHsmV2Service.class);
+ private static final String DEFAULT_HSM_TYPE = "hsm1.medium";
+ private static final String DEFAULT_BACKUP_POLICY = "DEFAULT";
+
+ private final SecureRandom SECURE_RANDOM = new SecureRandom();
+ private final StorageBackend<String, Cluster> clusters;
+ private final StorageBackend<String, Backup> backups;
+ private final Ec2Service ec2Service;
+
+ @Inject
+ public CloudHsmV2Service(StorageFactory storageFactory, Ec2Service ec2Service) {
+ this.clusters = storageFactory.create("cloudhsmv2", "cloudhsmv2-clusters.json",
+ new TypeReference<Map<String, Cluster>>() {});
+ this.backups = storageFactory.create("cloudhsmv2", "cloudhsmv2-backups.json",
+ new TypeReference<Map<String, Backup>>() {});
+ this.ec2Service = ec2Service;
+ }
+
+ CloudHsmV2Service(StorageBackend<String, Cluster> clusters, StorageBackend<String, Backup> backups, Ec2Service ec2Service) {
+ this.clusters = clusters;
+ this.backups = backups;
+ this.ec2Service = ec2Service;
+ }
+
+ // ──────────────────────────── CreateCluster ────────────────────────────
+
+ public Cluster createCluster(String hsmType, List<String> SubnetIds,
+ String sourceBackupId, Map<String, String> tags,
+ String mode, String networkType, BackupRetentionPolicy backupRetentionPolicy, String region) {
+ if (SubnetIds == null || SubnetIds.isEmpty()) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "SubnetIds must contain at least one entry.", 400);
+ }
+ if (hsmType == null) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "HsmType is required.", 400);
+ }
+ if (!hsmType.matches("^((p|)hsm[0-9][a-z.]*\\.[a-zA-Z]+)$")) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "HsmType " + hsmType + " is not valid.", 400);
+ }
+ if (mode != null && !mode.equals("FIPS") && !mode.equals("NON_FIPS")) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "Mode must be FIPS or NON_FIPS.", 400);
+ }
+ if (networkType != null && !networkType.equals("IPV4") && !networkType.equals("DUALSTACK")) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "NetworkType must be IPV4 or DUALSTACK.", 400);
+ }
+
+ Backup sourceBackup = null;
+ if (sourceBackupId != null && !sourceBackupId.isEmpty()) {
+ sourceBackup = getBackup(extractId(sourceBackupId), region);
+ if (mode == null && sourceBackup.getMode() != null) {
+ mode = sourceBackup.getMode();
+ }
+ }
+
+ String clusterId = "cluster-" + generateShortId();
+
+ Cluster cluster = new Cluster();
+ cluster.setClusterId(clusterId);
+ cluster.setState(ClusterState.UNINITIALIZED);
+ cluster.setHsmType(hsmType);
+ cluster.setVpcId("vpc-" + generateShortId());
+ cluster.setSubnetIds(new ArrayList<>(SubnetIds));
+ Map<String, String> subnetMapping = new LinkedHashMap<>();
+ if (ec2Service != null) {
+ List<Subnet> subnets = ec2Service.describeSubnets(region, SubnetIds, Collections.emptyMap());
+ for (int i = 0; i < SubnetIds.size(); i++) {
+ String subId = SubnetIds.get(i);
+ final int index = i;
+ String az = subnets.stream()
+ .filter(s -> s.getSubnetId().equals(subId))
+ .map(Subnet::getAvailabilityZone)
+ .findFirst()
+ .orElseGet(() -> region + (char) ('a' + index));
+ subnetMapping.put(az, subId);
+ }
+ } else {
+ for (int i = 0; i < SubnetIds.size(); i++) {
+ subnetMapping.put(region + (char) ('a' + i), SubnetIds.get(i));
+ }
+ }
+ cluster.setSubnetMapping(subnetMapping);
+ cluster.setSourceBackupId(sourceBackupId);
+ cluster.setSecurityGroup("sg-" + generateShortId());
+ cluster.setCreateTimestamp(Instant.now());
+ cluster.setBackupPolicy(DEFAULT_BACKUP_POLICY);
+ cluster.setTagList(tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>());
+ cluster.setMode(mode != null ? mode : "FIPS");
+ cluster.setNetworkType(networkType != null ? networkType : "IPV4");
+ if (backupRetentionPolicy != null) {
+ String brpValue = backupRetentionPolicy.getValue();
+ if (brpValue == null) {
+ throw new AwsException("CloudHsmInvalidRequestException", "BackupRetentionPolicy Value is required.", 400);
+ }
+ int val;
+ try {
+ val = Integer.parseInt(brpValue);
+ } catch (NumberFormatException e) {
+ throw new AwsException("CloudHsmInvalidRequestException", "BackupRetentionPolicy Value must be an integer.", 400);
+ }
+ if (val < 7 || val > 379) {
+ throw new AwsException("CloudHsmInvalidRequestException", "BackupRetentionPolicy Value must be between 7 and 379.", 400);
+ }
+ cluster.setBackupRetentionPolicy(backupRetentionPolicy);
+ } else {
+ cluster.setBackupRetentionPolicy(new BackupRetentionPolicy("DAYS", "90"));
+ }
+
+ Certificates certs = new Certificates();
+ certs.setClusterCsr(generateCsr(clusterId));
+
+ try {
+ KeyPair mfrKeyPair = generateKeyPair();
+ X500Name mfrName = new X500Name("CN=HSM Manufacturer CA,O=AWS,C=US");
+ certs.setManufacturerHardwareCertificate(generateCert(mfrName, mfrName, mfrKeyPair.getPublic(), mfrKeyPair.getPrivate()));
+
+ KeyPair awsKeyPair = generateKeyPair();
+ X500Name awsName = new X500Name("CN=AWS CloudHSM Hardware CA,O=AWS,C=US");
+ certs.setAwsHardwareCertificate(generateCert(awsName, mfrName, awsKeyPair.getPublic(), mfrKeyPair.getPrivate()));
+
+ KeyPair hsmKeyPair = generateKeyPair();
+ X500Name hsmName = new X500Name("CN=HSM Instance " + clusterId + ",O=AWS,C=US");
+ certs.setHsmCertificate(generateCert(hsmName, awsName, hsmKeyPair.getPublic(), awsKeyPair.getPrivate()));
+ } catch (Exception e) {
+ LOG.warnv("Failed to generate emulated hardware certs: {0}", e.getMessage());
+ }
+
+ cluster.setCertificates(certs);
+
+ String storageKey = regionKey(region, clusterId);
+ clusters.put(storageKey, cluster);
+
+ createBackupInternal(clusterId, region);
+
+ LOG.infov("Created CloudHSM v2 cluster {0} in region {1}", clusterId, region);
+ return cluster;
+ }
+
+ // ──────────────────────────── DescribeClusters ────────────────────────────
+
+ public Collection<Cluster> describeClusters(List<String> filterClusterIds,
+ List<String> filterStates, List<String> filterVpcIds, String region) {
+ Collection<Cluster> all = clusters.scan(k -> k.startsWith(region + "::"));
+
+ List<Cluster> filtered = new ArrayList<>();
+ for (Cluster c : all) {
+ boolean matchId = filterClusterIds == null || filterClusterIds.isEmpty()
+ || filterClusterIds.contains(c.getClusterId());
+ boolean matchState = filterStates == null || filterStates.isEmpty()
+ || filterStates.contains(c.getState().wireValue());
+ boolean matchVpc = filterVpcIds == null || filterVpcIds.isEmpty()
+ || filterVpcIds.contains(c.getVpcId());
+ if (matchId && matchState && matchVpc) {
+ filtered.add(c);
+ }
+ }
+ return filtered;
+ }
+
+ // ──────────────────────────── DeleteCluster ────────────────────────────
+
+ public Cluster deleteCluster(String clusterId, String region) {
+ Cluster cluster = getCluster(clusterId, region);
+
+ if (!cluster.getHsms().isEmpty()) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "Cluster " + clusterId + " has active HSMs. Delete all HSMs before deleting the cluster.", 400);
+ }
+
+ cluster.setState(ClusterState.DELETE_IN_PROGRESS);
+ clusters.delete(regionKey(region, clusterId));
+
+ LOG.infov("Deleted CloudHSM v2 cluster {0}", clusterId);
+ return cluster;
+ }
+
+ // ──────────────────────────── InitializeCluster ────────────────────────────
+
+ public Cluster initializeCluster(String clusterId, String signedCert, String trustAnchor, String region) {
+ Cluster cluster = getCluster(clusterId, region);
+
+ if (cluster.getState() != ClusterState.UNINITIALIZED) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "Cluster " + clusterId + " is in state " + cluster.getState().wireValue()
+ + ". InitializeCluster requires UNINITIALIZED state.", 400);
+ }
+
+ validatePemCertificate(signedCert, "SignedCert");
+ validatePemCertificate(trustAnchor, "TrustAnchor");
+
+ // Parse and validate the certificates
+ X509CertificateHolder signedCertHolder = parsePemCertificate(signedCert, "SignedCert");
+ X509CertificateHolder trustAnchorHolder = parsePemCertificate(trustAnchor, "TrustAnchor");
+
+ // Verify TrustAnchor is self-signed and SignedCert is issued by TrustAnchor
+ try {
+ JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
+ java.security.cert.X509Certificate trustAnchorCert = converter.getCertificate(trustAnchorHolder);
+ java.security.cert.X509Certificate signedCertObj = converter.getCertificate(signedCertHolder);
+
+ if (!trustAnchorHolder.getIssuer().equals(trustAnchorHolder.getSubject())) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "TrustAnchor must be a self-signed certificate.", 400);
+ }
+ trustAnchorCert.verify(trustAnchorCert.getPublicKey());
+
+ if (!signedCertHolder.getIssuer().equals(trustAnchorHolder.getSubject())) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "SignedCert must be issued by the provided TrustAnchor.", 400);
+ }
+ signedCertObj.verify(trustAnchorCert.getPublicKey());
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "Certificate signature verification failed: " + e.getMessage(), 400);
+ }
+
+ // Verify SignedCert matches the cluster CSR
+ String clusterCsr = cluster.getCertificates().getClusterCsr();
+ PKCS10CertificationRequest csrHolder = parsePemCsr(clusterCsr);
+ if (!signedCertHolder.getSubjectPublicKeyInfo().equals(csrHolder.getSubjectPublicKeyInfo())) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "SignedCert public key does not match the cluster CSR public key.", 400);
+ }
+
+ // Persist the cluster certificate
+ Certificates certs = cluster.getCertificates();
+ if (certs == null) {
+ certs = new Certificates();
+ }
+ certs.setClusterCertificate(signedCert);
+ cluster.setCertificates(certs);
+
+ cluster.setState(ClusterState.INITIALIZED);
+ cluster.setStateMessage("Cluster initialized successfully");
+
+ // Auto-transition to ACTIVE if HSMs are present
+ if (cluster.isReadyForActive()) {
+ cluster.setState(ClusterState.ACTIVE);
+ cluster.setStateMessage("Cluster is active");
+ }
+
+ clusters.put(regionKey(region, clusterId), cluster);
+ LOG.infov("Initialized CloudHSM v2 cluster {0}, state={1}", clusterId, cluster.getState());
+ return cluster;
+ }
+
+ // ──────────────────────────── CreateHsm ────────────────────────────
+
+ public Hsm createHsm(String clusterId, String availabilityZone, String ipAddress, String region) {
+ Cluster cluster = getCluster(clusterId, region);
+
+ if (cluster.getState() != ClusterState.INITIALIZED
+ && cluster.getState() != ClusterState.ACTIVE) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "Cannot create HSM in cluster " + clusterId + " with state " + cluster.getState().wireValue(), 400);
+ }
+
+ if (availabilityZone == null || availabilityZone.isBlank()) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "AvailabilityZone is required.", 400);
+ }
+
+ String subnetId = cluster.getSubnetMapping().get(availabilityZone);
+ if (subnetId == null) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "AvailabilityZone " + availabilityZone + " is not mapped to a subnet in this cluster.", 400);
+ }
+
+ Hsm hsm = new Hsm();
+ hsm.setHsmId("hsm-" + generateShortId());
+ hsm.setAvailabilityZone(availabilityZone);
+ hsm.setClusterId(clusterId);
+ hsm.setSubnetId(subnetId);
+ hsm.setEniId("eni-" + generateShortId());
+ hsm.setHsmType(cluster.getHsmType());
+
+ if (ipAddress != null) {
+ if (ipAddress.contains(":")) {
+ hsm.setEniIpV6(ipAddress);
+ hsm.setEniIp("10.0." + (SECURE_RANDOM.nextInt(254) + 1) + "." + (SECURE_RANDOM.nextInt(254) + 1));
+ } else {
+ hsm.setEniIp(ipAddress);
+ if ("DUALSTACK".equals(cluster.getNetworkType())) {
+ hsm.setEniIpV6("2001:db8::" + Integer.toHexString(SECURE_RANDOM.nextInt(65535)));
+ }
+ }
+ hsm.setIpAddress(ipAddress);
+ } else {
+ hsm.setEniIp("10.0." + (SECURE_RANDOM.nextInt(254) + 1) + "." + (SECURE_RANDOM.nextInt(254) + 1));
+ if ("DUALSTACK".equals(cluster.getNetworkType())) {
+ hsm.setEniIpV6("2001:db8::" + Integer.toHexString(SECURE_RANDOM.nextInt(65535)));
+ }
+ hsm.setIpAddress(hsm.getEniIp());
+ }
+
+ hsm.setState("ACTIVE");
+ hsm.setCreatedAt(Instant.now());
+
+ cluster.getHsms().add(hsm);
+
+ if (cluster.isReadyForActive()) {
+ cluster.setState(ClusterState.ACTIVE);
+ cluster.setStateMessage("Cluster is active");
+ }
+
+ clusters.put(regionKey(region, clusterId), cluster);
+
+ createBackupInternal(clusterId, region);
+
+ LOG.infov("Created HSM {0} in cluster {1}", hsm.getHsmId(), clusterId);
+ return hsm;
+ }
+
+ // ──────────────────────────── DeleteHsm ────────────────────────────
+
+ public Hsm deleteHsm(String clusterId, String hsmId, String eniId, String eniIp, String region) {
+ int count = 0;
+ if (hsmId != null && !hsmId.isEmpty()) {
+ count++;
+ }
+ if (eniId != null && !eniId.isEmpty()) {
+ count++;
+ }
+ if (eniIp != null && !eniIp.isEmpty()) {
+ count++;
+ }
+
+ if (count != 1) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ "Exactly one of HsmId, EniId, or EniIp must be specified", 400);
+ }
+
+ Cluster cluster = getCluster(clusterId, region);
+
+ Hsm target = null;
+ for (Hsm h : cluster.getHsms()) {
+ if ((hsmId != null && hsmId.equals(h.getHsmId())) ||
+ (eniId != null && eniId.equals(h.getEniId())) ||
+ (eniIp != null && eniIp.equals(h.getEniIp()))) {
+ target = h;
+ break;
+ }
+ }
+ if (target == null) {
+ String selector = hsmId != null ? hsmId : (eniId != null ? eniId : eniIp);
+ throw new AwsException("CloudHsmResourceNotFoundException",
+ "HSM " + selector + " not found in cluster " + clusterId, 400);
+ }
+
+ cluster.getHsms().remove(target);
+
+ // If cluster was ACTIVE but now has no HSMs, revert to INITIALIZED
+ if (cluster.getState() == ClusterState.ACTIVE && cluster.getHsms().isEmpty()) {
+ cluster.setState(ClusterState.INITIALIZED);
+ cluster.setStateMessage("No active HSMs");
+ }
+
+ clusters.put(regionKey(region, clusterId), cluster);
+ LOG.infov("Deleted HSM {0} from cluster {1}", target.getHsmId(), clusterId);
+ return target;
+ }
+
+ // ──────────────────────────── TagResource ────────────────────────────
+
+ public void tagResource(String resourceId, Map<String, String> tags, String region) {
+ if (resourceId == null || resourceId.isBlank()) {
+ throw new AwsException("CloudHsmInvalidRequestException", "ResourceId is required.", 400);
+ }
+ if (tags == null || tags.isEmpty() || tags.size() > 50) {
+ throw new AwsException("CloudHsmInvalidRequestException", "TagList must have length between 1 and 50", 400);
+ }
+ if (resourceId.startsWith("backup-")) {
+ Backup backup = getBackup(resourceId, region);
+ if (tags != null && !tags.isEmpty()) {
+ backup.getTagList().putAll(tags);
+ }
+ backups.put(regionKey(region, resourceId), backup);
+ } else {
+ Cluster cluster = getCluster(resourceId, region);
+ if (tags != null && !tags.isEmpty()) {
+ cluster.getTagList().putAll(tags);
+ }
+ clusters.put(regionKey(region, resourceId), cluster);
+ }
+ }
+
+ public void untagResource(String resourceId, List<String> tagKeys, String region) {
+ if (resourceId == null || resourceId.isBlank()) {
+ throw new AwsException("CloudHsmInvalidRequestException", "ResourceId is required.", 400);
+ }
+ if (tagKeys == null || tagKeys.isEmpty() || tagKeys.size() > 50) {
+ throw new AwsException("CloudHsmInvalidRequestException", "TagKeyList must have length between 1 and 50", 400);
+ }
+ if (resourceId.startsWith("backup-")) {
+ Backup backup = getBackup(resourceId, region);
+ tagKeys.forEach(backup.getTagList()::remove);
+ backups.put(regionKey(region, resourceId), backup);
+ } else {
+ Cluster cluster = getCluster(resourceId, region);
+ tagKeys.forEach(cluster.getTagList()::remove);
+ clusters.put(regionKey(region, resourceId), cluster);
+ }
+ }
+
+ public Map<String, String> listTags(String resourceId, String region) {
+ if (resourceId == null || resourceId.isBlank()) {
+ throw new AwsException("CloudHsmInvalidRequestException", "ResourceId is required.", 400);
+ }
+ if (resourceId.startsWith("backup-")) {
+ return new LinkedHashMap<>(getBackup(resourceId, region).getTagList());
+ } else {
+ return new LinkedHashMap<>(getCluster(resourceId, region).getTagList());
+ }
+ }
+
+ // ──────────────────────────── Helpers ────────────────────────────
+
+ Cluster getCluster(String clusterId, String region) {
+ if (clusterId == null || clusterId.isBlank()) {
+ throw new AwsException("CloudHsmInvalidRequestException", "ClusterId is required.", 400);
+ }
+ return clusters.get(regionKey(region, clusterId)).orElseThrow(() ->
+ new AwsException("CloudHsmResourceNotFoundException",
+ "Cluster " + clusterId + " not found.", 400));
+ }
+
+ private String regionKey(String region, String clusterId) {
+ return region + "::" + clusterId;
+ }
+
+ private String generateShortId() {
+ String alphabet = "234567abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ int length = 11 + SECURE_RANDOM.nextInt(6);
+ StringBuilder sb = new StringBuilder(length);
+ for (int i = 0; i < length; i++) {
+ sb.append(alphabet.charAt(SECURE_RANDOM.nextInt(alphabet.length())));
+ }
+ return sb.toString();
+ }
+
+ private String generateCsr(String clusterId) {
+ try {
+ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
+ keyGen.initialize(2048, SECURE_RANDOM);
+ KeyPair keyPair = keyGen.generateKeyPair();
+
+ X500Name subject = new X500Name("CN=" + clusterId + ",O=AWS CloudHSM,C=US");
+
+ PKCS10CertificationRequestBuilder csrBuilder =
+ new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic());
+
+ ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA")
+ .build(keyPair.getPrivate());
+
+ PKCS10CertificationRequest csr = csrBuilder.build(signer);
+
+ StringWriter sw = new StringWriter();
+ try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {
+ pemWriter.writeObject(csr);
+ }
+ return sw.toString();
+ } catch (Exception e) {
+ LOG.warnv("Failed to generate CSR for cluster {0}: {1}", clusterId, e.getMessage());
+ return "-----BEGIN CERTIFICATE REQUEST-----\nemulated-csr-" + clusterId + "\n-----END CERTIFICATE REQUEST-----\n";
+ }
+ }
+
+ private KeyPair generateKeyPair() throws Exception {
+ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
+ keyGen.initialize(2048, SECURE_RANDOM);
+ return keyGen.generateKeyPair();
+ }
+
+ private String generateCert(X500Name subject, X500Name issuer, PublicKey pubKey, PrivateKey signerKey) throws Exception {
+ BigInteger serial = new BigInteger(128, SECURE_RANDOM);
+ Instant now = Instant.now();
+ X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
+ issuer, serial, Date.from(now), Date.from(now.plusSeconds(365L * 24 * 3600)), subject, pubKey);
+
+ ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA")
+ .build(signerKey);
+ X509CertificateHolder holder = certBuilder.build(signer);
+ X509Certificate cert = new JcaX509CertificateConverter()
+ .getCertificate(holder);
+
+ StringWriter sw = new StringWriter();
+ try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {
+ pemWriter.writeObject(cert);
+ }
+ return sw.toString();
+ }
+
+ private void validatePemCertificate(String pem, String fieldName) {
+ if (pem == null || pem.isBlank()) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ fieldName + " is required.", 400);
+ }
+ if (!pem.contains("-----BEGIN CERTIFICATE-----")) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ fieldName + " must be a valid PEM-encoded certificate.", 400);
+ }
+ if (!pem.contains("-----END CERTIFICATE-----")) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ fieldName + " is malformed: missing PEM end marker.", 400);
+ }
+ }
+
+ private X509CertificateHolder parsePemCertificate(String pem, String fieldName) {
+ try (PEMParser parser = new PEMParser(new StringReader(pem))) {
+ Object obj = parser.readObject();
+ if (obj == null) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ fieldName + " could not be parsed as a valid certificate.", 400);
+ }
+ if (!(obj instanceof X509CertificateHolder)) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ fieldName + " is not a valid X.509 certificate.", 400);
+ }
+ return (X509CertificateHolder) obj;
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AwsException("CloudHsmInvalidRequestException",
+ fieldName + " is malformed: " + e.getMessage(), 400);
+ }
+ }
+
+ private PKCS10CertificationRequest parsePemCsr(String pem) {
+ try (PEMParser parser = new PEMParser(new StringReader(pem))) {
+ Object obj = parser.readObject();
+ if (obj instanceof PKCS10CertificationRequest) {
+ return (PKCS10CertificationRequest) obj;
+ }
+ throw new RuntimeException("Not a valid CSR");
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to parse CSR", e);
+ }
+ }
+
+ // ──────────────────────────── Backups ────────────────────────────
+
+ private void createBackupInternal(String clusterId, String region) {
+ Cluster cluster = getCluster(clusterId, region);
+ Backup backup = new Backup();
+ backup.setBackupId("backup-" + generateShortId());
+ backup.setBackupState("READY");
+ backup.setClusterId(clusterId);
+ backup.setCreateTimestamp(Instant.now());
+ backup.setNeverExpires("False");
+ backup.setMode(cluster.getMode());
+ backup.setHsmType(cluster.getHsmType());
+ backups.put(regionKey(region, backup.getBackupId()), backup);
+ }
+
+ public Collection<Backup> describeBackups(List<String> filterBackupIds, List<String> filterClusterIds,
+ List<String> filterStates, List<String> filterSourceBackupIds,
+ List<String> filterNeverExpires, Boolean shared, Boolean sortAscending, String region) {
+ Collection<Backup> all = backups.scan(k -> k.startsWith(region + "::"));
+ List<Backup> filtered = new ArrayList<>();
+ for (Backup b : all) {
+ boolean matchId = filterBackupIds == null || filterBackupIds.isEmpty() || filterBackupIds.contains(b.getBackupId());
+ boolean matchCluster = filterClusterIds == null || filterClusterIds.isEmpty() || filterClusterIds.contains(b.getClusterId());
+ boolean matchState = filterStates == null || filterStates.isEmpty() || filterStates.contains(b.getBackupState());
+ boolean matchSourceBackup = filterSourceBackupIds == null || filterSourceBackupIds.isEmpty() || filterSourceBackupIds.contains(b.getSourceBackup());
+ boolean matchNeverExpires = filterNeverExpires == null || filterNeverExpires.isEmpty() ||
+ filterNeverExpires.stream().anyMatch(f -> f.equalsIgnoreCase(b.getNeverExpires() == null ? "False" : b.getNeverExpires()));
+
+ if (matchId && matchCluster && matchState && matchSourceBackup && matchNeverExpires) {
+ filtered.add(b);
+ }
+ }
+
+ if (Boolean.TRUE.equals(sortAscending)) {
+ filtered.sort(java.util.Comparator.comparing(Backup::getCreateTimestamp));
+ } else {
+ filtered.sort(java.util.Comparator.comparing(Backup::getCreateTimestamp).reversed());
+ }
+
+ return filtered;
+ }
+
+ public Backup deleteBackup(String backupId, String region) {
+ Backup backup = getBackup(backupId, region);
+ backup.setBackupState("PENDING_DELETION");
+ backup.setDeleteTimestamp(Instant.now());
+ backups.put(regionKey(region, backupId), backup);
+ return backup;
+ }
+
+ public Backup restoreBackup(String backupId, String region) {
+ Backup backup = getBackup(backupId, region);
+ if (!"PENDING_DELETION".equals(backup.getBackupState())) {
+ throw new AwsException("CloudHsmInvalidRequestException", "Backup must be in PENDING_DELETION state", 400);
+ }
+ if (backup.getDeleteTimestamp() != null) {
+ long daysSinceDeletion = java.time.Duration.between(backup.getDeleteTimestamp(), Instant.now()).toDays();
+ if (daysSinceDeletion > 7) {
+ throw new AwsException("CloudHsmInvalidRequestException", "Backup is past the 7-day deletion window", 400);
+ }
+ }
+ backup.setBackupState("READY");
+ backup.setDeleteTimestamp(null);
+ backups.put(regionKey(region, backupId), backup);
+ return backup;
+ }
+
+ public Backup modifyBackupAttributes(String backupId, String neverExpires, String region) {
+ Backup backup = getBackup(backupId, region);
+ if (neverExpires != null) {
+ backup.setNeverExpires(neverExpires);
+ }
+ backups.put(regionKey(region, backupId), backup);
+ return backup;
+ }
+
+ public Backup copyBackupToRegion(String destinationRegion, String backupId, String sourceRegion) {
+ // Source region emulation: we'll just clone the backup locally.
+ Backup source = getBackup(backupId, sourceRegion != null ? sourceRegion : "us-east-1");
+ Backup copy = new Backup();
+ copy.setBackupId("backup-" + generateShortId());
+ copy.setBackupState("READY");
+ copy.setClusterId(source.getClusterId());
+ copy.setCreateTimestamp(source.getCreateTimestamp());
+ copy.setCopyTimestamp(Instant.now());
+ copy.setSourceRegion(sourceRegion != null ? sourceRegion : "us-east-1");
+ copy.setSourceBackup(backupId);
+ copy.setSourceCluster(source.getClusterId());
+ copy.setMode(source.getMode());
+ copy.setHsmType(source.getHsmType());
+ copy.setNeverExpires(source.getNeverExpires());
+ backups.put(regionKey(destinationRegion, copy.getBackupId()), copy);
+ return copy;
+ }
+
+ // ──────────────────────────── Resource Policies ────────────────────────────
+
+ public void putResourcePolicy(String resourceArn, String policy, String region) {
+ String id = extractId(resourceArn);
+ if (id.startsWith("backup-")) {
+ Backup backup = getBackup(id, region);
+ if (!"READY".equals(backup.getBackupState())) {
+ throw new AwsException("CloudHsmInvalidRequestException", "Backup must be READY to apply a policy", 400);
+ }
+ backup.setResourcePolicy(policy);
+ backups.put(regionKey(region, id), backup);
+ } else {
+ Cluster cluster = getCluster(id, region);
+ cluster.setResourcePolicy(policy);
+ clusters.put(regionKey(region, id), cluster);
+ }
+ }
+
+ public String getResourcePolicy(String resourceArn, String region) {
+ String id = extractId(resourceArn);
+ if (id.startsWith("backup-")) {
+ return getBackup(id, region).getResourcePolicy();
+ } else {
+ return getCluster(id, region).getResourcePolicy();
+ }
+ }
+
+ public String deleteResourcePolicy(String resourceArn, String region) {
+ String id = extractId(resourceArn);
+ String oldPolicy = null;
+ if (id.startsWith("backup-")) {
+ Backup backup = getBackup(id, region);
+ oldPolicy = backup.getResourcePolicy();
+ backup.setResourcePolicy(null);
+ backups.put(regionKey(region, id), backup);
+ } else {
+ Cluster cluster = getCluster(id, region);
+ oldPolicy = cluster.getResourcePolicy();
+ cluster.setResourcePolicy(null);
+ clusters.put(regionKey(region, id), cluster);
+ }
+ return oldPolicy;
+ }
+
+ private String extractId(String arn) {
+ if (arn == null) {
+ throw new AwsException("CloudHsmInvalidRequestException", "Invalid ResourceArn format", 400);
+ }
+ if (arn.contains("backup/")) {
+ return arn.substring(arn.lastIndexOf('/') + 1);
+ } else if (arn.contains("cluster/")) {
+ return arn.substring(arn.lastIndexOf('/') + 1);
+ }
+ if (arn.startsWith("cluster-") || arn.startsWith("backup-")) {
+ return arn;
+ }
+ throw new AwsException("CloudHsmInvalidRequestException", "Invalid ResourceArn format", 400);
+ }
+
+ // ──────────────────────────── ModifyCluster ────────────────────────────
+
+ public Cluster modifyCluster(String clusterId, String hsmType, BackupRetentionPolicy backupRetentionPolicy, String region) {
+ Cluster cluster = getCluster(clusterId, region);
+ if (hsmType != null && !hsmType.matches("^((p|)hsm[0-9][a-z.]*\\.[a-zA-Z]+)$")) {
+ throw new AwsException("CloudHsmInvalidRequestException", "HsmType " + hsmType + " is not valid.", 400);
+ }
+ if (hsmType != null) {
+ cluster.setHsmType(hsmType);
+ }
+ if (backupRetentionPolicy != null) {
+ String valStr = backupRetentionPolicy.getValue();
+ if (valStr == null) {
+ throw new AwsException("CloudHsmInvalidRequestException", "BackupRetentionPolicy Value is missing.", 400);
+ }
+ try {
+ int val = Integer.parseInt(valStr);
+ if (val < 7 || val > 379) {
+ throw new AwsException("CloudHsmInvalidRequestException", "BackupRetentionPolicy Value must be between 7 and 379.", 400);
+ }
+ } catch (NumberFormatException e) {
+ throw new AwsException("CloudHsmInvalidRequestException", "BackupRetentionPolicy Value must be a valid integer.", 400);
+ }
+ cluster.setBackupRetentionPolicy(backupRetentionPolicy);
+ }
+ clusters.put(regionKey(region, clusterId), cluster);
+ return cluster;
+ }
+
+ private Backup getBackup(String backupId, String region) {
+ if (backupId == null || backupId.isBlank()) {
+ throw new AwsException("CloudHsmInvalidRequestException", "BackupId is required.", 400);
+ }
+ return backups.get(regionKey(region, backupId)).orElseThrow(() ->
+ new AwsException("CloudHsmResourceNotFoundException", "Backup " + backupId + " not found.", 400));
+ }
+
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Backup.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Backup.java
new file mode 100644
index 0000000000..e8ce2541bf
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Backup.java
@@ -0,0 +1,141 @@
+package io.github.hectorvent.floci.services.cloudhsmv2.model;
+
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/**
+ * Domain model for a CloudHSM v2 Backup.
+ */
+@RegisterForReflection
+public class Backup {
+
+ private String backupId;
+ private String backupState;
+ private String clusterId;
+ private Instant createTimestamp;
+ private Instant deleteTimestamp;
+ private Instant copyTimestamp;
+ private String neverExpires;
+ private String sourceRegion;
+ private String sourceBackup;
+ private String sourceCluster;
+ private String resourcePolicy;
+ private Map<String, String> tagList = new LinkedHashMap<>();
+ private String mode;
+ private String hsmType;
+
+ public String getBackupId() {
+ return backupId;
+ }
+
+ public void setBackupId(String backupId) {
+ this.backupId = backupId;
+ }
+
+ public String getBackupState() {
+ return backupState;
+ }
+
+ public void setBackupState(String backupState) {
+ this.backupState = backupState;
+ }
+
+ public String getClusterId() {
+ return clusterId;
+ }
+
+ public void setClusterId(String clusterId) {
+ this.clusterId = clusterId;
+ }
+
+ public Instant getCreateTimestamp() {
+ return createTimestamp;
+ }
+
+ public void setCreateTimestamp(Instant createTimestamp) {
+ this.createTimestamp = createTimestamp;
+ }
+
+ public Instant getDeleteTimestamp() {
+ return deleteTimestamp;
+ }
+
+ public void setDeleteTimestamp(Instant deleteTimestamp) {
+ this.deleteTimestamp = deleteTimestamp;
+ }
+
+ public Instant getCopyTimestamp() {
+ return copyTimestamp;
+ }
+
+ public void setCopyTimestamp(Instant copyTimestamp) {
+ this.copyTimestamp = copyTimestamp;
+ }
+
+ public String getNeverExpires() {
+ return neverExpires;
+ }
+
+ public void setNeverExpires(String neverExpires) {
+ this.neverExpires = neverExpires;
+ }
+
+ public String getSourceRegion() {
+ return sourceRegion;
+ }
+
+ public void setSourceRegion(String sourceRegion) {
+ this.sourceRegion = sourceRegion;
+ }
+
+ public String getSourceBackup() {
+ return sourceBackup;
+ }
+
+ public void setSourceBackup(String sourceBackup) {
+ this.sourceBackup = sourceBackup;
+ }
+
+ public String getSourceCluster() {
+ return sourceCluster;
+ }
+
+ public void setSourceCluster(String sourceCluster) {
+ this.sourceCluster = sourceCluster;
+ }
+
+ public String getResourcePolicy() {
+ return resourcePolicy;
+ }
+
+ public void setResourcePolicy(String resourcePolicy) {
+ this.resourcePolicy = resourcePolicy;
+ }
+
+ public Map<String, String> getTagList() {
+ return tagList;
+ }
+
+ public void setTagList(Map<String, String> tagList) {
+ this.tagList = tagList != null ? tagList : new LinkedHashMap<>();
+ }
+
+ public String getMode() {
+ return mode;
+ }
+
+ public void setMode(String mode) {
+ this.mode = mode;
+ }
+
+ public String getHsmType() {
+ return hsmType;
+ }
+
+ public void setHsmType(String hsmType) {
+ this.hsmType = hsmType;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/BackupRetentionPolicy.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/BackupRetentionPolicy.java
new file mode 100644
index 0000000000..6ba57229b7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/BackupRetentionPolicy.java
@@ -0,0 +1,32 @@
+package io.github.hectorvent.floci.services.cloudhsmv2.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+public class BackupRetentionPolicy {
+ private String type;
+ private String value;
+
+ public BackupRetentionPolicy() {}
+
+ public BackupRetentionPolicy(String type, String value) {
+ this.type = type;
+ this.value = value;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Certificates.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Certificates.java
new file mode 100644
index 0000000000..4878a4abeb
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Certificates.java
@@ -0,0 +1,60 @@
+package io.github.hectorvent.floci.services.cloudhsmv2.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/**
+ * Certificate bundle for a CloudHSM v2 cluster.
+ *
+ * <p>Maps to the AWS {@code Certificates} structure returned in {@code DescribeClusters}.
+ * The CSR is generated at cluster creation; the remaining fields are populated during
+ * initialization.
+ */
+@RegisterForReflection
+public class Certificates {
+
+ private String clusterCsr;
+ private String hsmCertificate;
+ private String awsHardwareCertificate;
+ private String manufacturerHardwareCertificate;
+ private String clusterCertificate;
+
+ public String getClusterCsr() {
+ return clusterCsr;
+ }
+
+ public void setClusterCsr(String clusterCsr) {
+ this.clusterCsr = clusterCsr;
+ }
+
+ public String getHsmCertificate() {
+ return hsmCertificate;
+ }
+
+ public void setHsmCertificate(String hsmCertificate) {
+ this.hsmCertificate = hsmCertificate;
+ }
+
+ public String getAwsHardwareCertificate() {
+ return awsHardwareCertificate;
+ }
+
+ public void setAwsHardwareCertificate(String awsHardwareCertificate) {
+ this.awsHardwareCertificate = awsHardwareCertificate;
+ }
+
+ public String getManufacturerHardwareCertificate() {
+ return manufacturerHardwareCertificate;
+ }
+
+ public void setManufacturerHardwareCertificate(String manufacturerHardwareCertificate) {
+ this.manufacturerHardwareCertificate = manufacturerHardwareCertificate;
+ }
+
+ public String getClusterCertificate() {
+ return clusterCertificate;
+ }
+
+ public void setClusterCertificate(String clusterCertificate) {
+ this.clusterCertificate = clusterCertificate;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Cluster.java
new file mode 100644
index 0000000000..bc4fe8e466
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Cluster.java
@@ -0,0 +1,187 @@
+package io.github.hectorvent.floci.services.cloudhsmv2.model;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/**
+ * Domain model for a CloudHSM v2 cluster.
+ *
+ * <p>Follows the same mutable-POJO pattern used by other Floci service models
+ * (e.g. MemoryDB {@code Cluster}, ACM {@code Certificate}).
+ */
+@RegisterForReflection
+public class Cluster {
+
+ private String clusterId;
+ private ClusterState state;
+ private String stateMessage;
+ private String hsmType;
+ private String vpcId;
+ private String sourceBackupId;
+ private Certificates certificates;
+ private List<Hsm> hsms = new ArrayList<>();
+ private List<String> subnetIds = new ArrayList<>();
+ private Map<String, String> subnetMapping = new LinkedHashMap<>();
+ private String securityGroup;
+ private Instant createTimestamp;
+ private Map<String, String> tagList = new LinkedHashMap<>();
+ private String backupPolicy;
+ private BackupRetentionPolicy backupRetentionPolicy;
+ private String resourcePolicy;
+ private String mode;
+ private String networkType;
+
+ public String getClusterId() {
+ return clusterId;
+ }
+
+ public void setClusterId(String clusterId) {
+ this.clusterId = clusterId;
+ }
+
+ public ClusterState getState() {
+ return state;
+ }
+
+ public void setState(ClusterState state) {
+ this.state = state;
+ }
+
+ public String getStateMessage() {
+ return stateMessage;
+ }
+
+ public void setStateMessage(String stateMessage) {
+ this.stateMessage = stateMessage;
+ }
+
+ public String getHsmType() {
+ return hsmType;
+ }
+
+ public void setHsmType(String hsmType) {
+ this.hsmType = hsmType;
+ }
+
+ public String getVpcId() {
+ return vpcId;
+ }
+
+ public void setVpcId(String vpcId) {
+ this.vpcId = vpcId;
+ }
+
+ public String getSourceBackupId() {
+ return sourceBackupId;
+ }
+
+ public void setSourceBackupId(String sourceBackupId) {
+ this.sourceBackupId = sourceBackupId;
+ }
+
+ public Certificates getCertificates() {
+ return certificates;
+ }
+
+ public void setCertificates(Certificates certificates) {
+ this.certificates = certificates;
+ }
+
+ public List<Hsm> getHsms() {
+ return hsms;
+ }
+
+ public void setHsms(List<Hsm> hsms) {
+ this.hsms = hsms != null ? hsms : new ArrayList<>();
+ }
+
+ public List<String> getSubnetIds() {
+ return subnetIds;
+ }
+
+ public void setSubnetIds(List<String> subnetIds) {
+ this.subnetIds = subnetIds != null ? subnetIds : new ArrayList<>();
+ }
+
+ public Map<String, String> getSubnetMapping() {
+ return subnetMapping;
+ }
+
+ public void setSubnetMapping(Map<String, String> subnetMapping) {
+ this.subnetMapping = subnetMapping != null ? subnetMapping : new LinkedHashMap<>();
+ }
+
+ public String getSecurityGroup() {
+ return securityGroup;
+ }
+
+ public void setSecurityGroup(String securityGroup) {
+ this.securityGroup = securityGroup;
+ }
+
+ public Instant getCreateTimestamp() {
+ return createTimestamp;
+ }
+
+ public void setCreateTimestamp(Instant createTimestamp) {
+ this.createTimestamp = createTimestamp;
+ }
+
+ public Map<String, String> getTagList() {
+ return tagList;
+ }
+
+ public void setTagList(Map<String, String> tagList) {
+ this.tagList = tagList != null ? tagList : new LinkedHashMap<>();
+ }
+
+ public String getBackupPolicy() {
+ return backupPolicy;
+ }
+
+ public void setBackupPolicy(String backupPolicy) {
+ this.backupPolicy = backupPolicy;
+ }
+
+ public BackupRetentionPolicy getBackupRetentionPolicy() {
+ return backupRetentionPolicy;
+ }
+
+ public void setBackupRetentionPolicy(BackupRetentionPolicy backupRetentionPolicy) {
+ this.backupRetentionPolicy = backupRetentionPolicy;
+ }
+
+ public String getResourcePolicy() {
+ return resourcePolicy;
+ }
+
+ public void setResourcePolicy(String resourcePolicy) {
+ this.resourcePolicy = resourcePolicy;
+ }
+
+ public String getMode() {
+ return mode;
+ }
+
+ public void setMode(String mode) {
+ this.mode = mode;
+ }
+
+ public String getNetworkType() {
+ return networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ /** True when the cluster has been initialized and has at least one HSM. */
+ public boolean isReadyForActive() {
+ return state == ClusterState.INITIALIZED && !hsms.isEmpty();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/ClusterState.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/ClusterState.java
new file mode 100644
index 0000000000..701c770467
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/ClusterState.java
@@ -0,0 +1,40 @@
+package io.github.hectorvent.floci.services.cloudhsmv2.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/**
+ * CloudHSM v2 cluster lifecycle states.
+ *
+ * <p>A cluster starts as {@link #UNINITIALIZED} when created, transitions to
+ * {@link #INITIALIZED} after {@code InitializeCluster} succeeds, and finally
+ * reaches {@link #ACTIVE} once it is initialized <em>and</em> has at least one HSM.
+ */
+@RegisterForReflection
+public enum ClusterState {
+
+ CREATE_IN_PROGRESS,
+ UNINITIALIZED,
+ INITIALIZE_IN_PROGRESS,
+ INITIALIZED,
+ ACTIVE,
+ UPDATE_IN_PROGRESS,
+ DELETE_IN_PROGRESS,
+ DELETED,
+ DEGRADED;
+
+ /** Returns the AWS wire representation (e.g. {@code "UNINITIALIZED"}). */
+ public String wireValue() {
+ return name();
+ }
+
+ public static ClusterState fromWire(String value) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ try {
+ return valueOf(value);
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("Unknown ClusterState: " + value);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Hsm.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Hsm.java
new file mode 100644
index 0000000000..6a7563669d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/model/Hsm.java
@@ -0,0 +1,121 @@
+package io.github.hectorvent.floci.services.cloudhsmv2.model;
+
+import java.time.Instant;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/**
+ * Represents an HSM instance within a CloudHSM v2 cluster.
+ */
+@RegisterForReflection
+public class Hsm {
+
+ private String hsmId;
+ private String availabilityZone;
+ private String clusterId;
+ private String subnetId;
+ private String eniId;
+ private String eniIp;
+ private String ipAddress;
+ private String state;
+ private String stateMessage;
+ private Instant createdAt;
+ private String eniIpV6;
+ private String hsmType;
+
+ public String getHsmId() {
+ return hsmId;
+ }
+
+ public void setHsmId(String hsmId) {
+ this.hsmId = hsmId;
+ }
+
+ public String getAvailabilityZone() {
+ return availabilityZone;
+ }
+
+ public void setAvailabilityZone(String availabilityZone) {
+ this.availabilityZone = availabilityZone;
+ }
+
+ public String getClusterId() {
+ return clusterId;
+ }
+
+ public void setClusterId(String clusterId) {
+ this.clusterId = clusterId;
+ }
+
+ public String getSubnetId() {
+ return subnetId;
+ }
+
+ public void setSubnetId(String subnetId) {
+ this.subnetId = subnetId;
+ }
+
+ public String getEniId() {
+ return eniId;
+ }
+
+ public void setEniId(String eniId) {
+ this.eniId = eniId;
+ }
+
+ public String getEniIp() {
+ return eniIp;
+ }
+
+ public void setEniIp(String eniIp) {
+ this.eniIp = eniIp;
+ }
+
+ public String getIpAddress() {
+ return ipAddress;
+ }
+
+ public void setIpAddress(String ipAddress) {
+ this.ipAddress = ipAddress;
+ }
+
+ public String getState() {
+ return state;
+ }
+
+ public void setState(String state) {
+ this.state = state;
+ }
+
+ public String getStateMessage() {
+ return stateMessage;
+ }
+
+ public void setStateMessage(String stateMessage) {
+ this.stateMessage = stateMessage;
+ }
+
+ public Instant getCreatedAt() {
+ return createdAt;
+ }
+
+ public void setCreatedAt(Instant createdAt) {
+ this.createdAt = createdAt;
+ }
+
+ public String getEniIpV6() {
+ return eniIpV6;
+ }
+
+ public void setEniIpV6(String eniIpV6) {
+ this.eniIpV6 = eniIpV6;
+ }
+
+ public String getHsmType() {
+ return hsmType;
+ }
+
+ public void setHsmType(String hsmType) {
+ this.hsmType = hsmType;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
index 4f99898149..b39f318876 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
@@ -463,7 +463,6 @@ public class CloudWatchLogsService {
private AwsException invalidNextToken() {
return new AwsException("InvalidParameterException", "The specified nextToken is invalid.", 400);
}
-
/**
* A FilterLogEvents match paired with the stream that emitted it. FilterLogEvents is the
* cross-stream API, so the stream is what lets a caller attribute a hit; GetLogEvents needs
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 280c84b52b..53a0ac2cdf 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -492,5 +492,6 @@ floci:
port: 1883
iotdata:
enabled: true
+ cloudhsmv2:
rum:
enabled: true
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2IntegrationTest.java
new file mode 100644
index 0000000000..f7e549079e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2IntegrationTest.java
@@ -0,0 +1,925 @@
+package io.github.hectorvent.floci.services.cloudhsmv2;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class CloudHsmV2IntegrationTest {
+
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String TARGET_PREFIX = "BaldrApiService.";
+
+ private String createdClusterId;
+ private String createdHsmId;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ // ──────────────────────────── CreateCluster ────────────────────────────
+
+ @Test
+ @Order(1)
+ void createClusterBasic() {
+ createdClusterId = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "HsmType": "hsm1.medium",
+ "SubnetIds": ["subnet-abcdef01"]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Cluster.ClusterId", startsWith("cluster-"))
+ .body("Cluster.State", equalTo("UNINITIALIZED"))
+ .body("Cluster.HsmType", equalTo("hsm1.medium"))
+ .body("Cluster.VpcId", startsWith("vpc-"))
+ .body("Cluster.SecurityGroup", startsWith("sg-"))
+ .body("Cluster.BackupPolicy", equalTo("DEFAULT"))
+ .body("Cluster.CreateTimestamp", notNullValue())
+ .body("Cluster.Certificates", notNullValue())
+ .body("Cluster.Certificates.ClusterCsr", startsWith("-----BEGIN CERTIFICATE REQUEST-----"))
+ .body("Cluster.Certificates.AwsHardwareCertificate", startsWith("-----BEGIN CERTIFICATE-----"))
+ .body("Cluster.Certificates.ManufacturerHardwareCertificate", startsWith("-----BEGIN CERTIFICATE-----"))
+ .body("Cluster.Certificates.HsmCertificate", startsWith("-----BEGIN CERTIFICATE-----"))
+ .body("Cluster.Hsms", empty())
+ .extract().jsonPath().getString("Cluster.ClusterId");
+ }
+
+ @Test
+ @Order(2)
+ void createClusterMissingSubnetIdsFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "HsmType": "hsm1.medium"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(3)
+ void createClusterEmptySubnetIdsFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "HsmType": "hsm1.medium",
+ "SubnetMapping": {}
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(4)
+ void createClusterWithoutHsmTypeFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "SubnetIds": ["subnet-12345678"]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+ // ──────────────────────────── DescribeClusters ────────────────────────────
+
+ @Test
+ @Order(10)
+ void describeClustersReturnsAll() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters", notNullValue())
+ .body("Clusters.size()", greaterThanOrEqualTo(1));
+ }
+
+ @Test
+ @Order(11)
+ void describeClustersFilterByClusterId() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters.size()", equalTo(1))
+ .body("Clusters[0].ClusterId", equalTo(createdClusterId))
+ .body("Clusters[0].State", equalTo("UNINITIALIZED"))
+ .body("Clusters[0].Certificates.ClusterCsr", startsWith("-----BEGIN CERTIFICATE REQUEST-----"));
+ }
+
+ @Test
+ @Order(12)
+ void describeClustersFilterByState() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "states": ["UNINITIALIZED"]
+ }
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters", notNullValue())
+ .body("Clusters.size()", greaterThanOrEqualTo(1))
+ .body("Clusters.every { it.State == 'UNINITIALIZED' }", is(true));
+ }
+
+ @Test
+ @Order(13)
+ void describeClustersFilterNoMatch() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["cluster-nonexistent"]
+ }
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters.size()", equalTo(0));
+ }
+
+ // ──────────────────────────── CSR Generation ────────────────────────────
+
+ @Test
+ @Order(14)
+ void csrIsValidPem() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters[0].Certificates.ClusterCsr", startsWith("-----BEGIN CERTIFICATE REQUEST-----"))
+ .body("Clusters[0].Certificates.ClusterCsr", containsString("-----END CERTIFICATE REQUEST-----"));
+ }
+
+ // ──────────────────────────── InitializeCluster ────────────────────────────
+
+ @Test
+ @Order(20)
+ void initializeClusterMissingSignedCertFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "InitializeCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "TrustAnchor": "-----BEGIN CERTIFICATE-----\\nMIIBxTCCAW4=\\n-----END CERTIFICATE-----"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(21)
+ void initializeClusterMissingTrustAnchorFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "InitializeCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "SignedCert": "-----BEGIN CERTIFICATE-----\\nMIIBxTCCAW4=\\n-----END CERTIFICATE-----"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(22)
+ void initializeClusterInvalidPemFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "InitializeCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "SignedCert": "not-a-pem-certificate",
+ "TrustAnchor": "also-not-a-pem-certificate"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(23)
+ void initializeClusterMalformedPemFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "InitializeCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "SignedCert": "-----BEGIN CERTIFICATE-----\\ncorrupted-base64\\n-----END CERTIFICATE-----",
+ "TrustAnchor": "-----BEGIN CERTIFICATE-----\\ncorrupted-base64\\n-----END CERTIFICATE-----"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(24)
+ void initializeClusterNonExistentClusterFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "InitializeCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "cluster-nonexistent",
+ "SignedCert": "-----BEGIN CERTIFICATE-----\\nMIIBxTCCAW4=\\n-----END CERTIFICATE-----",
+ "TrustAnchor": "-----BEGIN CERTIFICATE-----\\nMIIBxTCCAW4=\\n-----END CERTIFICATE-----"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmResourceNotFoundException"));
+ }
+
+ @Test
+ @Order(30)
+ void initializeClusterSuccess() {
+ // Get the hardware certs from the cluster to use as valid PEM for initialization
+ String csr = given().header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters").contentType(CONTENT_TYPE).body("{\"Filters\":{\"clusterIds\":[\"" + createdClusterId + "\"]}}").when().post("/").then().statusCode(200).extract().jsonPath().getString("Clusters[0].Certificates.ClusterCsr");
+ String[] certs;
+ try { certs = generateCerts(csr); } catch (Exception e) { throw new RuntimeException(e); }
+ String signedCert = certs[0];
+ String trustAnchor = certs[1];
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "InitializeCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "SignedCert": %s,
+ "TrustAnchor": %s
+ }
+ """.formatted(createdClusterId,
+ jsonString(signedCert), jsonString(trustAnchor)))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("State", equalTo("INITIALIZED"))
+ .body("StateMessage", notNullValue());
+ }
+
+ @Test
+ @Order(31)
+ void initializeClusterAlreadyInitializedFails() {
+ String csr = given().header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters").contentType(CONTENT_TYPE).body("{\"Filters\":{\"clusterIds\":[\"" + createdClusterId + "\"]}}").when().post("/").then().statusCode(200).extract().jsonPath().getString("Clusters[0].Certificates.ClusterCsr");
+ String[] certs;
+ try { certs = generateCerts(csr); } catch (Exception e) { throw new RuntimeException(e); }
+ String signedCert = certs[0];
+ String trustAnchor = certs[1];
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "InitializeCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "SignedCert": %s,
+ "TrustAnchor": %s
+ }
+ """.formatted(createdClusterId,
+ jsonString(signedCert), jsonString(trustAnchor)))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(32)
+ void describeClustersShowsInitializedState() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters[0].State", equalTo("INITIALIZED"))
+ .body("Clusters[0].Certificates.ClusterCertificate", notNullValue());
+ }
+
+ // ──────────────────────────── Persistence ────────────────────────────
+
+ @Test
+ @Order(33)
+ void clusterCertificatePersistedAfterInit() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters[0].Certificates.ClusterCertificate", startsWith("-----BEGIN CERTIFICATE-----"))
+ .body("Clusters[0].Certificates.ClusterCsr", startsWith("-----BEGIN CERTIFICATE REQUEST-----"));
+ }
+
+ // ──────────────────────────── ACTIVE Gating ────────────────────────────
+
+ @Test
+ @Order(40)
+ void clusterDoesNotBecomeActiveWithoutHsm() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters[0].State", equalTo("INITIALIZED"))
+ .body("Clusters[0].Hsms.size()", equalTo(0));
+ }
+
+ @Test
+ @Order(41)
+ void createHsmTransitionsClusterToActive() {
+ createdHsmId = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "AvailabilityZone": "us-east-1a"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Hsm.HsmId", startsWith("hsm-"))
+ .body("Hsm.AvailabilityZone", equalTo("us-east-1a"))
+ .body("Hsm.ClusterId", equalTo(createdClusterId))
+ .body("Hsm.State", equalTo("ACTIVE"))
+ .extract().jsonPath().getString("Hsm.HsmId");
+
+ // Cluster should now be ACTIVE
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters[0].State", equalTo("ACTIVE"))
+ .body("Clusters[0].Hsms.size()", equalTo(1))
+ .body("Clusters[0].Hsms[0].HsmId", equalTo(createdHsmId));
+ }
+
+ @Test
+ @Order(42)
+ void deleteHsmRevertsClusterToInitialized() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "HsmId": "%s"
+ }
+ """.formatted(createdClusterId, createdHsmId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("HsmId", equalTo(createdHsmId));
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters[0].State", equalTo("INITIALIZED"))
+ .body("Clusters[0].Hsms.size()", equalTo(0));
+ }
+
+ @Test
+ @Order(43)
+ void deleteHsmByEniIdSuccess() {
+ // Create an HSM
+ String hsmId = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "AvailabilityZone": "us-east-1a"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Hsm.HsmId");
+
+ // Get its EniId
+ String eniId = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Clusters[0].Hsms.find { it.HsmId == '%s' }.EniId".formatted(hsmId));
+
+ // Delete by EniId
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "EniId": "%s"
+ }
+ """.formatted(createdClusterId, eniId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("HsmId", equalTo(hsmId));
+ }
+
+ @Test
+ @Order(44)
+ void deleteHsmByEniIpSuccess() {
+ // Create an HSM
+ String hsmId = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "AvailabilityZone": "us-east-1a"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Hsm.HsmId");
+
+ // Get its EniIp
+ String eniIp = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Clusters[0].Hsms.find { it.HsmId == '%s' }.EniIp".formatted(hsmId));
+
+ // Delete by EniIp
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "EniIp": "%s"
+ }
+ """.formatted(createdClusterId, eniIp))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("HsmId", equalTo(hsmId));
+ }
+
+ // ──────────────────────────── Error Responses ────────────────────────────
+
+ @Test
+ @Order(50)
+ void createHsmMissingAzFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(51)
+ void deleteHsmNotFoundFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "HsmId": "hsm-nonexistent"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmResourceNotFoundException"));
+ }
+
+ @Test
+ @Order(52)
+ void deleteHsmMissingSelectorFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(53)
+ void deleteHsmMultipleSelectorsFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "HsmId": "hsm-abc",
+ "EniId": "eni-xyz"
+ }
+ """.formatted(createdClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(54)
+ void deleteClusterWithHsmsFails() {
+ // Create a cluster, add an HSM, then try to delete the cluster
+ String tempClusterId = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "HsmType": "hsm1.medium",
+ "SubnetIds": ["subnet-temptest01"]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Cluster.ClusterId");
+
+ String csr = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(tempClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Clusters[0].Certificates.ClusterCsr");
+
+ String[] certs;
+ try { certs = generateCerts(csr); } catch (Exception e) { throw new RuntimeException(e); }
+ String signedCert = certs[0];
+ String trustAnchor = certs[1];
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "InitializeCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "SignedCert": %s,
+ "TrustAnchor": %s
+ }
+ """.formatted(tempClusterId, jsonString(signedCert), jsonString(trustAnchor)))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateHsm")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s",
+ "AvailabilityZone": "us-east-1a"
+ }
+ """.formatted(tempClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s"
+ }
+ """.formatted(tempClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmInvalidRequestException"));
+ }
+
+ @Test
+ @Order(60)
+ void unsupportedOperationReturnsError() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "SomeUnsupportedAction")
+ .contentType(CONTENT_TYPE)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("UnknownOperationException"));
+ }
+
+ // ──────────────────────────── DeleteCluster ────────────────────────────
+
+ @Test
+ @Order(100)
+ void deleteClusterSuccess() {
+ // Create a fresh cluster to delete
+ String tempClusterId = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "HsmType": "hsm1.medium",
+ "SubnetIds": ["subnet-deletetest"]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Cluster.ClusterId");
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "%s"
+ }
+ """.formatted(tempClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Cluster.State", equalTo("DELETE_IN_PROGRESS"));
+
+ // Verify it's gone
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeClusters")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Filters": {
+ "clusterIds": ["%s"]
+ }
+ }
+ """.formatted(tempClusterId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Clusters.size()", equalTo(0));
+ }
+
+ @Test
+ @Order(101)
+ void deleteClusterNotFoundFails() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ClusterId": "cluster-nonexistent"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("CloudHsmResourceNotFoundException"));
+ }
+
+ /** Escapes a PEM string as a JSON string value. */
+ private static String jsonString(String pem) {
+ if (pem == null) {
+ return "null";
+ }
+ return "\"" + pem
+ .replace("\\", "\\\\")
+ .replace("\"", "\\\"")
+ .replace("\n", "\\n")
+ .replace("\r", "\\r")
+ + "\"";
+ }
+
+ private String[] generateCerts(String csrPem) throws Exception {
+ java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
+ java.security.KeyPairGenerator keyGen = java.security.KeyPairGenerator.getInstance("RSA", "BC");
+ keyGen.initialize(2048, new java.security.SecureRandom());
+ java.security.KeyPair caKeyPair = keyGen.generateKeyPair();
+ org.bouncycastle.asn1.x500.X500Name caName = new org.bouncycastle.asn1.x500.X500Name("CN=Floci Test CA");
+ long now = System.currentTimeMillis();
+ java.util.Date startDate = new java.util.Date(now);
+ java.util.Date endDate = new java.util.Date(now + 365L * 24 * 3600 * 1000);
+ java.math.BigInteger serial = java.math.BigInteger.valueOf(now);
+ org.bouncycastle.cert.X509v3CertificateBuilder caBuilder = new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder(
+ caName, serial, startDate, endDate, caName, caKeyPair.getPublic());
+ org.bouncycastle.operator.ContentSigner caSigner = new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256WithRSA")
+ .setProvider("BC").build(caKeyPair.getPrivate());
+ org.bouncycastle.cert.X509CertificateHolder caHolder = caBuilder.build(caSigner);
+ java.io.StringWriter caSw = new java.io.StringWriter();
+ try (org.bouncycastle.openssl.jcajce.JcaPEMWriter pw = new org.bouncycastle.openssl.jcajce.JcaPEMWriter(caSw)) {
+ pw.writeObject(caHolder);
+ }
+ String trustAnchor = caSw.toString();
+ org.bouncycastle.pkcs.PKCS10CertificationRequest csr;
+ try (org.bouncycastle.openssl.PEMParser parser = new org.bouncycastle.openssl.PEMParser(new java.io.StringReader(csrPem))) {
+ csr = (org.bouncycastle.pkcs.PKCS10CertificationRequest) parser.readObject();
+ }
+ java.security.PublicKey csrPublicKey = new org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter().setProvider("BC").getPublicKey(csr.getSubjectPublicKeyInfo());
+ org.bouncycastle.cert.X509v3CertificateBuilder certBuilder = new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder(
+ caName, serial.add(java.math.BigInteger.ONE), startDate, endDate, csr.getSubject(), csrPublicKey);
+ org.bouncycastle.cert.X509CertificateHolder certHolder = certBuilder.build(caSigner);
+ java.io.StringWriter certSw = new java.io.StringWriter();
+ try (org.bouncycastle.openssl.jcajce.JcaPEMWriter pw = new org.bouncycastle.openssl.jcajce.JcaPEMWriter(certSw)) {
+ pw.writeObject(certHolder);
+ }
+ String signedCert = certSw.toString();
+ return new String[]{signedCert, trustAnchor};
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PublicIpOnLaunchTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PublicIpOnLaunchTest.java
index 750b02b2f5..82ab79afa8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PublicIpOnLaunchTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PublicIpOnLaunchTest.java
@@ -4,6 +4,14 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.ec2.model.Address;
+import io.github.hectorvent.floci.services.ec2.model.Image;
+import io.github.hectorvent.floci.services.ec2.model.InternetGateway;
+import io.github.hectorvent.floci.services.ec2.model.KeyPair;
+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
+import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
+import io.github.hectorvent.floci.services.ec2.model.NatGateway;
+import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 1082e9202a..b3c85d7738 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -304,5 +304,6 @@ floci:
port: 1883
iotdata:
enabled: true
+ cloudhsmv2:
rum:
enabled: true
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index b4c3b0f54a..334065176c 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -26,6 +26,10 @@ services:
doc: docs/services/cloudformation.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java, mode: switch }
+ - service: cloudhsmv2
+ doc: docs/services/cloudhsmv2.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java, mode: switch }
- service: cloudtrail
doc: docs/services/cloudtrail.md
sources: