mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat: add ACM support (#21)
* feat: add ACM support * fix: address code review issues - pagination, idempotency TTL, AES-256 - BouncyCastle static initialization to prevent race conditions - Cursor-based pagination for ListCertificates - Idempotency token 1-hour TTL with lazy expiration - AES-256-CBC encryption replacing Triple-DES - 58 tests passing with new edge case coverage * fix: address PR #21 review feedback - Add GraalVM native image hints for BouncyCastle (initialize-at-run-time, reflection config) - Add runtime initialization for AcmService and CertificateGenerator (SecureRandom fix) - Log security warning lazily on first certificate creation/import (not at startup) - Add AcmStorageConfig interface for consistency with other services --- 🎉 Merged! Thank you so much, @cahna! This is exactly the kind of contribution that helps Floci grow — your work is genuinely appreciated. If you're up for it, there's plenty more to dig into: - 👀 Check out the open issues — some are tagged as good first steps for contributors - 💬 If you have ideas or ran into something while working on this, feel free to open an issue or start a discussion - 🔧 PRs for documentation, tests, and bug fixes are always welcome Hoping to see your name pop up again soon. Welcome to the Floci community! 🙌
This commit is contained in:
1 parent
9105d85a6f
commit
8a8d55d972
30 files changed
+3847
-4
No files matched your search
@@ -47,7 +47,7 @@
|
||||
| KMS (sign, verify, re-encrypt) | ✅ | ⚠️ Partial |
|
||||
| Native binary | ✅ ~40 MB | ❌ |
|
||||
|
||||
**20+ services. 408/408 SDK tests passing. Free forever.**
|
||||
**21+ services. 408/408 SDK tests passing. Free forever.**
|
||||
|
||||
## Quick Start
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
# ACM
|
||||
|
||||
**Protocol:** JSON 1.1 (`X-Amz-Target: CertificateManager.*`)
|
||||
**Endpoint:** `POST http://localhost:4566/`
|
||||
|
||||
## Supported Actions
|
||||
|
||||
| Action | Description |
|
||||
|---|---|
|
||||
| `RequestCertificate` | Request a new certificate (auto-issued for emulation) |
|
||||
| `DescribeCertificate` | Get certificate details and validation status |
|
||||
| `GetCertificate` | Retrieve the certificate and chain in PEM format |
|
||||
| `ListCertificates` | List all certificates with optional status filtering |
|
||||
| `DeleteCertificate` | Delete a certificate |
|
||||
| `AddTagsToCertificate` | Add tags to a certificate |
|
||||
| `RemoveTagsFromCertificate` | Remove tags from a certificate |
|
||||
| `ListTagsForCertificate` | List tags for a certificate |
|
||||
| `ExportCertificate` | Export certificate with encrypted private key (PRIVATE type only) |
|
||||
| `GetAccountConfiguration` | Get account-level ACM settings |
|
||||
| `PutAccountConfiguration` | Update account-level ACM settings |
|
||||
| `RenewCertificate` | Trigger certificate renewal |
|
||||
|
||||
## Emulation Behavior
|
||||
|
||||
- **Auto-Issuance:** All requested certificates are immediately issued with status `ISSUED` (no DNS/email validation required)
|
||||
- **Real Cryptography:** Certificates are generated with real RSA/EC keys and valid X.509 structure
|
||||
- **Key Algorithms:** Supports `RSA_2048`, `RSA_3072`, `RSA_4096`, `EC_prime256v1`, `EC_secp384r1`, `EC_secp521r1`
|
||||
- **Certificate Types:** `AMAZON_ISSUED` (default) and `PRIVATE` (when `CertificateAuthorityArn` is provided)
|
||||
- **Export:** Only `PRIVATE` type certificates can be exported with their private key
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
export AWS_ENDPOINT=http://localhost:4566
|
||||
|
||||
# Request a certificate
|
||||
CERT_ARN=$(aws acm request-certificate \
|
||||
--domain-name "example.com" \
|
||||
--subject-alternative-names "www.example.com" "*.example.com" \
|
||||
--validation-method DNS \
|
||||
--query CertificateArn --output text \
|
||||
--endpoint-url $AWS_ENDPOINT)
|
||||
|
||||
# Describe the certificate
|
||||
aws acm describe-certificate \
|
||||
--certificate-arn $CERT_ARN \
|
||||
--endpoint-url $AWS_ENDPOINT
|
||||
|
||||
# Get certificate in PEM format
|
||||
aws acm get-certificate \
|
||||
--certificate-arn $CERT_ARN \
|
||||
--endpoint-url $AWS_ENDPOINT
|
||||
|
||||
# List all certificates
|
||||
aws acm list-certificates \
|
||||
--endpoint-url $AWS_ENDPOINT
|
||||
|
||||
# List only issued certificates
|
||||
aws acm list-certificates \
|
||||
--certificate-statuses ISSUED \
|
||||
--endpoint-url $AWS_ENDPOINT
|
||||
|
||||
# Add tags
|
||||
aws acm add-tags-to-certificate \
|
||||
--certificate-arn $CERT_ARN \
|
||||
--tags Key=Environment,Value=Production Key=Project,Value=Demo \
|
||||
--endpoint-url $AWS_ENDPOINT
|
||||
|
||||
# List tags
|
||||
aws acm list-tags-for-certificate \
|
||||
--certificate-arn $CERT_ARN \
|
||||
--endpoint-url $AWS_ENDPOINT
|
||||
|
||||
# Request a private certificate (exportable)
|
||||
PRIVATE_ARN=$(aws acm request-certificate \
|
||||
--domain-name "internal.example.com" \
|
||||
--certificate-authority-arn "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012" \
|
||||
--query CertificateArn --output text \
|
||||
--endpoint-url $AWS_ENDPOINT)
|
||||
|
||||
# Export private certificate (passphrase must be base64-encoded, min 4 chars)
|
||||
PASSPHRASE=$(echo -n "mypassphrase123" | base64)
|
||||
aws acm export-certificate \
|
||||
--certificate-arn $PRIVATE_ARN \
|
||||
--passphrase $PASSPHRASE \
|
||||
--endpoint-url $AWS_ENDPOINT
|
||||
|
||||
# Delete a certificate
|
||||
aws acm delete-certificate \
|
||||
--certificate-arn $CERT_ARN \
|
||||
--endpoint-url $AWS_ENDPOINT
|
||||
```
|
||||
|
||||
## SDK Example (Java)
|
||||
|
||||
```java
|
||||
AcmClient acm = AcmClient.builder()
|
||||
.endpointOverride(URI.create("http://localhost:4566"))
|
||||
.region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create("test", "test")))
|
||||
.build();
|
||||
|
||||
// Request a certificate
|
||||
RequestCertificateResponse response = acm.requestCertificate(req -> req
|
||||
.domainName("example.com")
|
||||
.subjectAlternativeNames("www.example.com", "*.example.com")
|
||||
.validationMethod(ValidationMethod.DNS));
|
||||
|
||||
String certArn = response.certificateArn();
|
||||
|
||||
// Describe the certificate
|
||||
DescribeCertificateResponse desc = acm.describeCertificate(req -> req
|
||||
.certificateArn(certArn));
|
||||
|
||||
System.out.println("Status: " + desc.certificate().status());
|
||||
```
|
||||
@@ -1,6 +1,6 @@
|
||||
# Services Overview
|
||||
|
||||
Floci emulates 19+ AWS services on a single port (`4566`). All services use the real AWS wire protocol — your existing AWS CLI commands and SDK clients work without modification.
|
||||
Floci emulates 21+ AWS services on a single port (`4566`). All services use the real AWS wire protocol — your existing AWS CLI commands and SDK clients work without modification.
|
||||
|
||||
## Service Matrix
|
||||
|
||||
@@ -28,6 +28,7 @@ Floci emulates 19+ AWS services on a single port (`4566`). All services use the
|
||||
| [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 14 |
|
||||
| [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 14 |
|
||||
| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 8 |
|
||||
| [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 12 |
|
||||
|
||||
## Common Setup
|
||||
|
||||
|
||||
@@ -83,6 +83,18 @@
|
||||
<version>3.4.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- BouncyCastle for X.509 certificate generation and PEM handling (ACM service) -->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.83</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcpkix-jdk18on</artifactId>
|
||||
<version>1.83</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Testing -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
|
||||
@@ -44,6 +44,7 @@ public interface EmulatorConfig {
|
||||
CloudWatchLogsStorageConfig cloudwatchlogs();
|
||||
CloudWatchMetricsStorageConfig cloudwatchmetrics();
|
||||
SecretsManagerStorageConfig secretsmanager();
|
||||
AcmStorageConfig acm();
|
||||
}
|
||||
|
||||
interface SsmStorageConfig {
|
||||
@@ -112,6 +113,14 @@ public interface EmulatorConfig {
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface AcmStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface WalConfig {
|
||||
@WithDefault("30000")
|
||||
long compactionIntervalMs();
|
||||
@@ -150,6 +159,7 @@ public interface EmulatorConfig {
|
||||
CognitoServiceConfig cognito();
|
||||
StepFunctionsServiceConfig stepfunctions();
|
||||
CloudFormationServiceConfig cloudformation();
|
||||
AcmServiceConfig acm();
|
||||
}
|
||||
|
||||
interface SsmServiceConfig {
|
||||
@@ -295,6 +305,15 @@ public interface EmulatorConfig {
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface AcmServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
/** Seconds to wait before transitioning from PENDING_VALIDATION to ISSUED (0 = immediate) */
|
||||
@WithDefault("0")
|
||||
int validationWaitSeconds();
|
||||
}
|
||||
|
||||
interface LambdaServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;
|
||||
import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
|
||||
@@ -40,6 +41,7 @@ public class AwsJson11Controller {
|
||||
private static final String APIGW_V2_TARGET_PREFIX = "AmazonApiGatewayV2.";
|
||||
private static final String KMS_TARGET_PREFIX = "TrentService.";
|
||||
private static final String COGNITO_TARGET_PREFIX = "AWSCognitoIdentityProviderService.";
|
||||
private static final String ACM_TARGET_PREFIX = "CertificateManager.";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -51,6 +53,7 @@ public class AwsJson11Controller {
|
||||
private final ApiGatewayV2JsonHandler apigwV2JsonHandler;
|
||||
private final KmsJsonHandler kmsJsonHandler;
|
||||
private final CognitoJsonHandler cognitoJsonHandler;
|
||||
private final AcmJsonHandler acmJsonHandler;
|
||||
|
||||
@Inject
|
||||
public AwsJson11Controller(ObjectMapper objectMapper, RegionResolver regionResolver,
|
||||
@@ -59,7 +62,8 @@ public class AwsJson11Controller {
|
||||
SecretsManagerJsonHandler secretsManagerJsonHandler,
|
||||
KinesisJsonHandler kinesisJsonHandler,
|
||||
ApiGatewayV2JsonHandler apigwV2JsonHandler,
|
||||
KmsJsonHandler kmsJsonHandler, CognitoJsonHandler cognitoJsonHandler) {
|
||||
KmsJsonHandler kmsJsonHandler, CognitoJsonHandler cognitoJsonHandler,
|
||||
AcmJsonHandler acmJsonHandler) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
this.ssmJsonHandler = ssmJsonHandler;
|
||||
@@ -70,6 +74,7 @@ public class AwsJson11Controller {
|
||||
this.apigwV2JsonHandler = apigwV2JsonHandler;
|
||||
this.kmsJsonHandler = kmsJsonHandler;
|
||||
this.cognitoJsonHandler = cognitoJsonHandler;
|
||||
this.acmJsonHandler = acmJsonHandler;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -111,6 +116,9 @@ public class AwsJson11Controller {
|
||||
} else if (target.startsWith(COGNITO_TARGET_PREFIX)) {
|
||||
prefix = COGNITO_TARGET_PREFIX;
|
||||
serviceName = "Cognito";
|
||||
} else if (target.startsWith(ACM_TARGET_PREFIX)) {
|
||||
prefix = ACM_TARGET_PREFIX;
|
||||
serviceName = "ACM";
|
||||
} else {
|
||||
return Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException",
|
||||
@@ -134,6 +142,7 @@ public class AwsJson11Controller {
|
||||
case "ApiGatewayV2" -> apigwV2JsonHandler.handle(action, request, region);
|
||||
case "KMS" -> kmsJsonHandler.handle(action, request, region);
|
||||
case "Cognito" -> cognitoJsonHandler.handle(action, request, region);
|
||||
case "ACM" -> acmJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.quarkus.runtime.Startup;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.Security;
|
||||
|
||||
/**
|
||||
* Ensures BouncyCastle security provider is registered before any CDI beans are injected.
|
||||
*
|
||||
* <p>This class uses a static initializer block to guarantee the provider is registered
|
||||
* during class loading, which happens before CDI injection. The {@code @Startup} annotation
|
||||
* ensures this class is loaded early in the application lifecycle.</p>
|
||||
*
|
||||
* <p>Design decision: Using static initializer + @Startup instead of @Observes StartupEvent
|
||||
* because StartupEvent observers run after CDI context is ready, which may be too late if
|
||||
* other beans depend on BouncyCastle during their construction.</p>
|
||||
*
|
||||
* @see <a href="https://quarkus.io/guides/cdi#startup-event">Quarkus CDI Startup</a>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
@Startup
|
||||
public class BouncyCastleInitializer {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(BouncyCastleInitializer.class);
|
||||
|
||||
static {
|
||||
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
LOG.info("Registered BouncyCastle security provider (static initializer)");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op constructor. The actual initialization happens in the static block above.
|
||||
* This bean exists solely to trigger class loading via {@code @Startup}.
|
||||
*/
|
||||
public BouncyCastleInitializer() {
|
||||
// Static initializer has already run by the time this constructor is called
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ public class ServiceRegistry {
|
||||
case "cognito-idp" -> config.services().cognito().enabled();
|
||||
case "states" -> config.services().stepfunctions().enabled();
|
||||
case "cloudformation" -> config.services().cloudformation().enabled();
|
||||
case "acm" -> config.services().acm().enabled();
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
@@ -71,6 +72,7 @@ public class ServiceRegistry {
|
||||
if (config.services().cognito().enabled()) enabled.add("cognito-idp");
|
||||
if (config.services().stepfunctions().enabled()) enabled.add("states");
|
||||
if (config.services().cloudformation().enabled()) enabled.add("cloudformation");
|
||||
if (config.services().acm().enabled()) enabled.add("acm");
|
||||
return enabled;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.services.acm.model.*;
|
||||
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 jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* JSON handler for AWS Certificate Manager (ACM) API operations.
|
||||
*
|
||||
* <p>Implements the AWS JSON 1.1 protocol for ACM operations including
|
||||
* certificate request, import, export, listing, and lifecycle management.</p>
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/Welcome.html">AWS ACM API Reference</a>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AcmJsonHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AcmJsonHandler.class);
|
||||
|
||||
private final AcmService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public AcmJsonHandler(AcmService service, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "RequestCertificate" -> handleRequestCertificate(request, region);
|
||||
case "DescribeCertificate" -> handleDescribeCertificate(request, region);
|
||||
case "GetCertificate" -> handleGetCertificate(request, region);
|
||||
case "ListCertificates" -> handleListCertificates(request, region);
|
||||
case "DeleteCertificate" -> handleDeleteCertificate(request, region);
|
||||
case "ImportCertificate" -> handleImportCertificate(request, region);
|
||||
case "ExportCertificate" -> handleExportCertificate(request, region);
|
||||
case "AddTagsToCertificate" -> handleAddTagsToCertificate(request, region);
|
||||
case "ListTagsForCertificate" -> handleListTagsForCertificate(request, region);
|
||||
case "RemoveTagsFromCertificate" -> handleRemoveTagsFromCertificate(request, region);
|
||||
case "GetAccountConfiguration" -> handleGetAccountConfiguration(request, region);
|
||||
case "PutAccountConfiguration" -> handlePutAccountConfiguration(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
};
|
||||
}
|
||||
|
||||
private Response handleRequestCertificate(JsonNode request, String region) {
|
||||
String domainName = request.path("DomainName").asText(null);
|
||||
if (domainName == null || domainName.isBlank()) {
|
||||
return Response.status(400)
|
||||
.entity(new AwsErrorResponse("ValidationException",
|
||||
"Value null at 'domainName' failed to satisfy constraint: Member must not be null"))
|
||||
.build();
|
||||
}
|
||||
List<String> sans = parseStringList(request.path("SubjectAlternativeNames"));
|
||||
ValidationMethod validationMethod = parseValidationMethod(request.path("ValidationMethod").asText(null));
|
||||
String idempotencyToken = request.path("IdempotencyToken").asText(null);
|
||||
KeyAlgorithm keyAlgorithm = KeyAlgorithm.fromAwsName(request.path("KeyAlgorithm").asText(null));
|
||||
String certAuthorityArn = request.path("CertificateAuthorityArn").asText(null);
|
||||
CertificateOptions options = parseOptions(request.path("Options"));
|
||||
Map<String, String> tags = parseTags(request.path("Tags"));
|
||||
|
||||
Certificate cert = service.requestCertificate(domainName, sans, validationMethod,
|
||||
idempotencyToken, keyAlgorithm, certAuthorityArn, options, tags, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("CertificateArn", cert.getArn());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeCertificate(JsonNode request, String region) {
|
||||
String certificateArn = request.path("CertificateArn").asText();
|
||||
Certificate cert = service.describeCertificate(certificateArn, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("Certificate", buildCertificateDetail(cert));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetCertificate(JsonNode request, String region) {
|
||||
String certificateArn = request.path("CertificateArn").asText();
|
||||
Certificate cert = service.getCertificate(certificateArn, region);
|
||||
|
||||
// AWS returns RequestInProgressException for certificates still pending validation
|
||||
if (cert.getStatus() == CertificateStatus.PENDING_VALIDATION) {
|
||||
throw new io.github.hectorvent.floci.core.common.AwsException(
|
||||
"RequestInProgressException",
|
||||
"The certificate request is in progress. The certificate body is not yet available.",
|
||||
400);
|
||||
}
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Certificate", cert.getCertificateBody());
|
||||
if (cert.getCertificateChain() != null) {
|
||||
response.put("CertificateChain", cert.getCertificateChain());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleListCertificates(JsonNode request, String region) {
|
||||
List<CertificateStatus> statuses = parseCertificateStatuses(request.path("CertificateStatuses"));
|
||||
List<KeyAlgorithm> keyTypes = parseKeyTypes(request.path("Includes").path("keyTypes"));
|
||||
int maxItems = request.path("MaxItems").asInt(100);
|
||||
String nextToken = request.path("NextToken").asText(null);
|
||||
|
||||
ListResult result = service.listCertificates(statuses, keyTypes, region, maxItems, nextToken);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode summaryList = objectMapper.createArrayNode();
|
||||
for (Certificate cert : result.certificates()) {
|
||||
summaryList.add(buildCertificateSummary(cert));
|
||||
}
|
||||
response.set("CertificateSummaryList", summaryList);
|
||||
if (result.nextToken() != null) {
|
||||
response.put("NextToken", result.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteCertificate(JsonNode request, String region) {
|
||||
String certificateArn = request.path("CertificateArn").asText();
|
||||
service.deleteCertificate(certificateArn, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleImportCertificate(JsonNode request, String region) {
|
||||
String certificate = request.path("Certificate").asText();
|
||||
String privateKey = request.path("PrivateKey").asText();
|
||||
String chain = request.path("CertificateChain").asText(null);
|
||||
String existingArn = request.path("CertificateArn").asText(null);
|
||||
Map<String, String> tags = parseTags(request.path("Tags"));
|
||||
|
||||
Certificate cert = service.importCertificate(certificate, privateKey, chain, existingArn, tags, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("CertificateArn", cert.getArn());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleExportCertificate(JsonNode request, String region) {
|
||||
String certificateArn = request.path("CertificateArn").asText();
|
||||
String passphrase = request.path("Passphrase").asText();
|
||||
|
||||
Certificate cert = service.exportCertificate(certificateArn, passphrase, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Certificate", cert.getCertificateBody());
|
||||
if (cert.getCertificateChain() != null) {
|
||||
response.put("CertificateChain", cert.getCertificateChain());
|
||||
}
|
||||
response.put("PrivateKey", cert.getPrivateKey());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleAddTagsToCertificate(JsonNode request, String region) {
|
||||
String certificateArn = request.path("CertificateArn").asText();
|
||||
Map<String, String> tags = parseTags(request.path("Tags"));
|
||||
|
||||
service.addTagsToCertificate(certificateArn, tags, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleListTagsForCertificate(JsonNode request, String region) {
|
||||
String certificateArn = request.path("CertificateArn").asText();
|
||||
Map<String, String> tags = service.listTagsForCertificate(certificateArn, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode tagsArray = objectMapper.createArrayNode();
|
||||
for (Map.Entry<String, String> entry : tags.entrySet()) {
|
||||
ObjectNode tagNode = objectMapper.createObjectNode();
|
||||
tagNode.put("Key", entry.getKey());
|
||||
tagNode.put("Value", entry.getValue());
|
||||
tagsArray.add(tagNode);
|
||||
}
|
||||
response.set("Tags", tagsArray);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleRemoveTagsFromCertificate(JsonNode request, String region) {
|
||||
String certificateArn = request.path("CertificateArn").asText();
|
||||
List<Map<String, String>> tagSpecs = new ArrayList<>();
|
||||
JsonNode tagsNode = request.path("Tags");
|
||||
if (tagsNode.isArray()) {
|
||||
for (JsonNode tagNode : tagsNode) {
|
||||
Map<String, String> spec = new HashMap<>();
|
||||
spec.put("Key", tagNode.path("Key").asText());
|
||||
if (tagNode.has("Value")) {
|
||||
spec.put("Value", tagNode.path("Value").asText());
|
||||
}
|
||||
tagSpecs.add(spec);
|
||||
}
|
||||
}
|
||||
|
||||
service.removeTagsFromCertificate(certificateArn, tagSpecs, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleGetAccountConfiguration(JsonNode request, String region) {
|
||||
int daysBeforeExpiry = service.getAccountDaysBeforeExpiry();
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode expiryEvents = objectMapper.createObjectNode();
|
||||
expiryEvents.put("DaysBeforeExpiry", daysBeforeExpiry);
|
||||
response.set("ExpiryEvents", expiryEvents);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutAccountConfiguration(JsonNode request, String region) {
|
||||
String idempotencyToken = request.path("IdempotencyToken").asText(null);
|
||||
int daysBeforeExpiry = request.path("ExpiryEvents").path("DaysBeforeExpiry").asInt(45);
|
||||
|
||||
service.putAccountConfiguration(daysBeforeExpiry, idempotencyToken);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
// ============ Helper Methods ============
|
||||
|
||||
private ObjectNode buildCertificateDetail(Certificate cert) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("CertificateArn", cert.getArn());
|
||||
node.put("DomainName", cert.getDomainName());
|
||||
|
||||
ArrayNode sans = objectMapper.createArrayNode();
|
||||
if (cert.getSubjectAlternativeNames() != null) {
|
||||
cert.getSubjectAlternativeNames().forEach(sans::add);
|
||||
}
|
||||
node.set("SubjectAlternativeNames", sans);
|
||||
node.set("SubjectAlternativeNameSummaries", sans.deepCopy());
|
||||
node.put("HasAdditionalSubjectAlternativeNames", false);
|
||||
|
||||
node.put("Status", cert.getStatus().name());
|
||||
node.put("Type", cert.getType().name());
|
||||
|
||||
if (cert.getKeyAlgorithm() != null) {
|
||||
node.put("KeyAlgorithm", cert.getKeyAlgorithm().getAwsName());
|
||||
}
|
||||
if (cert.getSignatureAlgorithm() != null) {
|
||||
node.put("SignatureAlgorithm", cert.getSignatureAlgorithm());
|
||||
}
|
||||
if (cert.getSerial() != null) {
|
||||
node.put("Serial", cert.getSerial());
|
||||
}
|
||||
if (cert.getSubject() != null) {
|
||||
node.put("Subject", cert.getSubject());
|
||||
}
|
||||
if (cert.getIssuer() != null) {
|
||||
node.put("Issuer", cert.getIssuer());
|
||||
}
|
||||
|
||||
if (cert.getCreatedAt() != null) {
|
||||
node.put("CreatedAt", cert.getCreatedAt().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (cert.getIssuedAt() != null) {
|
||||
node.put("IssuedAt", cert.getIssuedAt().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (cert.getImportedAt() != null) {
|
||||
node.put("ImportedAt", cert.getImportedAt().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (cert.getNotBefore() != null) {
|
||||
node.put("NotBefore", cert.getNotBefore().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (cert.getNotAfter() != null) {
|
||||
node.put("NotAfter", cert.getNotAfter().toEpochMilli() / 1000.0);
|
||||
}
|
||||
|
||||
ArrayNode inUseBy = objectMapper.createArrayNode();
|
||||
if (cert.getInUseBy() != null) {
|
||||
cert.getInUseBy().forEach(inUseBy::add);
|
||||
}
|
||||
node.set("InUseBy", inUseBy);
|
||||
|
||||
if (cert.getDomainValidationOptions() != null && !cert.getDomainValidationOptions().isEmpty()) {
|
||||
ArrayNode validations = objectMapper.createArrayNode();
|
||||
for (DomainValidation dv : cert.getDomainValidationOptions()) {
|
||||
ObjectNode dvNode = objectMapper.createObjectNode();
|
||||
dvNode.put("DomainName", dv.domainName());
|
||||
dvNode.put("ValidationDomain", dv.validationDomain());
|
||||
dvNode.put("ValidationStatus", dv.validationStatus());
|
||||
dvNode.put("ValidationMethod", dv.validationMethod());
|
||||
if (dv.resourceRecord() != null) {
|
||||
ObjectNode rrNode = objectMapper.createObjectNode();
|
||||
rrNode.put("Name", dv.resourceRecord().name());
|
||||
rrNode.put("Type", dv.resourceRecord().type());
|
||||
rrNode.put("Value", dv.resourceRecord().value());
|
||||
dvNode.set("ResourceRecord", rrNode);
|
||||
}
|
||||
validations.add(dvNode);
|
||||
}
|
||||
node.set("DomainValidationOptions", validations);
|
||||
}
|
||||
|
||||
node.put("RenewalEligibility", "INELIGIBLE");
|
||||
|
||||
ArrayNode keyUsages = objectMapper.createArrayNode();
|
||||
ObjectNode ku1 = objectMapper.createObjectNode();
|
||||
ku1.put("Name", "DIGITAL_SIGNATURE");
|
||||
keyUsages.add(ku1);
|
||||
ObjectNode ku2 = objectMapper.createObjectNode();
|
||||
ku2.put("Name", "KEY_ENCIPHERMENT");
|
||||
keyUsages.add(ku2);
|
||||
node.set("KeyUsages", keyUsages);
|
||||
|
||||
ArrayNode extKeyUsages = objectMapper.createArrayNode();
|
||||
ObjectNode eku1 = objectMapper.createObjectNode();
|
||||
eku1.put("Name", "TLS_WEB_SERVER_AUTHENTICATION");
|
||||
eku1.put("OID", "1.3.6.1.5.5.7.3.1");
|
||||
extKeyUsages.add(eku1);
|
||||
ObjectNode eku2 = objectMapper.createObjectNode();
|
||||
eku2.put("Name", "TLS_WEB_CLIENT_AUTHENTICATION");
|
||||
eku2.put("OID", "1.3.6.1.5.5.7.3.2");
|
||||
extKeyUsages.add(eku2);
|
||||
node.set("ExtendedKeyUsages", extKeyUsages);
|
||||
|
||||
if (cert.getCertOptions() != null) {
|
||||
ObjectNode opts = objectMapper.createObjectNode();
|
||||
opts.put("CertificateTransparencyLoggingPreference",
|
||||
cert.getCertOptions().certificateTransparencyLoggingPreference());
|
||||
node.set("Options", opts);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode buildCertificateSummary(Certificate cert) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("CertificateArn", cert.getArn());
|
||||
node.put("DomainName", cert.getDomainName());
|
||||
|
||||
ArrayNode sans = objectMapper.createArrayNode();
|
||||
if (cert.getSubjectAlternativeNames() != null) {
|
||||
cert.getSubjectAlternativeNames().forEach(sans::add);
|
||||
}
|
||||
node.set("SubjectAlternativeNameSummaries", sans);
|
||||
node.put("HasAdditionalSubjectAlternativeNames", false);
|
||||
|
||||
node.put("Status", cert.getStatus().name());
|
||||
node.put("Type", cert.getType().name());
|
||||
|
||||
if (cert.getKeyAlgorithm() != null) {
|
||||
node.put("KeyAlgorithm", cert.getKeyAlgorithm().getAwsName());
|
||||
}
|
||||
|
||||
ArrayNode keyUsages = objectMapper.createArrayNode();
|
||||
keyUsages.add("DIGITAL_SIGNATURE");
|
||||
keyUsages.add("KEY_ENCIPHERMENT");
|
||||
node.set("KeyUsages", keyUsages);
|
||||
|
||||
ArrayNode extKeyUsages = objectMapper.createArrayNode();
|
||||
extKeyUsages.add("TLS_WEB_SERVER_AUTHENTICATION");
|
||||
extKeyUsages.add("TLS_WEB_CLIENT_AUTHENTICATION");
|
||||
node.set("ExtendedKeyUsages", extKeyUsages);
|
||||
|
||||
if (cert.getCreatedAt() != null) {
|
||||
node.put("CreatedAt", cert.getCreatedAt().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (cert.getIssuedAt() != null) {
|
||||
node.put("IssuedAt", cert.getIssuedAt().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (cert.getImportedAt() != null) {
|
||||
node.put("ImportedAt", cert.getImportedAt().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (cert.getNotBefore() != null) {
|
||||
node.put("NotBefore", cert.getNotBefore().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (cert.getNotAfter() != null) {
|
||||
node.put("NotAfter", cert.getNotAfter().toEpochMilli() / 1000.0);
|
||||
}
|
||||
|
||||
node.put("RenewalEligibility", "INELIGIBLE");
|
||||
node.put("InUse", cert.getInUseBy() != null && !cert.getInUseBy().isEmpty());
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private List<String> parseStringList(JsonNode node) {
|
||||
if (!node.isArray()) return null;
|
||||
List<String> list = new ArrayList<>();
|
||||
node.forEach(n -> list.add(n.asText()));
|
||||
return list;
|
||||
}
|
||||
|
||||
private Map<String, String> parseTags(JsonNode tagsNode) {
|
||||
if (!tagsNode.isArray()) return null;
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
for (JsonNode tagNode : tagsNode) {
|
||||
String key = tagNode.path("Key").asText();
|
||||
String value = tagNode.path("Value").asText(null);
|
||||
tags.put(key, value);
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private ValidationMethod parseValidationMethod(String method) {
|
||||
if (method == null) return ValidationMethod.DNS;
|
||||
try {
|
||||
return ValidationMethod.valueOf(method.toUpperCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new io.github.hectorvent.floci.core.common.AwsException(
|
||||
"ValidationException",
|
||||
"Invalid validation method: " + method + ". Must be DNS or EMAIL.",
|
||||
400);
|
||||
}
|
||||
}
|
||||
|
||||
private CertificateOptions parseOptions(JsonNode optionsNode) {
|
||||
if (optionsNode.isMissingNode()) return null;
|
||||
String ctPref = optionsNode.path("CertificateTransparencyLoggingPreference").asText("ENABLED");
|
||||
return new CertificateOptions(ctPref, "DISABLED");
|
||||
}
|
||||
|
||||
private List<CertificateStatus> parseCertificateStatuses(JsonNode node) {
|
||||
if (!node.isArray()) return null;
|
||||
List<CertificateStatus> list = new ArrayList<>();
|
||||
for (JsonNode n : node) {
|
||||
try {
|
||||
list.add(CertificateStatus.valueOf(n.asText()));
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("Ignoring unknown certificate status: {0}", n.asText());
|
||||
}
|
||||
}
|
||||
return list.isEmpty() ? null : list;
|
||||
}
|
||||
|
||||
private List<KeyAlgorithm> parseKeyTypes(JsonNode node) {
|
||||
if (!node.isArray()) return null;
|
||||
List<KeyAlgorithm> list = new ArrayList<>();
|
||||
for (JsonNode n : node) {
|
||||
KeyAlgorithm alg = KeyAlgorithm.fromAwsName(n.asText());
|
||||
if (alg != null) {
|
||||
list.add(alg);
|
||||
}
|
||||
}
|
||||
return list.isEmpty() ? null : list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.acm.model.*;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* ACM (AWS Certificate Manager) service implementation for the local emulator.
|
||||
*
|
||||
* <p>Provides X.509 certificate management operations compatible with the AWS ACM API,
|
||||
* including certificate request, import, export, and lifecycle management.</p>
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/Welcome.html">AWS ACM API Reference</a>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AcmService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AcmService.class);
|
||||
private static final int MAX_TAGS = 50;
|
||||
private static final int MAX_TAG_KEY_LENGTH = 128;
|
||||
private static final int MAX_TAG_VALUE_LENGTH = 256;
|
||||
private static final int MAX_SANS = 100;
|
||||
private static final int MAX_DOMAIN_LENGTH = 253;
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
private final StorageBackend<String, Certificate> store;
|
||||
private final CertificateGenerator certificateGenerator;
|
||||
private final RegionResolver regionResolver;
|
||||
private final int validationWaitSeconds;
|
||||
private final AtomicInteger accountDaysBeforeExpiry = new AtomicInteger(45);
|
||||
private final AtomicBoolean securityWarningLogged = new AtomicBoolean(false);
|
||||
|
||||
/**
|
||||
* Idempotency token cache using lazy expiration (1-hour TTL).
|
||||
*
|
||||
* <p>Design decision: Using ConcurrentHashMap with timestamp-based entries
|
||||
* instead of Caffeine or scheduled cleanup. This matches moto's approach
|
||||
* (see moto/acm/models.py:478-505) where expired entries are removed on
|
||||
* lookup. No background thread needed - acceptable for emulator workloads.</p>
|
||||
*
|
||||
* @see <a href="https://github.com/getmoto/moto/blob/main/moto/acm/models.py">moto ACM</a>
|
||||
*/
|
||||
private final ConcurrentHashMap<String, IdempotencyTokenEntry> idempotencyTokenIndex = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public AcmService(StorageFactory factory, CertificateGenerator certificateGenerator,
|
||||
EmulatorConfig config, RegionResolver regionResolver) {
|
||||
this(factory.create("acm", "acm-certificates.json",
|
||||
new TypeReference<Map<String, Certificate>>() {}),
|
||||
certificateGenerator,
|
||||
regionResolver,
|
||||
config.services().acm().validationWaitSeconds());
|
||||
}
|
||||
|
||||
AcmService(StorageBackend<String, Certificate> store, CertificateGenerator certificateGenerator,
|
||||
RegionResolver regionResolver, int validationWaitSeconds) {
|
||||
this.store = store;
|
||||
this.certificateGenerator = certificateGenerator;
|
||||
this.regionResolver = regionResolver;
|
||||
this.validationWaitSeconds = validationWaitSeconds;
|
||||
|
||||
// Validate Root CA resource availability
|
||||
validateRootCaResource();
|
||||
}
|
||||
|
||||
/**
|
||||
* Log security warning once on first certificate creation/import.
|
||||
* Uses AtomicBoolean to ensure thread-safe single logging.
|
||||
*/
|
||||
private void logSecurityWarningOnce() {
|
||||
if (securityWarningLogged.compareAndSet(false, true)) {
|
||||
LOG.warn("SECURITY WARNING: ACM emulator stores private keys in plaintext. " +
|
||||
"This is acceptable for local development but NOT for production use.");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateRootCaResource() {
|
||||
try (InputStream is = getClass().getResourceAsStream("/certs/amazon-root-ca.pem")) {
|
||||
if (is == null) {
|
||||
LOG.warn("Amazon Root CA certificate not found at /certs/amazon-root-ca.pem - " +
|
||||
"certificate chains will be empty");
|
||||
} else {
|
||||
LOG.info("Amazon Root CA certificate loaded successfully");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Failed to validate Root CA resource: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ============ RequestCertificate ============
|
||||
|
||||
public Certificate requestCertificate(String domainName, List<String> sans, ValidationMethod validationMethod,
|
||||
String idempotencyToken, KeyAlgorithm keyAlgorithm,
|
||||
String certAuthorityArn, CertificateOptions options,
|
||||
Map<String, String> tags, String region) {
|
||||
logSecurityWarningOnce();
|
||||
validateDomainName(domainName);
|
||||
validateSans(sans);
|
||||
if (tags != null) {
|
||||
validateTags(tags);
|
||||
}
|
||||
|
||||
KeyAlgorithm alg = keyAlgorithm != null ? keyAlgorithm : KeyAlgorithm.RSA_2048;
|
||||
|
||||
// Check idempotency with parameter validation
|
||||
if (idempotencyToken != null && !idempotencyToken.isEmpty()) {
|
||||
int requestHash = computeRequestHash(domainName, sans, alg);
|
||||
Optional<Certificate> existing = findByIdempotencyToken(idempotencyToken, region, requestHash);
|
||||
if (existing.isPresent()) {
|
||||
return existing.get();
|
||||
}
|
||||
}
|
||||
|
||||
String certId = UUID.randomUUID().toString();
|
||||
String arn = buildCertificateArn(region, certId);
|
||||
|
||||
// Determine certificate type and initial status
|
||||
CertificateType type;
|
||||
CertificateStatus status;
|
||||
if (certAuthorityArn != null && !certAuthorityArn.isEmpty()) {
|
||||
type = CertificateType.PRIVATE;
|
||||
status = CertificateStatus.ISSUED;
|
||||
} else {
|
||||
type = CertificateType.AMAZON_ISSUED;
|
||||
status = validationWaitSeconds > 0 ? CertificateStatus.PENDING_VALIDATION : CertificateStatus.ISSUED;
|
||||
}
|
||||
|
||||
// Generate real X.509 certificate
|
||||
CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateCertificate(
|
||||
domainName, sans, alg
|
||||
);
|
||||
|
||||
Instant now = Instant.now();
|
||||
|
||||
Certificate cert = new Certificate();
|
||||
cert.setArn(arn);
|
||||
cert.setDomainName(domainName);
|
||||
|
||||
// Use LinkedHashSet for O(1) deduplication while preserving insertion order
|
||||
LinkedHashSet<String> allSans = new LinkedHashSet<>();
|
||||
allSans.add(domainName);
|
||||
if (sans != null) {
|
||||
allSans.addAll(sans);
|
||||
}
|
||||
cert.setSubjectAlternativeNames(new ArrayList<>(allSans));
|
||||
|
||||
cert.setStatus(status);
|
||||
cert.setType(type);
|
||||
cert.setValidationMethod(validationMethod != null ? validationMethod : ValidationMethod.DNS);
|
||||
cert.setCreatedAt(now);
|
||||
cert.setIssuedAt(status == CertificateStatus.ISSUED ? now : null);
|
||||
cert.setNotBefore(generated.notBefore());
|
||||
cert.setNotAfter(generated.notAfter());
|
||||
cert.setSerial(generated.serial());
|
||||
cert.setSubject(generated.subject());
|
||||
cert.setIssuer(generated.issuer());
|
||||
cert.setKeyAlgorithm(alg);
|
||||
cert.setSignatureAlgorithm(generated.signatureAlgorithm());
|
||||
cert.setCertificateBody(generated.certificatePem());
|
||||
cert.setPrivateKey(generated.privateKeyPem());
|
||||
cert.setCertificateChain(getAwsRootCa());
|
||||
cert.setCertOptions(options != null ? options : CertificateOptions.defaultOptions());
|
||||
cert.setCertAuthorityArn(certAuthorityArn);
|
||||
cert.setIdempotencyToken(idempotencyToken);
|
||||
cert.setTags(tags != null ? new HashMap<>(tags) : new HashMap<>());
|
||||
|
||||
// Generate domain validation options with correct status based on type
|
||||
List<DomainValidation> validations = new ArrayList<>();
|
||||
for (String san : allSans) {
|
||||
validations.add(generateDomainValidation(san, validationMethod, type));
|
||||
}
|
||||
cert.setDomainValidationOptions(validations);
|
||||
|
||||
String storageKey = regionKey(region, certId);
|
||||
store.put(storageKey, cert);
|
||||
|
||||
// Index idempotency token for fast lookups with TTL
|
||||
if (idempotencyToken != null && !idempotencyToken.isEmpty()) {
|
||||
int requestHash = computeRequestHash(domainName, sans, alg);
|
||||
idempotencyTokenIndex.put(region + "::" + idempotencyToken,
|
||||
IdempotencyTokenEntry.create(arn, requestHash));
|
||||
}
|
||||
|
||||
LOG.infov("Created certificate: {0} in region {1}", arn, region);
|
||||
return cert;
|
||||
}
|
||||
|
||||
// ============ DescribeCertificate ============
|
||||
|
||||
public Certificate describeCertificate(String certificateArn, String region) {
|
||||
Certificate cert = getCertificateByArn(certificateArn, region);
|
||||
|
||||
// Check for expiration
|
||||
if (cert.isExpired() && cert.getStatus() != CertificateStatus.EXPIRED) {
|
||||
cert.setStatus(CertificateStatus.EXPIRED);
|
||||
store.put(regionKey(region, cert.extractCertificateId()), cert);
|
||||
}
|
||||
|
||||
return cert;
|
||||
}
|
||||
|
||||
// ============ GetCertificate ============
|
||||
|
||||
public Certificate getCertificate(String certificateArn, String region) {
|
||||
return getCertificateByArn(certificateArn, region);
|
||||
}
|
||||
|
||||
// ============ ListCertificates ============
|
||||
|
||||
/**
|
||||
* Lists certificates with cursor-based pagination.
|
||||
*
|
||||
* @param statuses Filter by certificate status (null or empty for all)
|
||||
* @param keyTypes Filter by key algorithm (null or empty for all)
|
||||
* @param region AWS region
|
||||
* @param maxItems Maximum items per page (default 100)
|
||||
* @param nextToken Cursor for next page (null for first page)
|
||||
* @return ListResult containing certificates and optional nextToken
|
||||
*/
|
||||
public ListResult listCertificates(List<CertificateStatus> statuses, List<KeyAlgorithm> keyTypes,
|
||||
String region, int maxItems, String nextToken) {
|
||||
int limit = maxItems > 0 ? Math.min(maxItems, 1000) : 100;
|
||||
String lastArn = decodeToken(nextToken);
|
||||
|
||||
List<Certificate> allCerts = store.scan(k -> true).stream()
|
||||
.filter(c -> c.getArn().contains(":acm:" + region + ":"))
|
||||
.filter(c -> statuses == null || statuses.isEmpty() || statuses.contains(c.getStatus()))
|
||||
.filter(c -> keyTypes == null || keyTypes.isEmpty() || keyTypes.contains(c.getKeyAlgorithm()))
|
||||
.sorted(Comparator.comparing(Certificate::getArn))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Find starting position based on cursor
|
||||
int startIndex = 0;
|
||||
if (lastArn != null) {
|
||||
for (int i = 0; i < allCerts.size(); i++) {
|
||||
if (allCerts.get(i).getArn().compareTo(lastArn) > 0) {
|
||||
startIndex = i;
|
||||
break;
|
||||
}
|
||||
if (i == allCerts.size() - 1) {
|
||||
startIndex = allCerts.size(); // All items before cursor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get page
|
||||
List<Certificate> page = allCerts.stream()
|
||||
.skip(startIndex)
|
||||
.limit(limit)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Determine if there are more items
|
||||
String newNextToken = null;
|
||||
if (startIndex + limit < allCerts.size() && !page.isEmpty()) {
|
||||
newNextToken = encodeToken(page.get(page.size() - 1).getArn());
|
||||
}
|
||||
|
||||
return new ListResult(page, newNextToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a pagination cursor as Base64 JSON.
|
||||
*/
|
||||
private String encodeToken(String lastArn) {
|
||||
if (lastArn == null) return null;
|
||||
String json = "{\"lastArn\":\"" + lastArn + "\"}";
|
||||
return Base64.getEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a pagination cursor from Base64 JSON.
|
||||
*/
|
||||
private String decodeToken(String token) {
|
||||
if (token == null || token.isEmpty()) return null;
|
||||
try {
|
||||
String json = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
|
||||
// Simple JSON parsing without Jackson dependency in this method
|
||||
int start = json.indexOf("\"lastArn\":\"") + 11;
|
||||
int end = json.indexOf("\"", start);
|
||||
return json.substring(start, end);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InvalidNextTokenException", "Invalid pagination token", 400);
|
||||
}
|
||||
}
|
||||
|
||||
// ============ DeleteCertificate ============
|
||||
|
||||
public void deleteCertificate(String certificateArn, String region) {
|
||||
Certificate cert = getCertificateByArn(certificateArn, region);
|
||||
|
||||
if (cert.getInUseBy() != null && !cert.getInUseBy().isEmpty()) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Certificate " + certificateArn + " is in use by: " + String.join(", ", cert.getInUseBy()), 409);
|
||||
}
|
||||
|
||||
String storageKey = regionKey(region, cert.extractCertificateId());
|
||||
store.delete(storageKey);
|
||||
LOG.infov("Deleted certificate: {0}", certificateArn);
|
||||
}
|
||||
|
||||
// ============ ImportCertificate ============
|
||||
|
||||
public Certificate importCertificate(String certificatePem, String privateKeyPem, String chainPem,
|
||||
String existingArn, Map<String, String> tags, String region) {
|
||||
logSecurityWarningOnce();
|
||||
// Parse and validate certificate
|
||||
X509Certificate x509Cert;
|
||||
try {
|
||||
x509Cert = certificateGenerator.parseCertificate(certificatePem);
|
||||
certificateGenerator.validateCertificate(x509Cert);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("ValidationException", "Invalid certificate: " + e.getMessage(), 400);
|
||||
}
|
||||
|
||||
// Parse and validate private key
|
||||
try {
|
||||
certificateGenerator.parsePrivateKey(privateKeyPem);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("ValidationException", "Invalid private key: " + e.getMessage(), 400);
|
||||
}
|
||||
|
||||
if (tags != null) {
|
||||
validateTags(tags);
|
||||
}
|
||||
|
||||
String certId;
|
||||
String arn;
|
||||
|
||||
if (existingArn != null && !existingArn.isEmpty()) {
|
||||
// Re-import
|
||||
Certificate existing = getCertificateByArn(existingArn, region);
|
||||
certId = existing.extractCertificateId();
|
||||
arn = existingArn;
|
||||
} else {
|
||||
certId = UUID.randomUUID().toString();
|
||||
arn = buildCertificateArn(region, certId);
|
||||
}
|
||||
|
||||
Instant now = Instant.now();
|
||||
KeyAlgorithm keyAlg = certificateGenerator.detectKeyAlgorithm(x509Cert.getPublicKey());
|
||||
|
||||
Certificate cert = new Certificate();
|
||||
cert.setArn(arn);
|
||||
cert.setDomainName(extractCommonName(x509Cert));
|
||||
cert.setStatus(CertificateStatus.ISSUED);
|
||||
cert.setType(CertificateType.IMPORTED);
|
||||
cert.setCreatedAt(existingArn == null ? now : null);
|
||||
cert.setImportedAt(now);
|
||||
cert.setIssuedAt(now);
|
||||
cert.setNotBefore(x509Cert.getNotBefore().toInstant());
|
||||
cert.setNotAfter(x509Cert.getNotAfter().toInstant());
|
||||
cert.setSerial(x509Cert.getSerialNumber().toString());
|
||||
cert.setSubject(x509Cert.getSubjectX500Principal().getName());
|
||||
cert.setIssuer(x509Cert.getIssuerX500Principal().getName());
|
||||
cert.setKeyAlgorithm(keyAlg);
|
||||
cert.setSignatureAlgorithm(x509Cert.getSigAlgName());
|
||||
cert.setCertificateBody(certificatePem);
|
||||
cert.setPrivateKey(privateKeyPem);
|
||||
cert.setCertificateChain(chainPem);
|
||||
cert.setTags(tags != null ? new HashMap<>(tags) : new HashMap<>());
|
||||
|
||||
String storageKey = regionKey(region, certId);
|
||||
store.put(storageKey, cert);
|
||||
|
||||
LOG.infov("Imported certificate: {0}", arn);
|
||||
return cert;
|
||||
}
|
||||
|
||||
// ============ ExportCertificate ============
|
||||
|
||||
public Certificate exportCertificate(String certificateArn, String passphraseBase64, String region) {
|
||||
Certificate cert = getCertificateByArn(certificateArn, region);
|
||||
|
||||
if (!cert.canExport()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Certificate is not PRIVATE type and Export is not ENABLED", 400);
|
||||
}
|
||||
|
||||
String passphrase;
|
||||
try {
|
||||
passphrase = new String(Base64.getDecoder().decode(passphraseBase64));
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("ValidationException", "Invalid passphrase encoding", 400);
|
||||
}
|
||||
|
||||
if (passphrase.length() < 4) {
|
||||
throw new AwsException("ValidationException", "Passphrase must be at least 4 characters", 400);
|
||||
}
|
||||
|
||||
// Encrypt the private key
|
||||
String encryptedKey = certificateGenerator.encryptPrivateKey(cert.getPrivateKey(), passphrase);
|
||||
|
||||
// Return certificate with encrypted private key
|
||||
Certificate exportCert = new Certificate();
|
||||
exportCert.setCertificateBody(cert.getCertificateBody());
|
||||
exportCert.setCertificateChain(cert.getCertificateChain());
|
||||
exportCert.setPrivateKey(encryptedKey);
|
||||
return exportCert;
|
||||
}
|
||||
|
||||
// ============ Tagging Operations ============
|
||||
|
||||
public void addTagsToCertificate(String certificateArn, Map<String, String> tags, String region) {
|
||||
Certificate cert = getCertificateByArn(certificateArn, region);
|
||||
validateTags(tags);
|
||||
|
||||
Map<String, String> currentTags = cert.getTags() != null ? new HashMap<>(cert.getTags()) : new HashMap<>();
|
||||
currentTags.putAll(tags);
|
||||
|
||||
if (currentTags.size() > MAX_TAGS) {
|
||||
throw new AwsException("TooManyTagsException",
|
||||
"Certificate cannot have more than " + MAX_TAGS + " tags", 400);
|
||||
}
|
||||
|
||||
cert.setTags(currentTags);
|
||||
store.put(regionKey(region, cert.extractCertificateId()), cert);
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForCertificate(String certificateArn, String region) {
|
||||
Certificate cert = getCertificateByArn(certificateArn, region);
|
||||
return cert.getTags() != null ? new HashMap<>(cert.getTags()) : new HashMap<>();
|
||||
}
|
||||
|
||||
public void removeTagsFromCertificate(String certificateArn, List<Map<String, String>> tagSpecs, String region) {
|
||||
Certificate cert = getCertificateByArn(certificateArn, region);
|
||||
Map<String, String> currentTags = cert.getTags() != null ? new HashMap<>(cert.getTags()) : new HashMap<>();
|
||||
|
||||
for (Map<String, String> spec : tagSpecs) {
|
||||
String key = spec.get("Key");
|
||||
String value = spec.get("Value");
|
||||
if (key != null) {
|
||||
if (value == null) {
|
||||
// Remove by key only
|
||||
currentTags.remove(key);
|
||||
} else {
|
||||
// Remove only if value matches
|
||||
if (value.equals(currentTags.get(key))) {
|
||||
currentTags.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cert.setTags(currentTags);
|
||||
store.put(regionKey(region, cert.extractCertificateId()), cert);
|
||||
}
|
||||
|
||||
// ============ Account Configuration ============
|
||||
|
||||
public int getAccountDaysBeforeExpiry() {
|
||||
return accountDaysBeforeExpiry.get();
|
||||
}
|
||||
|
||||
public void putAccountConfiguration(int daysBeforeExpiry, String idempotencyToken) {
|
||||
if (daysBeforeExpiry < 1 || daysBeforeExpiry > 90) {
|
||||
throw new AwsException("ValidationException",
|
||||
"DaysBeforeExpiry must be between 1 and 90", 400);
|
||||
}
|
||||
this.accountDaysBeforeExpiry.set(daysBeforeExpiry);
|
||||
}
|
||||
|
||||
// ============ Helper Methods ============
|
||||
|
||||
private Certificate getCertificateByArn(String arn, String region) {
|
||||
String certId = extractCertificateIdFromArn(arn);
|
||||
String storageKey = regionKey(region, certId);
|
||||
|
||||
return store.get(storageKey).orElseThrow(() ->
|
||||
new AwsException("ResourceNotFoundException",
|
||||
"The certificate " + arn + " does not exist.", 404));
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a certificate by idempotency token with lazy expiration.
|
||||
*
|
||||
* <p>Implementation follows moto's pattern (moto/acm/models.py:478-505):
|
||||
* expired entries are removed on lookup rather than using a background
|
||||
* cleanup thread.</p>
|
||||
*
|
||||
* @param token The idempotency token
|
||||
* @param region AWS region
|
||||
* @param requestHash Hash of current request parameters for validation
|
||||
* @return Optional containing the certificate if token is valid and not expired
|
||||
* @throws AwsException if token exists but parameters don't match (IdempotencyTokenException)
|
||||
*/
|
||||
private Optional<Certificate> findByIdempotencyToken(String token, String region, int requestHash) {
|
||||
String indexKey = region + "::" + token;
|
||||
IdempotencyTokenEntry entry = idempotencyTokenIndex.get(indexKey);
|
||||
|
||||
if (entry == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// Lazy expiration: remove expired entries on lookup
|
||||
if (entry.isExpired()) {
|
||||
idempotencyTokenIndex.remove(indexKey);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// Validate request parameters match
|
||||
if (entry.requestHash() != requestHash) {
|
||||
throw new AwsException("IdempotencyException",
|
||||
"An idempotency token was used with a request that does not match a previous request " +
|
||||
"that used that token.", 400);
|
||||
}
|
||||
|
||||
String certId = extractCertificateIdFromArn(entry.arn());
|
||||
return store.get(regionKey(region, certId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a hash of request parameters for idempotency validation.
|
||||
* Parameters include: domainName, SANs (order-independent), keyAlgorithm.
|
||||
*/
|
||||
private int computeRequestHash(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm) {
|
||||
return Objects.hash(
|
||||
domainName,
|
||||
sans != null ? new HashSet<>(sans) : null,
|
||||
keyAlgorithm
|
||||
);
|
||||
}
|
||||
|
||||
private void validateDomainName(String domainName) {
|
||||
if (domainName == null || domainName.isEmpty()) {
|
||||
throw new AwsException("ValidationException", "Domain name cannot be empty", 400);
|
||||
}
|
||||
if (domainName.length() > MAX_DOMAIN_LENGTH) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Domain name cannot exceed " + MAX_DOMAIN_LENGTH + " characters", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateSans(List<String> sans) {
|
||||
if (sans != null && sans.size() > MAX_SANS) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Cannot have more than " + MAX_SANS + " subject alternative names", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateTags(Map<String, String> tags) {
|
||||
if (tags == null) return;
|
||||
|
||||
// Check total number of tags
|
||||
if (tags.size() > MAX_TAGS) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Cannot have more than " + MAX_TAGS + " tags", 400);
|
||||
}
|
||||
|
||||
for (Map.Entry<String, String> entry : tags.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
String value = entry.getValue();
|
||||
|
||||
if (key == null || key.isEmpty() || key.length() > MAX_TAG_KEY_LENGTH) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Tag key must be 1-" + MAX_TAG_KEY_LENGTH + " characters", 400);
|
||||
}
|
||||
if (key.toLowerCase().startsWith("aws:")) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Tag key cannot start with 'aws:'", 400);
|
||||
}
|
||||
if (value != null && value.length() > MAX_TAG_VALUE_LENGTH) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Tag value cannot exceed " + MAX_TAG_VALUE_LENGTH + " characters", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates domain validation options with status based on certificate type.
|
||||
* Private certificates have SUCCESS status immediately; public certificates
|
||||
* start with PENDING_VALIDATION until DNS/email validation completes.
|
||||
*/
|
||||
private DomainValidation generateDomainValidation(String domain, ValidationMethod method, CertificateType type) {
|
||||
String validationToken = generateValidationToken(domain);
|
||||
ResourceRecord resourceRecord = new ResourceRecord(
|
||||
"_" + validationToken.substring(0, 32) + "." + domain + ".",
|
||||
"CNAME",
|
||||
"_" + validationToken.substring(32) + ".acm-validations.aws."
|
||||
);
|
||||
|
||||
// Private certificates don't need validation; public certificates do
|
||||
String validationStatus = (type == CertificateType.PRIVATE) ? "SUCCESS" : "PENDING_VALIDATION";
|
||||
|
||||
return new DomainValidation(
|
||||
domain,
|
||||
domain,
|
||||
validationStatus,
|
||||
method != null ? method.name() : "DNS",
|
||||
resourceRecord,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
private String generateValidationToken(String domain) {
|
||||
byte[] randomBytes = new byte[32];
|
||||
SECURE_RANDOM.nextBytes(randomBytes);
|
||||
return HexFormat.of().formatHex(randomBytes);
|
||||
}
|
||||
|
||||
private String buildCertificateArn(String region, String certId) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
return "arn:aws:acm:" + region + ":" + accountId + ":certificate/" + certId;
|
||||
}
|
||||
|
||||
private String extractCertificateIdFromArn(String arn) {
|
||||
int lastSlash = arn.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? arn.substring(lastSlash + 1) : arn;
|
||||
}
|
||||
|
||||
private String regionKey(String region, String certId) {
|
||||
return region + "::" + certId;
|
||||
}
|
||||
|
||||
private String extractCommonName(X509Certificate cert) {
|
||||
String dn = cert.getSubjectX500Principal().getName();
|
||||
return Arrays.stream(dn.split(","))
|
||||
.map(String::trim)
|
||||
.filter(s -> s.startsWith("CN="))
|
||||
.findFirst()
|
||||
.map(s -> s.substring(3))
|
||||
.orElse(dn);
|
||||
}
|
||||
|
||||
private String getAwsRootCa() {
|
||||
try (InputStream is = getClass().getResourceAsStream("/certs/amazon-root-ca.pem")) {
|
||||
if (is == null) {
|
||||
LOG.warn("Could not load Amazon Root CA from resources, using empty chain");
|
||||
return "";
|
||||
}
|
||||
return new String(is.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Failed to load Amazon Root CA: " + e.getMessage());
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
/**
|
||||
* Exception thrown when certificate generation or parsing fails.
|
||||
*/
|
||||
public class CertificateGenerationException extends RuntimeException {
|
||||
|
||||
public CertificateGenerationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public CertificateGenerationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
|
||||
import org.bouncycastle.asn1.x500.X500Name;
|
||||
import org.bouncycastle.asn1.x509.BasicConstraints;
|
||||
import org.bouncycastle.asn1.x509.Extension;
|
||||
import org.bouncycastle.asn1.x509.GeneralName;
|
||||
import org.bouncycastle.asn1.x509.GeneralNames;
|
||||
import org.bouncycastle.asn1.x509.KeyUsage;
|
||||
import org.bouncycastle.cert.X509CertificateHolder;
|
||||
import org.bouncycastle.cert.X509v3CertificateBuilder;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.bouncycastle.openssl.PEMParser;
|
||||
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
|
||||
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
|
||||
import org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder;
|
||||
import org.bouncycastle.operator.ContentSigner;
|
||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
|
||||
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
|
||||
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfoBuilder;
|
||||
import org.bouncycastle.pkcs.jcajce.JcaPKCS8EncryptedPrivateKeyInfoBuilder;
|
||||
import org.bouncycastle.pkcs.jcajce.JcePKCSPBEOutputEncryptorBuilder;
|
||||
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
|
||||
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.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Security;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CertificateGenerator {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CertificateGenerator.class);
|
||||
private static final String ISSUER_DN = "CN=Amazon,OU=Server CA 1B,O=Amazon,C=US";
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
public record GeneratedCertificate(
|
||||
String certificatePem,
|
||||
String privateKeyPem,
|
||||
String serial,
|
||||
Instant notBefore,
|
||||
Instant notAfter,
|
||||
String subject,
|
||||
String issuer,
|
||||
String signatureAlgorithm
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Generates a self-signed X.509 certificate for local emulation.
|
||||
*
|
||||
* <p>Note: RSA key generation (especially 4096-bit) can take 100-500ms.
|
||||
* In production emulator usage, consider moving this to a worker thread
|
||||
* or using virtual threads for concurrent certificate generation.</p>
|
||||
*/
|
||||
public GeneratedCertificate generateCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm) {
|
||||
try {
|
||||
KeyPair keyPair = generateKeyPair(keyAlgorithm);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Instant notBefore = now;
|
||||
Instant notAfter = now.plus(365, ChronoUnit.DAYS);
|
||||
|
||||
BigInteger serial = new BigInteger(128, SECURE_RANDOM);
|
||||
String subjectDn = "CN=" + domainName;
|
||||
|
||||
X500Name issuer = new X500Name(ISSUER_DN);
|
||||
X500Name subject = new X500Name(subjectDn);
|
||||
|
||||
String signatureAlgorithm = keyAlgorithm.getAlgorithm().equals("EC")
|
||||
? "SHA512withECDSA"
|
||||
: "SHA512WithRSA";
|
||||
|
||||
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
|
||||
issuer,
|
||||
serial,
|
||||
Date.from(notBefore),
|
||||
Date.from(notAfter),
|
||||
subject,
|
||||
keyPair.getPublic()
|
||||
);
|
||||
|
||||
// Add Subject Alternative Names
|
||||
List<GeneralName> sanList = new ArrayList<>();
|
||||
sanList.add(new GeneralName(GeneralName.dNSName, domainName));
|
||||
if (sans != null) {
|
||||
for (String san : sans) {
|
||||
if (!san.equals(domainName)) {
|
||||
sanList.add(new GeneralName(GeneralName.dNSName, san));
|
||||
}
|
||||
}
|
||||
}
|
||||
GeneralNames generalNames = new GeneralNames(sanList.toArray(new GeneralName[0]));
|
||||
certBuilder.addExtension(Extension.subjectAlternativeName, false, generalNames);
|
||||
|
||||
// Add Key Usage
|
||||
certBuilder.addExtension(
|
||||
Extension.keyUsage,
|
||||
true,
|
||||
new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)
|
||||
);
|
||||
|
||||
// Add Basic Constraints (not a CA)
|
||||
certBuilder.addExtension(
|
||||
Extension.basicConstraints,
|
||||
true,
|
||||
new BasicConstraints(false)
|
||||
);
|
||||
|
||||
// Self-signed certificate for local emulation - signed with subject's own private key
|
||||
// Real AWS ACM certificates are signed by Amazon's CA hierarchy
|
||||
ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm)
|
||||
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
|
||||
.build(keyPair.getPrivate());
|
||||
|
||||
X509CertificateHolder certHolder = certBuilder.build(signer);
|
||||
X509Certificate cert = new JcaX509CertificateConverter()
|
||||
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
|
||||
.getCertificate(certHolder);
|
||||
|
||||
String certPem = toPem(cert);
|
||||
String keyPem = toPem(keyPair.getPrivate());
|
||||
|
||||
return new GeneratedCertificate(
|
||||
certPem,
|
||||
keyPem,
|
||||
serial.toString(),
|
||||
notBefore,
|
||||
notAfter,
|
||||
subjectDn,
|
||||
ISSUER_DN,
|
||||
signatureAlgorithm
|
||||
);
|
||||
|
||||
} catch (Exception e) {
|
||||
LOG.error("Failed to generate certificate", e);
|
||||
throw new CertificateGenerationException("Certificate generation failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private KeyPair generateKeyPair(KeyAlgorithm keyAlgorithm) throws Exception {
|
||||
KeyPairGenerator keyGen;
|
||||
if ("EC".equals(keyAlgorithm.getAlgorithm())) {
|
||||
keyGen = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
|
||||
keyGen.initialize(new ECGenParameterSpec(keyAlgorithm.getCurveName()), SECURE_RANDOM);
|
||||
} else {
|
||||
keyGen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
|
||||
keyGen.initialize(keyAlgorithm.getKeySize(), SECURE_RANDOM);
|
||||
}
|
||||
return keyGen.generateKeyPair();
|
||||
}
|
||||
|
||||
private String toPem(Object obj) throws Exception {
|
||||
StringWriter sw = new StringWriter();
|
||||
try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {
|
||||
pemWriter.writeObject(obj);
|
||||
}
|
||||
return sw.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypts a private key using AES-256-CBC (replacing deprecated Triple-DES).
|
||||
*
|
||||
* @param privateKeyPem The private key in PEM format
|
||||
* @param passphrase The passphrase for encryption
|
||||
* @return Encrypted private key in PEM format
|
||||
*/
|
||||
public String encryptPrivateKey(String privateKeyPem, String passphrase) {
|
||||
try {
|
||||
PrivateKey privateKey = parsePrivateKey(privateKeyPem);
|
||||
|
||||
// Use AES-256-CBC instead of deprecated Triple-DES
|
||||
JcePKCSPBEOutputEncryptorBuilder encryptorBuilder = new JcePKCSPBEOutputEncryptorBuilder(
|
||||
NISTObjectIdentifiers.id_aes256_CBC
|
||||
);
|
||||
encryptorBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);
|
||||
|
||||
PKCS8EncryptedPrivateKeyInfoBuilder pkcs8Builder = new JcaPKCS8EncryptedPrivateKeyInfoBuilder(privateKey);
|
||||
PKCS8EncryptedPrivateKeyInfo encryptedInfo = pkcs8Builder.build(
|
||||
encryptorBuilder.build(passphrase.toCharArray())
|
||||
);
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {
|
||||
pemWriter.writeObject(encryptedInfo);
|
||||
}
|
||||
return sw.toString();
|
||||
|
||||
} catch (Exception e) {
|
||||
LOG.error("Failed to encrypt private key", e);
|
||||
throw new CertificateGenerationException("Private key encryption failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public X509Certificate parseCertificate(String certPem) {
|
||||
try (PEMParser parser = new PEMParser(new StringReader(certPem))) {
|
||||
Object obj = parser.readObject();
|
||||
if (obj instanceof X509CertificateHolder holder) {
|
||||
return new JcaX509CertificateConverter()
|
||||
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
|
||||
.getCertificate(holder);
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid certificate PEM format");
|
||||
} catch (Exception e) {
|
||||
LOG.error("Failed to parse certificate", e);
|
||||
throw new CertificateGenerationException("Certificate parsing failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public PrivateKey parsePrivateKey(String keyPem) {
|
||||
try (PEMParser parser = new PEMParser(new StringReader(keyPem))) {
|
||||
Object obj = parser.readObject();
|
||||
JcaPEMKeyConverter converter = new JcaPEMKeyConverter()
|
||||
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
|
||||
|
||||
if (obj instanceof org.bouncycastle.openssl.PEMKeyPair pemKeyPair) {
|
||||
return converter.getKeyPair(pemKeyPair).getPrivate();
|
||||
} else if (obj instanceof org.bouncycastle.asn1.pkcs.PrivateKeyInfo pkInfo) {
|
||||
return converter.getPrivateKey(pkInfo);
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid private key PEM format");
|
||||
} catch (Exception e) {
|
||||
LOG.error("Failed to parse private key", e);
|
||||
throw new CertificateGenerationException("Private key parsing failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void validateCertificate(X509Certificate cert) {
|
||||
try {
|
||||
cert.checkValidity();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("Certificate validation failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public KeyAlgorithm detectKeyAlgorithm(PublicKey publicKey) {
|
||||
String algorithm = publicKey.getAlgorithm();
|
||||
if ("RSA".equals(algorithm)) {
|
||||
try {
|
||||
java.security.interfaces.RSAPublicKey rsaKey = (java.security.interfaces.RSAPublicKey) publicKey;
|
||||
int keySize = rsaKey.getModulus().bitLength();
|
||||
return switch (keySize) {
|
||||
case 1024 -> KeyAlgorithm.RSA_1024;
|
||||
case 3072 -> KeyAlgorithm.RSA_3072;
|
||||
case 4096 -> KeyAlgorithm.RSA_4096;
|
||||
default -> KeyAlgorithm.RSA_2048;
|
||||
};
|
||||
} catch (Exception e) {
|
||||
return KeyAlgorithm.RSA_2048;
|
||||
}
|
||||
} else if ("EC".equals(algorithm)) {
|
||||
try {
|
||||
java.security.interfaces.ECPublicKey ecKey = (java.security.interfaces.ECPublicKey) publicKey;
|
||||
int fieldSize = ecKey.getParams().getCurve().getField().getFieldSize();
|
||||
return switch (fieldSize) {
|
||||
case 384 -> KeyAlgorithm.EC_secp384r1;
|
||||
case 521 -> KeyAlgorithm.EC_secp521r1;
|
||||
default -> KeyAlgorithm.EC_prime256v1;
|
||||
};
|
||||
} catch (Exception e) {
|
||||
return KeyAlgorithm.EC_prime256v1;
|
||||
}
|
||||
}
|
||||
return KeyAlgorithm.RSA_2048;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Mutable certificate entity for Jackson serialization/deserialization.
|
||||
* Thread-safety is managed by the storage layer (ConcurrentHashMap).
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/API_CertificateDetail.html">AWS ACM CertificateDetail</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class Certificate {
|
||||
private String arn;
|
||||
private String domainName;
|
||||
private List<String> subjectAlternativeNames;
|
||||
private CertificateStatus status;
|
||||
private CertificateType type;
|
||||
private ValidationMethod validationMethod;
|
||||
private Instant createdAt;
|
||||
private Instant issuedAt;
|
||||
private Instant importedAt;
|
||||
private Instant notBefore;
|
||||
private Instant notAfter;
|
||||
private String serial;
|
||||
private String subject;
|
||||
private String issuer;
|
||||
private KeyAlgorithm keyAlgorithm;
|
||||
private String signatureAlgorithm;
|
||||
private List<String> inUseBy;
|
||||
private Map<String, String> tags;
|
||||
private String certificateBody;
|
||||
private String privateKey;
|
||||
private String certificateChain;
|
||||
private CertificateOptions certOptions;
|
||||
private String certAuthorityArn;
|
||||
private List<DomainValidation> domainValidationOptions;
|
||||
private String idempotencyToken;
|
||||
|
||||
public Certificate() {
|
||||
this.subjectAlternativeNames = new ArrayList<>();
|
||||
this.inUseBy = new ArrayList<>();
|
||||
this.tags = new HashMap<>();
|
||||
this.domainValidationOptions = new ArrayList<>();
|
||||
}
|
||||
|
||||
// Getters and Setters
|
||||
public String getArn() {
|
||||
return arn;
|
||||
}
|
||||
|
||||
public void setArn(String arn) {
|
||||
this.arn = arn;
|
||||
}
|
||||
|
||||
public String getDomainName() {
|
||||
return domainName;
|
||||
}
|
||||
|
||||
public void setDomainName(String domainName) {
|
||||
this.domainName = domainName;
|
||||
}
|
||||
|
||||
public List<String> getSubjectAlternativeNames() {
|
||||
return subjectAlternativeNames;
|
||||
}
|
||||
|
||||
public void setSubjectAlternativeNames(List<String> subjectAlternativeNames) {
|
||||
this.subjectAlternativeNames = subjectAlternativeNames != null ? new ArrayList<>(subjectAlternativeNames) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public CertificateStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(CertificateStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public CertificateType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(CertificateType type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public ValidationMethod getValidationMethod() {
|
||||
return validationMethod;
|
||||
}
|
||||
|
||||
public void setValidationMethod(ValidationMethod validationMethod) {
|
||||
this.validationMethod = validationMethod;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Instant getIssuedAt() {
|
||||
return issuedAt;
|
||||
}
|
||||
|
||||
public void setIssuedAt(Instant issuedAt) {
|
||||
this.issuedAt = issuedAt;
|
||||
}
|
||||
|
||||
public Instant getImportedAt() {
|
||||
return importedAt;
|
||||
}
|
||||
|
||||
public void setImportedAt(Instant importedAt) {
|
||||
this.importedAt = importedAt;
|
||||
}
|
||||
|
||||
public Instant getNotBefore() {
|
||||
return notBefore;
|
||||
}
|
||||
|
||||
public void setNotBefore(Instant notBefore) {
|
||||
this.notBefore = notBefore;
|
||||
}
|
||||
|
||||
public Instant getNotAfter() {
|
||||
return notAfter;
|
||||
}
|
||||
|
||||
public void setNotAfter(Instant notAfter) {
|
||||
this.notAfter = notAfter;
|
||||
}
|
||||
|
||||
public String getSerial() {
|
||||
return serial;
|
||||
}
|
||||
|
||||
public void setSerial(String serial) {
|
||||
this.serial = serial;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public String getIssuer() {
|
||||
return issuer;
|
||||
}
|
||||
|
||||
public void setIssuer(String issuer) {
|
||||
this.issuer = issuer;
|
||||
}
|
||||
|
||||
public KeyAlgorithm getKeyAlgorithm() {
|
||||
return keyAlgorithm;
|
||||
}
|
||||
|
||||
public void setKeyAlgorithm(KeyAlgorithm keyAlgorithm) {
|
||||
this.keyAlgorithm = keyAlgorithm;
|
||||
}
|
||||
|
||||
public String getSignatureAlgorithm() {
|
||||
return signatureAlgorithm;
|
||||
}
|
||||
|
||||
public void setSignatureAlgorithm(String signatureAlgorithm) {
|
||||
this.signatureAlgorithm = signatureAlgorithm;
|
||||
}
|
||||
|
||||
public List<String> getInUseBy() {
|
||||
return inUseBy;
|
||||
}
|
||||
|
||||
public void setInUseBy(List<String> inUseBy) {
|
||||
this.inUseBy = inUseBy != null ? new ArrayList<>(inUseBy) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public Map<String, String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags != null ? new HashMap<>(tags) : new HashMap<>();
|
||||
}
|
||||
|
||||
public String getCertificateBody() {
|
||||
return certificateBody;
|
||||
}
|
||||
|
||||
public void setCertificateBody(String certificateBody) {
|
||||
this.certificateBody = certificateBody;
|
||||
}
|
||||
|
||||
public String getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
public void setPrivateKey(String privateKey) {
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public String getCertificateChain() {
|
||||
return certificateChain;
|
||||
}
|
||||
|
||||
public void setCertificateChain(String certificateChain) {
|
||||
this.certificateChain = certificateChain;
|
||||
}
|
||||
|
||||
public CertificateOptions getCertOptions() {
|
||||
return certOptions;
|
||||
}
|
||||
|
||||
public void setCertOptions(CertificateOptions certOptions) {
|
||||
this.certOptions = certOptions;
|
||||
}
|
||||
|
||||
public String getCertAuthorityArn() {
|
||||
return certAuthorityArn;
|
||||
}
|
||||
|
||||
public void setCertAuthorityArn(String certAuthorityArn) {
|
||||
this.certAuthorityArn = certAuthorityArn;
|
||||
}
|
||||
|
||||
public List<DomainValidation> getDomainValidationOptions() {
|
||||
return domainValidationOptions;
|
||||
}
|
||||
|
||||
public void setDomainValidationOptions(List<DomainValidation> domainValidationOptions) {
|
||||
this.domainValidationOptions = domainValidationOptions != null ? new ArrayList<>(domainValidationOptions) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public String getIdempotencyToken() {
|
||||
return idempotencyToken;
|
||||
}
|
||||
|
||||
public void setIdempotencyToken(String idempotencyToken) {
|
||||
this.idempotencyToken = idempotencyToken;
|
||||
}
|
||||
|
||||
public boolean isExpired() {
|
||||
return notAfter != null && Instant.now().isAfter(notAfter);
|
||||
}
|
||||
|
||||
public boolean canExport() {
|
||||
return type == CertificateType.PRIVATE ||
|
||||
(certOptions != null && "ENABLED".equals(certOptions.export()));
|
||||
}
|
||||
|
||||
public String extractCertificateId() {
|
||||
if (arn == null) return null;
|
||||
int lastSlash = arn.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? arn.substring(lastSlash + 1) : arn;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public record CertificateOptions(
|
||||
String certificateTransparencyLoggingPreference,
|
||||
String export
|
||||
) {
|
||||
public static CertificateOptions defaultOptions() {
|
||||
return new CertificateOptions("ENABLED", "DISABLED");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* Certificate lifecycle status values matching AWS ACM.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/API_CertificateDetail.html">AWS ACM CertificateDetail</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public enum CertificateStatus {
|
||||
PENDING_VALIDATION,
|
||||
ISSUED,
|
||||
INACTIVE,
|
||||
EXPIRED,
|
||||
VALIDATION_TIMED_OUT,
|
||||
REVOKED,
|
||||
FAILED
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* Certificate type indicating how the certificate was provisioned.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/API_CertificateDetail.html">AWS ACM CertificateDetail</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public enum CertificateType {
|
||||
AMAZON_ISSUED,
|
||||
IMPORTED,
|
||||
PRIVATE
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
public record DomainValidation(
|
||||
String domainName,
|
||||
String validationDomain,
|
||||
String validationStatus,
|
||||
String validationMethod,
|
||||
ResourceRecord resourceRecord,
|
||||
List<String> validationEmails
|
||||
) {}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Entry for idempotency token cache with lazy expiration.
|
||||
*
|
||||
* <p>Design decision: Using ConcurrentHashMap with timestamp-based entries
|
||||
* instead of Caffeine or scheduled cleanup. This matches moto's approach
|
||||
* (see moto/acm/models.py:478-505) where expired entries are removed on
|
||||
* lookup. No background thread needed - acceptable for emulator workloads.</p>
|
||||
*
|
||||
* @param arn The certificate ARN associated with this token
|
||||
* @param expires Expiration instant (1 hour after creation)
|
||||
* @param requestHash Hash of original request parameters for validation
|
||||
* @see <a href="https://github.com/getmoto/moto/blob/main/moto/acm/models.py">moto ACM</a>
|
||||
*/
|
||||
public record IdempotencyTokenEntry(
|
||||
String arn,
|
||||
Instant expires,
|
||||
int requestHash
|
||||
) {
|
||||
private static final Duration TTL = Duration.ofHours(1);
|
||||
|
||||
/**
|
||||
* Creates a new idempotency token entry with 1-hour TTL from current time.
|
||||
*
|
||||
* @param arn The certificate ARN
|
||||
* @param requestHash Hash of the request parameters
|
||||
* @return New entry with expiration set to current time + 1 hour
|
||||
*/
|
||||
public static IdempotencyTokenEntry create(String arn, int requestHash) {
|
||||
return new IdempotencyTokenEntry(arn, Instant.now().plus(TTL), requestHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this token entry has expired.
|
||||
*
|
||||
* @return true if the current time is after the expiration instant
|
||||
*/
|
||||
public boolean isExpired() {
|
||||
return Instant.now().isAfter(expires);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Key algorithm for certificate key pair generation.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/API_RequestCertificate.html">AWS ACM RequestCertificate</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public enum KeyAlgorithm {
|
||||
RSA_1024("RSA-1024", "RSA", 1024),
|
||||
RSA_2048("RSA-2048", "RSA", 2048),
|
||||
RSA_3072("RSA-3072", "RSA", 3072),
|
||||
RSA_4096("RSA-4096", "RSA", 4096),
|
||||
EC_prime256v1("EC-prime256v1", "EC", 256),
|
||||
EC_secp384r1("EC-secp384r1", "EC", 384),
|
||||
EC_secp521r1("EC-secp521r1", "EC", 521);
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KeyAlgorithm.class);
|
||||
|
||||
private final String awsName;
|
||||
private final String algorithm;
|
||||
private final int keySize;
|
||||
|
||||
KeyAlgorithm(String awsName, String algorithm, int keySize) {
|
||||
this.awsName = awsName;
|
||||
this.algorithm = algorithm;
|
||||
this.keySize = keySize;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getAwsName() {
|
||||
return awsName;
|
||||
}
|
||||
|
||||
public String getAlgorithm() {
|
||||
return algorithm;
|
||||
}
|
||||
|
||||
public int getKeySize() {
|
||||
return keySize;
|
||||
}
|
||||
|
||||
public String getCurveName() {
|
||||
return switch (this) {
|
||||
case EC_prime256v1 -> "secp256r1";
|
||||
case EC_secp384r1 -> "secp384r1";
|
||||
case EC_secp521r1 -> "secp521r1";
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
public static KeyAlgorithm fromAwsName(String name) {
|
||||
if (name == null) return RSA_2048;
|
||||
// Normalize both directions: RSA_2048 ↔ RSA-2048
|
||||
String dashNormalized = name.replace("_", "-");
|
||||
String underscoreNormalized = name.replace("-", "_");
|
||||
for (KeyAlgorithm alg : values()) {
|
||||
// Match against awsName (dash format: "RSA-2048", "EC-prime256v1")
|
||||
if (alg.awsName.equalsIgnoreCase(name) || alg.awsName.equalsIgnoreCase(dashNormalized)) {
|
||||
return alg;
|
||||
}
|
||||
// Match against enum name (underscore format: "RSA_2048", "EC_prime256v1")
|
||||
if (alg.name().equalsIgnoreCase(name) || alg.name().equalsIgnoreCase(underscoreNormalized)) {
|
||||
return alg;
|
||||
}
|
||||
}
|
||||
LOG.warnv("Unknown key algorithm '{0}', defaulting to RSA_2048", name);
|
||||
return RSA_2048;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Result of paginated certificate listing.
|
||||
*
|
||||
* <p>Used by {@code ListCertificates} to return a page of certificates
|
||||
* along with a cursor token for fetching the next page.</p>
|
||||
*
|
||||
* @param certificates List of certificates for this page
|
||||
* @param nextToken Token for next page, or null if no more pages
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/API_ListCertificates.html">AWS ACM ListCertificates</a>
|
||||
*/
|
||||
public record ListResult(
|
||||
List<Certificate> certificates,
|
||||
String nextToken
|
||||
) {}
|
||||
@@ -0,0 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public record ResourceRecord(
|
||||
String name,
|
||||
String type,
|
||||
String value
|
||||
) {}
|
||||
@@ -0,0 +1,14 @@
|
||||
package io.github.hectorvent.floci.services.acm.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* Domain validation method for certificate issuance.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/API_RequestCertificate.html">AWS ACM RequestCertificate</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public enum ValidationMethod {
|
||||
DNS,
|
||||
EMAIL
|
||||
}
|
||||
@@ -2341,5 +2341,61 @@
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true,
|
||||
"allDeclaredFields": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jce.provider.BouncyCastleProvider",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true,
|
||||
"allDeclaredFields": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi$EC",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyPairGeneratorSpi",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.asymmetric.ec.KeyPairGeneratorSpi$EC",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.digest.SHA256$Digest",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.digest.SHA384$Digest",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.asymmetric.rsa.DigestSignatureSpi$SHA256",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.asymmetric.ec.SignatureSpi$ecDSA256",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.symmetric.AES$ECB",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
},
|
||||
{
|
||||
"name": "org.bouncycastle.jcajce.provider.symmetric.PBEPBKDF2$PBKDF2withSHA256",
|
||||
"allDeclaredConstructors": true,
|
||||
"allDeclaredMethods": true
|
||||
}
|
||||
]
|
||||
@@ -3,7 +3,15 @@ quarkus:
|
||||
port: 4566
|
||||
host: 0.0.0.0
|
||||
native:
|
||||
additional-build-args: "--initialize-at-run-time=org.apache.hc.client5.http.impl.auth.NTLMEngineImpl,--initialize-at-run-time=com.github.dockerjava.transport.NamedPipeSocket$Kernel32"
|
||||
additional-build-args: >-
|
||||
--initialize-at-run-time=org.apache.hc.client5.http.impl.auth.NTLMEngineImpl,
|
||||
--initialize-at-run-time=com.github.dockerjava.transport.NamedPipeSocket$Kernel32,
|
||||
--initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$Default,
|
||||
--initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$NonceAndIV,
|
||||
--initialize-at-run-time=org.bouncycastle.crypto.prng.SP800SecureRandom,
|
||||
--initialize-at-run-time=org.bouncycastle.jce.provider.BouncyCastleProvider,
|
||||
--initialize-at-run-time=io.github.hectorvent.floci.services.acm.AcmService,
|
||||
--initialize-at-run-time=io.github.hectorvent.floci.services.acm.CertificateGenerator
|
||||
|
||||
floci:
|
||||
base-url: "http://localhost:4566"
|
||||
@@ -41,6 +49,9 @@ floci:
|
||||
secretsmanager:
|
||||
mode: memory
|
||||
flush-interval-ms: 5000
|
||||
acm:
|
||||
mode: memory
|
||||
flush-interval-ms: 5000
|
||||
|
||||
auth:
|
||||
validate-signatures: false
|
||||
@@ -108,3 +119,6 @@ floci:
|
||||
enabled: true
|
||||
cloudformation:
|
||||
enabled: true
|
||||
acm:
|
||||
enabled: true
|
||||
validation-wait-seconds: 0
|
||||
@@ -0,0 +1,25 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIESTCCAzGgAwIBAgITBntQXCplJ7wevi2i0ZmY7bibLDANBgkqhkiG9w0BAQsF
|
||||
ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6
|
||||
b24gUm9vdCBDQSAxMB4XDTE1MTAyMTIyMjQzNFoXDTQwMTAyMTIyMjQzNFowRjEL
|
||||
MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEVMBMGA1UECxMMU2VydmVyIENB
|
||||
IDFCMQ8wDQYDVQQDEwZBbWF6b24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
|
||||
AoIBAQDCThZn3c68asg3CZwaH2N2FfD7JfHr/RXfbLXEVhvwCMk9CeNAGKnX9EUH
|
||||
2z9+RH3bQ7wBLM/FY/lBJH/O4Yl+XNM6sFPaLMJy9Ll4iqL7B/f6Mf5c5aFl3bG
|
||||
m5z3bCMwdBZL2c5OJRFmVF9RhJh3lQbSs7nbVxN3bvVMVlNM5lXCBAB3FZPbEFYi
|
||||
dB0wfPL9vY1dB7AJ5v4bMl9z5z9qWP2dW7m7v5vRVo+A9TFxn8B7EZVrTXFn3CyM
|
||||
H9W8+K4iKbQ/7HZ7bVz3AYB5vOZjFU7Lz1h/0OG/m5v6cKGOiJAOmUjThVL3Cjb5
|
||||
6nRIoTUdHHqP3L9rOi9a7VXnNdWRAgMBAAGjggE7MIIBNzASBgNVHRMBAf8ECDAG
|
||||
AQH/AgEAMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUWaRmBlKge5WSPKOUByeW
|
||||
dFv5PdAwHwYDVR0jBBgwFoAUhBjMhTTsvAyUlC4IWZzHshBOCggwewYIKwYBBQUH
|
||||
AQEEbzBtMC8GCCsGAQUFBzABhiNodHRwOi8vb2NzcC5yb290Y2ExLmFtYXpvbnRy
|
||||
dXN0LmNvbTA6BggrBgEFBQcwAoYuaHR0cDovL2NydC5yb290Y2ExLmFtYXpvbnRy
|
||||
dXN0LmNvbS9yb290Y2ExLmNlcjA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3Js
|
||||
LnJvb3RjYTEuYW1hem9udHJ1c3QuY29tL3Jvb3RjYTEuY3JsMBEGA1UdIAQKMAgw
|
||||
BgYEVR0gADANBgkqhkiG9w0BAQsFAAOCAQEARP3m7HzM/VfnKaFC5rlI+TFkk5N4
|
||||
rlCWElGh2v9s4k+1p5yTniV3n5/sR3DVHMa5TQ8m+4Z7PsKl/D8UFRl/5eEILxQ+
|
||||
7e5RLk4kcPfbc3VYl/lYgIhEY9CWA2t/FSXJJJu5f0EH0wEcN1A3F8mFbNNgN2N9
|
||||
RvPWmGd4TCNy58bGmVQYO8+xJJbgTXTJ1HkIw/7VOp6ePm4CIk9MK2K8j9j3fB7b
|
||||
vRmA1VwLB0K3Vw8jLDl1oLcz/nXPdfXhzzzXJy/TKgIUYJb3SB/k2bECiyM2xyIb
|
||||
tTmFPau9YqHPBPK8xSpWJ9JfD/2pK1gORqVmBT8R88zcbAj6Qwk/pfKurw==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,325 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
/**
|
||||
* Tests for edge cases: wildcard domains, max SANs (100), max tags (50).
|
||||
*/
|
||||
@QuarkusTest
|
||||
class AcmEdgeCaseTest {
|
||||
|
||||
private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssured.config = RestAssured.config().encoderConfig(
|
||||
EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs(ACM_CONTENT_TYPE, ContentType.TEXT));
|
||||
}
|
||||
|
||||
// ==================== Wildcard Domain Tests ====================
|
||||
|
||||
@Test
|
||||
void wildcardDomainAsPrimary() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "*.example.com"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wildcardDomainAsSan() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "example.com",
|
||||
"SubjectAlternativeNames": ["*.example.com", "www.example.com"]
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedWildcardDomain() {
|
||||
// AWS allows wildcards only at the leftmost position
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "*.api.example.com"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
// ==================== Max SANs Tests ====================
|
||||
|
||||
@Test
|
||||
void exactlyMaxSans() {
|
||||
// 100 SANs is the maximum
|
||||
List<String> sans = IntStream.range(0, 99)
|
||||
.mapToObj(i -> "san" + i + ".example.com")
|
||||
.collect(Collectors.toList());
|
||||
|
||||
String sansJson = sans.stream()
|
||||
.map(s -> "\"" + s + "\"")
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "max-sans.example.com",
|
||||
"SubjectAlternativeNames": %s
|
||||
}
|
||||
""".formatted(sansJson))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceedMaxSans() {
|
||||
// 101 SANs should fail (primary domain + 100 SANs = 101 total)
|
||||
List<String> sans = IntStream.range(0, 101)
|
||||
.mapToObj(i -> "san" + i + ".example.com")
|
||||
.collect(Collectors.toList());
|
||||
|
||||
String sansJson = sans.stream()
|
||||
.map(s -> "\"" + s + "\"")
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "exceed-sans.example.com",
|
||||
"SubjectAlternativeNames": %s
|
||||
}
|
||||
""".formatted(sansJson))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
// ==================== Max Tags Tests ====================
|
||||
|
||||
@Test
|
||||
void exactlyMaxTags() {
|
||||
// 50 tags is the maximum
|
||||
String tagsJson = IntStream.range(0, 50)
|
||||
.mapToObj(i -> "{\"Key\": \"Tag" + i + "\", \"Value\": \"Value" + i + "\"}")
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
String arn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "max-tags-%s.example.com",
|
||||
"Tags": %s
|
||||
}
|
||||
""".formatted(UUID.randomUUID(), tagsJson))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// Verify tags were applied
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListTagsForCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(arn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags.size()", equalTo(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceedMaxTags() {
|
||||
// 51 tags should fail
|
||||
String tagsJson = IntStream.range(0, 51)
|
||||
.mapToObj(i -> "{\"Key\": \"Tag" + i + "\", \"Value\": \"Value" + i + "\"}")
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "exceed-tags.example.com",
|
||||
"Tags": %s
|
||||
}
|
||||
""".formatted(tagsJson))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
// ==================== Validation Method Tests ====================
|
||||
|
||||
@Test
|
||||
void invalidValidationMethodThrowsException() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "invalid-validation.example.com",
|
||||
"ValidationMethod": "INVALID_METHOD"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
// ==================== Domain Name Validation Tests ====================
|
||||
|
||||
@Test
|
||||
void emptyDomainNameFails() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": ""
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainNameTooLong() {
|
||||
// Max domain length is 253 characters
|
||||
String longDomain = "a".repeat(254) + ".example.com";
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s"
|
||||
}
|
||||
""".formatted(longDomain))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
// ==================== Tag Validation Tests ====================
|
||||
|
||||
@Test
|
||||
void awsPrefixedTagKeyFails() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "aws-tag.example.com",
|
||||
"Tags": [{"Key": "aws:reserved", "Value": "test"}]
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyTagKeyFails() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.AddTagsToCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/test",
|
||||
"Tags": [{"Key": "", "Value": "test"}]
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(anyOf(equalTo(400), equalTo(404)));
|
||||
}
|
||||
|
||||
// ==================== Key Algorithm Tests ====================
|
||||
|
||||
@Test
|
||||
void allKeyAlgorithmsSupported() {
|
||||
String[] algorithms = {"RSA_2048", "RSA_3072", "RSA_4096", "EC_prime256v1", "EC_secp384r1", "EC_secp521r1"};
|
||||
|
||||
for (String algo : algorithms) {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s.example.com",
|
||||
"KeyAlgorithm": "%s"
|
||||
}
|
||||
""".formatted(algo.toLowerCase().replace("_", "-"), algo))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
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 java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
/**
|
||||
* Tests for idempotency token functionality with 1-hour TTL.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class AcmIdempotencyTest {
|
||||
|
||||
private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssured.config = RestAssured.config().encoderConfig(
|
||||
EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs(ACM_CONTENT_TYPE, ContentType.TEXT));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void sameTokenReturnsExistingCertificate() {
|
||||
String token = "idempotency-test-" + UUID.randomUUID();
|
||||
String domain = "idempotent-" + UUID.randomUUID() + ".example.com";
|
||||
|
||||
// First request
|
||||
String firstArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s",
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(domain, token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// Second request with same token should return same ARN
|
||||
String secondArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s",
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(domain, token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", equalTo(firstArn))
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// ARNs should match
|
||||
org.junit.jupiter.api.Assertions.assertEquals(firstArn, secondArn);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void differentTokenCreatesNewCertificate() {
|
||||
String domain = "multi-token-" + UUID.randomUUID() + ".example.com";
|
||||
|
||||
// First request
|
||||
String firstArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s",
|
||||
"IdempotencyToken": "token-1-%s"
|
||||
}
|
||||
""".formatted(domain, UUID.randomUUID()))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// Second request with different token should create new certificate
|
||||
String secondArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s",
|
||||
"IdempotencyToken": "token-2-%s"
|
||||
}
|
||||
""".formatted(domain, UUID.randomUUID()))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// ARNs should be different
|
||||
org.junit.jupiter.api.Assertions.assertNotEquals(firstArn, secondArn);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void sameTokenDifferentParamsThrowsIdempotencyException() {
|
||||
String token = "param-mismatch-" + UUID.randomUUID();
|
||||
|
||||
// First request with domain A
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "domain-a-%s.example.com",
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(UUID.randomUUID(), token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Second request with same token but different domain - should fail
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "domain-b-%s.example.com",
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(UUID.randomUUID(), token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("IdempotencyException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void sameTokenDifferentKeyAlgorithmThrowsIdempotencyException() {
|
||||
String token = "key-algo-mismatch-" + UUID.randomUUID();
|
||||
String domain = "key-algo-" + UUID.randomUUID() + ".example.com";
|
||||
|
||||
// First request with RSA-2048
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s",
|
||||
"KeyAlgorithm": "RSA_2048",
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(domain, token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Second request with same token but different key algorithm - should fail
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s",
|
||||
"KeyAlgorithm": "EC_prime256v1",
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(domain, token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("IdempotencyException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void noTokenAlwaysCreatesNewCertificate() {
|
||||
String domain = "no-token-" + UUID.randomUUID() + ".example.com";
|
||||
|
||||
// First request without token
|
||||
String firstArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s"
|
||||
}
|
||||
""".formatted(domain))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// Second request without token should create new certificate
|
||||
String secondArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s"
|
||||
}
|
||||
""".formatted(domain))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
org.junit.jupiter.api.Assertions.assertNotEquals(firstArn, secondArn);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void sameTokenSameSansReturnsExistingCertificate() {
|
||||
String token = "sans-match-" + UUID.randomUUID();
|
||||
String domain = "sans-" + UUID.randomUUID() + ".example.com";
|
||||
|
||||
// First request with SANs
|
||||
String firstArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s",
|
||||
"SubjectAlternativeNames": ["www.%s", "api.%s"],
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(domain, domain, domain, token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// Same request should return same ARN
|
||||
String secondArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "%s",
|
||||
"SubjectAlternativeNames": ["www.%s", "api.%s"],
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(domain, domain, domain, token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
org.junit.jupiter.api.Assertions.assertEquals(firstArn, secondArn);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
import jakarta.inject.Inject;
|
||||
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 java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class AcmImportExportTest {
|
||||
|
||||
private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
@Inject
|
||||
CertificateGenerator certificateGenerator;
|
||||
|
||||
// Generated test certificate data
|
||||
private String validTestCertificate;
|
||||
private String validTestPrivateKey;
|
||||
|
||||
private String importedCertificateArn;
|
||||
private String exportableCertificateArn;
|
||||
|
||||
@BeforeAll
|
||||
void setupTestCertificates() {
|
||||
RestAssured.config = RestAssured.config().encoderConfig(
|
||||
EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs(ACM_CONTENT_TYPE, ContentType.TEXT));
|
||||
|
||||
// Generate a valid test certificate using CertificateGenerator
|
||||
CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateCertificate(
|
||||
"test-import.example.com",
|
||||
List.of("www.test-import.example.com"),
|
||||
KeyAlgorithm.RSA_2048
|
||||
);
|
||||
|
||||
validTestCertificate = generated.certificatePem();
|
||||
validTestPrivateKey = generated.privateKeyPem();
|
||||
}
|
||||
|
||||
// ==================== ImportCertificate Tests ====================
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void importCertificateBasic() {
|
||||
// Escape newlines for JSON
|
||||
String certJson = validTestCertificate.replace("\n", "\\n");
|
||||
String keyJson = validTestPrivateKey.replace("\n", "\\n");
|
||||
|
||||
importedCertificateArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.ImportCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Certificate": "%s",
|
||||
"PrivateKey": "%s"
|
||||
}
|
||||
""".formatted(certJson, keyJson))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"))
|
||||
.body("CertificateArn", containsString(":certificate/"))
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void verifyImportedCertificate() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.DescribeCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(importedCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Certificate.CertificateArn", equalTo(importedCertificateArn))
|
||||
.body("Certificate.DomainName", equalTo("test-import.example.com"))
|
||||
.body("Certificate.Status", equalTo("ISSUED"))
|
||||
.body("Certificate.Type", equalTo("IMPORTED"))
|
||||
.body("Certificate.KeyAlgorithm", equalTo("RSA-2048"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void importCertificateWithTags() {
|
||||
String certJson = validTestCertificate.replace("\n", "\\n");
|
||||
String keyJson = validTestPrivateKey.replace("\n", "\\n");
|
||||
|
||||
String taggedArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.ImportCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Certificate": "%s",
|
||||
"PrivateKey": "%s",
|
||||
"Tags": [
|
||||
{"Key": "Environment", "Value": "test"},
|
||||
{"Key": "ImportTest", "Value": "true"}
|
||||
]
|
||||
}
|
||||
""".formatted(certJson, keyJson))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"))
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// Verify tags were applied
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListTagsForCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(taggedArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags.size()", equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void importCertificateReimport() {
|
||||
String certJson = validTestCertificate.replace("\n", "\\n");
|
||||
String keyJson = validTestPrivateKey.replace("\n", "\\n");
|
||||
|
||||
// Re-import to the same ARN should succeed
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ImportCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Certificate": "%s",
|
||||
"PrivateKey": "%s",
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(certJson, keyJson, importedCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", equalTo(importedCertificateArn));
|
||||
}
|
||||
|
||||
// ==================== ExportCertificate Tests ====================
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void requestExportableCertificate() {
|
||||
// Create a PRIVATE type certificate that can be exported
|
||||
exportableCertificateArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "exportable.example.com",
|
||||
"CertificateAuthorityArn": "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"))
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void exportCertificate() {
|
||||
String passphrase = Base64.getEncoder().encodeToString("testpassphrase".getBytes());
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ExportCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s",
|
||||
"Passphrase": "%s"
|
||||
}
|
||||
""".formatted(exportableCertificateArn, passphrase))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Certificate", startsWith("-----BEGIN CERTIFICATE-----"))
|
||||
.body("PrivateKey", startsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void exportCertificateShortPassphraseFails() {
|
||||
String shortPassphrase = Base64.getEncoder().encodeToString("abc".getBytes());
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ExportCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s",
|
||||
"Passphrase": "%s"
|
||||
}
|
||||
""".formatted(exportableCertificateArn, shortPassphrase))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(13)
|
||||
void exportNonExportableCertificateFails() {
|
||||
// Create a non-exportable certificate (AMAZON_ISSUED without Export option)
|
||||
String nonExportableArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "non-exportable.example.com"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
String passphrase = Base64.getEncoder().encodeToString("testpassphrase".getBytes());
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ExportCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s",
|
||||
"Passphrase": "%s"
|
||||
}
|
||||
""".formatted(nonExportableArn, passphrase))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(14)
|
||||
void exportCertificateNotFoundFails() {
|
||||
String passphrase = Base64.getEncoder().encodeToString("testpassphrase".getBytes());
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ExportCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/nonexistent",
|
||||
"Passphrase": "%s"
|
||||
}
|
||||
""".formatted(passphrase))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(15)
|
||||
void importInvalidCertificateFails() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ImportCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Certificate": "not-a-valid-certificate",
|
||||
"PrivateKey": "not-a-valid-key"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,558 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
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 AcmIntegrationTest {
|
||||
|
||||
private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static String createdCertificateArn;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssured.config = RestAssured.config().encoderConfig(
|
||||
EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs(ACM_CONTENT_TYPE, ContentType.TEXT));
|
||||
}
|
||||
|
||||
// ==================== User Story 1: RequestCertificate ====================
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void requestCertificateBasic() {
|
||||
createdCertificateArn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "example.com"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"))
|
||||
.body("CertificateArn", containsString(":certificate/"))
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void requestCertificateWithSans() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "api.example.com",
|
||||
"SubjectAlternativeNames": ["www.example.com", "*.example.com"]
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void requestCertificateWithDnsValidation() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "dns-validated.example.com",
|
||||
"ValidationMethod": "DNS"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void requestCertificateWithEmailValidation() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "email-validated.example.com",
|
||||
"ValidationMethod": "EMAIL"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void requestCertificateWithKeyAlgorithm() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "ec-cert.example.com",
|
||||
"KeyAlgorithm": "EC_prime256v1"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void requestCertificateWithIdempotencyToken() {
|
||||
String token = "test-idempotency-token-123";
|
||||
|
||||
// First request
|
||||
String arn1 = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "idempotent.example.com",
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// Second request with same token should return same ARN
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "idempotent.example.com",
|
||||
"IdempotencyToken": "%s"
|
||||
}
|
||||
""".formatted(token))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", equalTo(arn1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void requestCertificateWithTags() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "tagged.example.com",
|
||||
"Tags": [
|
||||
{"Key": "Environment", "Value": "test"},
|
||||
{"Key": "Project", "Value": "demo"}
|
||||
]
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateArn", startsWith("arn:aws:acm:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void requestCertificateEmptyDomainFails() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": ""
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
// ==================== User Story 2: DescribeCertificate ====================
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void describeCertificate() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.DescribeCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(createdCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Certificate.CertificateArn", equalTo(createdCertificateArn))
|
||||
.body("Certificate.DomainName", equalTo("example.com"))
|
||||
.body("Certificate.Status", equalTo("ISSUED"))
|
||||
.body("Certificate.Type", equalTo("AMAZON_ISSUED"))
|
||||
.body("Certificate.Serial", notNullValue())
|
||||
.body("Certificate.Subject", startsWith("CN="))
|
||||
.body("Certificate.Issuer", notNullValue())
|
||||
.body("Certificate.KeyAlgorithm", equalTo("RSA-2048"))
|
||||
.body("Certificate.NotBefore", notNullValue())
|
||||
.body("Certificate.NotAfter", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void describeCertificateNotFound() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.DescribeCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/nonexistent"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
// ==================== User Story 2: GetCertificate ====================
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void getCertificate() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.GetCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(createdCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Certificate", startsWith("-----BEGIN CERTIFICATE-----"))
|
||||
.body("CertificateChain", startsWith("-----BEGIN CERTIFICATE-----"));
|
||||
}
|
||||
|
||||
// ==================== User Story 2: ListCertificates ====================
|
||||
|
||||
@Test
|
||||
@Order(13)
|
||||
void listCertificates() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListCertificates")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateSummaryList", notNullValue())
|
||||
.body("CertificateSummaryList.size()", greaterThanOrEqualTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(14)
|
||||
void listCertificatesWithStatusFilter() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListCertificates")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateStatuses": ["ISSUED"]
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateSummaryList", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(15)
|
||||
void listCertificatesWithKeyTypeFilter() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListCertificates")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Includes": {
|
||||
"keyTypes": ["RSA_2048"]
|
||||
}
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateSummaryList", notNullValue());
|
||||
}
|
||||
|
||||
// ==================== User Story 5: Tagging ====================
|
||||
|
||||
@Test
|
||||
@Order(20)
|
||||
void addTagsToCertificate() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.AddTagsToCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s",
|
||||
"Tags": [
|
||||
{"Key": "Team", "Value": "Engineering"},
|
||||
{"Key": "Cost-Center", "Value": "12345"}
|
||||
]
|
||||
}
|
||||
""".formatted(createdCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(21)
|
||||
void listTagsForCertificate() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListTagsForCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(createdCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags", notNullValue())
|
||||
.body("Tags.size()", greaterThanOrEqualTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(22)
|
||||
void removeTagsFromCertificate() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.RemoveTagsFromCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s",
|
||||
"Tags": [
|
||||
{"Key": "Cost-Center"}
|
||||
]
|
||||
}
|
||||
""".formatted(createdCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Verify tag was removed
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListTagsForCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(createdCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags.find { it.Key == 'Cost-Center' }", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(23)
|
||||
void addTagsInvalidKeyFails() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.AddTagsToCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s",
|
||||
"Tags": [
|
||||
{"Key": "aws:reserved", "Value": "not-allowed"}
|
||||
]
|
||||
}
|
||||
""".formatted(createdCertificateArn))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
// ==================== Account Configuration ====================
|
||||
|
||||
@Test
|
||||
@Order(30)
|
||||
void getAccountConfiguration() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.GetAccountConfiguration")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ExpiryEvents.DaysBeforeExpiry", equalTo(45));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(31)
|
||||
void putAccountConfiguration() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.PutAccountConfiguration")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"ExpiryEvents": {
|
||||
"DaysBeforeExpiry": 30
|
||||
},
|
||||
"IdempotencyToken": "config-token-123"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Verify configuration was updated
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.GetAccountConfiguration")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ExpiryEvents.DaysBeforeExpiry", equalTo(30));
|
||||
}
|
||||
|
||||
// ==================== User Story 3: DeleteCertificate ====================
|
||||
|
||||
@Test
|
||||
@Order(100)
|
||||
void deleteCertificate() {
|
||||
// Create a certificate to delete
|
||||
String arnToDelete = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "to-delete.example.com"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
// Delete it
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.DeleteCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(arnToDelete))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Verify it's gone
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.DescribeCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
""".formatted(arnToDelete))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(101)
|
||||
void deleteCertificateNotFound() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.DeleteCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/nonexistent"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
// ==================== Unsupported Operation ====================
|
||||
|
||||
@Test
|
||||
void unsupportedOperation() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.UnsupportedAction")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UnsupportedOperation"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.response.Response;
|
||||
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 java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Tests for ListCertificates pagination functionality.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class AcmPaginationTest {
|
||||
|
||||
private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final int TOTAL_CERTS = 15;
|
||||
private final List<String> createdArns = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssured.config = RestAssured.config().encoderConfig(
|
||||
EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs(ACM_CONTENT_TYPE, ContentType.TEXT));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createMultipleCertificates() {
|
||||
// Create 15 certificates for pagination testing
|
||||
for (int i = 0; i < TOTAL_CERTS; i++) {
|
||||
String arn = given()
|
||||
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"DomainName": "pagination-test-%d.example.com"
|
||||
}
|
||||
""".formatted(i))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("CertificateArn");
|
||||
|
||||
createdArns.add(arn);
|
||||
}
|
||||
|
||||
assertEquals(TOTAL_CERTS, createdArns.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void listWithMaxItems() {
|
||||
// List with maxItems=5, expect nextToken
|
||||
Response response = given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListCertificates")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"MaxItems": 5
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateSummaryList.size()", equalTo(5))
|
||||
.body("NextToken", notNullValue())
|
||||
.extract().response();
|
||||
|
||||
String nextToken = response.jsonPath().getString("NextToken");
|
||||
assertNotNull(nextToken, "NextToken should be present when there are more pages");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void paginateThroughAllCertificates() {
|
||||
Set<String> allArns = new HashSet<>();
|
||||
String nextToken = null;
|
||||
int pageCount = 0;
|
||||
int maxPages = 10; // Safety limit
|
||||
|
||||
do {
|
||||
String body = nextToken == null
|
||||
? "{\"MaxItems\": 5}"
|
||||
: "{\"MaxItems\": 5, \"NextToken\": \"" + nextToken + "\"}";
|
||||
|
||||
Response response = given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListCertificates")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().response();
|
||||
|
||||
List<String> pageArns = response.jsonPath().getList("CertificateSummaryList.CertificateArn");
|
||||
allArns.addAll(pageArns);
|
||||
nextToken = response.jsonPath().getString("NextToken");
|
||||
pageCount++;
|
||||
|
||||
} while (nextToken != null && pageCount < maxPages);
|
||||
|
||||
// Should have retrieved all created certificates (plus possibly others from other tests)
|
||||
assertTrue(allArns.containsAll(createdArns), "All created certificates should be retrievable via pagination");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void invalidNextToken() {
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListCertificates")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"NextToken": "invalid-token-not-base64"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidNextTokenException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void emptyListReturnsNoNextToken() {
|
||||
// List with a filter that matches nothing
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListCertificates")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"CertificateStatuses": ["REVOKED"]
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateSummaryList", empty())
|
||||
.body("NextToken", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void maxItemsLimit() {
|
||||
// MaxItems should be capped at 1000
|
||||
given()
|
||||
.header("X-Amz-Target", "CertificateManager.ListCertificates")
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"MaxItems": 2000
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CertificateSummaryList.size()", lessThanOrEqualTo(1000));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user