diff --git a/README.md b/README.md index f0ddd5db07..ccde986927 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ LocalStack's community edition [sunset in March 2026](https://blog.localstack.cl | CodeBuild | Real Docker execution | No | | Native binary | ~40 MB | No | -**81 AWS services. Broad coverage. Free forever.** +**82 AWS services. Broad coverage. Free forever.** ## Architecture Overview diff --git a/docs/index.md b/docs/index.md index 23721fe2d6..df9cbbf53c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve ## Supported Services -Floci emulates 81 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details. +Floci emulates 82 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details. | Service | Protocol | |---|---| @@ -117,7 +117,7 @@ docker compose up -d aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket ``` -All 81 AWS services are immediately available at `http://localhost:4566`. +All 82 AWS services are immediately available at `http://localhost:4566`. [Get started →](getting-started/quick-start.md){ .md-button .md-button--primary } [View services →](services/index.md){ .md-button } diff --git a/docs/services/index.md b/docs/services/index.md index d270cbbea6..fcd51a7fda 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -1,6 +1,6 @@ # Services Overview -Floci emulates 81 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification. +Floci emulates 82 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification. This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table. @@ -94,6 +94,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 | | [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 | | [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 17 | +| [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 18 | | [Cloud Map](cloudmap.md) | `POST /` + `X-Amz-Target: Route53AutoNaming_v20170314.*` | JSON 1.1 | 22 | | [AWS Config](config.md) | `POST /` + `X-Amz-Target: StarlingDoveService.*` | JSON 1.1 | 20 | | [CloudTrail](cloudtrail.md) | `POST /` + `X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.*` | JSON 1.1 | 9 | diff --git a/docs/services/route53resolver.md b/docs/services/route53resolver.md new file mode 100644 index 0000000000..d1b9fc236c --- /dev/null +++ b/docs/services/route53resolver.md @@ -0,0 +1,96 @@ +# Route 53 Resolver + +## Supported Actions + + +| Action | Description | +| --- | --- | +| `ListFirewallDomainLists` | Lists all DNS Firewall domain lists, including the four AWS-managed lists computed per region. | +| `GetFirewallDomainList` | Returns a single DNS Firewall domain list by id, whether AWS-managed or custom. | +| `CreateFirewallDomainList` | Creates a custom DNS Firewall domain list with a random-suffix `rslvr-fdl-` id. | +| `DeleteFirewallDomainList` | Deletes a custom DNS Firewall domain list; AWS-managed lists cannot be deleted. | +| `CreateResolverEndpoint` | Creates an inbound (`rslvr-in-`) or outbound (`rslvr-out-`) resolver endpoint, returned immediately as `OPERATIONAL`. | +| `DeleteResolverEndpoint` | Deletes a resolver endpoint and returns its final description. | +| `GetResolverEndpoint` | Returns a resolver endpoint by id. | +| `ListResolverEndpoints` | Lists all resolver endpoints. | +| `UpdateResolverEndpoint` | Updates a resolver endpoint's `Name` and `ResolverEndpointType`; `IpAddresses` changes are not modelled. | +| `CreateResolverRule` | Creates a resolver rule, returned immediately as `COMPLETE`; `ResolverEndpointId` is not validated against an existing endpoint. | +| `DeleteResolverRule` | Deletes a resolver rule and returns its final description. | +| `GetResolverRule` | Returns a resolver rule by id. | +| `ListResolverRules` | Lists all resolver rules. | +| `UpdateResolverRule` | Updates a resolver rule's mutable configuration. | +| `AssociateResolverRule` | Associates a resolver rule with a VPC, returned immediately as `COMPLETE`. | +| `DisassociateResolverRule` | Removes the association between a resolver rule and a VPC. | +| `GetResolverRuleAssociation` | Returns a resolver rule association by id. | +| `ListResolverRuleAssociations` | Lists all resolver rule associations. | + + +## Design notes + +The four AWS-managed DNS Firewall domain lists (`AWSManagedDomainsAggregateThreatList` +and friends) are computed on every call from a fixed name list, with ids derived +deterministically from region+name (SHA-256 based) rather than stored — LZA's +`Custom::ResolverManagedDomainList` Lambda resolves a managed list's Id by Name and +needs it present and stable without any create call. This logic predates the rest of +this service and is untouched. + +Everything else (custom firewall domain lists, resolver endpoints, resolver rules, +rule associations) is backed by real per-service storage, added this session. Ids use +the project's standard random-suffix convention (`rslvr-fdl-...`, `rslvr-in-...` / +`rslvr-out-...`, `rslvr-rr-...`, `rslvr-rrassoc-...`), distinct from the deterministic +managed-list ids. Resolver endpoint ids are direction-aware as in AWS: `rslvr-in-` for +`INBOUND` (and `INBOUND_DELEGATION`), `rslvr-out-` for `OUTBOUND`. Any other `Direction` +is rejected with `InvalidParameterException`. + +Parameter rejections use the error code the operation actually models, which differs by +family: the resolver endpoint, rule and association operations model the singular +`InvalidParameterException`, while the DNS Firewall operations model `ValidationException` +and do not list `InvalidParameterException` at all. + +`CreateFirewallDomainList`, `CreateResolverEndpoint` and `CreateResolverRule` are +idempotent on `CreatorRequestId`, as they are in real AWS: replaying a token returns the +resource it originally created instead of allocating a second one. The check runs after +the request's own validation, so a replayed token never excuses a malformed body. A +request without a `CreatorRequestId` opts out and always allocates a new resource. +Idempotency is scoped per account and per region, matching this regional service: the same +token replayed in another region creates that region's own resource rather than handing +back the first region's. + +A token replayed with *different* parameters is a conflict, not a retry: +`CreateResolverEndpoint` and `CreateResolverRule` compare the retry against the stored +resource and raise `ResourceExistsException`, which both operations model. +`CreateFirewallDomainList` is the deliberate exception — it models no conflict error at +all, so a mismatched retry still returns the original list rather than an invented error +code. See `issues/route53resolver-firewall-domain-list-retry-conflict.md`. + +For `CreateResolverEndpoint` the comparison covers the actual `IpAddressRequests` entries, +not just how many there are, so a retry that keeps the count but changes a subnet or +address is a conflict. Order is not significant. The modelled `ResolverEndpoint` shape has +`IpAddressCount` and no IP list, so the addresses are recorded in a side store rather than +on the resource and never reach the response. If that record is ever missing for a stored +endpoint, the retry is reported as a conflict rather than compared on count alone — with +nothing to compare against, sameness cannot be established, and a loud error is preferable +to a success that may not match the request. + +## Limitations + +- **All create/update operations complete synchronously.** Real AWS transitions a + resolver endpoint through `CREATING`, a resolver rule through its own provisioning + states, before reaching a terminal status. This emulator returns the terminal state + (`OPERATIONAL` for endpoints, `COMPLETE` for rules and associations) immediately — + matching the "validate-and-echo" convention used elsewhere in this codebase (see + `ServiceCatalogService.copyProduct`, `CS-021`). +- **`UpdateResolverEndpoint` only applies `Name` and `ResolverEndpointType`.** Real AWS + additionally allows updating `IpAddresses` (adding/removing resolver IPs); that is not + modelled. +- **`CreateResolverRule`/`UpdateResolverRule` do not validate `ResolverEndpointId` + against an existing endpoint.** Any non-blank string is accepted. +- **No VPC-scoping or region-scoping is enforced for custom resources.** The four + stores go through `StorageFactory`, so every key is prefixed with the calling + credential's account id and custom resources *are* isolated per account: one account + cannot read, update or delete another's endpoints, rules, associations or domain + lists. Neither region nor VPC is part of the key, though, so a custom resource created + in one region is visible from every other, and `VPCId` on an association is stored but + never used to filter. The AWS-managed domain lists are the deliberate exception: they + are derived per region from the name list rather than stored, so they are region-scoped + and visible to every caller, as they are in AWS. diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 97ab787754..f5b5405acf 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -672,6 +672,7 @@ public interface EmulatorConfig { RumServiceConfig rum(); GuardDutyServiceConfig guardduty(); EmrServerlessServiceConfig emrserverless(); + Route53ResolverServiceConfig route53resolver(); NetworkFirewallServiceConfig networkfirewall(); ServiceCatalogServiceConfig servicecatalog(); SsoAdminServiceConfig ssoadmin(); @@ -733,6 +734,11 @@ public interface EmulatorConfig { boolean enabled(); } + interface Route53ResolverServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface NetworkFirewallServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index 0db9c7675f..9d6f2a838b 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -42,6 +42,7 @@ import io.github.hectorvent.floci.services.kinesisanalytics.KinesisAnalyticsV2Js import io.github.hectorvent.floci.services.kms.KmsJsonHandler; import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler; import io.github.hectorvent.floci.services.organizations.OrganizationsJsonHandler; +import io.github.hectorvent.floci.services.route53resolver.Route53ResolverJsonHandler; import io.github.hectorvent.floci.services.networkfirewall.NetworkFirewallJsonHandler; import io.github.hectorvent.floci.services.servicecatalog.ServiceCatalogJsonHandler; import io.github.hectorvent.floci.services.servicequotas.ServiceQuotasJsonHandler; @@ -107,6 +108,7 @@ public class AwsJson11Controller { private final ConfigServiceJsonHandler configServiceJsonHandler; private final CloudTrailJsonHandler cloudTrailJsonHandler; private final LightsailJsonHandler lightsailJsonHandler; + private final Route53ResolverJsonHandler route53ResolverJsonHandler; private final NetworkFirewallJsonHandler networkFirewallJsonHandler; private final ServiceCatalogJsonHandler serviceCatalogJsonHandler; private final CloudControlJsonHandler cloudControlJsonHandler; @@ -149,6 +151,7 @@ public class AwsJson11Controller { ConfigServiceJsonHandler configServiceJsonHandler, CloudTrailJsonHandler cloudTrailJsonHandler, LightsailJsonHandler lightsailJsonHandler, + Route53ResolverJsonHandler route53ResolverJsonHandler, NetworkFirewallJsonHandler networkFirewallJsonHandler, ServiceCatalogJsonHandler serviceCatalogJsonHandler, CloudControlJsonHandler cloudControlJsonHandler, @@ -195,6 +198,7 @@ public class AwsJson11Controller { this.configServiceJsonHandler = configServiceJsonHandler; this.cloudTrailJsonHandler = cloudTrailJsonHandler; this.lightsailJsonHandler = lightsailJsonHandler; + this.route53ResolverJsonHandler = route53ResolverJsonHandler; this.networkFirewallJsonHandler = networkFirewallJsonHandler; this.serviceCatalogJsonHandler = serviceCatalogJsonHandler; this.cloudControlJsonHandler = cloudControlJsonHandler; @@ -273,6 +277,7 @@ public class AwsJson11Controller { case "cloudtrail" -> cloudTrailJsonHandler.handle(action, request, region); case "application-autoscaling" -> applicationAutoScalingJsonHandler.handle(action, request, region); case "lightsail" -> lightsailJsonHandler.handle(action, request, region); + case "route53resolver" -> route53ResolverJsonHandler.handle(action, request, region, regionResolver.getAccountId()); case "network-firewall" -> networkFirewallJsonHandler.handle( action, request, region, regionResolver.getAccountId()); case "servicecatalog" -> serviceCatalogJsonHandler.handle( diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index cdbb9f631c..2b29ff1b77 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -519,6 +519,10 @@ public class ResolvedServiceCatalog { config.storage().services().guardduty().flushIntervalMs(), null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("guardduty"), Set.of(), Set.of(GuardDutyController.class)), + descriptor("route53resolver", "route53resolver", config.services().route53resolver().enabled(), true, + "route53resolver", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("Route53Resolver."), Set.of("route53resolver"), Set.of(), Set.of()), descriptor("network-firewall", "networkfirewall", config.services().networkfirewall().enabled(), true, "networkfirewall", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverJsonHandler.java new file mode 100644 index 0000000000..5fcbee06fe --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverJsonHandler.java @@ -0,0 +1,175 @@ +package io.github.hectorvent.floci.services.route53resolver; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +/** + * JSON 1.1 handler for Route 53 Resolver operations. + * Dispatches {@code X-Amz-Target: Route53Resolver.*} actions to {@link Route53ResolverService}. + * + * @see Route 53 Resolver API + */ +@ApplicationScoped +public class Route53ResolverJsonHandler { + + private static final Logger LOG = Logger.getLogger(Route53ResolverJsonHandler.class); + + private final Route53ResolverService service; + private final ObjectMapper objectMapper; + + @Inject + public Route53ResolverJsonHandler(Route53ResolverService service, ObjectMapper objectMapper) { + this.service = service; + this.objectMapper = objectMapper; + } + + public Response handle(String action, JsonNode request, String region, String accountId) { + LOG.debugv("Route53Resolver action: {0}", action); + try { + return switch (action) { + case "ListFirewallDomainLists" -> handleListFirewallDomainLists(region); + case "GetFirewallDomainList" -> handleGetFirewallDomainList(request, region); + case "CreateFirewallDomainList" -> firewallDomainListResponse( + service.createFirewallDomainList(request, region, accountId)); + case "DeleteFirewallDomainList" -> firewallDomainListResponse( + service.deleteFirewallDomainList(text(request, "FirewallDomainListId"))); + + case "CreateResolverEndpoint" -> resolverEndpointResponse( + service.createResolverEndpoint(request, region, accountId)); + case "DeleteResolverEndpoint" -> resolverEndpointResponse( + service.deleteResolverEndpoint(text(request, "ResolverEndpointId"))); + case "GetResolverEndpoint" -> resolverEndpointResponse( + service.getResolverEndpoint(text(request, "ResolverEndpointId"))); + case "ListResolverEndpoints" -> handleListResolverEndpoints(); + case "UpdateResolverEndpoint" -> resolverEndpointResponse( + service.updateResolverEndpoint(text(request, "ResolverEndpointId"), request)); + + case "CreateResolverRule" -> resolverRuleResponse( + service.createResolverRule(request, region, accountId)); + case "DeleteResolverRule" -> resolverRuleResponse( + service.deleteResolverRule(text(request, "ResolverRuleId"))); + case "GetResolverRule" -> resolverRuleResponse( + service.getResolverRule(text(request, "ResolverRuleId"))); + case "ListResolverRules" -> handleListResolverRules(); + case "UpdateResolverRule" -> resolverRuleResponse( + service.updateResolverRule(text(request, "ResolverRuleId"), request.path("Config"))); + + case "AssociateResolverRule" -> resolverRuleAssociationResponse( + service.associateResolverRule(request)); + case "DisassociateResolverRule" -> resolverRuleAssociationResponse( + service.disassociateResolverRule(request)); + case "GetResolverRuleAssociation" -> resolverRuleAssociationResponse( + service.getResolverRuleAssociation(text(request, "ResolverRuleAssociationId"))); + case "ListResolverRuleAssociations" -> handleListResolverRuleAssociations(); + + default -> Response.status(400) + .entity(new AwsErrorResponse("UnknownOperationException", + "Unknown operation: Route53Resolver." + action)) + .build(); + }; + } catch (io.github.hectorvent.floci.core.common.AwsException e) { + return Response.status(e.getHttpStatus()) + .entity(new AwsErrorResponse(e.jsonType(), e.getMessage())).build(); + } + } + + private String text(JsonNode request, String field) { + JsonNode value = request == null ? null : request.get(field); + return value == null || value.isNull() ? null : value.asText(); + } + + // ---------- Firewall domain lists ---------- + + private Response handleListFirewallDomainLists(String region) { + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode lists = result.putArray("FirewallDomainLists"); + for (Route53ResolverService.FirewallDomainList list : service.listFirewallDomainLists(region)) { + ObjectNode node = lists.addObject(); + node.put("Arn", list.arn()); + node.put("CreatorRequestId", "AWSManaged"); + node.put("Id", list.id()); + node.put("ManagedOwnerName", list.managedOwnerName()); + node.put("Name", list.name()); + } + for (ObjectNode custom : service.listCustomFirewallDomainLists()) { + lists.add(custom); + } + return Response.ok(result).build(); + } + + private Response handleGetFirewallDomainList(JsonNode request, String region) { + String id = text(request, "FirewallDomainListId"); + var custom = service.getCustomFirewallDomainList(id); + if (custom.isPresent()) { + return firewallDomainListResponse(custom.get()); + } + Route53ResolverService.FirewallDomainList list = service.getFirewallDomainList(region, id); + + ObjectNode result = objectMapper.createObjectNode(); + ObjectNode node = result.putObject("FirewallDomainList"); + node.put("Arn", list.arn()); + node.put("CreatorRequestId", "AWSManaged"); + node.put("Id", list.id()); + node.put("ManagedOwnerName", list.managedOwnerName()); + node.put("Name", list.name()); + + return Response.ok(result).build(); + } + + private Response firewallDomainListResponse(ObjectNode list) { + return Response.ok(objectMapper.createObjectNode().set("FirewallDomainList", list)).build(); + } + + // ---------- Resolver endpoints ---------- + + private Response resolverEndpointResponse(ObjectNode endpoint) { + return Response.ok(objectMapper.createObjectNode().set("ResolverEndpoint", endpoint)).build(); + } + + private Response handleListResolverEndpoints() { + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode endpoints = result.putArray("ResolverEndpoints"); + for (ObjectNode endpoint : service.listResolverEndpoints()) { + endpoints.add(endpoint); + } + return Response.ok(result).build(); + } + + // ---------- Resolver rules ---------- + + private Response resolverRuleResponse(ObjectNode rule) { + return Response.ok(objectMapper.createObjectNode().set("ResolverRule", rule)).build(); + } + + private Response handleListResolverRules() { + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode rules = result.putArray("ResolverRules"); + for (ObjectNode rule : service.listResolverRules()) { + rules.add(rule); + } + return Response.ok(result).build(); + } + + // ---------- Resolver rule associations ---------- + + private Response resolverRuleAssociationResponse(ObjectNode association) { + return Response.ok(objectMapper.createObjectNode() + .set("ResolverRuleAssociation", association)).build(); + } + + private Response handleListResolverRuleAssociations() { + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode associations = result.putArray("ResolverRuleAssociations"); + for (ObjectNode association : service.listResolverRuleAssociations()) { + associations.add(association); + } + return Response.ok(result).build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java new file mode 100644 index 0000000000..d2bf4086ec --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java @@ -0,0 +1,557 @@ +package io.github.hectorvent.floci.services.route53resolver; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; + +/** + * Route 53 Resolver: DNS Firewall (managed + custom domain lists), resolver + * endpoints, resolver rules, and resolver rule / VPC associations. + * + *
LZA's {@code Custom::ResolverManagedDomainList} Lambda resolves a managed + * list's Id by Name via {@code ListFirewallDomainLists}, so the AWS-managed + * lists must exist without any create call. Their ids are derived + * deterministically from region+name so they are stable across restarts + * without needing storage — this predates the rest of this class and is left + * untouched; only custom (created) resources use the stores below.
+ * + *All create/update operations complete synchronously: real AWS transitions + * resources through CREATING/UPDATING before a terminal state; this emulator + * returns the terminal state immediately (same convention as + * {@code ServiceCatalogService.copyProduct} and others — see CS-021).
+ */ +@ApplicationScoped +public class Route53ResolverService { + + public static final String MANAGED_OWNER_NAME = "Route 53 Resolver DNS Firewall"; + + /** + * Route 53 Resolver models two error vocabularies, and which one applies is per-operation. + * The resolver endpoint / rule / association operations list the singular + * {@code InvalidParameterException}; the later DNS Firewall operations list + * {@code ValidationException} and do not model {@code InvalidParameterException} at all + * (see {@code CreateFirewallDomainList} and {@code ListFirewallDomainLists} in botocore's + * route53resolver/2018-04-01 model). The plural {@code InvalidParametersException} this + * service used to raise belongs to Service Catalog and exists nowhere in this model. + */ + private static final String INVALID_PARAMETER = "InvalidParameterException"; + /** The DNS Firewall family's parameter-rejection error. See {@link #INVALID_PARAMETER}. */ + private static final String VALIDATION = "ValidationException"; + + /** The AWS-managed domain lists available in commercial regions. */ + static final ListThe scan-then-put pair is only atomic because every create method is + * {@code synchronized} — two overlapping retries with the same token would otherwise + * both miss the scan and persist twice.
+ * + *Idempotency is scoped to one region, as in AWS: Route 53 Resolver is regional, so + * the same token in {@code us-east-1} and {@code us-west-2} identifies two independent + * resources. The stores are account-partitioned by {@code AccountAwareStorageBackend} + * but carry no region in their keys, so the candidate's region comes from the ARN this + * service built for it — keeping the region off the wire response, which the modeled + * shapes have no field for. Same intent as {@code FisService.idempotencyKey} and + * {@code BedrockAgentCoreControlService.tokenKey}, which fold the region into the key.
+ */ + private java.util.OptionalOnly members the retry actually supplies are compared, so omitting an optional + * one is not read as a disagreement.
+ * + *{@code CreateFirewallDomainList} deliberately does not call this: its modeled error + * list carries no conflict error at all, so there is nothing faithful to raise and the + * lenient replay stands. Tracked in + * {@code issues/route53resolver-firewall-domain-list-retry-conflict.md} and pinned by a + * test so it cannot drift silently.
+ */ + private void requireReplayMatches(ObjectNode existing, JsonNode request, String... fields) { + for (String field : fields) { + JsonNode requested = request.get(field); + if (requested == null || requested.isNull()) { + continue; + } + JsonNode stored = existing.get(field); + if (stored == null || !stored.equals(requested)) { + throw replayConflict(request, existing, field); + } + } + } + + /** + * A retry that keeps the IP-request count but changes a subnet or address describes a + * different endpoint, so it is a conflict rather than a replay. Compared against the + * addresses recorded at create time, since the stored resource keeps only + * {@code IpAddressCount}. + * + *Order is not significant — the request list is a set of addresses, and a retry that + * merely reorders it is the same request — so both sides are normalised before comparing.
+ * + *A stored endpoint with no recorded addresses is reported as a conflict rather than + * waved through. Falling back to comparing {@code IpAddressCount} would accept a retry + * that kept the count but changed a subnet or address — the precise case this check + * exists to catch — so the weaker comparison is not a lenient version of this check, it + * is a silently wrong one. With nothing to compare against, the honest answer is that + * sameness cannot be established: a spurious {@code ResourceExistsException} is loud and + * recoverable, a wrong success is neither. No released build can reach this state — the + * endpoint store itself is new in the same change as this record — so the only ways in + * are a write interrupted between the two stores, or state left by an intermediate build + * of this branch.
+ */ + private void requireSameIpRequests(ObjectNode existing, JsonNode request, JsonNode ipAddresses) { + JsonNode recorded = endpointIpRequestStore.get(text(existing, "Id")) + .map(node -> node.get("IpAddressRequests")) + .orElse(null); + // Both sides are re-normalised here rather than trusting the stored order, so a record + // written before the ordering was corrected still compares as equal. + if (recorded == null + || !normalizedIpRequests(recorded).equals(normalizedIpRequests(ipAddresses))) { + throw replayConflict(request, existing, "IpAddressRequests"); + } + } + + /** + * The IP requests in a stable order, so a reordered retry is not read as a change. + * + *Ordered by {@link #canonicalKey}, not by {@code toString}: a node serialises its + * members in insertion order, so two requests carrying the same addresses written with + * their members in a different order sort differently and compare unequal — an + * equivalent retry rejected as a conflict. JSON member order is not significant, so the + * key must not depend on it.
+ */ + private ArrayNode normalizedIpRequests(JsonNode ipAddresses) { + ListThe caller passes the error code its own operation models, because the two families + * in this service do not share one — see {@link #INVALID_PARAMETER} and + * {@link #VALIDATION}.
+ */ + private static void requireEnum(String value, String field, ListSuccess path exercises the happy path by listing the pre-seeded AWS-managed + * domain lists, picking the first stable Id, and asserting the shape returned by + * {@code GetFirewallDomainList}. The not-found path verifies that an invalid Id + * produces the AWS-style {@code ResourceNotFoundException} (HTTP 400 with + * {@code __type} in the body).
+ */ +@QuarkusTest +class GetFirewallDomainListConsumerTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/route53resolver/aws4_request"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void getFirewallDomainList_success() { + // 1. List to obtain a real, seeded FirewallDomainList Id. Other tests create + // custom lists into the same store, so assert the managed lists are present + // by name rather than pinning the total or an index. + String firewallDomainListId = given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver.ListFirewallDomainLists") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("FirewallDomainLists", notNullValue()) + .body("FirewallDomainLists.Name", hasItems( + "AWSManagedDomainsAggregateThreatList", + "AWSManagedDomainsAmazonGuardDutyThreatList", + "AWSManagedDomainsBotnetCommandandControl", + "AWSManagedDomainsMalwareDomainList")) + .extract().path( + "FirewallDomainLists.find { it.Name == 'AWSManagedDomainsAggregateThreatList' }.Id"); + + // 2. Get the individual list and assert the response shape. + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver.GetFirewallDomainList") + .header("Authorization", AUTH_HEADER) + .body("{\"FirewallDomainListId\":\"" + firewallDomainListId + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("FirewallDomainList.Id", equalTo(firewallDomainListId)) + .body("FirewallDomainList.Arn", startsWith("arn:aws:route53resolver:")) + .body("FirewallDomainList.Name", notNullValue()) + .body("FirewallDomainList.Name", not(equalTo(""))); + } + + @Test + void getFirewallDomainList_notFound_returns400() { + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver.GetFirewallDomainList") + .header("Authorization", AUTH_HEADER) + .body("{\"FirewallDomainListId\":\"rslvr-fdl-nonexistent\"}") + .when() + .post("/") + .then() + // 404, matching Floci's dominant convention for ResourceNotFoundException. + // The Botocore packet does not pin an httpStatusCode for this shape and no + // AWS doc quote was obtained, so the real AWS status is UNVERIFIED — + // recorded as a known ambiguity rather than asserted as parity. + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverCustomResourcesConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverCustomResourcesConsumerTest.java new file mode 100644 index 0000000000..a73edc9f92 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverCustomResourcesConsumerTest.java @@ -0,0 +1,753 @@ +package io.github.hectorvent.floci.services.route53resolver; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Wire-level tests for the custom (non-managed) Route 53 Resolver operations + * added this session: firewall domain list CRUD, resolver endpoint CRUD, + * resolver rule CRUD, and resolver rule / VPC associations. + * + *These are all new persistence-backed additions layered onto the + * pre-existing, deterministic-id AWS-managed firewall domain list logic in + * {@link Route53ResolverService}, which is left untouched (see + * {@link Route53ResolverIntegrationTest} for its coverage).
+ */ +@QuarkusTest +class Route53ResolverCustomResourcesConsumerTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/route53resolver/aws4_request"; + /** Same access key (so the same account) in a second region, for region-scoping tests. */ + private static final String AUTH_HEADER_WEST = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/route53resolver/aws4_request"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static Response call(String action, String body) { + return callAs(AUTH_HEADER, action, body); + } + + private static Response callAs(String authHeader, String action, String body) { + return given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver." + action) + .header("Authorization", authHeader) + .body(body) + .when() + .post("/"); + } + + // ---------- CreateFirewallDomainList / DeleteFirewallDomainList ---------- + + @Test + void createFirewallDomainList_returnsCompleteListAndIsListable() { + String id = call("CreateFirewallDomainList", "{\"Name\":\"ab-custom-fdl\"," + + "\"CreatorRequestId\":\"tok-create-fdl\"}") + .then() + .statusCode(200) + .body("FirewallDomainList.Name", equalTo("ab-custom-fdl")) + .body("FirewallDomainList.Status", equalTo("COMPLETE")) + .extract().path("FirewallDomainList.Id"); + + call("GetFirewallDomainList", "{\"FirewallDomainListId\":\"" + id + "\"}") + .then() + .statusCode(200) + .body("FirewallDomainList.Id", equalTo(id)); + + call("ListFirewallDomainLists", "{}") + .then() + .statusCode(200) + .body("FirewallDomainLists.Id", hasItem(id)); + } + + @Test + void deleteFirewallDomainList_removesCustomList() { + String id = call("CreateFirewallDomainList", "{\"Name\":\"ab-delete-fdl\"," + + "\"CreatorRequestId\":\"tok-delete-fdl\"}") + .then().statusCode(200) + .extract().path("FirewallDomainList.Id"); + + call("DeleteFirewallDomainList", "{\"FirewallDomainListId\":\"" + id + "\"}") + .then() + .statusCode(200) + .body("FirewallDomainList.Status", equalTo("DELETING")); + + call("GetFirewallDomainList", "{\"FirewallDomainListId\":\"" + id + "\"}") + .then() + .statusCode(404); + } + + @Test + void createFirewallDomainList_missingName_returnsValidationException() { + // The DNS Firewall operations model ValidationException, not the resolver + // family's InvalidParameterException: CreateFirewallDomainList does not list + // InvalidParameterException among its errors at all. + call("CreateFirewallDomainList", "{\"CreatorRequestId\":\"tok-fdl-noname\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + // ---------- CreatorRequestId idempotency ---------- + + @Test + void createFirewallDomainList_replayedCreatorRequestId_returnsOriginalList() { + String body = "{\"Name\":\"ab-idem-fdl\",\"CreatorRequestId\":\"tok-idem-fdl\"}"; + + String first = call("CreateFirewallDomainList", body) + .then().statusCode(200).extract().path("FirewallDomainList.Id"); + String second = call("CreateFirewallDomainList", body) + .then().statusCode(200).extract().path("FirewallDomainList.Id"); + + assertEquals(first, second); + call("ListFirewallDomainLists", "{}") + .then() + .statusCode(200) + .body("FirewallDomainLists.findAll { it.CreatorRequestId == 'tok-idem-fdl' }.size()", + equalTo(1)); + } + + @Test + void createFirewallDomainList_withoutCreatorRequestId_createsDistinctLists() { + String body = "{\"Name\":\"ab-noidem-fdl\"}"; + + String first = call("CreateFirewallDomainList", body) + .then().statusCode(200).extract().path("FirewallDomainList.Id"); + String second = call("CreateFirewallDomainList", body) + .then().statusCode(200).extract().path("FirewallDomainList.Id"); + + assertNotEquals(first, second); + } + + @Test + void createResolverEndpoint_replayedCreatorRequestId_returnsOriginalEndpoint() { + String body = "{\"Name\":\"ab-idem-endpoint\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"tok-idem-endpoint\"}"; + + String first = call("CreateResolverEndpoint", body) + .then().statusCode(200).extract().path("ResolverEndpoint.Id"); + String second = call("CreateResolverEndpoint", body) + .then().statusCode(200).extract().path("ResolverEndpoint.Id"); + + assertEquals(first, second); + call("ListResolverEndpoints", "{}") + .then() + .statusCode(200) + .body("ResolverEndpoints.findAll { it.CreatorRequestId == 'tok-idem-endpoint' }.size()", + equalTo(1)); + } + + @Test + void createResolverEndpoint_withoutCreatorRequestId_createsDistinctEndpoints() { + String body = "{\"Name\":\"ab-noidem-endpoint\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}]}"; + + String first = call("CreateResolverEndpoint", body) + .then().statusCode(200).extract().path("ResolverEndpoint.Id"); + String second = call("CreateResolverEndpoint", body) + .then().statusCode(200).extract().path("ResolverEndpoint.Id"); + + assertNotEquals(first, second); + } + + @Test + void createResolverEndpoint_replayedCreatorRequestIdWithInvalidBody_stillValidates() { + String valid = "{\"Name\":\"ab-idem-validate\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"tok-idem-validate\"}"; + call("CreateResolverEndpoint", valid).then().statusCode(200); + + // Replaying the token does not excuse a malformed request body. + call("CreateResolverEndpoint", "{\"Name\":\"ab-idem-validate\",\"Direction\":\"INBOUND\"," + + "\"CreatorRequestId\":\"tok-idem-validate\"}") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + + // ... including an unrecognised Direction. + call("CreateResolverEndpoint", "{\"Name\":\"ab-idem-validate\",\"Direction\":\"SIDEWAYS\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"tok-idem-validate\"}") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + @Test + void createResolverRule_replayedCreatorRequestId_returnsOriginalRule() { + String body = "{\"Name\":\"ab-idem-rule\",\"RuleType\":\"FORWARD\"," + + "\"DomainName\":\"ab-idem-rule.example.com.\"," + + "\"TargetIps\":[{\"Ip\":\"10.0.0.1\",\"Port\":53}]," + + "\"CreatorRequestId\":\"tok-idem-rule\"}"; + + String first = call("CreateResolverRule", body) + .then().statusCode(200).extract().path("ResolverRule.Id"); + String second = call("CreateResolverRule", body) + .then().statusCode(200).extract().path("ResolverRule.Id"); + + assertEquals(first, second); + call("ListResolverRules", "{}") + .then() + .statusCode(200) + .body("ResolverRules.findAll { it.CreatorRequestId == 'tok-idem-rule' }.size()", equalTo(1)); + } + + @Test + void createResolverRule_withoutCreatorRequestId_createsDistinctRules() { + String body = "{\"Name\":\"ab-noidem-rule\",\"RuleType\":\"FORWARD\"," + + "\"DomainName\":\"ab-noidem-rule.example.com.\"," + + "\"TargetIps\":[{\"Ip\":\"10.0.0.1\",\"Port\":53}]}"; + + String first = call("CreateResolverRule", body) + .then().statusCode(200).extract().path("ResolverRule.Id"); + String second = call("CreateResolverRule", body) + .then().statusCode(200).extract().path("ResolverRule.Id"); + + assertNotEquals(first, second); + } + + // ---------- A replayed token with different parameters is a conflict ---------- + + @Test + void createResolverEndpoint_replayedCreatorRequestIdWithDifferentParameters_returnsResourceExists() { + String token = "tok-conflict-endpoint"; + call("CreateResolverEndpoint", "{\"Name\":\"ab-conflict-endpoint\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"" + token + "\"}") + .then().statusCode(200); + + // Same token, same region, different (but individually valid) Name: AWS models + // ResourceExistsException for this rather than silently returning the original. + call("CreateResolverEndpoint", "{\"Name\":\"ab-conflict-endpoint-renamed\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"" + token + "\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceExistsException")); + } + + @Test + void createResolverEndpoint_replayedCreatorRequestIdWithDifferentIpValues_returnsResourceExists() { + String token = "tok-conflict-endpoint-ips"; + call("CreateResolverEndpoint", "{\"Name\":\"ab-conflict-ips\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[" + + "{\"SubnetId\":\"subnet-aaa\",\"Ip\":\"10.0.0.5\"}," + + "{\"SubnetId\":\"subnet-bbb\",\"Ip\":\"10.0.1.5\"}]," + + "\"CreatorRequestId\":\"" + token + "\"}") + .then().statusCode(200); + + // Same COUNT of IP requests, different subnet and IP values. Comparing counts alone + // would read this as an equivalent replay and silently return the original endpoint. + call("CreateResolverEndpoint", "{\"Name\":\"ab-conflict-ips\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[" + + "{\"SubnetId\":\"subnet-ccc\",\"Ip\":\"10.0.2.5\"}," + + "{\"SubnetId\":\"subnet-ddd\",\"Ip\":\"10.0.3.5\"}]," + + "\"CreatorRequestId\":\"" + token + "\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceExistsException")); + } + + @Test + void createResolverEndpoint_replayedCreatorRequestIdWithIdenticalIps_returnsTheOriginal() { + String token = "tok-replay-endpoint-ips"; + String body = "{\"Name\":\"ab-replay-ips\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[" + + "{\"SubnetId\":\"subnet-aaa\",\"Ip\":\"10.0.0.5\"}," + + "{\"SubnetId\":\"subnet-bbb\",\"Ip\":\"10.0.1.5\"}]," + + "\"CreatorRequestId\":\"" + token + "\"}"; + + String first = call("CreateResolverEndpoint", body) + .then().statusCode(200).extract().path("ResolverEndpoint.Id"); + + // A genuine retry must still be idempotent — the stricter comparison must not turn + // every retry into a conflict. + call("CreateResolverEndpoint", body) + .then() + .statusCode(200) + .body("ResolverEndpoint.Id", equalTo(first)); + } + + @Test + void createResolverEndpoint_replayedWithReorderedFieldsWithinIpRequests_returnsTheOriginal() { + // Same two IP requests, but the members are written in a different order inside each + // object. JSON object member order is not significant, so this is the same request. + // The pair is chosen so that ordering the entries by their serialised form flips: + // by SubnetId, subnet-aaa sorts first; by Ip, 10.0.0.1 sorts first — opposite entries. + String token = "tok-field-order"; + String subnetFirst = "{\"Name\":\"ab-field-order\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[" + + "{\"SubnetId\":\"subnet-zzz\",\"Ip\":\"10.0.0.1\"}," + + "{\"SubnetId\":\"subnet-aaa\",\"Ip\":\"10.9.9.9\"}]," + + "\"CreatorRequestId\":\"" + token + "\"}"; + String ipFirst = "{\"Name\":\"ab-field-order\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[" + + "{\"Ip\":\"10.0.0.1\",\"SubnetId\":\"subnet-zzz\"}," + + "{\"Ip\":\"10.9.9.9\",\"SubnetId\":\"subnet-aaa\"}]," + + "\"CreatorRequestId\":\"" + token + "\"}"; + + String first = call("CreateResolverEndpoint", subnetFirst) + .then().statusCode(200).extract().path("ResolverEndpoint.Id"); + + call("CreateResolverEndpoint", ipFirst) + .then() + .statusCode(200) + .body("ResolverEndpoint.Id", equalTo(first)); + } + + @Test + void createResolverEndpoint_replayResponseOmitsInternalIpFingerprint() { + String token = "tok-replay-endpoint-nofingerprint"; + call("CreateResolverEndpoint", "{\"Name\":\"ab-nofingerprint\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-aaa\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"" + token + "\"}") + .then() + .statusCode(200) + // ResolverEndpoint models IpAddressCount but no IP list, so whatever we retain to + // detect a changed IP set must not reach the wire. + .body("ResolverEndpoint.IpAddressCount", equalTo(1)) + .body("ResolverEndpoint.any { it.key == 'IpAddressRequests' }", equalTo(false)) + .body("ResolverEndpoint.any { it.key == 'IpAddresses' }", equalTo(false)); + } + + @Test + void createResolverRule_replayedCreatorRequestIdWithDifferentParameters_returnsResourceExists() { + String token = "tok-conflict-rule"; + call("CreateResolverRule", "{\"Name\":\"ab-conflict-rule\",\"RuleType\":\"FORWARD\"," + + "\"DomainName\":\"ab-conflict.example.com.\"," + + "\"TargetIps\":[{\"Ip\":\"10.0.0.1\",\"Port\":53}]," + + "\"CreatorRequestId\":\"" + token + "\"}") + .then().statusCode(200); + + call("CreateResolverRule", "{\"Name\":\"ab-conflict-rule\",\"RuleType\":\"FORWARD\"," + + "\"DomainName\":\"ab-conflict-different.example.com.\"," + + "\"TargetIps\":[{\"Ip\":\"10.0.0.1\",\"Port\":53}]," + + "\"CreatorRequestId\":\"" + token + "\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceExistsException")); + } + + @Test + void createFirewallDomainList_replayedCreatorRequestIdWithDifferentParameters_returnsTheOriginal() { + // Deliberate divergence, pinned so it cannot drift silently: CreateFirewallDomainList + // models no conflict error at all (LimitExceeded / Validation / AccessDenied / + // InternalServiceError / Throttling only), so there is no faithful way to report a + // conflicting retry here. The lenient replay stands rather than inventing an error + // code. See issues/route53resolver-firewall-domain-list-retry-conflict.md. + String token = "tok-conflict-fdl"; + String first = call("CreateFirewallDomainList", + "{\"Name\":\"ab-conflict-fdl\",\"CreatorRequestId\":\"" + token + "\"}") + .then().statusCode(200).extract().path("FirewallDomainList.Id"); + + call("CreateFirewallDomainList", + "{\"Name\":\"ab-conflict-fdl-renamed\",\"CreatorRequestId\":\"" + token + "\"}") + .then() + .statusCode(200) + .body("FirewallDomainList.Id", equalTo(first)) + .body("FirewallDomainList.Name", equalTo("ab-conflict-fdl")); + } + + // ---------- CreatorRequestId replay is scoped to one region ---------- + + @Test + void createFirewallDomainList_sameCreatorRequestIdInAnotherRegion_createsRegionalList() { + String body = "{\"Name\":\"ab-xregion-fdl\",\"CreatorRequestId\":\"tok-xregion-fdl\"}"; + + String east = callAs(AUTH_HEADER, "CreateFirewallDomainList", body) + .then().statusCode(200) + .body("FirewallDomainList.Arn", startsWith("arn:aws:route53resolver:us-east-1:")) + .extract().path("FirewallDomainList.Id"); + + callAs(AUTH_HEADER_WEST, "CreateFirewallDomainList", body) + .then() + .statusCode(200) + // A replay in another region must not hand back us-east-1's resource. + .body("FirewallDomainList.Id", not(equalTo(east))) + .body("FirewallDomainList.Arn", startsWith("arn:aws:route53resolver:us-west-2:")); + } + + @Test + void createResolverEndpoint_sameCreatorRequestIdInAnotherRegion_createsRegionalEndpoint() { + String body = "{\"Name\":\"ab-xregion-endpoint\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"tok-xregion-endpoint\"}"; + + String east = callAs(AUTH_HEADER, "CreateResolverEndpoint", body) + .then().statusCode(200) + .body("ResolverEndpoint.Arn", startsWith("arn:aws:route53resolver:us-east-1:")) + .extract().path("ResolverEndpoint.Id"); + + callAs(AUTH_HEADER_WEST, "CreateResolverEndpoint", body) + .then() + .statusCode(200) + .body("ResolverEndpoint.Id", not(equalTo(east))) + .body("ResolverEndpoint.Arn", startsWith("arn:aws:route53resolver:us-west-2:")); + } + + @Test + void createResolverRule_sameCreatorRequestIdInAnotherRegion_createsRegionalRule() { + String body = "{\"Name\":\"ab-xregion-rule\",\"RuleType\":\"FORWARD\"," + + "\"DomainName\":\"ab-xregion-rule.example.com.\"," + + "\"TargetIps\":[{\"Ip\":\"10.0.0.1\",\"Port\":53}]," + + "\"CreatorRequestId\":\"tok-xregion-rule\"}"; + + String east = callAs(AUTH_HEADER, "CreateResolverRule", body) + .then().statusCode(200) + .body("ResolverRule.Arn", startsWith("arn:aws:route53resolver:us-east-1:")) + .extract().path("ResolverRule.Id"); + + callAs(AUTH_HEADER_WEST, "CreateResolverRule", body) + .then() + .statusCode(200) + .body("ResolverRule.Id", not(equalTo(east))) + .body("ResolverRule.Arn", startsWith("arn:aws:route53resolver:us-west-2:")); + } + + @Test + void createFirewallDomainList_replayWithinTheSameRegion_stillReturnsTheOriginal() { + String body = "{\"Name\":\"ab-sameregion-fdl\",\"CreatorRequestId\":\"tok-sameregion-fdl\"}"; + + String first = callAs(AUTH_HEADER_WEST, "CreateFirewallDomainList", body) + .then().statusCode(200).extract().path("FirewallDomainList.Id"); + String second = callAs(AUTH_HEADER_WEST, "CreateFirewallDomainList", body) + .then().statusCode(200).extract().path("FirewallDomainList.Id"); + + assertEquals(first, second); + } + + // ---------- Resolver endpoints ---------- + + private static String createEndpoint(String name) { + return call("CreateResolverEndpoint", "{\"Name\":\"" + name + "\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"tok-" + name + "\"}") + .then().statusCode(200) + .extract().path("ResolverEndpoint.Id"); + } + + @Test + void createResolverEndpoint_returnsOperationalEndpoint() { + call("CreateResolverEndpoint", "{\"Name\":\"ab-endpoint-create\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"tok-endpoint-create\"}") + .then() + .statusCode(200) + .body("ResolverEndpoint.Name", equalTo("ab-endpoint-create")) + .body("ResolverEndpoint.Direction", equalTo("INBOUND")) + .body("ResolverEndpoint.Status", equalTo("OPERATIONAL")) + .body("ResolverEndpoint.IpAddressCount", equalTo(1)); + } + + @Test + void createResolverEndpoint_inboundGetsInboundIdPrefix() { + call("CreateResolverEndpoint", "{\"Name\":\"ab-endpoint-inbound\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.5\"}],\"CreatorRequestId\":\"tok-endpoint-inbound\"}") + .then() + .statusCode(200) + .body("ResolverEndpoint.Direction", equalTo("INBOUND")) + .body("ResolverEndpoint.Id", startsWith("rslvr-in-")); + } + + @Test + void createResolverEndpoint_outboundGetsOutboundIdPrefix() { + call("CreateResolverEndpoint", "{\"Name\":\"ab-endpoint-outbound\",\"Direction\":\"OUTBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.6\"}],\"CreatorRequestId\":\"tok-endpoint-outbound\"}") + .then() + .statusCode(200) + .body("ResolverEndpoint.Direction", equalTo("OUTBOUND")) + .body("ResolverEndpoint.Id", startsWith("rslvr-out-")); + } + + @Test + void createResolverEndpoint_unknownDirection_returnsInvalidParameters() { + call("CreateResolverEndpoint", "{\"Name\":\"ab-endpoint-sideways\",\"Direction\":\"SIDEWAYS\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"IpAddressRequests\":[{\"SubnetId\":\"subnet-abc\"," + + "\"Ip\":\"10.0.0.7\"}],\"CreatorRequestId\":\"tok-endpoint-sideways\"}") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + @Test + void createResolverEndpoint_missingIpAddressRequests_returnsInvalidParameters() { + call("CreateResolverEndpoint", "{\"Name\":\"ab-endpoint-noip\",\"Direction\":\"INBOUND\"," + + "\"SecurityGroupIds\":[\"sg-abc123\"],\"CreatorRequestId\":\"tok-noip\"}") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + @Test + void getResolverEndpoint_returnsCreatedEndpoint() { + String id = createEndpoint("ab-endpoint-get"); + + call("GetResolverEndpoint", "{\"ResolverEndpointId\":\"" + id + "\"}") + .then() + .statusCode(200) + .body("ResolverEndpoint.Id", equalTo(id)); + } + + @Test + void getResolverEndpoint_unknownId_returnsResourceNotFound() { + call("GetResolverEndpoint", "{\"ResolverEndpointId\":\"rslvr-in-doesnotexist\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + void listResolverEndpoints_includesCreatedEndpoint() { + String id = createEndpoint("ab-endpoint-list"); + + call("ListResolverEndpoints", "{}") + .then() + .statusCode(200) + .body("ResolverEndpoints.Id", hasItem(id)); + } + + @Test + void updateResolverEndpoint_changesName() { + String id = createEndpoint("ab-endpoint-update-before"); + + call("UpdateResolverEndpoint", "{\"ResolverEndpointId\":\"" + id + + "\",\"Name\":\"ab-endpoint-update-after\"}") + .then() + .statusCode(200) + .body("ResolverEndpoint.Id", equalTo(id)) + .body("ResolverEndpoint.Name", equalTo("ab-endpoint-update-after")); + } + + @Test + void updateResolverEndpoint_unknownEndpointType_returnsInvalidParameters() { + String id = createEndpoint("ab-endpoint-badtype"); + + // ResolverEndpointType is an enum of IPV6 / IPV4 / DUALSTACK: storing anything + // else would have GetResolverEndpoint report an endpoint type AWS never allows. + call("UpdateResolverEndpoint", "{\"ResolverEndpointId\":\"" + id + + "\",\"ResolverEndpointType\":\"IPV5\"}") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + + call("GetResolverEndpoint", "{\"ResolverEndpointId\":\"" + id + "\"}") + .then() + .statusCode(200) + .body("ResolverEndpoint.ResolverEndpointType", equalTo(null)); + } + + @Test + void deleteResolverEndpoint_removesEndpoint() { + String id = createEndpoint("ab-endpoint-delete"); + + call("DeleteResolverEndpoint", "{\"ResolverEndpointId\":\"" + id + "\"}") + .then() + .statusCode(200) + .body("ResolverEndpoint.Status", equalTo("DELETING")); + + call("GetResolverEndpoint", "{\"ResolverEndpointId\":\"" + id + "\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } + + // ---------- Resolver rules ---------- + + private static String createRule(String name, String domain) { + return call("CreateResolverRule", "{\"Name\":\"" + name + "\",\"RuleType\":\"FORWARD\"," + + "\"DomainName\":\"" + domain + "\",\"TargetIps\":[{\"Ip\":\"10.0.0.1\",\"Port\":53}]," + + "\"CreatorRequestId\":\"tok-" + name + "\"}") + .then().statusCode(200) + .extract().path("ResolverRule.Id"); + } + + @Test + void createResolverRule_returnsCompleteRule() { + call("CreateResolverRule", "{\"Name\":\"ab-rule-create\",\"RuleType\":\"FORWARD\"," + + "\"DomainName\":\"example.com.\",\"TargetIps\":[{\"Ip\":\"10.0.0.1\",\"Port\":53}]," + + "\"CreatorRequestId\":\"tok-rule-create\"}") + .then() + .statusCode(200) + .body("ResolverRule.Name", equalTo("ab-rule-create")) + .body("ResolverRule.DomainName", equalTo("example.com.")) + .body("ResolverRule.RuleType", equalTo("FORWARD")) + .body("ResolverRule.Status", equalTo("COMPLETE")); + } + + @Test + void createResolverRule_emptyTargetIps_returnsInvalidParameters() { + // The model pins TargetIps to list min 1: present-but-empty is invalid. + // Absent TargetIps stays allowed (SYSTEM rules carry none). + call("CreateResolverRule", "{\"Name\":\"ab-rule-emptytargets\",\"RuleType\":\"FORWARD\"," + + "\"DomainName\":\"ab-rule-emptytargets.example.com.\",\"TargetIps\":[]," + + "\"CreatorRequestId\":\"tok-rule-emptytargets\"}") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + @Test + void createResolverRule_unknownRuleType_returnsInvalidParameters() { + // RuleTypeOption is FORWARD / SYSTEM / RECURSIVE / DELEGATE. An unmodelled value + // was stored verbatim and echoed back by Get/ListResolverRules as a real rule. + call("CreateResolverRule", "{\"Name\":\"ab-rule-badtype\",\"RuleType\":\"SIDEWAYS\"," + + "\"DomainName\":\"ab-rule-badtype.example.com.\"," + + "\"TargetIps\":[{\"Ip\":\"10.0.0.1\",\"Port\":53}]," + + "\"CreatorRequestId\":\"tok-rule-badtype\"}") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + + call("ListResolverRules", "{}") + .then() + .statusCode(200) + .body("ResolverRules.Name", not(hasItem("ab-rule-badtype"))); + } + + @Test + void getResolverRule_returnsCreatedRule() { + String id = createRule("ab-rule-get", "ab-rule-get.example.com."); + + call("GetResolverRule", "{\"ResolverRuleId\":\"" + id + "\"}") + .then() + .statusCode(200) + .body("ResolverRule.Id", equalTo(id)); + } + + @Test + void getResolverRule_unknownId_returnsResourceNotFound() { + call("GetResolverRule", "{\"ResolverRuleId\":\"rslvr-rr-doesnotexist\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + void listResolverRules_includesCreatedRule() { + String id = createRule("ab-rule-list", "ab-rule-list.example.com."); + + call("ListResolverRules", "{}") + .then() + .statusCode(200) + .body("ResolverRules.Id", hasItem(id)); + } + + @Test + void updateResolverRule_changesName() { + String id = createRule("ab-rule-update-before", "ab-rule-update.example.com."); + + call("UpdateResolverRule", "{\"ResolverRuleId\":\"" + id + + "\",\"Config\":{\"Name\":\"ab-rule-update-after\"}}") + .then() + .statusCode(200) + .body("ResolverRule.Id", equalTo(id)) + .body("ResolverRule.Name", equalTo("ab-rule-update-after")); + } + + @Test + void deleteResolverRule_removesRule() { + String id = createRule("ab-rule-delete", "ab-rule-delete.example.com."); + + call("DeleteResolverRule", "{\"ResolverRuleId\":\"" + id + "\"}") + .then() + .statusCode(200) + .body("ResolverRule.Status", equalTo("DELETING")); + + call("GetResolverRule", "{\"ResolverRuleId\":\"" + id + "\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } + + // ---------- Resolver rule associations ---------- + + @Test + void associateResolverRule_returnsCompleteAssociation() { + String ruleId = createRule("ab-assoc-rule", "ab-assoc.example.com."); + + String associationId = call("AssociateResolverRule", "{\"ResolverRuleId\":\"" + ruleId + + "\",\"VPCId\":\"vpc-abc123\",\"Name\":\"ab-assoc-name\"}") + .then() + .statusCode(200) + .body("ResolverRuleAssociation.ResolverRuleId", equalTo(ruleId)) + .body("ResolverRuleAssociation.VPCId", equalTo("vpc-abc123")) + .body("ResolverRuleAssociation.Status", equalTo("COMPLETE")) + .extract().path("ResolverRuleAssociation.Id"); + + call("GetResolverRuleAssociation", "{\"ResolverRuleAssociationId\":\"" + associationId + "\"}") + .then() + .statusCode(200) + .body("ResolverRuleAssociation.Id", equalTo(associationId)); + } + + @Test + void associateResolverRule_unknownRule_returnsResourceNotFound() { + call("AssociateResolverRule", "{\"ResolverRuleId\":\"rslvr-rr-doesnotexist\"," + + "\"VPCId\":\"vpc-abc123\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + void listResolverRuleAssociations_includesAssociatedRule() { + String ruleId = createRule("ab-list-assoc-rule", "ab-list-assoc.example.com."); + call("AssociateResolverRule", "{\"ResolverRuleId\":\"" + ruleId + + "\",\"VPCId\":\"vpc-list-assoc\"}") + .then().statusCode(200); + + call("ListResolverRuleAssociations", "{}") + .then() + .statusCode(200) + .body("ResolverRuleAssociations.ResolverRuleId", hasItem(ruleId)); + } + + @Test + void disassociateResolverRule_removesAssociation() { + String ruleId = createRule("ab-disassoc-rule", "ab-disassoc.example.com."); + call("AssociateResolverRule", "{\"ResolverRuleId\":\"" + ruleId + + "\",\"VPCId\":\"vpc-disassoc\"}") + .then().statusCode(200); + + call("DisassociateResolverRule", "{\"ResolverRuleId\":\"" + ruleId + + "\",\"VPCId\":\"vpc-disassoc\"}") + .then() + .statusCode(200) + .body("ResolverRuleAssociation.Status", equalTo("DELETING")); + + call("ListResolverRuleAssociations", "{}") + .then() + .statusCode(200) + .body("ResolverRuleAssociations.findAll { it.ResolverRuleId == '" + ruleId + "' }.size()", + equalTo(0)); + } + + @Test + void disassociateResolverRule_unknownAssociation_returnsResourceNotFound() { + call("DisassociateResolverRule", "{\"ResolverRuleId\":\"rslvr-rr-neverassociated\"," + + "\"VPCId\":\"vpc-neverassociated\"}") + .then() + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverIntegrationTest.java new file mode 100644 index 0000000000..5c811e8eb8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverIntegrationTest.java @@ -0,0 +1,89 @@ +package io.github.hectorvent.floci.services.route53resolver; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.startsWith; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * Integration tests for Route 53 Resolver DNS Firewall operations + * (JSON 1.1 protocol, {@code X-Amz-Target: Route53Resolver.*}). + * + *LZA's {@code Custom::ResolverManagedDomainList} Lambda pages through + * {@code ListFirewallDomainLists} and resolves an AWS-managed list's Id by + * Name, so the managed lists must be present out of the box.
+ */ +@QuarkusTest +class Route53ResolverIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/route53resolver/aws4_request"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void listFirewallDomainLists_returnsAwsManagedLists() { + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver.ListFirewallDomainLists") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("FirewallDomainLists.Name", hasItems( + "AWSManagedDomainsAggregateThreatList", + "AWSManagedDomainsMalwareDomainList", + "AWSManagedDomainsBotnetCommandandControl")) + .body("FirewallDomainLists[0].Id", startsWith("rslvr-fdl-")) + .body("FirewallDomainLists[0].ManagedOwnerName", equalTo("Route 53 Resolver DNS Firewall")); + } + + @Test + void listFirewallDomainLists_idsAreStableAcrossCalls() { + String firstId = given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver.ListFirewallDomainLists") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("FirewallDomainLists[0].Id"); + + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver.ListFirewallDomainLists") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("FirewallDomainLists[0].Id", equalTo(firstId)); + } + + @Test + void unknownOperation_returns400() { + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver.DoesNotExist") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/") + .then() + .statusCode(400); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java new file mode 100644 index 0000000000..e73fde202d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java @@ -0,0 +1,92 @@ +package io.github.hectorvent.floci.services.route53resolver; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * What {@code CreateResolverEndpoint} does when a stored endpoint has no recorded + * {@code IpAddressRequests} — a state the public API cannot produce, so it needs the + * hermetic constructor. + * + *The recorded addresses are what a replayed {@code CreatorRequestId} is checked + * against. Without them the service cannot tell a genuine retry from a different request + * that happens to reuse the token, so it reports the conflict rather than returning an + * endpoint that may not match what was asked for. Failing closed is the safe direction: + * a spurious {@code ResourceExistsException} is loud and recoverable, while a wrong + * success is silent.
+ */ +class Route53ResolverReplayFallbackTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private InMemoryStorage