diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityAttributesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityAttributesTest.java index 122c137522..9132e183f2 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityAttributesTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityAttributesTest.java @@ -11,25 +11,37 @@ import org.junit.jupiter.api.TestMethodOrder; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.services.ses.SesClient; import software.amazon.awssdk.services.ses.model.DeleteIdentityRequest; +import software.amazon.awssdk.services.ses.model.GetIdentityDkimAttributesRequest; import software.amazon.awssdk.services.ses.model.GetIdentityMailFromDomainAttributesRequest; import software.amazon.awssdk.services.ses.model.GetIdentityMailFromDomainAttributesResponse; import software.amazon.awssdk.services.ses.model.GetIdentityNotificationAttributesRequest; import software.amazon.awssdk.services.ses.model.GetIdentityNotificationAttributesResponse; +import software.amazon.awssdk.services.ses.model.IdentityDkimAttributes; import software.amazon.awssdk.services.ses.model.IdentityMailFromDomainAttributes; import software.amazon.awssdk.services.ses.model.IdentityNotificationAttributes; +import software.amazon.awssdk.services.ses.model.SetIdentityDkimEnabledRequest; import software.amazon.awssdk.services.ses.model.SetIdentityFeedbackForwardingEnabledRequest; import software.amazon.awssdk.services.ses.model.SetIdentityHeadersInNotificationsEnabledRequest; import software.amazon.awssdk.services.ses.model.SetIdentityMailFromDomainRequest; +import software.amazon.awssdk.services.ses.model.VerifyDomainDkimRequest; import software.amazon.awssdk.services.ses.model.VerifyDomainIdentityRequest; import software.amazon.awssdk.services.sesv2.SesV2Client; import software.amazon.awssdk.services.sesv2.model.BadRequestException; import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest; import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.DkimAttributes; +import software.amazon.awssdk.services.sesv2.model.DkimSigningAttributes; +import software.amazon.awssdk.services.sesv2.model.DkimStatus; +import software.amazon.awssdk.services.sesv2.model.DkimSigningAttributesOrigin; +import software.amazon.awssdk.services.sesv2.model.DkimSigningKeyLength; import software.amazon.awssdk.services.sesv2.model.GetEmailIdentityRequest; import software.amazon.awssdk.services.sesv2.model.GetEmailIdentityResponse; import software.amazon.awssdk.services.sesv2.model.IdentityInfo; import software.amazon.awssdk.services.sesv2.model.ListEmailIdentitiesRequest; +import software.amazon.awssdk.services.sesv2.model.NotFoundException; +import software.amazon.awssdk.services.sesv2.model.PutEmailIdentityDkimSigningAttributesRequest; +import software.amazon.awssdk.services.sesv2.model.PutEmailIdentityDkimSigningAttributesResponse; import software.amazon.awssdk.services.sesv2.model.PutEmailIdentityMailFromAttributesRequest; import software.amazon.awssdk.services.sesv2.model.VerificationStatus; @@ -46,6 +58,13 @@ class SesIdentityAttributesTest { private static SesV2Client sesV2; private static String v1Domain; private static String v2Domain; + // DKIM tests use their own identities so their token regeneration / status resets don't interfere + // with the ordered MAIL FROM / notification tests above. + private static String dkimDomain; + // A separate domain that is DKIM-verified (Success) via Route53, plus an email under it, to check + // that an email inherits its parent domain's *verified* DKIM. + private static String verifiedDkimDomain; + private static String verifiedDkimEmail; @BeforeAll static void setup() { @@ -54,6 +73,9 @@ class SesIdentityAttributesTest { String suffix = TestFixtures.uniqueName(); v1Domain = suffix + ".v1-attrs.example.com"; v2Domain = suffix + ".v2-attrs.example.com"; + dkimDomain = suffix + ".dkim-attrs.example.com"; + verifiedDkimDomain = suffix + ".dkim-verified.example.com"; + verifiedDkimEmail = "user@" + verifiedDkimDomain; } @AfterAll @@ -62,13 +84,17 @@ class SesIdentityAttributesTest { try { sesV1.deleteIdentity(DeleteIdentityRequest.builder().identity(v1Domain).build()); } catch (Exception ignored) {} + try { + sesV1.deleteIdentity(DeleteIdentityRequest.builder().identity(dkimDomain).build()); + } catch (Exception ignored) {} sesV1.close(); } if (sesV2 != null) { - try { - sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder() - .emailIdentity(v2Domain).build()); - } catch (Exception ignored) {} + for (String id : new String[] {v2Domain, verifiedDkimEmail, verifiedDkimDomain}) { + try { + sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(id).build()); + } catch (Exception ignored) {} + } sesV2.close(); } } @@ -198,4 +224,91 @@ class SesIdentityAttributesTest { sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(domain).build()); } } + + // ───────────────────────── DKIM ───────────────────────── + + @Test + @Order(20) + void verifyDomainDkim_returnsStableTokens() { + sesV1.verifyDomainIdentity(VerifyDomainIdentityRequest.builder().domain(dkimDomain).build()); + + List first = sesV1.verifyDomainDkim( + VerifyDomainDkimRequest.builder().domain(dkimDomain).build()).dkimTokens(); + assertThat(first).hasSize(3); + + List second = sesV1.verifyDomainDkim( + VerifyDomainDkimRequest.builder().domain(dkimDomain).build()).dkimTokens(); + assertThat(second).isEqualTo(first); + } + + @Test + @Order(21) + void setIdentityDkimEnabled_togglesFlag() { + sesV1.setIdentityDkimEnabled(SetIdentityDkimEnabledRequest.builder() + .identity(dkimDomain).dkimEnabled(false).build()); + + IdentityDkimAttributes attrs = sesV1.getIdentityDkimAttributes( + GetIdentityDkimAttributesRequest.builder().identities(dkimDomain).build()) + .dkimAttributes().get(dkimDomain); + assertThat(attrs.dkimEnabled()).isFalse(); + + sesV1.setIdentityDkimEnabled(SetIdentityDkimEnabledRequest.builder() + .identity(dkimDomain).dkimEnabled(true).build()); + } + + @Test + @Order(22) + void setIdentityDkimEnabled_unknownIdentity_throws() { + assertThatThrownBy(() -> sesV1.setIdentityDkimEnabled(SetIdentityDkimEnabledRequest.builder() + .identity("unknown." + dkimDomain).dkimEnabled(true).build())) + .isInstanceOf(AwsServiceException.class); + } + + @Test + @Order(23) + void putEmailIdentityDkimSigningAttributes_regeneratesTokensOnKeyLengthChange() { + List before = sesV2.getEmailIdentity(GetEmailIdentityRequest.builder() + .emailIdentity(dkimDomain).build()).dkimAttributes().tokens(); + + PutEmailIdentityDkimSigningAttributesResponse resp = sesV2.putEmailIdentityDkimSigningAttributes( + PutEmailIdentityDkimSigningAttributesRequest.builder() + .emailIdentity(dkimDomain) + .signingAttributesOrigin(DkimSigningAttributesOrigin.AWS_SES) + .signingAttributes(DkimSigningAttributes.builder() + .nextSigningKeyLength(DkimSigningKeyLength.RSA_1024_BIT).build()) + .build()); + assertThat(resp.dkimTokens()).hasSize(3); + assertThat(resp.dkimTokens()).isNotEqualTo(before); + } + + @Test + @Order(24) + void putEmailIdentityDkimSigningAttributes_unknownIdentity_throwsNotFound() { + assertThatThrownBy(() -> sesV2.putEmailIdentityDkimSigningAttributes( + PutEmailIdentityDkimSigningAttributesRequest.builder() + .emailIdentity("ghost." + dkimDomain) + .signingAttributesOrigin(DkimSigningAttributesOrigin.AWS_SES) + .build())) + .isInstanceOf(NotFoundException.class); + } + + @Test + @Order(25) + void emailIdentity_inheritsVerifiedParentDomainDkim() { + // Bring the parent domain to DKIM Success via Route53 so the email inherits SUCCESS (not Pending). + TestFixtures.verifySesDomainIdentityViaRoute53(sesV2, verifiedDkimDomain); + DkimAttributes domainDkim = sesV2.getEmailIdentity(GetEmailIdentityRequest.builder() + .emailIdentity(verifiedDkimDomain).build()).dkimAttributes(); + assertThat(domainDkim.status()).isEqualTo(DkimStatus.SUCCESS); + + sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder() + .emailIdentity(verifiedDkimEmail).build()); + DkimAttributes emailDkim = sesV2.getEmailIdentity(GetEmailIdentityRequest.builder() + .emailIdentity(verifiedDkimEmail).build()).dkimAttributes(); + + // The email carries no DKIM of its own; it mirrors the verified domain's status and tokens. + assertThat(emailDkim.signingEnabled()).isTrue(); + assertThat(emailDkim.status()).isEqualTo(DkimStatus.SUCCESS); + assertThat(emailDkim.tokens()).isEqualTo(domainDkim.tokens()); + } } diff --git a/docs/services/ses.md b/docs/services/ses.md index b573d5fad3..772b48883f 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -43,7 +43,9 @@ Floci exposes the classic Amazon SES Query API used by `aws ses ...` commands an | `SetIdentityHeadersInNotificationsEnabled` | Toggle headers-in-notifications per notification type | | `SetIdentityMailFromDomain` | Set or clear the MAIL FROM domain for an identity | | `GetIdentityMailFromDomainAttributes` | Read MAIL FROM domain settings | -| `GetIdentityDkimAttributes` | Return DKIM status for identities | +| `GetIdentityDkimAttributes` | Return DKIM status for identities (an email inherits its domain's DKIM) | +| `SetIdentityDkimEnabled` | Enable or disable DKIM signing for an identity | +| `VerifyDomainDkim` | Return a domain's (stable) DKIM CNAME tokens | | `PutIdentityPolicy` | Create or replace a sending-authorization policy on an identity | | `GetIdentityPolicies` | Return the requested policies for an identity | | `ListIdentityPolicies` | List an identity's policy names | @@ -193,6 +195,7 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS | `GET` | `/v2/email/identities/{emailIdentity}` | `GetEmailIdentity` | | `DELETE` | `/v2/email/identities/{emailIdentity}` | `DeleteEmailIdentity` | | `PUT` | `/v2/email/identities/{emailIdentity}/dkim` | `PutEmailIdentityDkimAttributes` | +| `PUT` | `/v2/email/identities/{emailIdentity}/dkim/signing` | `PutEmailIdentityDkimSigningAttributes` (Easy DKIM / BYODKIM) | | `PUT` | `/v2/email/identities/{emailIdentity}/feedback` | `PutEmailIdentityFeedbackAttributes` | | `PUT` | `/v2/email/identities/{emailIdentity}/mail-from` | `PutEmailIdentityMailFromAttributes` | | `PUT` | `/v2/email/identities/{emailIdentity}/configuration-set` | `PutEmailIdentityConfigurationSetAttributes` | @@ -283,3 +286,5 @@ For a **single-recipient** list-managed send, Floci injects a functional unsubsc Tag operations support these ARN forms: `arn:aws:ses:::configuration-set/`, `arn:aws:ses:::template/`, and `arn:aws:ses:::identity/`. Tags supplied to `CreateConfigurationSet`, `CreateEmailTemplate`, and `CreateEmailIdentity` are reachable through `ListTagsForResource`; `UpdateEmailTemplate` does not modify tags. Other resource types return `NotFoundException`. Identity, identity-policy, template, custom-verification-template, configuration-set, and sent-message state is shared between the v1 Query API and the v2 REST JSON API, so a template created with `CreateTemplate` resolves through `SendEmail` on v2 (and vice versa), a policy written with `PutIdentityPolicy` (v1) is returned by `GetEmailIdentityPolicies` (v2), a custom verification email template created with `CreateCustomVerificationEmailTemplate` (v1) is returned by `GetCustomVerificationEmailTemplate` (v2), a configuration set created with `CreateConfigurationSet` is visible to both `DescribeConfigurationSet` (v1) and `GetConfigurationSet` (v2), and every send appears in the same `GET /_aws/ses` inspection mailbox. + +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 `._domainkey.` 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 `user@example.com` but not `user@mail.example.com` 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). diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 92170cfd25..a0ce0adedd 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -392,6 +392,8 @@ public class AwsQueryController { "GetAccountSendingEnabled", "ListVerifiedEmailAddresses", "DeleteVerifiedEmailAddress", "SetIdentityNotificationTopic", "GetIdentityNotificationAttributes", "SetIdentityFeedbackForwardingEnabled", + "SetIdentityDkimEnabled", + "VerifyDomainDkim", "SetIdentityHeadersInNotificationsEnabled", "SetIdentityMailFromDomain", "GetIdentityMailFromDomainAttributes", "GetIdentityDkimAttributes", diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java index 42185d3b49..8c5d0d457b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java @@ -150,7 +150,7 @@ public class SesController { result.put("IdentityType", toV2IdentityType(identity.getIdentityType())); result.put("VerifiedForSendingStatus", "Success".equals(identity.getVerificationStatus())); - result.set("DkimAttributes", buildDkimAttributes(identity)); + result.set("DkimAttributes", buildDkimAttributes(identity, region)); LOG.infov("SES V2 CreateEmailIdentity: {0}", emailIdentity); return Response.ok(result).build(); @@ -199,7 +199,7 @@ public class SesController { throw new AwsException("NotFoundException", "Identity " + emailIdentity + " does not exist.", 404); } - return Response.ok(buildFullIdentityResponse(identity)).build(); + return Response.ok(buildFullIdentityResponse(identity, region)).build(); } @DELETE @@ -320,6 +320,50 @@ public class SesController { } } + @PUT + @Path("/identities/{emailIdentity}/dkim/signing") + public Response putEmailIdentityDkimSigningAttributes(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = (body == null || body.isBlank()) + ? objectMapper.createObjectNode() : objectMapper.readTree(body); + requireJsonObject(request); + String origin = request.path("SigningAttributesOrigin").asText(null); + if (!"AWS_SES".equals(origin) && !"EXTERNAL".equals(origin)) { + throw new AwsException("BadRequestException", + "SigningAttributesOrigin must be AWS_SES or EXTERNAL.", 400); + } + JsonNode attrs = requireObjectOrAbsent(request, "SigningAttributes"); + String selector = attrs.path("DomainSigningSelector").asText(null); + String nextKeyLength = attrs.path("NextSigningKeyLength").asText(null); + if (nextKeyLength != null + && !"RSA_1024_BIT".equals(nextKeyLength) && !"RSA_2048_BIT".equals(nextKeyLength)) { + throw new AwsException("BadRequestException", + "NextSigningKeyLength must be RSA_1024_BIT or RSA_2048_BIT.", 400); + } + String privateKey = attrs.path("DomainSigningPrivateKey").asText(null); + if ("EXTERNAL".equals(origin) + && (selector == null || selector.isBlank() + || privateKey == null || privateKey.isBlank())) { + throw new AwsException("BadRequestException", + "EXTERNAL origin requires DomainSigningSelector and DomainSigningPrivateKey.", 400); + } + SesService.DkimSigningResult result = sesService.putDkimSigningAttributes( + emailIdentity, origin, selector, nextKeyLength, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("DkimStatus", toV2Status(result.dkimStatus())); + ArrayNode tokens = out.putArray("DkimTokens"); + result.dkimTokens().forEach(tokens::add); + return Response.ok(out).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (Exception e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + // ────────────────── Identity MAIL FROM ────────────────────────── @PUT @@ -2105,7 +2149,7 @@ public class SesController { // ──────────────────────────── Helpers ──────────────────────────── - private ObjectNode buildFullIdentityResponse(Identity identity) { + private ObjectNode buildFullIdentityResponse(Identity identity, String region) { ObjectNode result = objectMapper.createObjectNode(); result.put("IdentityType", toV2IdentityType(identity.getIdentityType())); result.put("VerifiedForSendingStatus", @@ -2113,7 +2157,7 @@ public class SesController { result.put("VerificationStatus", toV2Status(identity.getVerificationStatus())); result.put("FeedbackForwardingStatus", identity.isFeedbackForwardingEnabled()); - result.set("DkimAttributes", buildDkimAttributes(identity)); + result.set("DkimAttributes", buildDkimAttributes(identity, region)); ObjectNode mailFromAttributes = result.putObject("MailFromAttributes"); mailFromAttributes.put("BehaviorOnMxFailure", v1BehaviorToV2(identity.getBehaviorOnMxFailure())); @@ -2161,16 +2205,28 @@ public class SesController { + "constraint: Member must satisfy enum value set: [REJECT_MESSAGE, USE_DEFAULT_VALUE]", 400); } - private ObjectNode buildDkimAttributes(Identity identity) { + private ObjectNode buildDkimAttributes(Identity identity, String region) { + // An email identity reports its parent domain's DKIM (SigningEnabled / Status / Tokens all + // inherit from the domain), matching AWS; a domain reports its own. + Identity src = sesService.effectiveDkimSource(identity, region); ObjectNode dkim = objectMapper.createObjectNode(); - dkim.put("SigningEnabled", identity.isDkimEnabled()); - dkim.put("Status", toV2Status(identity.getDkimVerificationStatus())); + dkim.put("SigningEnabled", src.isDkimEnabled()); + dkim.put("Status", toV2Status(src.getDkimVerificationStatus())); ArrayNode tokens = dkim.putArray("Tokens"); - if (identity.getDkimTokens() != null) { - for (String token : identity.getDkimTokens()) { + if (src.getDkimTokens() != null) { + for (String token : src.getDkimTokens()) { tokens.add(token); } } + dkim.put("SigningAttributesOrigin", src.getDkimSigningAttributesOrigin()); + dkim.put("NextSigningKeyLength", src.getDkimNextSigningKeyLength()); + dkim.put("CurrentSigningKeyLength", src.getDkimCurrentSigningKeyLength()); + if (src.getDkimLastKeyGenerationTimestamp() != null) { + // SES v2 (restJson1) serializes this timestamp as epoch seconds (a number); emitting an + // ISO string breaks the SDK's unixTimestamp unmarshaller. + dkim.put("LastKeyGenerationTimestamp", + src.getDkimLastKeyGenerationTimestamp().toEpochMilli() / 1000.0); + } return dkim; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java index 5566af60c7..e5bb966474 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java @@ -71,6 +71,8 @@ public class SesQueryHandler { case "SetIdentityNotificationTopic" -> handleSetIdentityNotificationTopic(params, region); case "GetIdentityNotificationAttributes" -> handleGetIdentityNotificationAttributes(params, region); case "SetIdentityFeedbackForwardingEnabled" -> handleSetIdentityFeedbackForwardingEnabled(params, region); + case "SetIdentityDkimEnabled" -> handleSetIdentityDkimEnabled(params, region); + case "VerifyDomainDkim" -> handleVerifyDomainDkim(params, region); case "SetIdentityHeadersInNotificationsEnabled" -> handleSetIdentityHeadersInNotificationsEnabled(params, region); case "SetIdentityMailFromDomain" -> handleSetIdentityMailFromDomain(params, region); case "GetIdentityMailFromDomainAttributes" -> handleGetIdentityMailFromDomainAttributes(params, region); @@ -334,14 +336,16 @@ public class SesQueryHandler { var xml = new XmlBuilder().start("DkimAttributes"); for (String identityValue : identities) { Identity identity = sesService.getIdentityVerificationAttributes(identityValue, region); + // An email identity reports its parent domain's DKIM state (matching AWS). + Identity src = sesService.effectiveDkimSource(identity, region); xml.start("entry"); xml.elem("key", identityValue); xml.start("value"); - xml.elem("DkimEnabled", identity != null ? String.valueOf(identity.isDkimEnabled()) : "false"); - xml.elem("DkimVerificationStatus", identity != null ? identity.getDkimVerificationStatus() : "NotStarted"); + xml.elem("DkimEnabled", src != null ? String.valueOf(src.isDkimEnabled()) : "false"); + xml.elem("DkimVerificationStatus", src != null ? src.getDkimVerificationStatus() : "NotStarted"); xml.start("DkimTokens"); - if (identity != null && identity.getDkimTokens() != null) { - for (String token : identity.getDkimTokens()) { + if (src != null && src.getDkimTokens() != null) { + for (String token : src.getDkimTokens()) { xml.elem("member", token); } } @@ -360,6 +364,24 @@ public class SesQueryHandler { return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetIdentityFeedbackForwardingEnabled", AwsNamespaces.SES)).build(); } + private Response handleSetIdentityDkimEnabled(MultivaluedMap params, String region) { + String identityValue = getParam(params, "Identity"); + boolean enabled = parseRequiredBoolean(params, "DkimEnabled"); + sesService.setDkimAttributes(identityValue, enabled, region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetIdentityDkimEnabled", AwsNamespaces.SES)).build(); + } + + private Response handleVerifyDomainDkim(MultivaluedMap params, String region) { + String domain = getParam(params, "Domain"); + List tokens = sesService.verifyDomainDkim(domain, region); + var xml = new XmlBuilder().start("DkimTokens"); + for (String token : tokens) { + xml.elem("member", token); + } + xml.end("DkimTokens"); + return Response.ok(AwsQueryResponse.envelope("VerifyDomainDkim", AwsNamespaces.SES, xml.build())).build(); + } + private Response handleSetIdentityHeadersInNotificationsEnabled(MultivaluedMap params, String region) { String identityValue = getParam(params, "Identity"); String notificationType = getParam(params, "NotificationType"); 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.java index a55d615802..5229e61ec5 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 @@ -255,10 +255,13 @@ public class SesService { if (existing != null) return existing; Identity identity = new Identity(domain, "Domain"); - identity.setDkimTokens(generateDkimTokens()); + regenerateDkimTokens(identity); identity.setVerificationStatus("Pending"); identity.setDkimEnabled(true); - identity.setDkimVerificationStatus("Pending"); + // The create response reports DKIM verification as NotStarted (SES hasn't begun tracking the + // CNAMEs yet); the first Get/List refresh transitions it to Pending. Matches AWS, where + // CreateEmailIdentity returns NOT_STARTED but a subsequent GetEmailIdentity returns PENDING. + identity.setDkimVerificationStatus("NotStarted"); identityStore.put(key, identity); LOG.infov("Verified domain identity: {0} in region {1}", domain, region); return identity; @@ -677,27 +680,33 @@ public class SesService { } public void setDkimAttributes(String identityValue, boolean signingEnabled, String region) { - String key = identityKey(region, identityValue); - Identity identity = identityStore.get(key).orElse(null); - - if (identity == null) { - String domain = identityValue != null && identityValue.contains("@") - ? identityValue.substring(identityValue.indexOf('@') + 1) - : identityValue; - if (identityValue != null && identityValue.contains("@") - && identityStore.get(identityKey(region, domain)).isPresent()) { + if (identityValue == null || identityValue.isBlank()) { + throw new AwsException("InvalidParameterValue", "Identity is required.", 400); + } + // DKIM is a domain concept and an email reports its parent domain's DKIM (via effectiveDkimSource), + // so toggling DKIM on an email whose parent domain is a registered identity is a no-op that leaves + // the domain untouched — matching real AWS, regardless of whether the email identity itself exists. + if (identityValue.contains("@")) { + String domain = identityValue.substring(identityValue.indexOf('@') + 1); + if (identityStore.get(identityKey(region, domain)).isPresent()) { return; } - throw new AwsException("BadRequestException", + } + String key = identityKey(region, identityValue); + Identity identity = identityStore.get(key).orElse(null); + if (identity == null) { + String domain = identityValue.contains("@") + ? identityValue.substring(identityValue.indexOf('@') + 1) + : identityValue; + // v1-native code; the v2 controller remaps InvalidParameterValue -> BadRequestException. + throw new AwsException("InvalidParameterValue", "Domain " + domain + " is not verified for DKIM signing.", 400); } + // Only toggle the signing flag. DkimVerificationStatus tracks DNS record detection (via the + // Route53 lookup in refreshIdentityState), not the enabled flag — matching real AWS, where + // SetIdentityDkimEnabled / PutEmailIdentityDkimAttributes leave the verification status alone. identity.setDkimEnabled(signingEnabled); - if (signingEnabled) { - identity.setDkimVerificationStatus("Success"); - } else { - identity.setDkimVerificationStatus("NotStarted"); - } identityStore.put(key, identity); LOG.infov("Updated DKIM attributes for {0}: signingEnabled={1}", identityValue, signingEnabled); } @@ -710,6 +719,128 @@ public class SesService { return tokens; } + /** + * Generates a fresh Easy DKIM token set and records the key length / generation timestamp. New + * tokens mean the previously published CNAMEs no longer match, so the verification status resets + * to Pending (re-detected via the Route53 lookup) and the origin returns to AWS_SES. Only meaningful + * for domain identities; refreshIdentityState re-upgrades to Success once the new records exist. + */ + private void regenerateDkimTokens(Identity identity) { + identity.setDkimTokens(generateDkimTokens()); + identity.setDkimCurrentSigningKeyLength(identity.getDkimNextSigningKeyLength()); + identity.setDkimLastKeyGenerationTimestamp(Instant.now(clock)); + identity.setDkimSigningAttributesOrigin("AWS_SES"); + // The new tokens' CNAMEs aren't detected yet, so DKIM verification resets to Pending. The + // identity's own verification is NOT revoked by a key rotation (matching AWS) — keep Success + // when already verified; a not-yet-verified identity stays Pending. + identity.setDkimVerificationStatus("Pending"); + if (!"Success".equals(identity.getVerificationStatus())) { + identity.setVerificationStatus("Pending"); + } + } + + /** + * v1 VerifyDomainDkim: returns the domain identity's DKIM tokens (3), generating them if needed. + * Tokens are stable across calls (AWS does not regenerate them). The domain is registered as a + * pending identity if it does not exist yet, matching AWS's lenient behavior (VerifyDomainDkim + * starts DKIM setup for any domain). + */ + public List verifyDomainDkim(String domain, String region) { + validateIdentityWhitespace(domain, "Domain"); + if (domain == null || domain.isBlank()) { + throw new AwsException("InvalidParameterValue", "Domain is required.", 400); + } + if (domain.contains("@")) { + // Domain-only action: an email-shaped value must not create an email-valued "Domain". + throw new AwsException("InvalidParameterValue", "Domain " + domain + " is invalid.", 400); + } + String key = identityKey(region, domain); + Identity identity = identityStore.get(key).orElse(null); + if (identity == null) { + identity = new Identity(domain, "Domain"); + identity.setVerificationStatus("Pending"); + identity.setDkimEnabled(true); + identity.setDkimVerificationStatus("Pending"); + } + if (!hasDkimTokens(identity)) { + regenerateDkimTokens(identity); + } + identityStore.put(key, identity); + LOG.infov("VerifyDomainDkim: {0} (region {1})", domain, region); + return identity.getDkimTokens(); + } + + /** + * v2 PutEmailIdentityDkimSigningAttributes. AWS_SES (Easy DKIM): sets the next signing key length + * and regenerates tokens when the length changes. EXTERNAL (BYODKIM): switches the origin and + * clears the Easy DKIM tokens (the caller publishes its own selector, which Floci does not use for + * signing). Returns the resulting DKIM status and tokens. + */ + public DkimSigningResult putDkimSigningAttributes(String identityValue, String origin, + String signingSelector, String nextKeyLength, + String region) { + // DKIM signing attributes are domain-level; AWS rejects a missing/blank value or an + // email-address identity here (verified: all return the same 400 "must be a valid domain") + // rather than mutating state that the email would just inherit back from its parent domain. + if (identityValue == null || identityValue.isBlank() || identityValue.contains("@")) { + throw new AwsException("BadRequestException", + "The EmailIdentity value must be a valid domain.", 400); + } + String key = identityKey(region, identityValue); + Identity identity = identityStore.get(key) + .orElseThrow(() -> new AwsException("NotFoundException", + "Email identity " + identityValue + " does not exist.", 404)); + if ("EXTERNAL".equals(origin)) { + identity.setDkimSigningAttributesOrigin("EXTERNAL"); + // Clear the Easy DKIM tokens and reset the status: Floci can't verify a BYODKIM selector, + // so leaving a prior Success/Pending with no tokens (and no Route53 detection path) would + // be inconsistent. + identity.setDkimTokens(new ArrayList<>()); + identity.setDkimVerificationStatus("Pending"); + LOG.infov("PutEmailIdentityDkimSigningAttributes(EXTERNAL): {0} selector={1}", + identityValue, signingSelector); + } else { + identity.setDkimSigningAttributesOrigin("AWS_SES"); + // DKIM tokens are a domain concept; only (re)generate them for a domain identity. + if ("Domain".equals(identity.getIdentityType())) { + if (nextKeyLength != null && !nextKeyLength.equals(identity.getDkimCurrentSigningKeyLength())) { + identity.setDkimNextSigningKeyLength(nextKeyLength); + regenerateDkimTokens(identity); + } else if (!hasDkimTokens(identity)) { + regenerateDkimTokens(identity); + } + } + LOG.infov("PutEmailIdentityDkimSigningAttributes(AWS_SES): {0} keyLength={1}", + identityValue, nextKeyLength); + } + identityStore.put(key, refreshIdentityState(identity, region)); + Identity src = effectiveDkimSource(identity, region); + return new DkimSigningResult(src.getDkimVerificationStatus(), + src.getDkimTokens() == null ? List.of() : src.getDkimTokens()); + } + + /** Carrier for the PutEmailIdentityDkimSigningAttributes response ({@code dkimStatus} is v1-native). */ + public record DkimSigningResult(String dkimStatus, List dkimTokens) {} + + /** + * Resolves which identity's DKIM state should be reported for {@code identity}. A domain reports + * its own DKIM; an email address reports its parent domain's DKIM (SigningEnabled / Status / + * Tokens all inherit from the domain), matching AWS. Falls back to the identity itself when the + * parent domain is not a registered identity. + */ + public Identity effectiveDkimSource(Identity identity, String region) { + if (identity == null || !"EmailAddress".equals(identity.getIdentityType())) { + return identity; + } + String addr = identity.getIdentity(); + int at = addr == null ? -1 : addr.indexOf('@'); + if (at < 0 || at == addr.length() - 1) { + return identity; + } + Identity domainIdentity = identityStore.get(identityKey(region, addr.substring(at + 1))).orElse(null); + return domainIdentity == null ? identity : refreshIdentityState(domainIdentity, region); + } + private Identity refreshIdentityState(Identity identity, String region) { if (identity == null) { return null; @@ -717,19 +848,30 @@ public class SesService { boolean changed = false; if ("Domain".equals(identity.getIdentityType()) && identity.getDkimTokens() == null) { - identity.setDkimTokens(generateDkimTokens()); + regenerateDkimTokens(identity); changed = true; } if ("Domain".equals(identity.getIdentityType()) && hasDkimTokens(identity)) { changed |= normalizePendingDomainState(identity); - if (!"Success".equals(identity.getVerificationStatus()) - && hasAllExpectedDkimRecords(identity, region)) { - identity.setVerificationStatus("Success"); - if (identity.isDkimEnabled()) { - identity.setDkimVerificationStatus("Success"); + // Upgrade identity- and DKIM-verification independently so that, e.g., after a key rotation + // (which resets only DkimVerificationStatus while the identity stays verified), the DKIM + // status can still return to Success once the new records are detected. + // Only look up DNS when a status can still be upgraded — skip the (cached) Route53 check + // once both identity- and DKIM-verification are already Success. DKIM verification tracks + // DNS detection independently of the signing-enabled flag, so it can reach Success even + // when DKIM signing is disabled, and can re-pend/re-upgrade after a key rotation. + boolean needsUpgrade = !"Success".equals(identity.getVerificationStatus()) + || !"Success".equals(identity.getDkimVerificationStatus()); + if (needsUpgrade && hasAllExpectedDkimRecords(identity, region)) { + if (!"Success".equals(identity.getVerificationStatus())) { + identity.setVerificationStatus("Success"); + changed = true; + } + if (!"Success".equals(identity.getDkimVerificationStatus())) { + identity.setDkimVerificationStatus("Success"); + changed = true; } - changed = true; } } @@ -754,8 +896,9 @@ public class SesService { identity.setVerificationStatus("Pending"); changed = true; } - if (identity.isDkimEnabled() - && !"Success".equals(identity.getDkimVerificationStatus()) + // DKIM verification tracks DNS detection, not the signing-enabled flag, so a domain that has + // begun tracking (NotStarted -> Pending) reports Pending on Get even while signing is disabled. + if (!"Success".equals(identity.getDkimVerificationStatus()) && !"Pending".equals(identity.getDkimVerificationStatus())) { identity.setDkimVerificationStatus("Pending"); changed = true; diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java index 1214ebfbbe..f2bdc73648 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java @@ -35,6 +35,18 @@ public class Identity { @JsonProperty("DkimTokens") private List dkimTokens; + @JsonProperty("DkimSigningAttributesOrigin") + private String dkimSigningAttributesOrigin = "AWS_SES"; // "AWS_SES" (Easy DKIM) or "EXTERNAL" (BYODKIM) + + @JsonProperty("DkimNextSigningKeyLength") + private String dkimNextSigningKeyLength = "RSA_2048_BIT"; + + @JsonProperty("DkimCurrentSigningKeyLength") + private String dkimCurrentSigningKeyLength = "RSA_2048_BIT"; + + @JsonProperty("DkimLastKeyGenerationTimestamp") + private Instant dkimLastKeyGenerationTimestamp; + @JsonProperty("NotificationAttributes") private Map notificationAttributes = new HashMap<>(); @@ -95,6 +107,18 @@ public class Identity { public List getDkimTokens() { return dkimTokens; } public void setDkimTokens(List dkimTokens) { this.dkimTokens = dkimTokens; } + public String getDkimSigningAttributesOrigin() { return dkimSigningAttributesOrigin; } + public void setDkimSigningAttributesOrigin(String origin) { this.dkimSigningAttributesOrigin = origin; } + + public String getDkimNextSigningKeyLength() { return dkimNextSigningKeyLength; } + public void setDkimNextSigningKeyLength(String len) { this.dkimNextSigningKeyLength = len; } + + public String getDkimCurrentSigningKeyLength() { return dkimCurrentSigningKeyLength; } + public void setDkimCurrentSigningKeyLength(String len) { this.dkimCurrentSigningKeyLength = len; } + + public Instant getDkimLastKeyGenerationTimestamp() { return dkimLastKeyGenerationTimestamp; } + public void setDkimLastKeyGenerationTimestamp(Instant ts) { this.dkimLastKeyGenerationTimestamp = ts; } + public Map getNotificationAttributes() { return notificationAttributes; } public void setNotificationAttributes(Map notificationAttributes) { this.notificationAttributes = notificationAttributes; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesDkimSigningActionsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesDkimSigningActionsIntegrationTest.java new file mode 100644 index 0000000000..dcbe1cd488 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesDkimSigningActionsIntegrationTest.java @@ -0,0 +1,254 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.XmlParser; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +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.hasSize; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Integration tests for the DKIM actions: v1 {@code VerifyDomainDkim} / {@code SetIdentityDkimEnabled} + * and v2 {@code PutEmailIdentityDkimSigningAttributes}, plus the email-inherits-parent-domain DKIM + * behavior. Verified against real AWS (tokens stable on VerifyDomainDkim; email DKIM mirrors the + * parent domain; DKIM status tracks DNS detection, not the enabled flag). + */ +@QuarkusTest +class SesDkimSigningActionsIntegrationTest { + + private static final String V1_AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request"; + private static final String V2_AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + + private io.restassured.specification.RequestSpecification v1(String action) { + return given().contentType("application/x-www-form-urlencoded") + .header("Authorization", V1_AUTH).formParam("Action", action); + } + + @Test + void verifyDomainDkim_returnsThreeStableTokens_andRegistersDomain() { + String domain = "dkim-verify.floci.test"; + List first = XmlParser.extractAll(v1("VerifyDomainDkim").formParam("Domain", domain) + .when().post("/").then().statusCode(200).extract().asString(), "member"); + assertEquals(3, first.size()); + + // Stable across calls (AWS does not regenerate). + List second = XmlParser.extractAll(v1("VerifyDomainDkim").formParam("Domain", domain) + .when().post("/").then().statusCode(200).extract().asString(), "member"); + assertEquals(first, second); + + // The domain is now a DKIM identity, visible via GetIdentityDkimAttributes. + v1("GetIdentityDkimAttributes").formParam("Identities.member.1", domain) + .when().post("/").then().statusCode(200) + .body(containsString("" + domain + "")) + .body(containsString("true")); + } + + @Test + void setIdentityDkimEnabled_togglesFlag_andUnknownIdentityErrors() { + String domain = "dkim-toggle.floci.test"; + v1("VerifyDomainIdentity").formParam("Domain", domain).when().post("/").then().statusCode(200); + + v1("SetIdentityDkimEnabled").formParam("Identity", domain).formParam("DkimEnabled", "false") + .when().post("/").then().statusCode(200) + .body(containsString("SetIdentityDkimEnabledResponse")); + + v1("GetIdentityDkimAttributes").formParam("Identities.member.1", domain) + .when().post("/").then().statusCode(200) + .body(containsString("false")); + + // Unknown identity -> v1-native InvalidParameterValue. + v1("SetIdentityDkimEnabled").formParam("Identity", "unknown-dkim.floci.test") + .formParam("DkimEnabled", "true") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("is not verified for DKIM signing.")); + } + + @Test + void putDkimSigningAttributes_awsSes_regeneratesTokensOnKeyLengthChange() { + String domain = "dkim-signing.floci.test"; + List before = given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"EmailIdentity\":\"" + domain + "\"}") + .when().post("/v2/email/identities").then().statusCode(200) + .extract().path("DkimAttributes.Tokens"); + + // Change the key length (default is RSA_2048_BIT) -> tokens regenerate. + Response resp = given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"SigningAttributesOrigin\":\"AWS_SES\"," + + "\"SigningAttributes\":{\"NextSigningKeyLength\":\"RSA_1024_BIT\"}}") + .when().put("/v2/email/identities/" + domain + "/dkim/signing").then().statusCode(200) + .body("DkimTokens", hasSize(3)) + // Regenerated tokens reset the status: the new CNAMEs are not yet detected in DNS. + .body("DkimStatus", equalTo("PENDING")).extract().response(); + List after = resp.path("DkimTokens"); + assertNotEquals(before, after, "changing the key length must regenerate the tokens"); + + given().header("Authorization", V2_AUTH) + .when().get("/v2/email/identities/" + domain).then().statusCode(200) + .body("DkimAttributes.CurrentSigningKeyLength", equalTo("RSA_1024_BIT")) + .body("DkimAttributes.Tokens", equalTo(after)); + } + + @Test + void putDkimSigningAttributes_emailIdentity_returns400() { + // DKIM signing attributes are domain-level; an email-shaped identity is rejected. + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"SigningAttributesOrigin\":\"AWS_SES\"}") + .when().put("/v2/email/identities/bob@dkim-emailsigning.floci.test/dkim/signing") + .then().statusCode(400).body("__type", equalTo("BadRequestException")) + .body("message", equalTo("The EmailIdentity value must be a valid domain.")); + } + + @Test + void putDkimSigningAttributes_blankIdentity_returns400() { + // A blank/whitespace identity is rejected with the same 400 "must be a valid domain" as an + // email-shaped one (verified against AWS), rather than falling through to a 404. + given().urlEncodingEnabled(false).contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"SigningAttributesOrigin\":\"AWS_SES\"}") + .when().put("/v2/email/identities/%20/dkim/signing") + .then().statusCode(400).body("__type", equalTo("BadRequestException")) + .body("message", equalTo("The EmailIdentity value must be a valid domain.")); + } + + @Test + void putDkimSigningAttributes_unknownIdentity_returns404() { + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"SigningAttributesOrigin\":\"AWS_SES\"}") + .when().put("/v2/email/identities/ghost-signing.floci.test/dkim/signing") + .then().statusCode(404).body("__type", equalTo("NotFoundException")); + } + + @Test + void putDkimSigningAttributes_externalWithBlankPrivateKey_returns400() { + String domain = "dkim-external.floci.test"; + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"EmailIdentity\":\"" + domain + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"SigningAttributesOrigin\":\"EXTERNAL\",\"SigningAttributes\":" + + "{\"DomainSigningSelector\":\"sel\",\"DomainSigningPrivateKey\":\"\"}}") + .when().put("/v2/email/identities/" + domain + "/dkim/signing") + .then().statusCode(400).body("__type", equalTo("BadRequestException")); + } + + @Test + void setIdentityDkimEnabled_missingIdentity_returns400() { + v1("SetIdentityDkimEnabled").formParam("DkimEnabled", "true") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Identity is required.")); + } + + @Test + void verifyDomainDkim_whitespaceDomain_returns400() { + v1("VerifyDomainDkim").formParam("Domain", " dkim-ws.floci.test") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("whitespace")); + } + + @Test + void verifyDomainDkim_emailShapedInput_returns400() { + v1("VerifyDomainDkim").formParam("Domain", "bob@dkim-bad.floci.test") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + } + + @Test + void putDkimSigningAttributes_invalidKeyLength_returns400() { + String domain = "dkim-badkeylen.floci.test"; + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"EmailIdentity\":\"" + domain + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"SigningAttributesOrigin\":\"AWS_SES\"," + + "\"SigningAttributes\":{\"NextSigningKeyLength\":\"RSA_4096_BIT\"}}") + .when().put("/v2/email/identities/" + domain + "/dkim/signing") + .then().statusCode(400).body("__type", equalTo("BadRequestException")); + } + + @Test + void putDkimSigningAttributes_external_clearsTokensAndResetsStatusToPending() { + String domain = "dkim-byodkim.floci.test"; + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"EmailIdentity\":\"" + domain + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"SigningAttributesOrigin\":\"EXTERNAL\",\"SigningAttributes\":" + + "{\"DomainSigningSelector\":\"sel\",\"DomainSigningPrivateKey\":\"key\"}}") + .when().put("/v2/email/identities/" + domain + "/dkim/signing").then().statusCode(200) + .body("DkimStatus", equalTo("PENDING")) + .body("DkimTokens", hasSize(0)); + + given().header("Authorization", V2_AUTH) + .when().get("/v2/email/identities/" + domain).then().statusCode(200) + .body("DkimAttributes.Status", equalTo("PENDING")) + .body("DkimAttributes.SigningAttributesOrigin", equalTo("EXTERNAL")) + .body("DkimAttributes.Tokens", hasSize(0)); + } + + @Test + void putDkimSigningAttributes_nonObjectBody_returns400() { + given().contentType("application/json").header("Authorization", V2_AUTH).body("[]") + .when().put("/v2/email/identities/dkim-nonobj.floci.test/dkim/signing") + .then().statusCode(400).body("__type", equalTo("BadRequestException")); + } + + @Test + void putEmailIdentityDkimAttributes_existingEmailWithRegisteredDomain_isNoOp() { + String domain = "dkim-emailtoggle.floci.test"; + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"EmailIdentity\":\"" + domain + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"EmailIdentity\":\"bob@" + domain + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + + // Toggling DKIM on the email is a no-op (DKIM is domain-controlled) — 200, nothing changes. + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"SigningEnabled\": false}") + .when().put("/v2/email/identities/bob@" + domain + "/dkim").then().statusCode(200); + + // The email still reports the domain's DKIM (enabled), and the domain is untouched. + given().header("Authorization", V2_AUTH) + .when().get("/v2/email/identities/bob@" + domain).then().statusCode(200) + .body("DkimAttributes.SigningEnabled", equalTo(true)); + given().header("Authorization", V2_AUTH) + .when().get("/v2/email/identities/" + domain).then().statusCode(200) + .body("DkimAttributes.SigningEnabled", equalTo(true)); + } + + @Test + void emailIdentity_inheritsParentDomainDkim() { + String domain = "dkim-inherit.floci.test"; + List domainTokens = given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"EmailIdentity\":\"" + domain + "\"}") + .when().post("/v2/email/identities").then().statusCode(200) + .extract().path("DkimAttributes.Tokens"); + + // An email under that domain inherits the domain's DKIM (tokens, enabled, pending status). + given().contentType("application/json").header("Authorization", V2_AUTH) + .body("{\"EmailIdentity\":\"bob@" + domain + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + + given().header("Authorization", V2_AUTH) + .when().get("/v2/email/identities/bob@" + domain).then().statusCode(200) + .body("DkimAttributes.SigningEnabled", equalTo(true)) + .body("DkimAttributes.Status", equalTo("PENDING")) + .body("DkimAttributes.Tokens", equalTo(domainTokens)) + .body("DkimAttributes.Tokens", not(hasSize(0))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java index bc8ff05c0b..a79707eb53 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java @@ -78,7 +78,9 @@ class SesServiceLegacyDkimTokensTest { assertTrue(refreshed.getDkimTokens().stream().allMatch(token -> token != null && !token.isBlank())); assertEquals("Pending", refreshed.getVerificationStatus()); assertFalse(refreshed.isDkimEnabled()); - assertEquals("NotStarted", refreshed.getDkimVerificationStatus()); + // Once tokens are backfilled the domain is pending DNS detection (status tracks detection, not + // the signing flag), rather than staying NotStarted. + assertEquals("Pending", refreshed.getDkimVerificationStatus()); List persistedTokens = identityStore.get(key).orElseThrow().getDkimTokens(); assertNotNull(persistedTokens); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java index ffcca1bb04..56bc8f0ff5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java @@ -54,8 +54,19 @@ class SesV2IntegrationTest { .body("IdentityType", equalTo("DOMAIN")) .body("VerifiedForSendingStatus", equalTo(false)) .body("DkimAttributes.SigningEnabled", equalTo(true)) - .body("DkimAttributes.Status", equalTo("PENDING")) + // CreateEmailIdentity reports NOT_STARTED (SES hasn't begun tracking the CNAMEs yet). + .body("DkimAttributes.Status", equalTo("NOT_STARTED")) .body("DkimAttributes.Tokens", not(empty())); + + // A subsequent GetEmailIdentity transitions the DKIM status to PENDING, matching AWS. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/v2example.com") + .then() + .statusCode(200) + .body("DkimAttributes.Status", equalTo("PENDING")); } @Test @@ -199,6 +210,64 @@ class SesV2IntegrationTest { .body("DkimAttributes.SigningEnabled", equalTo(true)) .body("DkimAttributes.Status", equalTo("SUCCESS")) .body("DkimAttributes.Tokens", not(empty())); + + // DKIM verification status tracks DNS detection independently of the signing flag: disabling + // DKIM keeps Status=SUCCESS while the CNAMEs remain published. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"SigningEnabled": false} + """) + .when() + .put("/v2/email/identities/v2dkim-success.floci.test/dkim") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/v2dkim-success.floci.test") + .then() + .statusCode(200) + .body("DkimAttributes.SigningEnabled", equalTo(false)) + .body("DkimAttributes.Status", equalTo("SUCCESS")); + + // Re-enable so the key-rotation assertion below starts from the signing-enabled state. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"SigningEnabled": true} + """) + .when() + .put("/v2/email/identities/v2dkim-success.floci.test/dkim") + .then() + .statusCode(200); + + // Rotating the DKIM key must not revoke the identity's sending verification (matching AWS): + // VerificationStatus stays SUCCESS, but DKIM re-pends until the new tokens' records are detected. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"SigningAttributesOrigin":"AWS_SES","SigningAttributes":{"NextSigningKeyLength":"RSA_1024_BIT"}} + """) + .when() + .put("/v2/email/identities/v2dkim-success.floci.test/dkim/signing") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/v2dkim-success.floci.test") + .then() + .statusCode(200) + .body("VerificationStatus", equalTo("SUCCESS")) + .body("DkimAttributes.Status", equalTo("PENDING")); } @Test @@ -519,7 +588,9 @@ class SesV2IntegrationTest { .then() .statusCode(200) .body("DkimAttributes.SigningEnabled", equalTo(true)) - .body("DkimAttributes.Status", equalTo("SUCCESS")); + // example.com is not a DKIM-verified domain identity, so the enabled flag is set but the + // DKIM verification status stays NOT_STARTED (status tracks DNS detection, not the flag). + .body("DkimAttributes.Status", equalTo("NOT_STARTED")); } @Test