Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ses): add the S/MIME identity certificate operations (#5111)
Kenshin Okinaka3f6fb371d18e
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityCertificateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityCertificateTest.javanew file mode 100644index 0000000000..ccf965f5d2--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityCertificateTest.java@@ -0,0 +1,174 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import software.amazon.awssdk.core.SdkBytes;+import software.amazon.awssdk.services.acm.AcmClient;+import software.amazon.awssdk.services.sesv2.SesV2Client;+import software.amazon.awssdk.services.sesv2.model.AlreadyExistsException;+import software.amazon.awssdk.services.sesv2.model.BadRequestException;+import software.amazon.awssdk.services.sesv2.model.IdentityCertificate;+import software.amazon.awssdk.services.sesv2.model.IdentityCertificateStatus;+import software.amazon.awssdk.services.sesv2.model.ListEmailIdentityCertificatesResponse;+import software.amazon.awssdk.services.sesv2.model.NotFoundException;++import java.nio.file.Files;+import java.nio.file.Path;+import java.time.Instant;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++/**+ * SDK compatibility test for the S/MIME identity certificate operations on a verified domain identity:+ * {@code associateEmailIdentityCertificate}, {@code listEmailIdentityCertificates} (including the+ * {@code CertificateExpiryTime} timestamp an ACTIVE entry carries) and+ * {@code disassociateEmailIdentityCertificate}, plus the {@code deleteEmailIdentity} guard.+ */+@DisplayName("SES v2 Identity Certificates")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesIdentityCertificateTest {++ private static final String DOMAIN = TestFixtures.uniqueName("compat-smime") + ".example.com";++ private static SesV2Client sesV2;+ private static AcmClient acm;+ private static String certificateArn;+ private static String missingCertificateArn;++ @BeforeAll+ static void setup() throws Exception {+ sesV2 = TestFixtures.sesV2Client();+ acm = TestFixtures.acmClient();+ TestFixtures.verifySesDomainIdentityViaRoute53(sesV2, DOMAIN);+ byte[][] certAndKey = generateSelfSignedCert("alice@" + DOMAIN);+ certificateArn = acm.importCertificate(b -> b+ .certificate(SdkBytes.fromByteArray(certAndKey[0]))+ .privateKey(SdkBytes.fromByteArray(certAndKey[1]))).certificateArn();+ missingCertificateArn = certificateArn.substring(0, certificateArn.indexOf("certificate/"))+ + "certificate/00000000-0000-0000-0000-000000000000";+ }++ @AfterAll+ static void cleanup() {+ if (sesV2 != null) {+ try {+ sesV2.disassociateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN).fromAddress("alice@" + DOMAIN));+ sesV2.disassociateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN).fromAddress("bob@" + DOMAIN));+ sesV2.deleteEmailIdentity(b -> b.emailIdentity(DOMAIN));+ } catch (Exception ignored) {+ // Best-effort cleanup; the emulator is reset between runs.+ }+ sesV2.close();+ }+ if (acm != null) {+ try {+ acm.deleteCertificate(b -> b.certificateArn(certificateArn));+ } catch (Exception ignored) {+ // Best-effort cleanup; the emulator is reset between runs.+ }+ acm.close();+ }+ }++ @Test+ @Order(1)+ @DisplayName("Associate certificates and list them with their status")+ void associateAndList() {+ sesV2.associateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN)+ .fromAddress("bob@" + DOMAIN).certificateArn(missingCertificateArn));+ sesV2.associateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN)+ .fromAddress("alice@" + DOMAIN).certificateArn(certificateArn));++ ListEmailIdentityCertificatesResponse response =+ sesV2.listEmailIdentityCertificates(b -> b.emailIdentity(DOMAIN));++ assertThat(response.certificates()).extracting(IdentityCertificate::fromAddress)+ .containsExactly("alice@" + DOMAIN, "bob@" + DOMAIN);+ IdentityCertificate active = response.certificates().get(0);+ assertThat(active.status()).isEqualTo(IdentityCertificateStatus.ACTIVE);+ assertThat(active.certificateArn()).isEqualTo(certificateArn);+ assertThat(active.certificateExpiryTime()).isAfter(Instant.now());+ IdentityCertificate failed = response.certificates().get(1);+ assertThat(failed.status()).isEqualTo(IdentityCertificateStatus.FAILED);+ assertThat(failed.certificateExpiryTime()).isNull();+ assertThat(response.nextToken()).isNull();+ }++ @Test+ @Order(2)+ @DisplayName("List pages with PageSize and NextToken")+ void listPages() {+ ListEmailIdentityCertificatesResponse first =+ sesV2.listEmailIdentityCertificates(b -> b.emailIdentity(DOMAIN).pageSize(1));+ ListEmailIdentityCertificatesResponse second = sesV2.listEmailIdentityCertificates(b -> b+ .emailIdentity(DOMAIN).pageSize(1).nextToken(first.nextToken()));++ assertThat(first.certificates()).extracting(IdentityCertificate::fromAddress)+ .containsExactly("alice@" + DOMAIN);+ assertThat(second.certificates()).extracting(IdentityCertificate::fromAddress)+ .containsExactly("bob@" + DOMAIN);+ assertThat(second.nextToken()).isNull();+ }++ @Test+ @Order(3)+ @DisplayName("Errors surface as the modelled exceptions")+ void errors() {+ assertThatThrownBy(() -> sesV2.associateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN)+ .fromAddress("ALICE@" + DOMAIN).certificateArn(certificateArn)))+ .isInstanceOf(AlreadyExistsException.class);+ assertThatThrownBy(() -> sesV2.associateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN)+ .certificateArn(certificateArn)))+ .isInstanceOf(BadRequestException.class)+ .hasMessageContaining("FromAddress is required when EmailIdentity is a domain.");+ assertThatThrownBy(() -> sesV2.listEmailIdentityCertificates(b -> b.emailIdentity("nosuch-" + DOMAIN)))+ .isInstanceOf(NotFoundException.class);+ }++ @Test+ @Order(4)+ @DisplayName("DeleteEmailIdentity is refused until every certificate is disassociated")+ void deleteGuard() {+ assertThatThrownBy(() -> sesV2.deleteEmailIdentity(b -> b.emailIdentity(DOMAIN)))+ .isInstanceOf(BadRequestException.class)+ .hasMessageContaining("because it has certificates associated with it");++ sesV2.disassociateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN).fromAddress("alice@" + DOMAIN));+ sesV2.disassociateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN).fromAddress("bob@" + DOMAIN));+ sesV2.disassociateEmailIdentityCertificate(b -> b.emailIdentity(DOMAIN).fromAddress("bob@" + DOMAIN));++ assertThat(sesV2.listEmailIdentityCertificates(b -> b.emailIdentity(DOMAIN)).certificates()).isEmpty();+ sesV2.deleteEmailIdentity(b -> b.emailIdentity(DOMAIN));+ }++ private static byte[][] generateSelfSignedCert(String email) throws Exception {+ Path keyFile = Files.createTempFile("smime-key", ".pem");+ Path certFile = Files.createTempFile("smime-cert", ".pem");+ try {+ ProcessBuilder pb = new ProcessBuilder("openssl", "req", "-x509", "-newkey", "rsa:2048",+ "-keyout", keyFile.toString(), "-out", certFile.toString(),+ "-days", "365", "-nodes", "-subj", "/CN=" + email,+ "-addext", "subjectAltName=email:" + email,+ "-addext", "basicConstraints=critical,CA:FALSE",+ "-addext", "keyUsage=critical,digitalSignature",+ "-addext", "extendedKeyUsage=emailProtection");+ pb.redirectErrorStream(true);+ Process p = pb.start();+ p.getInputStream().readAllBytes();+ if (p.waitFor() != 0) {+ throw new IllegalStateException("openssl failed with exit code " + p.exitValue());+ }+ return new byte[][] { Files.readAllBytes(certFile), Files.readAllBytes(keyFile) };+ } finally {+ Files.deleteIfExists(keyFile);+ Files.deleteIfExists(certFile);+ }+ }+}diff --git a/docs/services/ses.md b/docs/services/ses.mdindex 80694327c7..92e58e4cd6 100644--- a/docs/services/ses.md+++ b/docs/services/ses.md@@ -386,6 +386,9 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS| `POST` | `/v2/email/list-export-jobs` | `ListExportJobs` || `PUT` | `/v2/email/export-jobs/{JobId}/cancel` | `CancelExportJob` || `POST` | `/v2/email/update-configuration-sets` | `UpdateConfigurationSet` |+| `POST` | `/v2/email/identity/certificates` | `AssociateEmailIdentityCertificate` |+| `POST` | `/v2/email/identity/certificates/delete` | `DisassociateEmailIdentityCertificate` |+| `POST` | `/v2/email/identity/certificates/list` | `ListEmailIdentityCertificates` |Floci models no leased dedicated IPs: `GetDedicatedIps` is empty and IP-targeted operations return `NotFoundException`, as real AWS does for an account with no leased IPs, with required request members validated first (`BadRequestException`). `PutDedicatedIpPoolScalingAttributes` rejects downgrading a `MANAGED` pool to `STANDARD`, and `PutAccountDedicatedIpWarmupAttributes` stores the flag behind `GetAccount.DedicatedIpAutoWarmupEnabled` (default `true`).@@ -457,6 +460,8 @@ The contact lists (`ListContactLists`, `ListContacts`), the dedicated-IP lists (DKIM follows AWS's domain-centric model. A **domain** identity carries DKIM tokens (generated at verification, stable across `VerifyDomainDkim` calls); its `DkimVerificationStatus` tracks **DNS record detection** — it transitions to `Success` when the expected `<token>._domainkey.<domain>` CNAMEs are present in the Route53 emulation, not when DKIM is enabled. An **email** identity has no DKIM of its own: its `DkimAttributes` (`SigningEnabled`, `Status`, `Tokens`) are inherited from its parent domain identity when one is registered. The parent is the exact domain after the `@` (verified against AWS): a verified `example.com` covers `[email protected]` but not `[email protected]` unless `mail.example.com` is itself a registered identity. `SetIdentityDkimEnabled` / `PutEmailIdentityDkimAttributes` only toggle the signing flag (they no longer force the verification status); `PutEmailIdentityDkimSigningAttributes` sets the signing origin (`AWS_SES` Easy DKIM — regenerating tokens when the key length changes — or `EXTERNAL` BYODKIM).+S/MIME certificate associations are stored per region and never used: Floci does not sign mail. Associating validates the request as SES does (a domain identity needs a `FromAddress` in the domain or one of its subdomains, one certificate per address regardless of case) but, like SES, does not inspect the certificate. `ListEmailIdentityCertificates` reports `ACTIVE` while the association meets the [S/MIME certificate considerations](https://docs.aws.amazon.com/ses/latest/dg/send-email-authentication-smime.html#send-email-authentication-smime-certificate-considerations), plus the requirements a probe found SES also enforces (an end-entity certificate whose key usage includes `digitalSignature` and whose extended key usage includes `emailProtection`), checked against Floci's ACM and identity verification when the list is read, with the certificate's expiry as `CertificateExpiryTime`, and `FAILED` otherwise. There is no `PROVISIONING` phase, `DisassociateEmailIdentityCertificate` removes an association at once, and the certificate is not listed as in use by ACM. As on SES, `DeleteEmailIdentity` refuses an identity that still has a certificate associated, whatever its status. The v1 `DeleteIdentity` and `DeleteVerifiedEmailAddress` share the identities and refuse it too, with the same `BadRequestException` the tenant-association guard returns there; SES's v1 behaviour was not probed.+### IAM enforcementWith `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, every SES v2 operation is authorized as the `ses:`diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateService.javanew file mode 100644index 0000000000..a07e4a6229--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateService.java@@ -0,0 +1,369 @@+package io.github.hectorvent.floci.services.ses;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.CertificateMaterialException;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.Pem;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.acm.AcmService;+import io.github.hectorvent.floci.services.acm.model.Certificate;+import io.github.hectorvent.floci.services.acm.model.CertificateStatus;+import io.github.hectorvent.floci.services.ses.model.IdentityCertificate;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.security.AlgorithmParameters;+import java.security.GeneralSecurityException;+import java.security.PublicKey;+import java.security.cert.CertificateParsingException;+import java.security.cert.X509Certificate;+import java.security.interfaces.ECPublicKey;+import java.security.interfaces.RSAPublicKey;+import java.security.spec.ECGenParameterSpec;+import java.security.spec.ECParameterSpec;+import java.time.Clock;+import java.time.Instant;+import java.util.ArrayList;+import java.util.Collection;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Set;+import java.util.regex.Pattern;++/**+ * S/MIME certificate associations of email identities (Associate/Disassociate/ListEmailIdentityCertificates).+ * Floci stores them and never signs mail. Messages and precedence follow real SES (probed 2026-10-04):+ * the request members are checked before the identity is looked up, and the certificate itself is+ * not checked when it is associated. The status applies the SES Developer Guide's certificate+ * requirements, plus the ones a probe found SES also enforces, when the list is read: an association+ * is ACTIVE while its identity is verified and its ARN names an issued, currently valid end-entity+ * certificate in Floci's ACM, with an allowed key, the email-signing key usages and an RFC822Name+ * SAN equal to the From address, and FAILED otherwise.+ */+@ApplicationScoped+public class SesIdentityCertificateService {++ private static final Logger LOG = Logger.getLogger(SesIdentityCertificateService.class);++ static final String STATUS_ACTIVE = "ACTIVE";+ static final String STATUS_FAILED = "FAILED";++ private static final int RFC822_NAME = 1;+ private static final int DIGITAL_SIGNATURE = 0;+ private static final String EMAIL_PROTECTION = "1.3.6.1.5.5.7.3.4";+ private static final Set<Integer> RSA_SIGNING_KEY_SIZES = Set.of(2048, 3072, 4096);+ private static final List<String> EC_SIGNING_CURVES = List.of("secp256r1", "secp384r1", "secp521r1");++ private static final Pattern CERTIFICATE_ARN =+ Pattern.compile("arn:[\\w+=/,.@-]+:[\\w+=/,.@-]+:[\\w+=/,.@-]*:[0-9]+:certificate/[\\w+=,.@-]+");++ private final StorageBackend<String, IdentityCertificate> store;+ private final SesIdentityService identityService;+ private final AcmService acmService;+ private final Clock clock;+ // Keeps an association and the identity delete-guard from interleaving, so a delete never+ // leaves an association behind on a gone identity.+ private final Object mutationLock = new Object();++ @Inject+ public SesIdentityCertificateService(StorageFactory storageFactory, SesIdentityService identityService,+ AcmService acmService, Clock clock) {+ this(storageFactory.create("ses", "ses-identity-certificates.json",+ new TypeReference<Map<String, IdentityCertificate>>() {}), identityService, acmService, clock);+ }++ SesIdentityCertificateService(StorageBackend<String, IdentityCertificate> store,+ SesIdentityService identityService, AcmService acmService, Clock clock) {+ this.store = store;+ this.identityService = identityService;+ this.acmService = acmService;+ this.clock = clock;+ }++ /** A view of an association with its current status, for ListEmailIdentityCertificates. */+ public record Entry(String fromAddress, String status, String certificateArn, Instant expiryTime) {}++ public void associate(String emailIdentity, String fromAddress, String certificateArn, String region) {+ List<String> violations = new ArrayList<>();+ requireIdentityMember(emailIdentity, violations);+ if (certificateArn == null) {+ violations.add(violation("certificateArn", "Member must not be null"));+ } else {+ if (certificateArn.length() < 20) {+ violations.add(violation("certificateArn", "Member must have length greater than or equal to 20"));+ }+ if (certificateArn.length() > 2048) {+ violations.add(violation("certificateArn", "Member must have length less than or equal to 2048"));+ }+ if (!CERTIFICATE_ARN.matcher(certificateArn).matches()) {+ violations.add(violation("certificateArn",+ "Member must satisfy regular expression pattern: " + CERTIFICATE_ARN.pattern()));+ }+ }+ throwViolations(violations);+ String sender = resolveFromAddress(emailIdentity, fromAddress);+ synchronized (mutationLock) {+ requireIdentity(emailIdentity, region);+ String key = key(region, emailIdentity, sender);+ IdentityCertificate existing = store.get(key).orElse(null);+ if (existing != null) {+ throw new AwsException("AlreadyExistsException",+ "A certificate is already associated with sender <" + existing.fromAddress()+ + "> on identity <" + emailIdentity + ">.", 400);+ }+ store.put(key, new IdentityCertificate(emailIdentity, sender, certificateArn, Instant.now(clock)));+ }+ LOG.infov("Associated certificate {0} with sender {1} on identity {2} in region {3}",+ certificateArn, sender, emailIdentity, region);+ }++ /** Idempotent: an identity with no association for the address is a silent success, as on SES. */+ public void disassociate(String emailIdentity, String fromAddress, String region) {+ List<String> violations = new ArrayList<>();+ requireIdentityMember(emailIdentity, violations);+ throwViolations(violations);+ String sender = resolveFromAddress(emailIdentity, fromAddress);+ synchronized (mutationLock) {+ requireIdentity(emailIdentity, region);+ store.delete(key(region, emailIdentity, sender));+ }+ LOG.infov("Disassociated certificate from sender {0} on identity {1} in region {2}",+ sender, emailIdentity, region);+ }++ public PaginatedResult<Entry> list(String emailIdentity, Integer pageSize, String nextToken, String region) {+ List<String> violations = new ArrayList<>();+ requireIdentityMember(emailIdentity, violations);+ throwViolations(violations);+ SesListPaging paging = SesListPaging.V2_LIST_EMAIL_IDENTITY_CERTIFICATES;+ paging.checkRequest(pageSize, nextToken);+ requireIdentity(emailIdentity, region);+ List<IdentityCertificate> associations = store.scan(k -> k.startsWith(identityPrefix(region, emailIdentity)));+ PaginatedResult<IdentityCertificate> page = paging.page(region, emailIdentity, associations,+ c -> c.fromAddress().toLowerCase(Locale.ROOT), pageSize, nextToken);+ boolean identityVerified = identityService.isIdentityVerified(emailIdentity, region);+ List<Entry> entries = page.items().stream().map(c -> entry(c, identityVerified, region)).toList();+ return new PaginatedResult<>(entries, page.nextToken());+ }++ /**+ * Runs an identity deletion under the association lock. SES refuses to delete an identity that+ * still has a certificate associated, whatever its status, and does not cascade.+ */+ public void deleteIdentityGuarded(String emailIdentity, String accountId, String region, Runnable deleteAction) {+ synchronized (mutationLock) {+ if (store.keys().stream().anyMatch(k -> k.startsWith(identityPrefix(region, emailIdentity)))) {+ String identityArn = AwsArnUtils.Arn.of("ses", region, accountId, "identity/" + emailIdentity)+ .toString();+ throw new AwsException("BadRequestException",+ "Cannot delete <" + identityArn + "> because it has certificates associated with it. "+ + "Disassociate all certificates and try again.", 400);+ }+ deleteAction.run();+ }+ }++ private Entry entry(IdentityCertificate association, boolean identityVerified, String region) {+ Certificate certificate = identityVerified+ ? usableCertificate(association.certificateArn(), association.fromAddress(), region)+ : null;+ if (certificate == null) {+ return new Entry(association.fromAddress(), STATUS_FAILED, association.certificateArn(), null);+ }+ return new Entry(association.fromAddress(), STATUS_ACTIVE, association.certificateArn(),+ certificate.getNotAfter());+ }++ private Certificate usableCertificate(String certificateArn, String fromAddress, String region) {+ Certificate certificate;+ try {+ certificate = acmService.getCertificate(certificateArn, region);+ } catch (AwsException e) {+ if (!"ResourceNotFoundException".equals(e.getErrorCode())) {+ throw e;+ }+ LOG.debugv("Certificate {0} is not in ACM, so its association is FAILED", certificateArn);+ return null;+ }+ // ACM looks the certificate up by its id alone, so an ARN naming another region or account+ // could still find one here.+ if (!certificateArn.equals(certificate.getArn()) || certificate.getStatus() != CertificateStatus.ISSUED) {+ return null;+ }+ Instant now = Instant.now(clock);+ Instant notBefore = certificate.getNotBefore();+ Instant notAfter = certificate.getNotAfter();+ if ((notBefore != null && notBefore.isAfter(now)) || (notAfter != null && !notAfter.isAfter(now))) {+ return null;+ }+ X509Certificate x509 = parse(certificate);+ if (x509 == null || !isSigningKey(x509.getPublicKey()) || !isEmailSigningCertificate(x509)+ || !emailSubjectAlternativeNames(x509).contains(fromAddress)) {+ return null;+ }+ return certificate;+ }++ private static X509Certificate parse(Certificate certificate) {+ if (certificate.getCertificateBody() == null) {+ return null;+ }+ try {+ return Pem.parseCertificate(certificate.getCertificateBody());+ } catch (CertificateMaterialException e) {+ LOG.debugv(e, "Certificate {0} could not be parsed, so its association is FAILED", certificate.getArn());+ return null;+ }+ }++ /**+ * Read from the key itself: ACM's stored KeyAlgorithm folds every RSA size and EC curve it does+ * not name into RSA_2048 or EC_prime256v1.+ */+ private static boolean isSigningKey(PublicKey key) {+ if (key instanceof RSAPublicKey rsa) {+ return RSA_SIGNING_KEY_SIZES.contains(rsa.getModulus().bitLength());+ }+ if (key instanceof ECPublicKey ec) {+ ECParameterSpec params = ec.getParams();+ for (String curve : EC_SIGNING_CURVES) {+ ECParameterSpec named = namedCurve(curve);+ if (named != null && named.getCurve().equals(params.getCurve())+ && named.getGenerator().equals(params.getGenerator())+ && named.getOrder().equals(params.getOrder())) {+ return true;+ }+ }+ }+ return false;+ }++ /**+ * What SES requires beyond the Developer Guide's list (probed 2026-10-06): an end-entity+ * certificate (a CA certificate fails even with both usages) whose key usage includes+ * digitalSignature and whose extended key usage includes emailProtection. Other usages may sit+ * alongside them.+ */+ private static boolean isEmailSigningCertificate(X509Certificate x509) {+ if (x509.getBasicConstraints() != -1) {+ return false;+ }+ boolean[] keyUsage = x509.getKeyUsage();+ if (keyUsage == null || !keyUsage[DIGITAL_SIGNATURE]) {+ return false;+ }+ try {+ List<String> extendedKeyUsage = x509.getExtendedKeyUsage();+ return extendedKeyUsage != null && extendedKeyUsage.contains(EMAIL_PROTECTION);+ } catch (CertificateParsingException e) {+ LOG.debugv(e, "The extended key usage of {0} could not be read",+ x509.getSubjectX500Principal().getName());+ return false;+ }+ }++ private static ECParameterSpec namedCurve(String name) {+ try {+ AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");+ parameters.init(new ECGenParameterSpec(name));+ return parameters.getParameterSpec(ECParameterSpec.class);+ } catch (GeneralSecurityException e) {+ LOG.warnv(e, "EC curve {0} is unavailable, so no key on it counts as a signing key", name);+ return null;+ }+ }++ private static List<String> emailSubjectAlternativeNames(X509Certificate x509) {+ try {+ Collection<List<?>> names = x509.getSubjectAlternativeNames();+ if (names == null) {+ return List.of();+ }+ return names.stream()+ .filter(name -> Integer.valueOf(RFC822_NAME).equals(name.get(0)))+ .map(name -> (String) name.get(1))+ .toList();+ } catch (CertificateParsingException e) {+ LOG.debugv(e, "The SAN of {0} could not be read, so it names no sender",+ x509.getSubjectX500Principal().getName());+ return List.of();+ }+ }++ private void requireIdentity(String emailIdentity, String region) {+ if (identityService.find(emailIdentity, region).isEmpty()) {+ throw new AwsException("NotFoundException", "Email identity <" + emailIdentity + "> does not exist.", 404);+ }+ }++ /**+ * The sender an association is keyed by. A domain identity needs an address in the domain or one+ * of its subdomains; an email identity defaults to itself. These checks come before the identity+ * is looked up, so whether the identity is a domain is read from its shape.+ */+ private static String resolveFromAddress(String emailIdentity, String fromAddress) {+ boolean domain = !emailIdentity.contains("@");+ if (fromAddress == null) {+ if (domain) {+ throw badRequest("FromAddress is required when EmailIdentity is a domain.");+ }+ return emailIdentity;+ }+ int at = fromAddress.lastIndexOf('@');+ if (at <= 0 || at == fromAddress.length() - 1 || fromAddress.indexOf('@') != at+ || fromAddress.chars().anyMatch(Character::isWhitespace)) {+ throw badRequest("FromAddress <" + fromAddress + "> is not a valid email address.");+ }+ if (domain) {+ String addressDomain = fromAddress.substring(at + 1).toLowerCase(Locale.ROOT);+ String identityDomain = emailIdentity.toLowerCase(Locale.ROOT);+ if (!addressDomain.equals(identityDomain) && !addressDomain.endsWith("." + identityDomain)) {+ throw badRequest("FromAddress <" + fromAddress + "> does not belong to the domain identity <"+ + emailIdentity + ">.");+ }+ } else if (!fromAddress.equals(emailIdentity)) {+ // The model requires an exact match; SES's wording for a mismatch was not probed.+ throw badRequest("FromAddress <" + fromAddress + "> does not match the email identity <"+ + emailIdentity + ">.");+ }+ return fromAddress;+ }++ private static void requireIdentityMember(String emailIdentity, List<String> violations) {+ if (emailIdentity == null) {+ violations.add(violation("emailIdentity", "Member must not be null"));+ } else if (emailIdentity.isEmpty()) {+ violations.add(violation("emailIdentity", "Member must have length greater than or equal to 1"));+ }+ }++ private static String violation(String member, String constraint) {+ return "Value at '" + member + "' failed to satisfy constraint: " + constraint;+ }++ private static void throwViolations(List<String> violations) {+ if (violations.isEmpty()) {+ return;+ }+ String count = violations.size() == 1 ? "1 validation error detected: "+ : violations.size() + " validation errors detected: ";+ throw badRequest(count + String.join("; ", violations));+ }++ private static AwsException badRequest(String message) {+ return new AwsException("BadRequestException", message, 400);+ }++ private static String identityPrefix(String region, String emailIdentity) {+ return "certificate::" + region + "::" + emailIdentity.length() + "::" + emailIdentity + "::";+ }++ private static String key(String region, String emailIdentity, String fromAddress) {+ return identityPrefix(region, emailIdentity) + fromAddress.toLowerCase(Locale.ROOT);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.javaindex 57f8c0425b..c9f1f27d31 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java@@ -47,7 +47,9 @@ import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAb* Reads and the single-domain attribute writes call* {@link SesIdentityService} directly; create, delete, the policy operations and the default* configuration set go through the {@link SesService} facade, which checks the configuration set- * exists, guards the delete against tenant associations and cascades the identity's policies.+ * exists, guards the delete against tenant and certificate associations and cascades the+ * identity's policies. The S/MIME certificate associations ({@code /v2/email/identity/certificates})+ * call {@link SesIdentityCertificateService}.*/@Path("/v2/email")@Produces(MediaType.APPLICATION_JSON)@@ -62,14 +64,17 @@ public class SesIdentityController {private final SesIdentityService identityService;private final SesService sesService;+ private final SesIdentityCertificateService certificateService;private final RegionResolver regionResolver;private final ObjectMapper objectMapper;@Injectpublic SesIdentityController(SesIdentityService identityService, SesService sesService,+ SesIdentityCertificateService certificateService,RegionResolver regionResolver, ObjectMapper objectMapper) {this.identityService = identityService;this.sesService = sesService;+ this.certificateService = certificateService;this.regionResolver = regionResolver;this.objectMapper = objectMapper;}@@ -451,6 +456,60 @@ public class SesIdentityController {}}+ @POST+ @Path("/identity/certificates")+ public Response associateEmailIdentityCertificate(@Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ JsonNode request = readOptionBody(objectMapper, body);+ try {+ certificateService.associate(stringMemberOrAbsent(request, "EmailIdentity"),+ stringMemberOrAbsent(request, "FromAddress"), stringMemberOrAbsent(request, "CertificateArn"),+ region);+ } catch (AwsException e) {+ throw remapV1Exception(e);+ }+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ @POST+ @Path("/identity/certificates/delete")+ public Response disassociateEmailIdentityCertificate(@Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ JsonNode request = readOptionBody(objectMapper, body);+ try {+ certificateService.disassociate(stringMemberOrAbsent(request, "EmailIdentity"),+ stringMemberOrAbsent(request, "FromAddress"), region);+ } catch (AwsException e) {+ throw remapV1Exception(e);+ }+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ @POST+ @Path("/identity/certificates/list")+ public Response listEmailIdentityCertificates(@Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ JsonNode request = readOptionBody(objectMapper, body);+ PaginatedResult<SesIdentityCertificateService.Entry> page;+ try {+ page = certificateService.list(stringMemberOrAbsent(request, "EmailIdentity"),+ intMemberOrAbsent(request, "PageSize"), stringMemberOrAbsent(request, "NextToken"), region);+ } catch (AwsException e) {+ throw remapV1Exception(e);+ }+ ObjectNode result = objectMapper.createObjectNode();+ ArrayNode certificates = result.putArray("Certificates");+ for (SesIdentityCertificateService.Entry entry : page.items()) {+ ObjectNode item = certificates.addObject();+ item.put("FromAddress", entry.fromAddress());+ item.put("Status", entry.status());+ item.put("CertificateArn", entry.certificateArn());+ putTimestamp(item, "CertificateExpiryTime", entry.expiryTime());+ }+ result.put("NextToken", page.nextToken());+ return Response.ok(result).build();+ }+private ObjectNode buildFullIdentityResponse(Identity identity, String region) {ObjectNode result = objectMapper.createObjectNode();result.put("IdentityType", toV2IdentityType(identity.getIdentityType()));diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.javaindex d958145b44..9d411f80e0 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java@@ -183,7 +183,7 @@ public class SesIdentityService {&& isIdentityVerified(fromEmail.substring(at + 1), region);}- private boolean isIdentityVerified(String identity, String region) {+ boolean isIdentityVerified(String identity, String region) {Identity id = getIdentityVerificationAttributes(identity, region);return id != null && "Success".equals(id.getVerificationStatus());}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.javaindex 0b250aea72..67ee85d083 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java@@ -107,6 +107,17 @@ public enum SesListPaging {token -> badRequest("Provided NextToken is invalid"),true),+ /**+ * ListEmailIdentityCertificates (probed 2026-10-04) answers Smithy's page-size messages; its+ * default could not be measured and is taken to be the bound.+ */+ V2_LIST_EMAIL_IDENTITY_CERTIFICATES(Namespace.IDENTITY_CERTIFICATE, 1000, 1000,+ size -> badRequest("1 validation error detected: Value '" + size + "' at 'pageSize' failed to "+ + "satisfy constraint: Member must have value "+ + (size < 1 ? "greater than or equal to 1" : "less than or equal to 1000")),+ token -> badRequest("Invalid NextToken."),+ false),+/** 12 pools came back whole without a PageSize, so the default is taken to be the bound. */V2_LIST_DEDICATED_IP_POOLS(Namespace.DEDICATED_IP_POOL, 1000, 1000,size -> badRequest("The page size must be in [1, 1000] range."),@@ -145,6 +156,7 @@ public enum SesListPaging {static final String IMPORT_JOB = "import-job";static final String CONTACT_LIST = "contact-list";static final String CONTACT = "contact";+ static final String IDENTITY_CERTIFICATE = "identity-certificate";static final String DEDICATED_IP_POOL = "dedicated-ip-pool";static final String DEDICATED_IP = "dedicated-ip";static final String SUPPRESSED_DESTINATION = "suppressed-destination";diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.javaindex 190ed1401c..c1ecf1da03 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java@@ -120,6 +120,9 @@ public class SesService {// the tenant record; the facade keeps the associations, the delete cascade, the send-time tenant// gate and the tenant-scoped suppression routing.private final SesTenantService tenantService;+ // S/MIME certificate associations live in SesIdentityCertificateService, which the v2 controller+ // calls directly; the facade only reaches it for the identity delete-guard.+ private final SesIdentityCertificateService certificateService;private final SmtpRelay smtpRelay;private final SesEventPublisher eventPublisher;private final String defaultAccountId;@@ -136,7 +139,7 @@ public class SesService {SesSuppressionService suppressionService, SesDedicatedIpService dedicatedIpService,SesTemplateService templateService, SesSentEmailService sentEmailService,SesTenantService tenantService, SesConfigurationSetService configSetService,- SmtpRelay smtpRelay,+ SesIdentityCertificateService certificateService, SmtpRelay smtpRelay,SesEventPublisher eventPublisher, EmulatorConfig config,RegionResolver regionResolver) {this.identityService = identityService;@@ -149,6 +152,7 @@ public class SesService {this.policyService = policyService;this.cvetService = cvetService;this.tenantService = tenantService;+ this.certificateService = certificateService;this.smtpRelay = smtpRelay;this.eventPublisher = eventPublisher;this.defaultAccountId = config.defaultAccountId();@@ -166,6 +170,7 @@ public class SesService {SesPolicyService policyService,SesCvetService cvetService,SesTenantService tenantService,+ SesIdentityCertificateService certificateService,SmtpRelay smtpRelay) {this.identityService = identityService;this.sentEmailService = sentEmailService;@@ -177,6 +182,7 @@ public class SesService {this.policyService = policyService;this.cvetService = cvetService;this.tenantService = tenantService;+ this.certificateService = certificateService;this.smtpRelay = smtpRelay;this.eventPublisher = null;this.defaultAccountId = "000000000000";@@ -201,8 +207,10 @@ public class SesService {if (identityValue == null || identityValue.isBlank()) {return;}+ String accountId = regionResolver != null ? regionResolver.getAccountId() : defaultAccountId;tenantService.deleteBackingResource(SesTenantService.RESOURCE_TYPE_IDENTITY, identityValue,- region, () -> doDeleteIdentity(identityValue, region));+ region, () -> certificateService.deleteIdentityGuarded(identityValue, accountId, region,+ () -> doDeleteIdentity(identityValue, region)));}private void doDeleteIdentity(String identityValue, String region) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/IdentityCertificate.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/IdentityCertificate.javanew file mode 100644index 0000000000..3fbe418a4d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/IdentityCertificate.java@@ -0,0 +1,16 @@+package io.github.hectorvent.floci.services.ses.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;++/**+ * An S/MIME certificate association created by {@code AssociateEmailIdentityCertificate}.+ * {@code fromAddress} keeps the spelling the caller gave; SES matches it without regard to case.+ */+@RegisterForReflection+public record IdentityCertificate(String emailIdentity,+ String fromAddress,+ String certificateArn,+ Instant associatedTimestamp) {+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateServiceTest.javanew file mode 100644index 0000000000..c75d6ef217--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateServiceTest.java@@ -0,0 +1,396 @@+package io.github.hectorvent.floci.services.ses;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.core.storage.PersistentStorage;+import io.github.hectorvent.floci.services.acm.AcmService;+import io.github.hectorvent.floci.services.acm.model.Certificate;+import io.github.hectorvent.floci.services.acm.model.CertificateStatus;+import io.github.hectorvent.floci.services.ses.model.Identity;+import io.github.hectorvent.floci.services.ses.model.IdentityCertificate;+import io.github.hectorvent.floci.testing.MutableClock;+import org.bouncycastle.asn1.x509.KeyPurposeId;+import org.bouncycastle.asn1.x509.KeyUsage;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Path;+import java.time.Clock;+import java.time.Duration;+import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.atomic.AtomicBoolean;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++class SesIdentityCertificateServiceTest {++ private static final String REGION = "us-east-1";+ private static final String ACCOUNT = "000000000000";+ private static final String DOMAIN = "example.com";+ private static final String CERT_ARN =+ "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555";+ private static final String OTHER_CERT_ARN =+ "arn:aws:acm:us-east-1:000000000000:certificate/99999999-2222-3333-4444-555555555555";++ // A SAN of [email protected], matching the sender most tests associate.+ private static final SmimeTestCertificates.Pem ALICE_CERTIFICATE =+ SmimeTestCertificates.rsa("[email protected]", 2048);++ private final MutableClock clock = new MutableClock();+ private SesIdentityService identityService;+ private AcmService acmService;+ private SesIdentityCertificateService service;++ @BeforeEach+ void setUp() {+ identityService = new SesIdentityService(new InMemoryStorage<>(), null, Clock.systemUTC());+ markVerified(identityService.verifyDomainIdentity(DOMAIN, REGION));+ identityService.verifyEmailIdentity("[email protected]", REGION);+ acmService = mock(AcmService.class);+ when(acmService.getCertificate(anyString(), anyString())).thenAnswer(invocation -> {+ throw new AwsException("ResourceNotFoundException", "missing", 404);+ });+ service = new SesIdentityCertificateService(new InMemoryStorage<>(), identityService, acmService, clock);+ }++ @Test+ void associate_domainNeedsFromAddress() {+ assertBadRequest("FromAddress is required when EmailIdentity is a domain.",+ () -> service.associate(DOMAIN, null, CERT_ARN, REGION));+ }++ @Test+ void associate_fromAddressMustBeAnAddressInTheDomain() {+ assertBadRequest("FromAddress <not-an-address> is not a valid email address.",+ () -> service.associate(DOMAIN, "not-an-address", CERT_ARN, REGION));+ assertBadRequest("FromAddress <[email protected]> does not belong to the domain identity <example.com>.",+ () -> service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION));+ assertBadRequest("FromAddress <[email protected]> does not belong to the domain identity <example.com>.",+ () -> service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION));+ }++ @Test+ void associate_acceptsSubdomainAddress() {+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);++ assertEquals(List.of("[email protected]"), fromAddresses(service.list(DOMAIN, null, null, REGION)));+ }++ @Test+ void associate_emailIdentityDefaultsFromAddressToItself() {+ service.associate("[email protected]", null, CERT_ARN, REGION);++ assertEquals(List.of("[email protected]"),+ fromAddresses(service.list("[email protected]", null, null, REGION)));+ assertBadRequest("FromAddress <[email protected]> does not match the email identity <[email protected]>.",+ () -> service.associate("[email protected]", "[email protected]", CERT_ARN, REGION));+ }++ @Test+ void emailIdentityFromAddressMustMatchExactly() {+ assertBadRequest("FromAddress <[email protected]> does not match the email identity <[email protected]>.",+ () -> service.associate("[email protected]", "[email protected]", CERT_ARN, REGION));+ assertBadRequest("FromAddress <[email protected]> does not match the email identity <[email protected]>.",+ () -> service.disassociate("[email protected]", "[email protected]", REGION));+ }++ @Test+ void associate_malformedArnReportsBothConstraints() {+ assertBadRequest("2 validation errors detected: Value at 'certificateArn' failed to satisfy constraint: "+ + "Member must have length greater than or equal to 20; Value at 'certificateArn' failed to "+ + "satisfy constraint: Member must satisfy regular expression pattern: "+ + "arn:[\\w+=/,.@-]+:[\\w+=/,.@-]+:[\\w+=/,.@-]*:[0-9]+:certificate/[\\w+=,.@-]+",+ () -> service.associate(DOMAIN, "[email protected]", "not-an-arn", REGION));+ }++ @Test+ void associate_missingIdentityIsNotFound() {+ AwsException e = assertThrows(AwsException.class,+ () -> service.associate("missing.example.com", "[email protected]", CERT_ARN, REGION));+ assertEquals("NotFoundException", e.getErrorCode());+ assertEquals(404, e.getHttpStatus());+ assertEquals("Email identity <missing.example.com> does not exist.", e.getMessage());+ }++ @Test+ void associate_duplicateAddressIgnoresCaseAndKeepsFirstSpelling() {+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);++ AwsException e = assertThrows(AwsException.class,+ () -> service.associate(DOMAIN, "[email protected]", OTHER_CERT_ARN, REGION));+ assertEquals("AlreadyExistsException", e.getErrorCode());+ assertEquals("A certificate is already associated with sender <[email protected]> on identity <example.com>.",+ e.getMessage());+ assertEquals(List.of("[email protected]"), fromAddresses(service.list(DOMAIN, null, null, REGION)));+ }++ @Test+ void list_statusFollowsTheAcmCertificate() {+ Instant notAfter = clock.instant().plus(Duration.ofDays(365));+ Certificate issued = certificate(CERT_ARN, CertificateStatus.ISSUED, notAfter);+ when(acmService.getCertificate(eq(CERT_ARN), eq(REGION))).thenReturn(issued);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ service.associate(DOMAIN, "[email protected]", OTHER_CERT_ARN, REGION);++ List<SesIdentityCertificateService.Entry> entries = service.list(DOMAIN, null, null, REGION).items();++ assertEquals(new SesIdentityCertificateService.Entry("[email protected]", "ACTIVE", CERT_ARN, notAfter),+ entries.get(0));+ assertEquals(new SesIdentityCertificateService.Entry("[email protected]", "FAILED", OTHER_CERT_ARN, null),+ entries.get(1));+ }++ @Test+ void list_expiredOrUnissuedCertificateIsFailed() {+ Certificate certificate = certificate(CERT_ARN, CertificateStatus.ISSUED, clock.instant().plusSeconds(60));+ when(acmService.getCertificate(eq(CERT_ARN), eq(REGION))).thenReturn(certificate);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ assertEquals("ACTIVE", service.list(DOMAIN, null, null, REGION).items().getFirst().status());++ clock.advance(Duration.ofSeconds(60));+ assertEquals("FAILED", service.list(DOMAIN, null, null, REGION).items().getFirst().status());++ certificate.setNotAfter(clock.instant().plusSeconds(60));+ certificate.setStatus(CertificateStatus.PENDING_VALIDATION);+ assertEquals("FAILED", service.list(DOMAIN, null, null, REGION).items().getFirst().status());+ }++ @Test+ void list_certificateNeedsAnAllowedKey() {+ Certificate certificate = certificate(CERT_ARN, CertificateStatus.ISSUED, clock.instant().plusSeconds(3600));+ when(acmService.getCertificate(eq(CERT_ARN), eq(REGION))).thenReturn(certificate);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);++ // ACM records RSA-1536 as RSA_2048 and Ed25519 as RSA_2048, so the key itself has to be read.+ for (SmimeTestCertificates.Pem refused : List.of(SmimeTestCertificates.rsa("[email protected]", 1024),+ SmimeTestCertificates.rsa("[email protected]", 1536),+ SmimeTestCertificates.ed25519("[email protected]"))) {+ certificate.setCertificateBody(refused.certificate());+ assertEquals("FAILED", service.list(DOMAIN, null, null, REGION).items().getFirst().status());+ }+ for (SmimeTestCertificates.Pem allowed : List.of(SmimeTestCertificates.rsa("[email protected]", 3072),+ SmimeTestCertificates.ec("[email protected]", "secp256r1"),+ SmimeTestCertificates.ec("[email protected]", "secp521r1"))) {+ certificate.setCertificateBody(allowed.certificate());+ assertEquals("ACTIVE", service.list(DOMAIN, null, null, REGION).items().getFirst().status());+ }+ }++ @Test+ void list_certificateMustBeAnEmailSigningEndEntity() {+ Certificate certificate = certificate(CERT_ARN, CertificateStatus.ISSUED, clock.instant().plusSeconds(3600));+ when(acmService.getCertificate(eq(CERT_ARN), eq(REGION))).thenReturn(certificate);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ int signing = KeyUsage.digitalSignature;+ KeyPurposeId email = KeyPurposeId.id_kp_emailProtection;+ // The eight shapes probed against SES on 2026-10-06, with the status it reported for each.+ Map<SmimeTestCertificates.Extensions, String> probed = new LinkedHashMap<>();+ probed.put(new SmimeTestCertificates.Extensions(true, 0), "FAILED");+ probed.put(new SmimeTestCertificates.Extensions(false, signing, email), "ACTIVE");+ probed.put(new SmimeTestCertificates.Extensions(false, 0), "FAILED");+ probed.put(new SmimeTestCertificates.Extensions(false, 0, email), "FAILED");+ probed.put(new SmimeTestCertificates.Extensions(false, signing), "FAILED");+ probed.put(new SmimeTestCertificates.Extensions(true, signing, email), "FAILED");+ probed.put(new SmimeTestCertificates.Extensions(null, signing, email), "ACTIVE");+ probed.put(new SmimeTestCertificates.Extensions(false, signing | KeyUsage.keyEncipherment, email,+ KeyPurposeId.id_kp_clientAuth), "ACTIVE");++ probed.forEach((extensions, expected) -> {+ certificate.setCertificateBody(+ SmimeTestCertificates.rsa("[email protected]", 2048, extensions).certificate());+ assertEquals(expected, service.list(DOMAIN, null, null, REGION).items().getFirst().status(),+ extensions.toString());+ });+ }++ @Test+ void list_certificateNotYetValidIsFailed() {+ Certificate certificate = certificate(CERT_ARN, CertificateStatus.ISSUED, clock.instant().plusSeconds(3600));+ certificate.setNotBefore(clock.instant().plusSeconds(60));+ when(acmService.getCertificate(eq(CERT_ARN), eq(REGION))).thenReturn(certificate);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);++ assertEquals("FAILED", service.list(DOMAIN, null, null, REGION).items().getFirst().status());++ clock.advance(Duration.ofSeconds(60));+ assertEquals("ACTIVE", service.list(DOMAIN, null, null, REGION).items().getFirst().status());+ }++ @Test+ void list_certificateSanMustNameTheFromAddressExactly() {+ when(acmService.getCertificate(eq(CERT_ARN), eq(REGION)))+ .thenReturn(certificate(CERT_ARN, CertificateStatus.ISSUED, clock.instant().plusSeconds(3600)));+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);++ assertEquals(List.of("FAILED", "FAILED"), statuses(service.list(DOMAIN, null, null, REGION)));+ }++ @Test+ void list_unverifiedIdentityIsFailed() {+ Identity pending = identityService.verifyDomainIdentity("pending.example.com", REGION);+ Certificate certificate = certificate(CERT_ARN, CertificateStatus.ISSUED, clock.instant().plusSeconds(3600));+ certificate.setCertificateBody(SmimeTestCertificates.rsa("[email protected]", 2048).certificate());+ when(acmService.getCertificate(eq(CERT_ARN), eq(REGION))).thenReturn(certificate);+ service.associate("pending.example.com", "[email protected]", CERT_ARN, REGION);++ assertEquals(List.of("FAILED"), statuses(service.list("pending.example.com", null, null, REGION)));++ markVerified(pending);+ assertEquals(List.of("ACTIVE"), statuses(service.list("pending.example.com", null, null, REGION)));+ }++ @Test+ void list_certificateFoundUnderAnotherArnIsFailed() {+ String otherRegionArn = CERT_ARN.replace("us-east-1", "us-west-2");+ when(acmService.getCertificate(eq(otherRegionArn), eq(REGION)))+ .thenReturn(certificate(CERT_ARN, CertificateStatus.ISSUED, clock.instant().plusSeconds(3600)));+ service.associate(DOMAIN, "[email protected]", otherRegionArn, REGION);++ assertEquals("FAILED", service.list(DOMAIN, null, null, REGION).items().getFirst().status());+ }++ @Test+ void list_sortsByAddressAndPages() {+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);++ PaginatedResult<SesIdentityCertificateService.Entry> first = service.list(DOMAIN, 2, null, REGION);+ PaginatedResult<SesIdentityCertificateService.Entry> second =+ service.list(DOMAIN, 2, first.nextToken(), REGION);++ assertEquals(List.of("[email protected]", "[email protected]"), fromAddresses(first));+ assertEquals(List.of("[email protected]"), fromAddresses(second));+ assertNull(second.nextToken());+ }++ @Test+ void list_validatesPageSizeAndToken() {+ assertBadRequest("1 validation error detected: Value '0' at 'pageSize' failed to satisfy constraint: "+ + "Member must have value greater than or equal to 1", () -> service.list(DOMAIN, 0, null, REGION));+ assertBadRequest("1 validation error detected: Value '1001' at 'pageSize' failed to satisfy constraint: "+ + "Member must have value less than or equal to 1000", () -> service.list(DOMAIN, 1001, null, REGION));+ assertBadRequest("Invalid NextToken.", () -> service.list(DOMAIN, null, "bogus", REGION));+ }++ @Test+ void list_tokenIsBoundToTheIdentity() {+ identityService.verifyDomainIdentity("example.net", REGION);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ String token = service.list(DOMAIN, 1, null, REGION).nextToken();++ assertBadRequest("Invalid NextToken.", () -> service.list("example.net", 1, token, REGION));+ }++ @Test+ void disassociate_isIdempotentAndMatchesAddressWithoutCase() {+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);++ service.disassociate(DOMAIN, "[email protected]", REGION);+ service.disassociate(DOMAIN, "[email protected]", REGION);++ assertTrue(service.list(DOMAIN, null, null, REGION).items().isEmpty());+ }++ @Test+ void disassociate_checksTheAddressBeforeTheIdentity() {+ assertBadRequest("FromAddress <[email protected]> does not belong to the domain identity <missing.example.com>.",+ () -> service.disassociate("missing.example.com", "[email protected]", REGION));+ AwsException e = assertThrows(AwsException.class,+ () -> service.disassociate("missing.example.com", "[email protected]", REGION));+ assertEquals("NotFoundException", e.getErrorCode());+ assertBadRequest("FromAddress is required when EmailIdentity is a domain.",+ () -> service.disassociate(DOMAIN, null, REGION));+ }++ @Test+ void deleteIdentityGuarded_refusesWhileACertificateIsAssociated() {+ service.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);+ AtomicBoolean deleted = new AtomicBoolean();++ assertBadRequest("Cannot delete <arn:aws:ses:us-east-1:000000000000:identity/example.com> because it has "+ + "certificates associated with it. Disassociate all certificates and try again.",+ () -> service.deleteIdentityGuarded(DOMAIN, ACCOUNT, REGION, () -> deleted.set(true)));+ assertFalse(deleted.get());++ service.disassociate(DOMAIN, "[email protected]", REGION);+ service.deleteIdentityGuarded(DOMAIN, ACCOUNT, REGION, () -> deleted.set(true));+ assertTrue(deleted.get());+ }++ @Test+ void deleteIdentityGuarded_ignoresAnotherIdentitysAssociations() {+ identityService.verifyDomainIdentity("sub.example.com", REGION);+ service.associate("sub.example.com", "[email protected]", CERT_ARN, REGION);+ AtomicBoolean deleted = new AtomicBoolean();++ service.deleteIdentityGuarded(DOMAIN, ACCOUNT, REGION, () -> deleted.set(true));++ assertTrue(deleted.get());+ }++ @Test+ void associationsSurviveAPersistentStorageReload(@TempDir Path dir) {+ SesIdentityCertificateService first = persistentService(dir);+ first.associate(DOMAIN, "[email protected]", CERT_ARN, REGION);++ SesIdentityCertificateService reloaded = persistentService(dir);++ assertEquals(List.of(new SesIdentityCertificateService.Entry("[email protected]", "FAILED", CERT_ARN, null)),+ reloaded.list(DOMAIN, null, null, REGION).items());+ assertThrows(AwsException.class, () -> reloaded.associate(DOMAIN, "[email protected]", CERT_ARN, REGION));+ }++ private SesIdentityCertificateService persistentService(Path dir) {+ PersistentStorage<String, IdentityCertificate> store = new PersistentStorage<>(+ dir.resolve("ses-identity-certificates.json"),+ new TypeReference<Map<String, IdentityCertificate>>() {});+ store.load();+ return new SesIdentityCertificateService(store, identityService, acmService, clock);+ }++ private void markVerified(Identity identity) {+ identity.setVerificationStatus("Success");+ identityService.save(identity, REGION);+ }++ private static Certificate certificate(String arn, CertificateStatus status, Instant notAfter) {+ Certificate certificate = new Certificate();+ certificate.setArn(arn);+ certificate.setStatus(status);+ certificate.setNotAfter(notAfter);+ certificate.setCertificateBody(ALICE_CERTIFICATE.certificate());+ return certificate;+ }++ private static List<String> statuses(PaginatedResult<SesIdentityCertificateService.Entry> page) {+ return page.items().stream().map(SesIdentityCertificateService.Entry::status).toList();+ }++ private static List<String> fromAddresses(PaginatedResult<SesIdentityCertificateService.Entry> page) {+ return page.items().stream().map(SesIdentityCertificateService.Entry::fromAddress).toList();+ }++ private static void assertBadRequest(String message, Runnable call) {+ AwsException e = assertThrows(AwsException.class, call::run);+ assertEquals("BadRequestException", e.getErrorCode());+ assertEquals(400, e.getHttpStatus());+ assertEquals(message, e.getMessage());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateV2IntegrationTest.javanew file mode 100644index 0000000000..52c2566f15--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateV2IntegrationTest.java@@ -0,0 +1,212 @@+package io.github.hectorvent.floci.services.ses;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.Response;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.List;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasKey;+import static org.hamcrest.Matchers.not;+import static org.hamcrest.Matchers.nullValue;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++@QuarkusTest+class SesIdentityCertificateV2IntegrationTest {++ private static final String SES_AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";+ private static final String ACM_AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/acm/aws4_request";+ private static final String MISSING_CERT_ARN =+ "arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-0000-000000000000";++ @BeforeAll+ static void configure() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void matchingCertificateOnAVerifiedIdentityIsActive() {+ String identity = "[email protected]";+ createIdentity(identity);+ String certificateArn = importCertificate(identity);+ associate(identity, null, certificateArn).then().statusCode(200).body(equalTo("{}"));++ Response list = list("{\"EmailIdentity\":\"" + identity + "\"}");+ list.then().statusCode(200)+ .body("Certificates.FromAddress", equalTo(List.of(identity)))+ .body("Certificates[0].Status", equalTo("ACTIVE"))+ .body("Certificates[0].CertificateArn", equalTo(certificateArn))+ .body("NextToken", nullValue());+ double expiry = list.jsonPath().getDouble("Certificates[0].CertificateExpiryTime");+ assertTrue(expiry > 0, "CertificateExpiryTime is epoch seconds");+ }++ @Test+ void rsa1024CertificateImportedThroughAcmIsFailed() {+ String identity = "[email protected]";+ createIdentity(identity);+ String certificateArn = importCertificate(SmimeTestCertificates.rsa(identity, 1024));+ associate(identity, null, certificateArn).then().statusCode(200);++ list("{\"EmailIdentity\":\"" + identity + "\"}").then().statusCode(200)+ .body("Certificates.Status", equalTo(List.of("FAILED")))+ .body("Certificates[0]", not(hasKey("CertificateExpiryTime")));+ }++ @Test+ void unverifiedDomainListsEveryAssociationAsFailedAndPages() {+ String domain = "smime-list.floci.test";+ createIdentity(domain);+ String certificateArn = importCertificate("alice@" + domain);++ associate(domain, "bob@" + domain, MISSING_CERT_ARN).then().statusCode(200);+ associate(domain, "alice@" + domain, certificateArn).then().statusCode(200);++ list("{\"EmailIdentity\":\"" + domain + "\"}").then().statusCode(200)+ .body("Certificates.FromAddress", equalTo(List.of("alice@" + domain, "bob@" + domain)))+ .body("Certificates.Status", equalTo(List.of("FAILED", "FAILED")))+ .body("Certificates[0]", not(hasKey("CertificateExpiryTime")))+ .body("NextToken", nullValue());++ Response firstPage = list("{\"EmailIdentity\":\"" + domain + "\",\"PageSize\":1}");+ String token = firstPage.jsonPath().getString("NextToken");+ assertEquals(List.of("alice@" + domain), firstPage.jsonPath().getList("Certificates.FromAddress"));+ list("{\"EmailIdentity\":\"" + domain + "\",\"PageSize\":1,\"NextToken\":\"" + token + "\"}")+ .then().statusCode(200)+ .body("Certificates.FromAddress", equalTo(List.of("bob@" + domain)));+ }++ @Test+ void requestErrorsFollowSes() {+ String domain = "smime-errors.floci.test";+ createIdentity(domain);++ associate(domain, null, MISSING_CERT_ARN).then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("FromAddress is required when EmailIdentity is a domain."));+ associate("nosuch.floci.test", "[email protected]", MISSING_CERT_ARN).then().statusCode(404)+ .body("__type", equalTo("NotFoundException"))+ .body("message", equalTo("Email identity <nosuch.floci.test> does not exist."));+ associate(domain, "alice@" + domain, MISSING_CERT_ARN).then().statusCode(200);+ associate(domain, "ALICE@" + domain, MISSING_CERT_ARN).then().statusCode(400)+ .body("__type", equalTo("AlreadyExistsException"))+ .body("message", equalTo("A certificate is already associated with sender <alice@" + domain+ + "> on identity <" + domain + ">."));+ list("{\"EmailIdentity\":\"" + domain + "\",\"PageSize\":0}").then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value '0' at 'pageSize' failed to "+ + "satisfy constraint: Member must have value greater than or equal to 1"));+ list("{\"EmailIdentity\":\"" + domain + "\",\"NextToken\":\"bogus\"}").then().statusCode(400)+ .body("message", equalTo("Invalid NextToken."));+ list("{\"EmailIdentity\":\" padded.floci.test\"}").then().statusCode(400)+ .body("__type", equalTo("BadRequestException"));+ list("{\"EmailIdentity\":123}").then().statusCode(400)+ .body("__type", equalTo("SerializationException"));+ }++ @Test+ void disassociateIsIdempotent() {+ String domain = "smime-disassociate.floci.test";+ createIdentity(domain);+ associate(domain, "alice@" + domain, MISSING_CERT_ARN).then().statusCode(200);++ disassociate("{\"EmailIdentity\":\"" + domain + "\",\"FromAddress\":\"alice@" + domain + "\"}")+ .then().statusCode(200).body(equalTo("{}"));+ disassociate("{\"EmailIdentity\":\"" + domain + "\",\"FromAddress\":\"alice@" + domain + "\"}")+ .then().statusCode(200);++ list("{\"EmailIdentity\":\"" + domain + "\"}").then().statusCode(200)+ .body("Certificates", equalTo(List.of()));+ }++ @Test+ void deleteEmailIdentityIsRefusedWhileACertificateIsAssociated() {+ String identity = "[email protected]";+ createIdentity(identity);+ given().contentType("application/json").header("Authorization", SES_AUTH)+ .body("{\"EmailIdentity\":\"" + identity + "\",\"CertificateArn\":\"" + MISSING_CERT_ARN + "\"}")+ .when().post("/v2/email/identity/certificates").then().statusCode(200);++ given().header("Authorization", SES_AUTH)+ .when().delete("/v2/email/identities/" + identity).then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("Cannot delete <arn:aws:ses:us-east-1:000000000000:identity/" + identity+ + "> because it has certificates associated with it. "+ + "Disassociate all certificates and try again."));++ disassociate("{\"EmailIdentity\":\"" + identity + "\"}").then().statusCode(200);+ given().header("Authorization", SES_AUTH)+ .when().delete("/v2/email/identities/" + identity).then().statusCode(200);+ }++ @Test+ void v1DeletesShareTheGuard() {+ String identity = "[email protected]";+ createIdentity(identity);+ associate(identity, null, MISSING_CERT_ARN).then().statusCode(200);++ v1Delete("DeleteIdentity", "Identity", identity).then().statusCode(400)+ .body(containsString("<Code>BadRequestException</Code>"))+ .body(containsString("because it has certificates associated with it."));+ v1Delete("DeleteVerifiedEmailAddress", "EmailAddress", identity).then().statusCode(400)+ .body(containsString("<Code>BadRequestException</Code>"))+ .body(containsString("because it has certificates associated with it."));++ disassociate("{\"EmailIdentity\":\"" + identity + "\"}").then().statusCode(200);+ v1Delete("DeleteVerifiedEmailAddress", "EmailAddress", identity).then().statusCode(200);+ }++ private static Response v1Delete(String action, String member, String identity) {+ return given().contentType("application/x-www-form-urlencoded")+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")+ .formParam("Action", action)+ .formParam(member, identity)+ .when().post("/");+ }++ private static void createIdentity(String identity) {+ given().contentType("application/json").header("Authorization", SES_AUTH)+ .body("{\"EmailIdentity\":\"" + identity + "\"}")+ .when().post("/v2/email/identities").then().statusCode(200);+ }++ private static Response associate(String identity, String fromAddress, String certificateArn) {+ String from = fromAddress == null ? "" : ",\"FromAddress\":\"" + fromAddress + "\"";+ return given().contentType("application/json").header("Authorization", SES_AUTH)+ .body("{\"EmailIdentity\":\"" + identity + "\"" + from+ + ",\"CertificateArn\":\"" + certificateArn + "\"}")+ .when().post("/v2/email/identity/certificates");+ }++ private static Response disassociate(String body) {+ return given().contentType("application/json").header("Authorization", SES_AUTH)+ .body(body).when().post("/v2/email/identity/certificates/delete");+ }++ private static Response list(String body) {+ return given().contentType("application/json").header("Authorization", SES_AUTH)+ .body(body).when().post("/v2/email/identity/certificates/list");+ }++ private static String importCertificate(String email) {+ return importCertificate(SmimeTestCertificates.rsa(email, 2048));+ }++ private static String importCertificate(SmimeTestCertificates.Pem pem) {+ String certJson = pem.certificate().replace("\r\n", "\n").replace("\n", "\\n");+ String keyJson = pem.privateKey().replace("\r\n", "\n").replace("\n", "\\n");+ return given().header("X-Amz-Target", "CertificateManager.ImportCertificate")+ .header("Authorization", ACM_AUTH)+ .contentType("application/x-amz-json-1.1")+ .body("{\"Certificate\":\"" + certJson + "\",\"PrivateKey\":\"" + keyJson + "\"}")+ .when().post("/").then().statusCode(200)+ .extract().jsonPath().getString("CertificateArn");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.javaindex 64bf552777..b27aaaeee6 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ses;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.acm.AcmService;import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes;import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;import io.github.hectorvent.floci.services.ses.model.Contact;@@ -10,6 +11,7 @@ import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTempimport io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;import io.github.hectorvent.floci.services.ses.model.EmailTemplate;import io.github.hectorvent.floci.services.ses.model.Identity;+import io.github.hectorvent.floci.services.ses.model.IdentityCertificate;import io.github.hectorvent.floci.services.ses.model.SentEmail;import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;import io.github.hectorvent.floci.services.ses.model.Tenant;@@ -44,6 +46,7 @@ final class SesServiceTestBuilder {private final InMemoryStorage<String, Tenant> tenantStore = new InMemoryStorage<>();private final InMemoryStorage<String, TenantResourceAssociation> tenantAssociationStore =new InMemoryStorage<>();+ private final InMemoryStorage<String, IdentityCertificate> certificateStore = new InMemoryStorage<>();private SmtpRelay smtpRelay = mock(SmtpRelay.class);// Default null, matching the production null-Route53 case: SesIdentityService treats a null@@ -60,6 +63,7 @@ final class SesServiceTestBuilder {private SesIdentityService identityService;private SesCvetService cvetService;private SesSentEmailService sentEmailService;+ private SesIdentityCertificateService certificateService;static SesServiceTestBuilder create() {return new SesServiceTestBuilder();@@ -157,6 +161,13 @@ final class SesServiceTestBuilder {return identityService;}+ SesIdentityCertificateService certificateService() {+ if (certificateService == null) {+ throw new IllegalStateException("call build() first");+ }+ return certificateService;+ }+SesService build() {contactService = new SesContactService(contactListStore, contactStore, clock);suppressionService = new SesSuppressionService(suppressionStore, accountSuppressionStore,@@ -165,6 +176,8 @@ final class SesServiceTestBuilder {identityService = new SesIdentityService(identityStore, route53Service, clock);sentEmailService = new SesSentEmailService(emailStore);cvetService = new SesCvetService(cvetStore);+ certificateService = new SesIdentityCertificateService(certificateStore, identityService,+ mock(AcmService.class), clock);return new SesService(identityService,sentEmailService,@@ -176,6 +189,7 @@ final class SesServiceTestBuilder {new SesPolicyService(policyStore, objectMapper),cvetService,new SesTenantService(tenantStore, tenantAssociationStore, clock, new SecureRandom()),+ certificateService,smtpRelay);}}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SmimeTestCertificates.java b/src/test/java/io/github/hectorvent/floci/services/ses/SmimeTestCertificates.javanew file mode 100644index 0000000000..3637099661--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SmimeTestCertificates.java@@ -0,0 +1,113 @@+package io.github.hectorvent.floci.services.ses;++import org.bouncycastle.asn1.x500.X500Name;+import org.bouncycastle.asn1.x509.BasicConstraints;+import org.bouncycastle.asn1.x509.ExtendedKeyUsage;+import org.bouncycastle.asn1.x509.Extension;+import org.bouncycastle.asn1.x509.GeneralName;+import org.bouncycastle.asn1.x509.GeneralNames;+import org.bouncycastle.asn1.x509.KeyPurposeId;+import org.bouncycastle.asn1.x509.KeyUsage;+import org.bouncycastle.cert.X509CertificateHolder;+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;+import org.bouncycastle.openssl.jcajce.JcaPEMWriter;+import org.bouncycastle.operator.ContentSigner;+import org.bouncycastle.operator.OperatorCreationException;+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;++import java.io.IOException;+import java.io.StringWriter;+import java.math.BigInteger;+import java.security.GeneralSecurityException;+import java.security.KeyPair;+import java.security.KeyPairGenerator;+import java.security.spec.ECGenParameterSpec;+import java.time.Duration;+import java.time.Instant;+import java.util.Date;++/** Self-signed certificates whose SAN carries an email address, which ACM's own generator cannot mint. */+final class SmimeTestCertificates {++ record Pem(String certificate, String privateKey) {}++ /** The extensions SES checks besides the SAN; {@link #EMAIL_SIGNING} is the shape it accepts. */+ record Extensions(Boolean ca, int keyUsage, KeyPurposeId... extendedKeyUsage) {}++ static final Extensions EMAIL_SIGNING =+ new Extensions(false, KeyUsage.digitalSignature, KeyPurposeId.id_kp_emailProtection);++ // Well before the MutableClock the Quarkus tests run on, so a certificate is already valid there.+ private static final Instant NOT_BEFORE = Instant.parse("2020-01-01T00:00:00Z");++ private SmimeTestCertificates() {+ }++ static Pem rsa(String email, int keySize) {+ return rsa(email, keySize, EMAIL_SIGNING);+ }++ static Pem rsa(String email, int keySize, Extensions extensions) {+ try {+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");+ generator.initialize(keySize);+ return create(email, generator.generateKeyPair(), "SHA256withRSA", extensions);+ } catch (GeneralSecurityException e) {+ throw new IllegalStateException("Could not generate an RSA key for " + email, e);+ }+ }++ static Pem ec(String email, String curve) {+ try {+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");+ generator.initialize(new ECGenParameterSpec(curve));+ return create(email, generator.generateKeyPair(), "SHA256withECDSA", EMAIL_SIGNING);+ } catch (GeneralSecurityException e) {+ throw new IllegalStateException("Could not generate an EC key for " + email, e);+ }+ }++ static Pem ed25519(String email) {+ try {+ return create(email, KeyPairGenerator.getInstance("Ed25519").generateKeyPair(), "Ed25519",+ EMAIL_SIGNING);+ } catch (GeneralSecurityException e) {+ throw new IllegalStateException("Could not generate an Ed25519 key for " + email, e);+ }+ }++ private static Pem create(String email, KeyPair keyPair, String signatureAlgorithm, Extensions extensions) {+ try {+ Instant now = Instant.now();+ X500Name subject = new X500Name("CN=" + email);+ JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(subject,+ BigInteger.valueOf(now.toEpochMilli()), Date.from(NOT_BEFORE),+ Date.from(now.plus(Duration.ofDays(365))), subject, keyPair.getPublic());+ builder.addExtension(Extension.subjectAlternativeName, false,+ new GeneralNames(new GeneralName(GeneralName.rfc822Name, email)));+ if (extensions.ca() != null) {+ builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(extensions.ca()));+ }+ if (extensions.keyUsage() != 0) {+ builder.addExtension(Extension.keyUsage, true, new KeyUsage(extensions.keyUsage()));+ }+ if (extensions.extendedKeyUsage().length > 0) {+ builder.addExtension(Extension.extendedKeyUsage, false,+ new ExtendedKeyUsage(extensions.extendedKeyUsage()));+ }+ ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());+ X509CertificateHolder holder = builder.build(signer);+ return new Pem(pem(holder), pem(keyPair.getPrivate()));+ } catch (IOException | OperatorCreationException e) {+ throw new IllegalStateException("Could not generate a test certificate for " + email, e);+ }+ }++ private static String pem(Object object) throws IOException {+ StringWriter out = new StringWriter();+ try (JcaPEMWriter writer = new JcaPEMWriter(out)) {+ writer.writeObject(object);+ }+ return out.toString();+ }+}