diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTagResourceTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTagResourceTest.java index 9d4c610b8c..bec9e6f73a 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTagResourceTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTagResourceTest.java @@ -58,6 +58,8 @@ class SesTagResourceTest { private static String cvetArn; private static String poolName; private static String poolArn; + private static String tenantName; + private static String tenantArn; @BeforeAll static void setup() { @@ -76,6 +78,7 @@ class SesTagResourceTest { cvetArn = "arn:aws:ses:us-east-1:000000000000:custom-verification-email-template/" + cvetName; poolName = "sdk-tag-pool-" + suffix; poolArn = "arn:aws:ses:us-east-1:000000000000:dedicated-ip-pool/" + poolName; + tenantName = "sdk-tag-tenant-" + suffix; sesV2.createConfigurationSet(CreateConfigurationSetRequest.builder() .configurationSetName(configSetName) @@ -123,6 +126,11 @@ class SesTagResourceTest { } catch (Exception e) { System.out.println("Cleanup: failed to delete pool " + poolName + ": " + e.getMessage()); } + try { + sesV2.deleteTenant(r -> r.tenantName(tenantName)); + } catch (Exception e) { + System.out.println("Cleanup: failed to delete tenant " + tenantName + ": " + e.getMessage()); + } sesV2.close(); } } @@ -403,4 +411,39 @@ class SesTagResourceTest { assertThat(afterUntag.tags()).hasSize(1); assertThat(afterUntag.tags().get(0).key()).isEqualTo("owner"); } + + @Test + @Order(60) + void tenant_createWithTags_tagAndUntag_lifecycle() { + // The tenant ARN carries two path segments (tenant//); AWS resolves it by + // the TenantId alone, so the real ARN from CreateTenant is used throughout. + tenantArn = sesV2.createTenant(r -> r.tenantName(tenantName) + .tags(Tag.builder().key("env").value("dev").build())).tenantArn(); + + ListTagsForResourceResponse listed = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(tenantArn).build()); + assertThat(listed.tags()).hasSize(1); + assertThat(listed.tags().get(0).key()).isEqualTo("env"); + + sesV2.tagResource(TagResourceRequest.builder() + .resourceArn(tenantArn) + .tags(Tag.builder().key("owner").value("alice").build()) + .build()); + + sesV2.untagResource(UntagResourceRequest.builder() + .resourceArn(tenantArn) + .tagKeys("env") + .build()); + + ListTagsForResourceResponse afterUntag = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(tenantArn).build()); + assertThat(afterUntag.tags()).hasSize(1); + assertThat(afterUntag.tags().get(0).key()).isEqualTo("owner"); + + assertThatThrownBy(() -> sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(tenantArn.substring(0, tenantArn.lastIndexOf('/')) + + "/tn-000000000000000000000000000000").build())) + .hasMessageContaining("No Tenant present with name: " + tenantName + + "with tenantId: tn-000000000000000000000000000000"); + } } diff --git a/docs/services/ses.md b/docs/services/ses.md index 3ef790a52a..9665a0ca45 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -305,9 +305,9 @@ Suppressed recipients are filtered out of the SMTP relay step (non-suppressed re For a **single-recipient** list-managed send, Floci injects a functional unsubscribe link (matching AWS, which only does this for one recipient): the `{{amazonSESUnsubscribeUrl}}` body placeholder is replaced (up to twice) and a `List-Unsubscribe` header plus `List-Unsubscribe-Post: List-Unsubscribe=One-Click` are added (applied to the relayed message and shown under `Headers` at `GET /_aws/ses`; a caller-supplied `List-Unsubscribe` is overridden, matching AWS). The `{{amazonSESUnsubscribeUrl}}` placeholder is also preserved through template rendering so a templated body can carry it. On a send without `ListManagementOptions`, the placeholder is left in the body verbatim (neither replaced nor stripped) — this specific behavior is Floci's choice and is not verified against real SES. Unlike AWS's opaque hosted URL, the link points at Floci's own `/_aws/ses/unsubscribe?region=…&contactList=…&address=…&topic=…` endpoint. `GET` (a browser click) only renders a confirmation page and changes nothing — matching AWS's landing-page behavior and avoiding the RFC 8058 hazard where a client or bot that prefetches the link would silently unsubscribe the contact — while `POST` (the one-click request the confirmation form submits) applies the opt-out (a topic → `OPT_OUT` for that topic; no topic → `UnsubscribeAll`), auto-creating the contact if needed. Two deviations from AWS here: the link is carried as readable query parameters rather than an opaque token (so, like the rest of Floci, the endpoint is unauthenticated and only safe on a trusted dev/test network — a `POST` can opt out any contact), and only the one-click URL entry is emitted — its scheme follows Floci's base URL (`http` unless TLS is enabled) — whereas AWS also includes a `mailto:` entry, which Floci can't service since it has no inbound mail endpoint. Raw (MIME) sends do not get link injection yet. -Tag operations accept `arn:aws:ses:::/` ARNs for six resource types — `configuration-set`, `template`, `identity`, `contact-list`, `custom-verification-email-template`, and `dedicated-ip-pool`; other types return `NotFoundException`. Tags supplied to `CreateConfigurationSet`, `CreateEmailTemplate`, `CreateEmailIdentity`, `CreateContactList`, `CreateCustomVerificationEmailTemplate`, and `CreateDedicatedIpPool` are reachable through `ListTagsForResource`; `UpdateEmailTemplate` and `UpdateCustomVerificationEmailTemplate` do not modify tags. +Tag operations accept `arn:aws:ses:::/` ARNs for seven resource types: `configuration-set`, `template`, `identity`, `contact-list`, `custom-verification-email-template`, `dedicated-ip-pool`, and `tenant`; other types return `NotFoundException`. Tags supplied to `CreateConfigurationSet`, `CreateEmailTemplate`, `CreateEmailIdentity`, `CreateContactList`, `CreateCustomVerificationEmailTemplate`, `CreateDedicatedIpPool`, and `CreateTenant` are reachable through `ListTagsForResource`; `UpdateEmailTemplate` and `UpdateCustomVerificationEmailTemplate` do not modify tags. A tenant ARN has two path segments (`tenant//`) and resolves by the TenantId alone (the name is never matched, so tags are TenantId-scoped across delete/recreate), with the list ordered by key and the not-found wording reproducing AWS's own missing space ("No Tenant present with name: \with tenantId: \"). Tenant tags live on the tenant record (shared with `CreateTenant`/`GetTenant`). -ARN handling is uniform across the six types (probe-confirmed against real AWS). A foreign account id fails first with `BadRequestException` ("Operations on a resource created in a different account is not allowed"). A region differing from the signing region fails `TagResource` / `UntagResource` with `BadRequestException` ("Failed to tag resource" / "Failed to untag resource"); `ListTagsForResource` instead checks existence in the signing region (`NotFoundException`, "No \ present with name: \") and keys tags by the literal ARN, so a mismatched-region ARN returns `200` with an empty tag set. An empty `Tags` array on `TagResource` is not an error — the account, region, and existence checks still run, then the empty merge no-ops — while a missing/empty `TagKeys` on `UntagResource` fails with a message-less `ValidationException` (AWS sends only the error-type header with an empty body; Floci's standard error body carries `"message": null`). A non-string tag `Key`/`Value` or a non-object `Tags` element is rejected with `SerializationException` rather than coerced, matching AWS's restJson1 deserializer. +ARN handling is otherwise uniform across the types (probe-confirmed against real AWS). A foreign account id fails first with `BadRequestException` ("Operations on a resource created in a different account is not allowed"). A region differing from the signing region fails `TagResource` / `UntagResource` with `BadRequestException` ("Failed to tag resource" / "Failed to untag resource"); `ListTagsForResource` instead checks existence in the signing region (`NotFoundException`, "No \ present with name: \") and keys tags by the literal ARN, so a mismatched-region ARN returns `200` with an empty tag set. An empty `Tags` array on `TagResource` is not an error (the account, region, and existence checks still run, then the empty merge no-ops), while a missing/empty `TagKeys` on `UntagResource` fails with a message-less `ValidationException` (AWS sends only the error-type header with an empty body; Floci's standard error body carries `"message": null`). A non-string tag `Key`/`Value` or a non-object `Tags` element is rejected with `SerializationException` rather than coerced, matching AWS's restJson1 deserializer. The same AWS-compatible validation applies wherever tags are set (including `CreateContactList` and `TagResource`): at most 50 tags, unique keys, keys 1–128 / values 0–256 code points, characters limited to letters, numbers, Unicode whitespace and `_ . : / = + - @`, and the reserved `aws:` key prefix. `TagResource` applies the 50-tag limit to the merged (existing + incoming) set. Violations return `BadRequestException` with AWS's messages. 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 9147b04efc..48596cb113 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 @@ -1988,6 +1988,7 @@ public class SesService { case "contact-list" -> contactService.listTags(ref.name(), region); case "custom-verification-email-template" -> cvetService.listTags(ref.name(), region); case "dedicated-ip-pool" -> dedicatedIpService.listTags(ref.name(), region); + case "tenant" -> listTenantTags(ref.name(), region); default -> throw new AwsException("NotFoundException", "Resource " + arn + " was not found.", 404); }; @@ -2018,6 +2019,7 @@ public class SesService { case "contact-list" -> contactService.tag(ref.name(), region, tags); case "custom-verification-email-template" -> cvetService.tag(ref.name(), region, tags); case "dedicated-ip-pool" -> dedicatedIpService.tag(ref.name(), region, tags); + case "tenant" -> tagTenant(ref.name(), region, tags); default -> throw new AwsException("NotFoundException", "Resource " + arn + " was not found.", 404); } @@ -2044,11 +2046,41 @@ public class SesService { case "contact-list" -> contactService.untag(ref.name(), region, tagKeys); case "custom-verification-email-template" -> cvetService.untag(ref.name(), region, tagKeys); case "dedicated-ip-pool" -> dedicatedIpService.untag(ref.name(), region, tagKeys); + case "tenant" -> untagTenant(ref.name(), region, tagKeys); default -> throw new AwsException("NotFoundException", "Resource " + arn + " was not found.", 404); } } + // A tenant tag ARN carries two path segments (tenant//), so parseSesArn's + // first-slash split leaves "/" as the resource name; the tenant domain owns + // that remainder's decomposition and the id-only resolution (see SesTenantService.TenantTagArn). + + private List listTenantTags(String resourceName, String region) { + Tenant tenant = tenantService.tenantForTagArn(resourceName, region); + // AWS returns a tenant's tags ordered by key (probe-confirmed). + return (tenant.tags() == null ? List.of() : tenant.tags()).stream() + .sorted(Comparator.comparing(Tag::key, Comparator.nullsLast(Comparator.naturalOrder()))) + .toList(); + } + + private void tagTenant(String resourceName, String region, List newTags) { + tenantService.mutateTags(resourceName, region, tags -> SesTags.merge(tags, newTags)); + LOG.infov("Tagged SES tenant <{0}> (region {1}, +{2} tags)", + resourceName, region, newTags.size()); + } + + private void untagTenant(String resourceName, String region, List tagKeys) { + Set toRemove = new HashSet<>(tagKeys); + tenantService.mutateTags(resourceName, region, tags -> { + List remaining = new ArrayList<>(tags); + remaining.removeIf(t -> toRemove.contains(t.key())); + return remaining; + }); + LOG.infov("Untagged SES tenant <{0}> (region {1}, -{2} keys)", + resourceName, region, tagKeys.size()); + } + private List listConfigurationSetTags(String name, String region) { ConfigurationSet cs = configSetService.find(name, region) .orElseThrow(() -> new AwsException("NotFoundException", diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java index b0c349bc59..7f0baa3c3e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java @@ -23,6 +23,7 @@ import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -175,6 +176,64 @@ public class SesTenantService { return tenantStore.get(tenantKey(region, tenantName)); } + /** + * Resolves a tenant by its TenantId, for the ARN-dispatched tag operations: AWS resolves a + * tenant tag ARN by the id segment alone; the name segment is not matched (probe-confirmed). + */ + public Optional findByTenantId(String tenantId, String region) { + String prefix = tenantKeyPrefix(region); + return tenantStore.scan(k -> k.startsWith(prefix)).stream() + .filter(t -> tenantId != null && tenantId.equals(t.tenantId())) + .findFirst(); + } + + /** + * The name/id decomposition of a tenant tag ARN's resource remainder ({@code /} + * after the generic dispatch split off the {@code tenant/} type segment). AWS parses a remainder + * without a slash as a null name with the whole segment as the id, and resolves by the id alone + * (probe-confirmed): tenant-domain knowledge, so it lives here, not in the tag dispatch. + */ + record TenantTagArn(String name, String tenantId) { + static TenantTagArn parse(String resourceRemainder) { + int slash = resourceRemainder.indexOf('/'); + return new TenantTagArn(slash < 0 ? null : resourceRemainder.substring(0, slash), + slash < 0 ? resourceRemainder : resourceRemainder.substring(slash + 1)); + } + } + + /** Resolves a tenant from a tag ARN's resource remainder, for the facade's tag listing. */ + public Tenant tenantForTagArn(String resourceRemainder, String region) { + TenantTagArn arn = TenantTagArn.parse(resourceRemainder); + return findByTenantId(arn.tenantId(), region) + .orElseThrow(() -> tagArnTenantNotFound(arn)); + } + + /** + * Applies a tag mutation for the facade's ARN-dispatched tagging. The tenant is re-resolved by + * TenantId and mutated INSIDE the shared lock, so concurrent tag calls can't lose each other's + * merges, a concurrent suppression-attribute update isn't overwritten by a stale copy, and a + * delete/recreate between the caller's lookup and this write can't resurrect the old record. + */ + public void mutateTags(String resourceRemainder, String region, UnaryOperator> mutation) { + TenantTagArn arn = TenantTagArn.parse(resourceRemainder); + synchronized (tenantMutationLock) { + Tenant current = findByTenantId(arn.tenantId(), region) + .orElseThrow(() -> tagArnTenantNotFound(arn)); + // The record's list may be a mutable one (Jackson-built); hand the callback an immutable + // copy so an in-place mutation can't reach the stored record, and store an immutable copy + // so the persisted list can't be aliased either. + List tags = current.tags() == null ? List.of() : List.copyOf(current.tags()); + tenantStore.put(tenantKey(region, current.tenantName()), + current.withTags(List.copyOf(mutation.apply(tags)))); + } + } + + /** The tag-dispatch not-found error: the missing space before "with" is AWS's own. */ + private static AwsException tagArnTenantNotFound(TenantTagArn arn) { + return new AwsException("NotFoundException", + "No Tenant present with name: " + arn.name() + "with tenantId: " + arn.tenantId(), 404); + } + // ──────────────────────── Resource associations (Phase 2) ──────────────────────── // Behavior and messages probe-confirmed against real AWS us-east-1, 2026-08-28. diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/Tenant.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/Tenant.java index 74067ebdb1..3927f4841e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/Tenant.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/Tenant.java @@ -19,6 +19,12 @@ public record Tenant(String tenantName, String sendingStatus, TenantSuppressionAttributes suppressionAttributes) { + /** Copy with different tags (records are immutable; the store is replace-only). */ + public Tenant withTags(List newTags) { + return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, newTags, sendingStatus, + suppressionAttributes); + } + /** Copy with different suppression attributes (records are immutable; the store is replace-only). */ public Tenant withSuppressionAttributes(TenantSuppressionAttributes attrs) { return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, sendingStatus, attrs); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java index f05348b6d9..a6d0504e4e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test; import java.security.SecureRandom; import java.time.Clock; +import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -139,6 +140,65 @@ class SesTenantServiceTest { assertThrows(AwsException.class, () -> service.deleteTenant(null, REGION)).getMessage()); } + @Test + void findByTenantId_matchesIdOnly_perRegion() { + Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION); + assertEquals("acme", service.findByTenantId(tenant.tenantId(), REGION).orElseThrow().tenantName()); + assertTrue(service.findByTenantId("tn-000000000000000000000000000000", REGION).isEmpty()); + assertTrue(service.findByTenantId(tenant.tenantId(), "eu-west-1").isEmpty()); + } + + @Test + void tenantForTagArn_resolvesByIdAlone_notFoundMessagesMatchAws() { + Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION); + // The name segment is never matched; only the id resolves. + assertEquals("acme", + service.tenantForTagArn("wrong-name/" + tenant.tenantId(), REGION).tenantName()); + // The missing space before "with" is AWS's own wording. + assertEquals("No Tenant present with name: acmewith tenantId: tn-0000", + assertThrows(AwsException.class, + () -> service.tenantForTagArn("acme/tn-0000", REGION)).getMessage()); + // A remainder without a slash parses as a null name with the segment as the id. + assertEquals("No Tenant present with name: nullwith tenantId: acme", + assertThrows(AwsException.class, + () -> service.tenantForTagArn("acme", REGION)).getMessage()); + } + + @Test + void mutateTags_appliesToCurrentRecordUnderLock() { + Tenant tenant = service.createTenant("acme", List.of(new Tag("team", "floci")), ACCOUNT, REGION); + service.mutateTags("acme/" + tenant.tenantId(), REGION, tags -> List.of(new Tag("env", "dev"))); + List tags = service.getTenant("acme", REGION).tags(); + assertEquals(1, tags.size()); + assertEquals("env", tags.get(0).key()); + + // A stale TenantId (delete/recreate happened since the caller's lookup) must not resurrect + // the old record: the mutation re-resolves by id under the lock and 404s. + service.deleteTenant("acme", REGION); + service.createTenant("acme", List.of(), ACCOUNT, REGION); + AwsException e = assertThrows(AwsException.class, () -> service.mutateTags( + "acme/" + tenant.tenantId(), REGION, current -> current)); + assertEquals("No Tenant present with name: acmewith tenantId: " + tenant.tenantId(), + e.getMessage()); + assertEquals(0, service.getTenant("acme", REGION).tags().size()); + } + + @Test + void mutateTags_shieldsTheStoredRecordFromCallbackMutation() { + Tenant tenant = service.createTenant("acme", + new ArrayList<>(List.of(new Tag("team", "floci"))), ACCOUNT, REGION); + // The callback gets an immutable copy: an in-place mutation fails fast instead of + // silently aliasing the stored record's list. + assertThrows(UnsupportedOperationException.class, () -> service.mutateTags( + "acme/" + tenant.tenantId(), REGION, tags -> { + tags.add(new Tag("env", "dev")); + return tags; + })); + List tags = service.getTenant("acme", REGION).tags(); + assertEquals(1, tags.size()); + assertEquals("team", tags.get(0).key()); + } + // ──────────────────────── Resource associations (Phase 2) ──────────────────────── private static SesTenantService.AssociationResource identityRef(String name) { diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantTagV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantTagV2IntegrationTest.java new file mode 100644 index 0000000000..8c0b7901b9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantTagV2IntegrationTest.java @@ -0,0 +1,160 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; + +/** + * Integration tests for the tag operations on TENANT ARNs (the follow-up gap noted on the tenant + * tracking issue). Probe-confirmed quirks: the ARN is resolved by the TenantId segment ALONE (the + * name segment is never matched), tags are TenantId-scoped (a recreated same-name tenant's old ARN + * 404s), the not-found message carries AWS's own missing space ("name: with tenantId:"), the + * tag list renders ordered by key, and the generic cross-account/cross-region tag semantics apply. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesTenantTagV2IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String TENANT = "floci-tag-tenant"; + private static final String ARN_PREFIX = "arn:aws:ses:us-east-1:000000000000:"; + + private static String tenantArn; + private static String tenantId; + + private static io.restassured.specification.RequestSpecification v2() { + return given().contentType("application/json").header("Authorization", AUTH); + } + + @Test + @Order(1) + void createTenantWithTags_visibleThroughListTagsForResource() { + JsonPath created = v2() + .body("{\"TenantName\":\"" + TENANT + "\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"floci\"}]}") + .when().post("/v2/email/tenants").then().statusCode(200) + .extract().jsonPath(); + tenantArn = created.getString("TenantArn"); + tenantId = created.getString("TenantId"); + + v2().when().get("/v2/email/tags?ResourceArn=" + tenantArn).then().statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("team")); + } + + @Test + @Order(2) + void tagUntag_lifecycle_sortedByKey_reflectsIntoGetTenant() { + v2().body("{\"ResourceArn\":\"" + tenantArn + "\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"dev\"}]}") + .when().post("/v2/email/tags").then().statusCode(200); + v2().when().get("/v2/email/tags?ResourceArn=" + tenantArn).then().statusCode(200) + .body("Tags", hasSize(2)) + // Ordered by key: env before team (probe-confirmed). + .body("Tags[0].Key", equalTo("env")) + .body("Tags[1].Key", equalTo("team")); + + // Re-tagging an existing key replaces its value. + v2().body("{\"ResourceArn\":\"" + tenantArn + "\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"prod\"}]}") + .when().post("/v2/email/tags").then().statusCode(200); + v2().when().get("/v2/email/tags?ResourceArn=" + tenantArn).then().statusCode(200) + .body("Tags[0].Value", equalTo("prod")); + + // Untag removes the key; a nonexistent key is a silent success. + v2().when().delete("/v2/email/tags?ResourceArn=" + tenantArn + "&TagKeys=env") + .then().statusCode(200); + v2().when().delete("/v2/email/tags?ResourceArn=" + tenantArn + "&TagKeys=ghost-key") + .then().statusCode(200); + + v2().body("{\"TenantName\":\"" + TENANT + "\"}") + .when().post("/v2/email/tenants/get").then().statusCode(200) + .body("Tenant.Tags", hasSize(1)) + .body("Tenant.Tags[0].Key", equalTo("team")); + } + + @Test + @Order(3) + void arnResolution_isByTenantIdAlone() { + // A wrong name with a valid id resolves that id's tenant. + v2().when().get("/v2/email/tags?ResourceArn=" + + ARN_PREFIX + "tenant/wrong-name/" + tenantId) + .then().statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("team")); + + // A valid name with a wrong id is a 404, with AWS's own missing space in the message. + v2().when().get("/v2/email/tags?ResourceArn=" + + ARN_PREFIX + "tenant/" + TENANT + "/tn-000000000000000000000000000000") + .then().statusCode(404) + .body("message", equalTo("No Tenant present with name: " + TENANT + + "with tenantId: tn-000000000000000000000000000000")); + + // An ARN without the id segment parses as a null name and the segment as the id. + v2().when().get("/v2/email/tags?ResourceArn=" + ARN_PREFIX + "tenant/" + TENANT) + .then().statusCode(404) + .body("message", equalTo("No Tenant present with name: nullwith tenantId: " + TENANT)); + } + + @Test + @Order(4) + void crossAccountAndCrossRegion_matchTheGenericTagSemantics() { + v2().when().get("/v2/email/tags?ResourceArn=" + + tenantArn.replace(":000000000000:", ":111111111111:")) + .then().statusCode(400) + .body("message", equalTo( + "Operations on a resource created in a different account is not allowed")); + + // Matches the observable behavior of the other taggable types: existence is checked against + // the signing region, then a mismatched-region ARN yields an empty tag set (for tenants the + // tags live on the tenant record itself; the empty result comes from the dispatch's + // explicit region comparison). + v2().when().get("/v2/email/tags?ResourceArn=" + + tenantArn.replace(":us-east-1:", ":eu-west-1:")) + .then().statusCode(200) + .body("Tags", hasSize(0)); + + // Tag and Untag take the generic pre-dispatch region guard instead: 400 with the same + // wording as the other six taggable types, probe-confirmed on a tenant ARN directly + // (the guard fires before any tenant resolution, so nothing is mutated). + String crossRegionArn = tenantArn.replace(":us-east-1:", ":eu-west-1:"); + v2().body("{\"ResourceArn\":\"" + crossRegionArn + + "\",\"Tags\":[{\"Key\":\"x\",\"Value\":\"y\"}]}") + .when().post("/v2/email/tags").then().statusCode(400) + .body("message", equalTo("Failed to tag resource")); + v2().when().delete("/v2/email/tags?ResourceArn=" + crossRegionArn + "&TagKeys=team") + .then().statusCode(400) + .body("message", equalTo("Failed to untag resource")); + + // The guarded calls left the tenant's tags untouched. + v2().when().get("/v2/email/tags?ResourceArn=" + tenantArn).then().statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("team")); + } + + @Test + @Order(5) + void tags_areTenantIdScoped_acrossRecreation() { + v2().body("{\"TenantName\":\"" + TENANT + "\"}") + .when().post("/v2/email/tenants/delete").then().statusCode(200); + v2().when().get("/v2/email/tags?ResourceArn=" + tenantArn).then().statusCode(404) + .body("message", equalTo("No Tenant present with name: " + TENANT + + "with tenantId: " + tenantId)); + + JsonPath recreated = v2().body("{\"TenantName\":\"" + TENANT + "\"}") + .when().post("/v2/email/tenants").then().statusCode(200) + .extract().jsonPath(); + v2().when().get("/v2/email/tags?ResourceArn=" + recreated.getString("TenantArn")) + .then().statusCode(200) + .body("Tags", hasSize(0)); + v2().when().get("/v2/email/tags?ResourceArn=" + tenantArn).then().statusCode(404); + + v2().body("{\"TenantName\":\"" + TENANT + "\"}") + .when().post("/v2/email/tenants/delete").then().statusCode(200); + } +}