mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(ses): add the S/MIME identity certificate operations (#5111)
* feat(ses): add the S/MIME identity certificate operations Implement AssociateEmailIdentityCertificate, DisassociateEmailIdentityCertificate and ListEmailIdentityCertificates as a control plane only: associations are stored per region and Floci never signs mail. Request validation, messages and precedence follow real SES: a domain identity needs a FromAddress in the domain or a subdomain, one certificate per address regardless of case, the request members are checked before the identity, and the certificate is not inspected on association. The reported status is Floci's own rule: ACTIVE while the ARN names an issued, unexpired ACM certificate (with its expiry as CertificateExpiryTime), FAILED otherwise. Disassociation is immediate and idempotent, and the list pages through SesListPaging. DeleteEmailIdentity now refuses an identity that still has a certificate associated, as SES does. The v1 DeleteIdentity and DeleteVerifiedEmailAddress share the identities and refuse it too. * fix(ses): apply the documented S/MIME certificate requirements ListEmailIdentityCertificates now reports ACTIVE only when the association meets the SES Developer Guide's S/MIME certificate considerations: the identity is verified, and the certificate is currently valid, has an allowed key (RSA 2048/3072/4096 or EC P-256, P-384, P-521, read from the certificate itself since ACM's stored key algorithm folds other sizes into those) and an RFC822Name SAN equal to the From address, case-sensitively. The docs link that section instead of calling the criteria undocumented. * fix(ses): require an email-signing end-entity S/MIME certificate A probe against SES found requirements beyond the Developer Guide's list: a CA certificate fails even with the right usages, and the certificate needs both a key usage including digitalSignature and an extended key usage including emailProtection, while other usages may sit alongside them. ListEmailIdentityCertificates now applies them, and the docs list them next to the guide's link. * refactor(ses): reuse SesIdentityService's verified-identity check
This commit is contained in:
1 parent
c81290823b
commit
3f6fb371d1
12 files changed
+1382
-4
No files matched your search
+396
@@ -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 alice@example.com, matching the sender most tests associate.
|
||||
private static final SmimeTestCertificates.Pem ALICE_CERTIFICATE =
|
||||
SmimeTestCertificates.rsa("alice@example.com", 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("alice@example.org", 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 <alice@other.example.net> does not belong to the domain identity <example.com>.",
|
||||
() -> service.associate(DOMAIN, "alice@other.example.net", CERT_ARN, REGION));
|
||||
assertBadRequest("FromAddress <alice@notexample.com> does not belong to the domain identity <example.com>.",
|
||||
() -> service.associate(DOMAIN, "alice@notexample.com", CERT_ARN, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void associate_acceptsSubdomainAddress() {
|
||||
service.associate(DOMAIN, "alice@sub.example.com", CERT_ARN, REGION);
|
||||
|
||||
assertEquals(List.of("alice@sub.example.com"), fromAddresses(service.list(DOMAIN, null, null, REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void associate_emailIdentityDefaultsFromAddressToItself() {
|
||||
service.associate("alice@example.org", null, CERT_ARN, REGION);
|
||||
|
||||
assertEquals(List.of("alice@example.org"),
|
||||
fromAddresses(service.list("alice@example.org", null, null, REGION)));
|
||||
assertBadRequest("FromAddress <bob@example.org> does not match the email identity <alice@example.org>.",
|
||||
() -> service.associate("alice@example.org", "bob@example.org", CERT_ARN, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailIdentityFromAddressMustMatchExactly() {
|
||||
assertBadRequest("FromAddress <Alice@example.org> does not match the email identity <alice@example.org>.",
|
||||
() -> service.associate("alice@example.org", "Alice@example.org", CERT_ARN, REGION));
|
||||
assertBadRequest("FromAddress <ALICE@example.org> does not match the email identity <alice@example.org>.",
|
||||
() -> service.disassociate("alice@example.org", "ALICE@example.org", 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, "alice@example.com", "not-an-arn", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void associate_missingIdentityIsNotFound() {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.associate("missing.example.com", "alice@missing.example.com", 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, "Alice@Example.com", CERT_ARN, REGION);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.associate(DOMAIN, "ALICE@EXAMPLE.COM", OTHER_CERT_ARN, REGION));
|
||||
assertEquals("AlreadyExistsException", e.getErrorCode());
|
||||
assertEquals("A certificate is already associated with sender <Alice@Example.com> on identity <example.com>.",
|
||||
e.getMessage());
|
||||
assertEquals(List.of("Alice@Example.com"), 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, "alice@example.com", CERT_ARN, REGION);
|
||||
service.associate(DOMAIN, "bob@example.com", OTHER_CERT_ARN, REGION);
|
||||
|
||||
List<SesIdentityCertificateService.Entry> entries = service.list(DOMAIN, null, null, REGION).items();
|
||||
|
||||
assertEquals(new SesIdentityCertificateService.Entry("alice@example.com", "ACTIVE", CERT_ARN, notAfter),
|
||||
entries.get(0));
|
||||
assertEquals(new SesIdentityCertificateService.Entry("bob@example.com", "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, "alice@example.com", 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, "alice@example.com", 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("alice@example.com", 1024),
|
||||
SmimeTestCertificates.rsa("alice@example.com", 1536),
|
||||
SmimeTestCertificates.ed25519("alice@example.com"))) {
|
||||
certificate.setCertificateBody(refused.certificate());
|
||||
assertEquals("FAILED", service.list(DOMAIN, null, null, REGION).items().getFirst().status());
|
||||
}
|
||||
for (SmimeTestCertificates.Pem allowed : List.of(SmimeTestCertificates.rsa("alice@example.com", 3072),
|
||||
SmimeTestCertificates.ec("alice@example.com", "secp256r1"),
|
||||
SmimeTestCertificates.ec("alice@example.com", "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, "alice@example.com", 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("alice@example.com", 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, "alice@example.com", 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, "Alice@example.com", CERT_ARN, REGION);
|
||||
service.associate(DOMAIN, "bob@example.com", 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("alice@pending.example.com", 2048).certificate());
|
||||
when(acmService.getCertificate(eq(CERT_ARN), eq(REGION))).thenReturn(certificate);
|
||||
service.associate("pending.example.com", "alice@pending.example.com", 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, "alice@example.com", otherRegionArn, REGION);
|
||||
|
||||
assertEquals("FAILED", service.list(DOMAIN, null, null, REGION).items().getFirst().status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_sortsByAddressAndPages() {
|
||||
service.associate(DOMAIN, "carol@example.com", CERT_ARN, REGION);
|
||||
service.associate(DOMAIN, "Bob@example.com", CERT_ARN, REGION);
|
||||
service.associate(DOMAIN, "alice@example.com", 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("alice@example.com", "Bob@example.com"), fromAddresses(first));
|
||||
assertEquals(List.of("carol@example.com"), 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, "alice@example.com", CERT_ARN, REGION);
|
||||
service.associate(DOMAIN, "bob@example.com", 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, "alice@example.com", CERT_ARN, REGION);
|
||||
|
||||
service.disassociate(DOMAIN, "ALICE@example.com", REGION);
|
||||
service.disassociate(DOMAIN, "ALICE@example.com", REGION);
|
||||
|
||||
assertTrue(service.list(DOMAIN, null, null, REGION).items().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disassociate_checksTheAddressBeforeTheIdentity() {
|
||||
assertBadRequest("FromAddress <alice@example.com> does not belong to the domain identity <missing.example.com>.",
|
||||
() -> service.disassociate("missing.example.com", "alice@example.com", REGION));
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.disassociate("missing.example.com", "alice@missing.example.com", 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, "alice@example.com", 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, "alice@example.com", 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", "alice@sub.example.com", 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, "Alice@example.com", CERT_ARN, REGION);
|
||||
|
||||
SesIdentityCertificateService reloaded = persistentService(dir);
|
||||
|
||||
assertEquals(List.of(new SesIdentityCertificateService.Entry("Alice@example.com", "FAILED", CERT_ARN, null)),
|
||||
reloaded.list(DOMAIN, null, null, REGION).items());
|
||||
assertThrows(AwsException.class, () -> reloaded.associate(DOMAIN, "alice@example.com", 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());
|
||||
}
|
||||
}
|
||||
+212
@@ -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 = "smime-active@floci.test";
|
||||
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 = "smime-rsa1024@floci.test";
|
||||
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", "alice@nosuch.floci.test", 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 = "smime-delete@floci.test";
|
||||
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 = "smime-v1-delete@floci.test";
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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.CustomVerificationEmailTemp
|
||||
import 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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user