From 09dcbabe2b5caae3ef74a6dac411abc0b36d279d Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Thu, 24 Sep 2026 18:51:09 -0600 Subject: [PATCH] feat(rds): manage event notification subscriptions (#4332) * feat(rds): manage event notification subscriptions CreateEventSubscription, DescribeEventSubscriptions, ModifyEventSubscription and DeleteEventSubscription were all missing, so the subscription resource could not be created. Constraints come from the model. A SubscriptionName under 255 characters, a required SnsTopicArn, SourceType limited to the documented valid values, and a SourceIds list that may only be supplied alongside the SourceType its ids belong to. An omitted Enabled activates the subscription, which the model describes only in the negative: a subscription that is not activated is created but not active. Modify applies only the members the request names. Nothing is published to the topic. A subscription is stored and reported back and no RDS event reaches SNS through it. The docs say so. * fix(rds): synchronize the event subscription methods and cite the SourceIds constraint createEventSubscription checked for a duplicate name and then stored, so two concurrent creates of the same name both passed the check and the second overwrote the first with neither caller seeing SubscriptionAlreadyExist. The four methods are synchronized now, matching the 48 other public synchronized methods in this file and the find-then-throw-then-store shape of createDbSnapshot. The comment on the SourceIds coupling said only that the model states it, which sent a reviewer to the operation documentation where it is absent. It now quotes the constraint and says it lives on CreateEventSubscriptionMessage.SourceIds rather than on the operation. * fix(rds): keep a rejected modify inert, carry subscription tags, and page the describe Four findings from the automated review, all confirmed against the model. ModifyEventSubscription wrote SnsTopicArn before validating SourceType, so a request carrying a new topic and an unmodelled source type answered 400 with the topic already changed. The store returns the live instance, so a later describe reported it. This is the same shape as the Lambda code signing bug in #4286 and I did not carry the lesson across. CreateEventSubscriptionMessage has a Tags member that was dropped on the floor, and resolveTagHandle had no arm for an es: ARN, so a subscription could neither be created with tags nor tagged afterwards. DescribeEventSubscriptionsMessage has MaxRecords and Marker, and its output shape has Marker. None were read or emitted, so a bounded page returned everything with no way to continue. The new test used var, which AGENTS.md prohibits, the same thing flagged on #4286. * fix(rds): bound MaxRecords and resume paging past a deleted marker Two defects I introduced in the pagination added last round. MaxRecords was unbounded. Zero built an empty page and then read its last element, throwing IndexOutOfBoundsException, and a negative value produced invalid bounds. The model documents minimum 20, maximum 100, default 100, and handleDescribeEvents a few hundred lines up already enforces that range. An omitted value now defaults to 100 rather than returning everything. The marker resumed by looking for its own name, so a subscription deleted between calls left the offset at zero and handed back the first page again. Resuming at the first name strictly greater than the marker is stable under deletion. The test used MaxRecords 1, a value the model rejects, so it exercised a page size real RDS never serves. It now creates 21 subscriptions and pages with 20. * fix(rds): validate MaxRecords before the named-subscription shortcut The range check sat after the early return for a named subscription, so a request naming one alongside an out-of-range MaxRecords succeeded. Request validation should not depend on which branch serves the read. --- docs/services/rds.md | 14 ++ .../floci/services/rds/RdsQueryHandler.java | 80 ++++++ .../floci/services/rds/RdsService.java | 170 +++++++++++++ .../services/rds/model/EventSubscription.java | 54 ++++ .../RdsEventSubscriptionIntegrationTest.java | 231 ++++++++++++++++++ 5 files changed, 549 insertions(+) create mode 100644 src/main/java/io/github/hectorvent/floci/services/rds/model/EventSubscription.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/rds/RdsEventSubscriptionIntegrationTest.java diff --git a/docs/services/rds.md b/docs/services/rds.md index 357335851c..1e6a724761 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -29,6 +29,10 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou | `PromoteReadReplicaDBCluster` | Refused with `InvalidDBClusterStateFault`: no cluster is created as a replica of an instance | | `DescribeOrderableDBInstanceOptions` | List deterministic instance class options | | `DescribeEvents` | - | +| `CreateEventSubscription` | Create an event notification subscription (stored, nothing is published) | +| `DescribeEventSubscriptions` | List subscriptions, or the one the request names | +| `ModifyEventSubscription` | Update the members the request names | +| `DeleteEventSubscription` | Delete a subscription | | `CreateDBSubnetGroup` | Create a DB subnet group; tags given here are readable through `ListTagsForResource` | | `DescribeDBSubnetGroups` | List DB subnet groups | | `ModifyDBSubnetGroup` | Update DB subnet group description and subnet list | @@ -135,6 +139,16 @@ checked against the instance's other window. Modifications apply immediately — `arn:aws:rds:::cluster-snapshot:`. RDS reserved instances aren't modeled (there's no reserved-instance API), so tagging doesn't apply to them. +## Event notification subscriptions + +The four subscription actions manage the resource itself. **Nothing is published to the topic.** +A subscription is stored and reported back so a client can manage it. No RDS event reaches SNS +through it, so an SNS subscriber sees nothing. + +`SnsTopicArn` is required and is not resolved against the SNS service. `SourceType` is checked +against the model's valid values, and a request naming `SourceIds` must also name the `SourceType` +they belong to, as the model requires. An omitted `Enabled` activates the subscription. + ## Configuration | Variable | Default | Description | diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java index 5b739a38fa..2807553467 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java @@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.rds.model.DbEndpoint; import io.github.hectorvent.floci.services.docdb.DocDbQueryHandler; import io.github.hectorvent.floci.services.neptune.NeptuneQueryHandler; import io.github.hectorvent.floci.services.rds.model.DbInstance; +import io.github.hectorvent.floci.services.rds.model.EventSubscription; import io.github.hectorvent.floci.services.rds.model.DbInstanceScalingChanges; import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings; import io.github.hectorvent.floci.services.rds.model.LogExportChanges; @@ -90,6 +91,10 @@ public class RdsQueryHandler { case "PromoteReadReplicaDBCluster" -> handlePromoteReadReplicaDbCluster(params, region); case "DescribeOrderableDBInstanceOptions" -> handleDescribeOrderableDbInstanceOptions(params); case "DescribeEvents" -> handleDescribeEvents(params, region); + case "CreateEventSubscription" -> handleCreateEventSubscription(params, region); + case "DescribeEventSubscriptions" -> handleDescribeEventSubscriptions(params, region); + case "ModifyEventSubscription" -> handleModifyEventSubscription(params, region); + case "DeleteEventSubscription" -> handleDeleteEventSubscription(params, region); case "CreateDBSubnetGroup" -> handleCreateDbSubnetGroup(params, region); case "DescribeDBSubnetGroups" -> handleDescribeDbSubnetGroups(params, region); case "ModifyDBSubnetGroup" -> handleModifyDbSubnetGroup(params, region); @@ -277,6 +282,81 @@ public class RdsQueryHandler { } } + // ── Event notification subscriptions ──────────────────────────────────── + + private Response handleCreateEventSubscription(MultivaluedMap params, String region) { + EventSubscription subscription = service.createEventSubscription(region, + params.getFirst("SubscriptionName"), + params.getFirst("SnsTopicArn"), + params.getFirst("SourceType"), + memberList(params, "SourceIds"), + memberList(params, "EventCategories"), + optionalBoolean(params.getFirst("Enabled")), + parseTags(params)); + return Response.ok(AwsQueryResponse.envelope("CreateEventSubscription", AwsNamespaces.RDS, + new XmlBuilder().raw(eventSubscriptionXml(subscription)).build())).build(); + } + + private Response handleModifyEventSubscription(MultivaluedMap params, String region) { + EventSubscription subscription = service.modifyEventSubscription(region, + params.getFirst("SubscriptionName"), + params.getFirst("SnsTopicArn"), + params.getFirst("SourceType"), + memberList(params, "EventCategories"), + optionalBoolean(params.getFirst("Enabled"))); + return Response.ok(AwsQueryResponse.envelope("ModifyEventSubscription", AwsNamespaces.RDS, + new XmlBuilder().raw(eventSubscriptionXml(subscription)).build())).build(); + } + + private Response handleDeleteEventSubscription(MultivaluedMap params, String region) { + EventSubscription subscription = service.deleteEventSubscription(region, + params.getFirst("SubscriptionName")); + return Response.ok(AwsQueryResponse.envelope("DeleteEventSubscription", AwsNamespaces.RDS, + new XmlBuilder().raw(eventSubscriptionXml(subscription)).build())).build(); + } + + private Response handleDescribeEventSubscriptions(MultivaluedMap params, String region) { + RdsService.EventSubscriptionPage page = service.describeEventSubscriptions(region, + params.getFirst("SubscriptionName"), + optionalInt(params.getFirst("MaxRecords")), + params.getFirst("Marker")); + XmlBuilder xml = new XmlBuilder().start("EventSubscriptionsList"); + for (EventSubscription subscription : page.subscriptions()) { + xml.raw(eventSubscriptionXml(subscription)); + } + xml.end("EventSubscriptionsList"); + if (page.marker() != null) { + xml.elem("Marker", page.marker()); + } + return Response.ok(AwsQueryResponse.envelope("DescribeEventSubscriptions", AwsNamespaces.RDS, + xml.build())).build(); + } + + private static String eventSubscriptionXml(EventSubscription s) { + XmlBuilder xml = new XmlBuilder().start("EventSubscription") + .elem("CustomerAwsId", s.getCustomerAwsId()) + .elem("CustSubscriptionId", s.getCustSubscriptionId()) + .elem("SnsTopicArn", s.getSnsTopicArn()) + .elem("Status", s.getStatus()) + .elem("SubscriptionCreationTime", s.getSubscriptionCreationTime()) + .elem("Enabled", String.valueOf(s.isEnabled())) + .elem("EventSubscriptionArn", s.getEventSubscriptionArn()); + if (s.getSourceType() != null) { + xml.elem("SourceType", s.getSourceType()); + } + xml.start("SourceIdsList"); + for (String id : s.getSourceIdsList()) { + xml.elem("SourceId", id); + } + xml.end("SourceIdsList"); + xml.start("EventCategoriesList"); + for (String category : s.getEventCategoriesList()) { + xml.elem("EventCategory", category); + } + xml.end("EventCategoriesList"); + return xml.end("EventSubscription").build(); + } + private Response handleDescribeEvents(MultivaluedMap params, String region) { String sourceIdentifier = params.getFirst("SourceIdentifier"); String sourceType = params.getFirst("SourceType"); diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 7424bbbcce..65dbbfe465 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -35,6 +35,7 @@ import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup; import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot; import io.github.hectorvent.floci.services.rds.model.DbEndpoint; import io.github.hectorvent.floci.services.rds.model.DbInstance; +import io.github.hectorvent.floci.services.rds.model.EventSubscription; import io.github.hectorvent.floci.services.kms.KmsService; import io.github.hectorvent.floci.services.kms.model.KmsKey; import io.github.hectorvent.floci.services.rds.model.DbInstanceScalingChanges; @@ -167,6 +168,7 @@ public class RdsService implements Resettable, ResourceProvider { private final StorageBackend globalClusters; private final StorageBackend snapshotData; private StorageBackend events = new InMemoryStorage<>(); + private final StorageBackend eventSubscriptions; private final RdsContainerManager containerManager; private final RdsProxyManager proxyManager; // CreateDBCluster/CreateDBInstance register the new resource only after the @@ -237,6 +239,8 @@ public class RdsService implements Resettable, ResourceProvider { this.metricsService = metricsService; this.instances = storageFactory.create("rds", "rds-instances.json", new TypeReference>() {}); + this.eventSubscriptions = storageFactory.create("rds", "rds-event-subscriptions.json", + new TypeReference>() {}); this.clusters = storageFactory.create("rds", "rds-clusters.json", new TypeReference>() {}); this.parameterGroups = storageFactory.create("rds", "rds-parameter-groups.json", @@ -397,6 +401,7 @@ public class RdsService implements Resettable, ResourceProvider { this.snapshots = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(); this.clusterSnapshots = new InMemoryStorage<>(); this.snapshotData = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(); + this.eventSubscriptions = new InMemoryStorage<>(); } public void restorePersistedRuntime() { @@ -1960,6 +1965,16 @@ public class RdsService implements Resettable, ResourceProvider { putSnapshotForScope(currentAccountId(), effectiveRegion, resourceId, snapshot); }); } + case "es" -> { + EventSubscription subscription = eventSubscriptions + .get(eventSubscriptionKey(effectiveRegion, resourceId)) + .orElseThrow(() -> new AwsException("SubscriptionNotFound", + "Subscription " + resourceId + " not found.", 404)); + yield new TagHandle(subscription.getTags(), updated -> { + subscription.setTags(updated); + eventSubscriptions.put(eventSubscriptionKey(effectiveRegion, resourceId), subscription); + }); + } case "db-proxy" -> { DbProxy proxy = proxies.scan(k -> true).stream() .filter(candidate -> effectiveRegion.equals(regionFromArn(candidate.getDbProxyArn()))) @@ -8473,4 +8488,159 @@ public class RdsService implements Resettable, ResourceProvider { new SupportedResourceType("rds:db", "rds", true), new SupportedResourceType("rds:cluster", "rds", true)); } + // ── Event notification subscriptions ──────────────────────────────────── + + /** The model's SourceType valid values. */ + private static final Set EVENT_SOURCE_TYPES = Set.of( + "db-instance", "db-cluster", "db-parameter-group", "db-security-group", "db-snapshot", + "db-cluster-snapshot", "db-proxy", "zero-etl", "custom-engine-version", + "blue-green-deployment"); + private static final int MAX_SUBSCRIPTION_NAME = 255; + /** The model documents MaxRecords as minimum 20, maximum 100, default 100. */ + private static final int MIN_MAX_RECORDS = 20; + private static final int MAX_MAX_RECORDS = 100; + private static final int DEFAULT_MAX_RECORDS = 100; + + /** + * Nothing is published to the topic. The subscription is stored and reported back so a client + * can manage it, and no RDS event reaches SNS through it. + */ + public synchronized EventSubscription createEventSubscription(String region, String subscriptionName, + String snsTopicArn, String sourceType, + List sourceIds, + List eventCategories, Boolean enabled, + Map tags) { + if (subscriptionName == null || subscriptionName.isBlank()) { + throw new AwsException("InvalidParameterValue", "SubscriptionName is required.", 400); + } + if (subscriptionName.length() >= MAX_SUBSCRIPTION_NAME) { + throw new AwsException("InvalidParameterValue", + "SubscriptionName must be less than " + MAX_SUBSCRIPTION_NAME + " characters.", 400); + } + if (snsTopicArn == null || snsTopicArn.isBlank()) { + throw new AwsException("SNSTopicArnNotFound", + "SnsTopicArn is required and must name an existing topic.", 404); + } + if (sourceType != null && !EVENT_SOURCE_TYPES.contains(sourceType)) { + throw new AwsException("InvalidParameterValue", + "SourceType must be one of " + EVENT_SOURCE_TYPES + ".", 400); + } + // CreateEventSubscriptionMessage.SourceIds carries the coupling in its own member + // documentation, not in the operation's: "Constraints: If SourceIds are supplied, + // SourceType must also be provided." The operation docs walk through both specified, + // SourceType alone, and neither, and never mention SourceIds alone, so the member doc is + // the only place it is stated. + if (sourceIds != null && !sourceIds.isEmpty() && (sourceType == null || sourceType.isBlank())) { + throw new AwsException("InvalidParameterCombination", + "SourceType must be provided when SourceIds are supplied.", 400); + } + String key = eventSubscriptionKey(region, subscriptionName); + if (eventSubscriptions.get(key).isPresent()) { + throw new AwsException("SubscriptionAlreadyExist", + "Subscription " + subscriptionName + " already exists.", 400); + } + String accountId = regionResolver.getAccountId(); + EventSubscription subscription = new EventSubscription(); + subscription.setCustomerAwsId(accountId); + subscription.setCustSubscriptionId(subscriptionName); + subscription.setSnsTopicArn(snsTopicArn); + subscription.setStatus("active"); + subscription.setSubscriptionCreationTime(Instant.now().toString()); + subscription.setSourceType(sourceType); + subscription.setSourceIdsList(sourceIds == null ? new ArrayList<>() : new ArrayList<>(sourceIds)); + subscription.setEventCategoriesList( + eventCategories == null ? new ArrayList<>() : new ArrayList<>(eventCategories)); + // The model documents the subscription as created but inactive when Enabled is false, and + // says nothing about a default, so an omitted Enabled activates it as the console does. + subscription.setEnabled(enabled == null || enabled); + subscription.setEventSubscriptionArn(AwsArnUtils.Arn.of("rds", region, accountId, + "es:" + subscriptionName).toString()); + subscription.setTags(tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags)); + eventSubscriptions.put(key, subscription); + return subscription; + } + + /** ModifyEventSubscription applies only the members the request names. */ + public synchronized EventSubscription modifyEventSubscription(String region, String subscriptionName, + String snsTopicArn, String sourceType, + List eventCategories, Boolean enabled) { + EventSubscription subscription = requireEventSubscription(region, subscriptionName); + // Validated before anything is applied. The store hands back the live instance, so setting + // the topic first would leave it written when a later member is rejected, and a describe + // would report a change the request was answered 400 for. + if (sourceType != null && !sourceType.isBlank() && !EVENT_SOURCE_TYPES.contains(sourceType)) { + throw new AwsException("InvalidParameterValue", + "SourceType must be one of " + EVENT_SOURCE_TYPES + ".", 400); + } + if (snsTopicArn != null && !snsTopicArn.isBlank()) { + subscription.setSnsTopicArn(snsTopicArn); + } + if (sourceType != null && !sourceType.isBlank()) { + subscription.setSourceType(sourceType); + } + if (eventCategories != null && !eventCategories.isEmpty()) { + subscription.setEventCategoriesList(new ArrayList<>(eventCategories)); + } + if (enabled != null) { + subscription.setEnabled(enabled); + } + eventSubscriptions.put(eventSubscriptionKey(region, subscriptionName), subscription); + return subscription; + } + + public synchronized EventSubscription deleteEventSubscription(String region, String subscriptionName) { + EventSubscription subscription = requireEventSubscription(region, subscriptionName); + eventSubscriptions.delete(eventSubscriptionKey(region, subscriptionName)); + return subscription; + } + + /** Every subscription in the region, or the one the request names. */ + /** One page of subscriptions, plus the marker to continue from, or null at the end. */ + public record EventSubscriptionPage(List subscriptions, String marker) {} + + public synchronized EventSubscriptionPage describeEventSubscriptions( + String region, String subscriptionName, Integer maxRecords, String marker) { + // Ahead of the named-subscription shortcut, so a bad page size is rejected whether or not + // the request also names a subscription. Request validation does not depend on which branch + // serves the read. + if (maxRecords != null && (maxRecords < MIN_MAX_RECORDS || maxRecords > MAX_MAX_RECORDS)) { + throw new AwsException("InvalidParameterValue", + "MaxRecords must be between " + MIN_MAX_RECORDS + " and " + MAX_MAX_RECORDS + ".", 400); + } + if (subscriptionName != null && !subscriptionName.isBlank()) { + return new EventSubscriptionPage( + List.of(requireEventSubscription(region, subscriptionName)), null); + } + String prefix = eventSubscriptionKey(region, ""); + List all = eventSubscriptions.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(EventSubscription::getCustSubscriptionId)) + .toList(); + // The marker is the last name of the previous page and the next page starts after it. + // Resuming at the first name strictly greater than the marker rather than at the marker's + // own index means a subscription deleted between calls does not restart the walk, which an + // exact-match lookup would do by silently leaving the offset at zero. + int from = 0; + if (marker != null && !marker.isBlank()) { + while (from < all.size() && all.get(from).getCustSubscriptionId().compareTo(marker) <= 0) { + from++; + } + } + int limit = maxRecords == null ? DEFAULT_MAX_RECORDS : maxRecords; + int to = Math.min(all.size(), from + limit); + List page = all.subList(Math.min(from, all.size()), to); + String next = to < all.size() && !page.isEmpty() + ? page.get(page.size() - 1).getCustSubscriptionId() : null; + return new EventSubscriptionPage(page, next); + } + + private EventSubscription requireEventSubscription(String region, String subscriptionName) { + return eventSubscriptions.get(eventSubscriptionKey(region, subscriptionName)) + .orElseThrow(() -> new AwsException("SubscriptionNotFound", + "Subscription " + subscriptionName + " not found.", 404)); + } + + private static String eventSubscriptionKey(String region, String subscriptionName) { + return "es::" + region + "::" + subscriptionName; + } + } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/EventSubscription.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/EventSubscription.java new file mode 100644 index 0000000000..aad0585cd7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/EventSubscription.java @@ -0,0 +1,54 @@ +package io.github.hectorvent.floci.services.rds.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** An RDS event notification subscription, as DescribeEventSubscriptions reports it. */ +@RegisterForReflection +public class EventSubscription { + + private String customerAwsId; + private String custSubscriptionId; + private String snsTopicArn; + private String status; + private String subscriptionCreationTime; + private String sourceType; + private List sourceIdsList = new ArrayList<>(); + private List eventCategoriesList = new ArrayList<>(); + private boolean enabled; + private String eventSubscriptionArn; + private Map tags = new LinkedHashMap<>(); + + public String getCustomerAwsId() { return customerAwsId; } + public void setCustomerAwsId(String customerAwsId) { this.customerAwsId = customerAwsId; } + public String getCustSubscriptionId() { return custSubscriptionId; } + public void setCustSubscriptionId(String custSubscriptionId) { this.custSubscriptionId = custSubscriptionId; } + public String getSnsTopicArn() { return snsTopicArn; } + public void setSnsTopicArn(String snsTopicArn) { this.snsTopicArn = snsTopicArn; } + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + public String getSubscriptionCreationTime() { return subscriptionCreationTime; } + public void setSubscriptionCreationTime(String subscriptionCreationTime) { + this.subscriptionCreationTime = subscriptionCreationTime; + } + public String getSourceType() { return sourceType; } + public void setSourceType(String sourceType) { this.sourceType = sourceType; } + public List getSourceIdsList() { return sourceIdsList; } + public void setSourceIdsList(List sourceIdsList) { this.sourceIdsList = sourceIdsList; } + public List getEventCategoriesList() { return eventCategoriesList; } + public void setEventCategoriesList(List eventCategoriesList) { + this.eventCategoriesList = eventCategoriesList; + } + public boolean isEnabled() { return enabled; } + public void setEnabled(boolean enabled) { this.enabled = enabled; } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } + public String getEventSubscriptionArn() { return eventSubscriptionArn; } + public void setEventSubscriptionArn(String eventSubscriptionArn) { + this.eventSubscriptionArn = eventSubscriptionArn; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsEventSubscriptionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsEventSubscriptionIntegrationTest.java new file mode 100644 index 0000000000..6bd1cccd26 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsEventSubscriptionIntegrationTest.java @@ -0,0 +1,231 @@ +package io.github.hectorvent.floci.services.rds; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** Create, Describe, Modify and Delete for an RDS event notification subscription. */ +@QuarkusTest +class RdsEventSubscriptionIntegrationTest { + + private static final String TOPIC = "arn:aws:sns:us-east-1:000000000000:rds-events"; + + private static ValidatableResponse rds(String action, String... formParams) { + RequestSpecification request = given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260615/us-east-1/rds/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test") + .contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("Version", "2014-10-31"); + for (int i = 0; i < formParams.length; i += 2) { + request = request.formParam(formParams[i], formParams[i + 1]); + } + return request.when().post("/").then(); + } + + private static String name(String prefix) { + return prefix + "-" + Long.toString(System.nanoTime(), 36); + } + + @Test + void createDescribeModifyAndDelete() { + String subscription = name("sub"); + rds("CreateEventSubscription", + "SubscriptionName", subscription, + "SnsTopicArn", TOPIC, + "SourceType", "db-instance", + "SourceIds.member.1", "db-one", + "EventCategories.member.1", "availability") + .statusCode(200) + .body("CreateEventSubscriptionResponse.CreateEventSubscriptionResult.EventSubscription.CustSubscriptionId", + equalTo(subscription)) + .body("CreateEventSubscriptionResponse.CreateEventSubscriptionResult.EventSubscription.Status", + equalTo("active")) + .body("CreateEventSubscriptionResponse.CreateEventSubscriptionResult.EventSubscription.Enabled", + equalTo("true")) + .body("CreateEventSubscriptionResponse.CreateEventSubscriptionResult.EventSubscription.SourceIdsList.SourceId", + equalTo("db-one")) + .body("CreateEventSubscriptionResponse.CreateEventSubscriptionResult.EventSubscription.EventSubscriptionArn", + containsString(":es:" + subscription)); + + rds("DescribeEventSubscriptions", "SubscriptionName", subscription) + .statusCode(200) + .body(containsString("" + subscription + "")); + + rds("ModifyEventSubscription", "SubscriptionName", subscription, "Enabled", "false") + .statusCode(200) + .body("ModifyEventSubscriptionResponse.ModifyEventSubscriptionResult.EventSubscription.Enabled", + equalTo("false")) + // SourceType was not named, so it survives the modify. + .body("ModifyEventSubscriptionResponse.ModifyEventSubscriptionResult.EventSubscription.SourceType", + equalTo("db-instance")); + + rds("DeleteEventSubscription", "SubscriptionName", subscription).statusCode(200); + rds("DescribeEventSubscriptions", "SubscriptionName", subscription).statusCode(404); + } + + @Test + void aRejectedModifyChangesNothing() { + String subscription = name("atomic"); + rds("CreateEventSubscription", "SubscriptionName", subscription, "SnsTopicArn", TOPIC, + "SourceType", "db-instance").statusCode(200); + + // Valid SnsTopicArn, invalid SourceType. The topic must not survive the 400. + rds("ModifyEventSubscription", "SubscriptionName", subscription, + "SnsTopicArn", "arn:aws:sns:us-east-1:000000000000:other", "SourceType", "db-widget") + .statusCode(400); + + rds("DescribeEventSubscriptions", "SubscriptionName", subscription) + .statusCode(200) + .body(containsString("" + TOPIC + "")) + .body(not(containsString("rds-events-other"))); + } + + @Test + void tagsGivenAtCreateAreReadableThroughListTagsForResource() { + String subscription = name("tagged"); + String arn = rds("CreateEventSubscription", "SubscriptionName", subscription, + "SnsTopicArn", TOPIC, "Tags.Tag.1.Key", "team", "Tags.Tag.1.Value", "platform") + .statusCode(200) + .extract().path("CreateEventSubscriptionResponse.CreateEventSubscriptionResult" + + ".EventSubscription.EventSubscriptionArn"); + + rds("ListTagsForResource", "ResourceName", arn) + .statusCode(200) + .body(containsString("team")) + .body(containsString("platform")); + } + + @Test + void describeHonoursMaxRecordsAndMarker() { + // The model bounds MaxRecords at 20, so a meaningful page needs more than 20 rows. + String prefix = "page-" + Long.toString(System.nanoTime(), 36); + for (int i = 0; i < 21; i++) { + rds("CreateEventSubscription", "SubscriptionName", String.format("%s-%02d", prefix, i), + "SnsTopicArn", TOPIC).statusCode(200); + } + + String marker = rds("DescribeEventSubscriptions", "MaxRecords", "20") + .statusCode(200) + .extract().path("DescribeEventSubscriptionsResponse" + + ".DescribeEventSubscriptionsResult.Marker"); + assertNotNull(marker, "a bounded page short of the end carries a Marker"); + + rds("DescribeEventSubscriptions", "MaxRecords", "20", "Marker", marker) + .statusCode(200) + .body(not(containsString("" + marker + ""))); + } + + @Test + void anOutOfRangeMaxRecordsIsRefused() { + // 0 used to build an empty page and then read its last element. + rds("DescribeEventSubscriptions", "MaxRecords", "0").statusCode(400) + .body(containsString("InvalidParameterValue")); + rds("DescribeEventSubscriptions", "MaxRecords", "-5").statusCode(400); + rds("DescribeEventSubscriptions", "MaxRecords", "19").statusCode(400); + rds("DescribeEventSubscriptions", "MaxRecords", "101").statusCode(400); + rds("DescribeEventSubscriptions", "MaxRecords", "20").statusCode(200); + } + + @Test + void anOutOfRangeMaxRecordsIsRefusedEvenWhenASubscriptionIsNamed() { + String subscription = name("named"); + rds("CreateEventSubscription", "SubscriptionName", subscription, "SnsTopicArn", TOPIC) + .statusCode(200); + + // The named-subscription read used to return before the page size was looked at. + rds("DescribeEventSubscriptions", "SubscriptionName", subscription, "MaxRecords", "0") + .statusCode(400) + .body(containsString("InvalidParameterValue")); + rds("DescribeEventSubscriptions", "SubscriptionName", subscription, "MaxRecords", "20") + .statusCode(200); + } + + @Test + void aMarkerWhoseSubscriptionIsGoneDoesNotRestartTheWalk() { + String prefix = "gone-" + Long.toString(System.nanoTime(), 36); + for (int i = 0; i < 21; i++) { + rds("CreateEventSubscription", "SubscriptionName", String.format("%s-%02d", prefix, i), + "SnsTopicArn", TOPIC).statusCode(200); + } + String marker = rds("DescribeEventSubscriptions", "MaxRecords", "20") + .statusCode(200) + .extract().path("DescribeEventSubscriptionsResponse" + + ".DescribeEventSubscriptionsResult.Marker"); + assertNotNull(marker); + + rds("DeleteEventSubscription", "SubscriptionName", marker).statusCode(200); + + // Resuming from a name that no longer exists must not hand back the first page again. + rds("DescribeEventSubscriptions", "MaxRecords", "20", "Marker", marker) + .statusCode(200) + .body(not(containsString("" + prefix + "-00"))); + } + + @Test + void sourceIdsWithoutASourceTypeIsRefused() { + rds("CreateEventSubscription", + "SubscriptionName", name("nosrctype"), + "SnsTopicArn", TOPIC, + "SourceIds.member.1", "db-one") + .statusCode(400) + .body(containsString("InvalidParameterCombination")); + } + + @Test + void anUnmodelledSourceTypeIsRefused() { + rds("CreateEventSubscription", + "SubscriptionName", name("badtype"), + "SnsTopicArn", TOPIC, + "SourceType", "db-widget") + .statusCode(400) + .body(containsString("InvalidParameterValue")); + } + + @Test + void aMissingTopicArnIsRefusedAndASecondCreateClashes() { + rds("CreateEventSubscription", "SubscriptionName", name("notopic")) + .statusCode(404) + .body(containsString("SNSTopicArnNotFound")); + + String subscription = name("dup"); + rds("CreateEventSubscription", "SubscriptionName", subscription, "SnsTopicArn", TOPIC) + .statusCode(200); + rds("CreateEventSubscription", "SubscriptionName", subscription, "SnsTopicArn", TOPIC) + .statusCode(400) + .body(containsString("SubscriptionAlreadyExist")); + } + + @Test + void describeWithNoNameListsThemAndAnUnknownNameIsNotFound() { + String subscription = name("listed"); + rds("CreateEventSubscription", "SubscriptionName", subscription, "SnsTopicArn", TOPIC) + .statusCode(200); + + rds("DescribeEventSubscriptions") + .statusCode(200) + .body(containsString("" + subscription + "")); + + rds("DescribeEventSubscriptions", "SubscriptionName", "no-such-subscription") + .statusCode(404) + .body(containsString("SubscriptionNotFound")); + } + + @Test + void anInactiveSubscriptionIsCreatedButNotActive() { + String subscription = name("off"); + rds("CreateEventSubscription", + "SubscriptionName", subscription, "SnsTopicArn", TOPIC, "Enabled", "false") + .statusCode(200) + .body("CreateEventSubscriptionResponse.CreateEventSubscriptionResult.EventSubscription.Enabled", + equalTo("false")) + .body(not(containsString("true"))); + } +}