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

* feat(cloudhsmv2): implement CloudHSM v2 service

* refactor(cloudhsmv2): delete HSM parameters and docs

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

* fix: greptile bot reviews

* refactor(cloudhsmv2): delete HSM parameters and docs

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

* fix: greptile bot reviews

* fix(cloudhsmv2): fix backup retention policy parsing and SDK test cert usage

* fix(cloudhsmv2): fix CreateHsm IP generation, ModifyCluster validation, and duplicate test Order

* docs(cloudhsmv2): add service to mkdocs, readme, and index matrices

* fix(rds): preserve configured database images (#2035)

* fix(cloudhsmv2): resolve remaining AWS-compatibility edge cases

* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency (#1810)

* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency

A Map state ran its iterations one after another. AWS runs them
concurrently up to MaxConcurrency (default 0 = unlimited), which is a
correctness requirement, not just a speed-up: a Map whose iterations
coordinate — e.g. a dependency-ordered fan-out where one child blocks
until a sibling completes — deadlocks when the iterations are serialised.

Run each iteration on the shared executor under the execution's account,
gated by a Semaphore sized to MaxConcurrency (unlimited when 0). Results
are written into per-index slots so the output array preserves input order
regardless of completion order, MaxConcurrency=1 stays strictly sequential,
and a failed iteration cancels the rest and fails the Map (fail-fast,
matching the default ToleratedFailureCount of 0).

* fix(stepfunctions): cap Map worker threads with a bounded pool + handle interruption

Address review: submitting every iteration to the shared cached pool behind
a Semaphore spawned one thread per item (a 1000-item Map with
MaxConcurrency=5 created ~1000 threads, ~995 parked). Run iterations on a
fixed-size per-Map ThreadPoolExecutor sized to MaxConcurrency so live
threads are capped and the rest queue. shutdownNow() in finally stops the
iterations on any exit, and an InterruptedException from the driver now
preserves the interrupt status.

* fix(stepfunctions): make Map concurrency bounded and fail-fast

* docs(stepfunctions): document map concurrency

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after OpenTofu registry flake

* test(stepfunctions): pin Map item selection order

* perf(lambda): reuse a populated code volume across restarts via a completion marker (#1827)

* perf(lambda): reuse populated code volumes across restarts

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* ci: retry transient gosu downloads

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>

* fix(apigateway): apply MOCK integration response headers (#1822)

* fix(apigateway): apply mock response headers for OPTIONS

* refactor(apigateway): drop the OPTIONS route in favour of #1955

Both this PR and #1955 added an @OPTIONS method on the same @Path in
ApiGatewayExecuteController and ApiGatewayUserRequestController, so whichever
merged second would not have compiled.

#1955's version is the more complete one: it covers ApiGatewayAwsExecuteController
(the /_aws/execute-api path) as well, forwards the request body, and skips
GlobalCorsFilter for deployed-API paths -- without which a real browser preflight
is short-circuited before it ever reaches the route.

This PR keeps only its own contribution: invokeMock returned early on the
empty-response-template path and dropped static method.response.header.* mappings.
ApiGatewayMockCorsHeadersTest now exercises that over GET, since the dropped-header
bug is verb-agnostic, leaving the two PRs independently mergeable in either order.

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after autoscaling test flake

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>

* fix(cloudwatch): return logStreamName on FilterLogEvents results (#2259)

FilterLogEvents is the cross-stream search API, so a match is only
attributable if the response names the stream that emitted it. Floci
served FilterLogEvents and GetLogEvents from one serializer emitting
eventId, timestamp, message and ingestionTime, so a caller searching a
whole log group could tell which group a hit came from but not which
stream, and tooling written against real AWS lost that attribution
without any error.

Derive the stream from the event's storage key rather than persisting it
on the event. Keys are already
<region>::<group>::<stream>::<timestamp>::<uuid>, so the key is an
authoritative record of the emitter for every event in the store,
including ones written before this change. Storing the name on LogEvent
instead would leave every already-persisted event with a null
logStreamName and need a backfill pass to repair it. The stream is read
back between the group prefix and the trailing timestamp and uuid, both
generated here, so a stream name is recovered whole even though nothing
stops a caller from creating one that holds a ':'.

filterLogEvents walks the keyset once and pairs each event with its
stream, which also collapses the stream-restricted branch: it previously
ran one full keyset scan per requested stream, since a scan walks every
key regardless of the prefix it filters on.

GetLogEvents keeps its existing shape. Real AWS returns OutputLogEvent
there, which carries no logStreamName, because the caller named the
stream in the request.

Closes #2210

* fix(ec2): start sshd even when run-instances omits a key pair (#2245)

* fix(ec2): start sshd even when run-instances omits a key pair

Reported in #2184: run-instances without --key-name left every
container with no SSH daemon listening at all, "connection refused"
regardless of image (alpine, Amazon Linux 2023, Ubuntu all affected).

The cause: startSshd() only ran inside the same conditional as
injectSshKey(), so no key pair meant sshd never started. Real AWS AMIs
run sshd as part of normal boot regardless of whether a key pair is
attached - the daemon is always there, it just has nothing to
authenticate an unattached client with. Floci's behavior diverged by
not running the daemon at all in that case, rather than running it and
correctly having no way in.

Splits the two: injectSshKey still only runs when a key was actually
provided (nothing to inject otherwise), but startSshd now always runs.
It's fully self-contained already (installs openssh-server if absent,
generates host keys, starts the daemon) and never depended on anything
injectSshKey sets up, so making it unconditional needed no other
changes.

Verified: new test launches an instance with no public key and asserts
sshd still starts (and confirms nothing gets written to
authorized_keys, since there's no key to inject). Confirmed it fails
with the fix reverted (no /usr/sbin/sshd invocation happens without a
key) and passes with it restored. Full ec2 package regression is green
(268 tests) - including the several existing tests that already
launched with no key pair and needed no changes to keep passing.

* fix(ec2): stop silently claiming sshd started when it never actually did

Follow-up on a comment from duytanisme on #2245: sshd not starting even
when an SSH key IS provided, requiring a manual exec-in or a custom
user-data script to work around it.

Root cause: startSshd() ran every step through execInContainer(),
which discards the exec's exit code entirely and only throws if the
Docker API call itself fails. The install step's shell script is an
if/elif chain with no matching branch, or whose install command itself
failed (no network yet, apt lock held, etc.) - and a bash if/elif with
no matching branch and no else clause exits 0 by convention. So a
container without a package manager, or one where the install call
failed for any reason, still reported success, ssh-keygen and sshd
then both ran anyway against a daemon that was never installed, and
"Started sshd in EC2 instance" got logged regardless.

Switches every step to execInContainerForResult and checks its exit
code explicitly, following the exact pattern already used by
configureLinkLocalMetadataEndpoint for the same class of problem:
bail out and log a specific warning with the actual command output at
whichever step actually failed, instead of silently proceeding.

Also adds an explicit "command -v sshd" as the last statement of the
install script, so its own exit code is the real source of truth for
whether sshd is actually available afterward, and switches the start
command from a hardcoded /usr/sbin/sshd to a bare "sshd" resolved via
PATH (matching how ssh-keygen is already invoked two lines above),
since not every image installs it to that exact path.

Verified: new test forces the install probe to fail and asserts
ssh-keygen and the start command are never even attempted. Confirmed
it fails (proceeds anyway) with the exit-code check disabled and
passes with it restored. Updated the existing no-key-pair test for the
new bare "sshd" command. Full ec2 package regression is green (269
tests).

* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates (#1867)

* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): preserve log group on failed rename

* fix(cloudformation): scope update rollback to attempted resources

* fix(cloudformation): delete resources after stack updates

* test(cloudformation): wire cloudfront fixture dependency

* fix: include Step Functions update date in describe response

* fix: preserve Step Functions describe response shape

* fix: preserve generated Step Functions names

* fix(s3): derive S3 host suffix matching from DNS config (#1843)

* fix(s3): derive S3 host suffix matching from DNS config

S3VirtualHostFilter hardcoded the wildcard-DNS suffixes (localhost.floci.io,
localhost.localstack.cloud) in two places: the bare service-host check
(isS3ServiceEndpointHost) and the virtual-hosted bucket fallback (isAwsS3Domain).
Both now derive their suffix set from the embedded DNS source of truth plus any
configured floci.dns.extra-suffixes, so a custom DNS suffix is recognised the same
way the builtins are.

Why: the two literal lists duplicated what the DNS server already knows and could
drift from it silently. Deriving from EmbeddedDnsServer.BUILTIN_SUFFIXES keeps them
in lockstep, and folding in extra-suffixes means a user migrating from LocalStack
via a custom suffix gets consistent S3 host handling (bucket routing and service
endpoint detection), not just the DNS resolution they get today.

How:
- buildServiceHostSuffixes() computes {localhost} + BUILTIN_SUFFIXES + extra-suffixes
  once per instance; isS3ServiceEndpointHost() checks membership instead of literals.
- matchesConfiguredSuffixHost() routes the virtual-hosted forms bucket.<suffix>,
  bucket.s3.<suffix> and bucket.s3.<region>.<suffix> for every configured suffix,
  replacing the hardcoded localstack/floci branches in isAwsS3Domain.
- EmbeddedDnsServer.BUILTIN_SUFFIXES widened to public so the filter reuses the list.

The virtual-host match now requires the full builtin suffix (.localhost.localstack.cloud)
rather than the bare parent domain (.localstack.cloud), matching LocalStack's actual
wildcard DNS (*.localhost.localstack.cloud).

* test(s3): derive DEFAULT_SUFFIXES from the production factory

The test constant hardcoded a copy of the builtin suffix set, which would
silently drift if a new builtin were added to EmbeddedDnsServer.BUILTIN_SUFFIXES.
Widen buildServiceHostSuffixes() to package-private and reuse it in the test so
the two stay in sync automatically.

* fix(s3): include the configured hostname in the derived suffix set

EmbeddedDnsServer resolves builtins + floci.hostname + floci.dns.extra-suffixes,
but the derived service-host set carried only two of the three. The configured
hostname reaches the filter as baseHostname, and matchesEndpointHost excludes the
bare s3.<host> remainder by design, so the bucket form one level down
(bucket.s3.<hostname>) matched nothing. DNS still resolves that host, so the
request reached Floci and was then handled path-style, binding the first path
segment as the bucket, rather than being refused.

Carry the hostname into buildServiceHostSuffixes so all three DNS inputs are
mirrored and a host that resolves by wildcard DNS routes under the same rules.

* fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#2023)

* fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#1984)

Every instance was given PublicIpAddress 127.0.0.1 unconditionally in
Ec2ContainerManager, so a private-subnet instance wrongly reported an
internet-facing address (breaks the ssh-reachability / public-vs-private
distinction). runInstances now flags the instance (associatePublicIp) from its
subnet's MapPublicIpOnLaunch, and the container manager exposes a public
address only when that flag is set. Private-subnet instances get no
PublicIpAddress — DescribeInstances omits the element (XmlBuilder skips nulls),
matching real EC2. The value for public instances stays the host-reachable
127.0.0.1 (unchanged). Unit test covers the public-vs-private flag.

Supports the aws-bench project: un-excludes the ssh-reachability scenario.

* fix(ec2): honor the launch-time AssociatePublicIpAddress override

* fix(ec2): honor the top-level AssociatePublicIpAddress and an explicit-false launch configuration

Two gaps left by the previous commit, both flagged in review.

RunInstances only read the override off the primary network-interface spec
(NetworkInterface.1.AssociatePublicIpAddress), so the legacy top-level
AssociatePublicIpAddress parameter — what the CLI and older SDKs send — was
silently dropped and the subnet default decided instead. It is now read as a
fallback; AWS rejects both shapes at once, so the interface spec wins when
present.

The launch-configuration path was worse than before. LaunchConfiguration
stored a primitive boolean, so an absent flag and an explicit false were
indistinguishable, and the reconciler could only forward an explicit true.
An LC that set AssociatePublicIpAddress=false in a MapPublicIpOnLaunch subnet
still got a public address. The field is now a nullable Boolean the whole way
through (service, query handler, CFN provisioner), so false overrides the
subnet and only null falls back to it. DescribeLaunchConfigurations omits the
element when it was never set, as AWS does.

Tests: a handler-level test pins all four parse cases (top-level, interface
spec, both present, absent), and the reconciler test pins true/false/null
reaching runInstances unchanged.

* feat(cloudfront): enforce signed private content (#1831)

* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): enforce signed private content

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

* fix(cloudfront): wildcard aliases match exactly one subdomain level

wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched
a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the
wildcard at that level only:

  "you can't add alternate domain names that are at levels higher or lower than the
   wildcard. For example, you can't add the alternate domain names example.com or
   marketing.product.example.com."

  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

Practical effect: a distribution owning "*.example.com" would answer for
a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to
nobody. Require the label standing in for the wildcard to contain no dot.

wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour
(a.b.example.test resolving to the *.example.test distribution); it now asserts no
match, plus the same for a deeper wildcard.

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix(cloudfront): match wildcards in signed policy queries

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

- Fix malformed dummy certificate in sdk-test-java by generating a self-signed X.509 cert programmatically using BouncyCastle
- Apply fixes for tag operations targeting backups
- Escape backslashes in regex
- Resolve compilation issues

* fix(test): Add CloudFrontClient to TestFixtures to resolve merge conflict

* revert(test): revert CloudFrontClient addition to TestFixtures

* fix(cloudhsmv2): fix CSR public key mismatch in SDK tests by signing properly extracted CSR

* test(ec2): fix Ec2PublicIpOnLaunchTest compilation after StorageBackend changes

* fix(cloudhsmv2): remove explicit BouncyCastle JCA provider to fix native image certificate validation

* fix(cloudhsmv2): add null check for DestinationRegion in copy backup

* fix(test): correct storage imports in Ec2PublicIpOnLaunchTest after rebase

* fix(cloudhsmv2): resolve code review comments including AZ lookup and validation

* style(cloudhsmv2): remove trailing whitespace in CloudHsmV2Test

---------

Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in>
Co-authored-by: Aniket Shukla <aniketshukla619@gmail.com>
Co-authored-by: Alex Banna <alexanderbanna@gmail.com>
Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
Co-authored-by: TiM <tim@nuimarkets.com>
Co-authored-by: Olamide Kosile <64154023+Mide69@users.noreply.github.com>
Co-authored-by: lex00 <121451605+lex00@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-08-17 00:00:49 -05:00
1 parent bfda938f72
commit 1cc97d57c1
25 files changed
+3173 -3

No files matched your search

+2
View File
@@ -11,3 +11,5 @@
!target/lib/*
!target/quarkus-app/*
!native/**
!.mvn/**
!mvnw
+1 -1
View File
@@ -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 |
+11
View File
@@ -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>
@@ -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)
@@ -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};
}
}
+29
View File
@@ -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 -->
+1
View File
@@ -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 |
+1
View File
@@ -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
@@ -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();
@@ -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
@@ -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,
@@ -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;
}
}
}
@@ -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));
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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();
}
}
@@ -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);
}
}
}
@@ -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;
}
}
@@ -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
+1
View File
@@ -492,5 +492,6 @@ floci:
port: 1883
iotdata:
enabled: true
cloudhsmv2:
rum:
enabled: true
@@ -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};
}
}
@@ -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;
+1
View File
@@ -304,5 +304,6 @@ floci:
port: 1883
iotdata:
enabled: true
cloudhsmv2:
rum:
enabled: true
+4
View File
@@ -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: