feat(route53resolver): add Route 53 Resolver with DNS Firewall domain lists (#2582)

* feat(route53resolver): AWS-managed DNS Firewall domain lists

New JSON 1.1 service exposing ListFirewallDomainLists with the four
AWS-managed domain lists, deterministic ids stable across restarts.
LZA's NetworkPrepStack Custom::ResolverManagedDomainList Lambda resolves
managed list ids by name and previously failed with UnknownOperation.

* feat(route53resolver): full-parity build-out (16 ops)

Adds firewall domain list CRUD, resolver endpoint CRUD, resolver rule
CRUD, and rule-association management, backed by four new
StorageBackend stores. The pre-existing deterministic AWS-managed
domain list logic (AWS_MANAGED_DOMAIN_LIST_NAMES, managedList(),
FirewallDomainList) is untouched -- LZA's bootstrap Lambda depends on
those ids being stable across calls.

Also fixes the JSON-1.1 dispatch case in AwsJson11Controller to pass
the account id through to the handler, matching every other service's
dispatch signature (route53resolver was the one holdout still calling
handle() with the old 3-arg signature).

* fix(config): declare route53resolver enabled toggle in both application.yml files

Upstream's ServiceConfigYamlCoverageTest requires every service config with an
enabled() toggle to declare it explicitly in both files; this branch predates
that test and fails it without the declaration.

* docs(route53resolver): register the generated action table

* fix(route53resolver): declare storageKey and storageMode on the service descriptor

The service persists four stores through StorageFactory, but its catalog
descriptor left storageKey and storageMode null, so it was invisible to
PersistentPathValidator's boot check and to per-service storage config
resolution. Mirror the organizations descriptor.

* fix(route53resolver): make creates idempotent on CreatorRequestId

CreateFirewallDomainList, CreateResolverEndpoint and CreateResolverRule
allocated a new resource on every call, so an LZA/CloudFormation retry of
the same CreatorRequestId left duplicates behind. Real AWS returns the
resource the token originally created. Dedupe per store, after the
operation's own validation so a replayed token cannot excuse a malformed
body; a blank or absent token still allocates.

* fix(route53resolver): give outbound resolver endpoints rslvr-out ids

Every CreateResolverEndpoint allocated an inbound-style rslvr-in- id
regardless of Direction, so an outbound endpoint carried an id AWS would
never issue. Key the prefix off Direction (INBOUND/INBOUND_DELEGATION ->
rslvr-in, OUTBOUND -> rslvr-out) and reject values outside the
ResolverEndpointDirection enum instead of silently defaulting to inbound.

* test(route53resolver): assert managed domain lists by name, not by count

ListFirewallDomainLists returns the four managed lists plus whatever
custom lists other tests in the run have created, so size()==4 and the
[0] index extraction were both order-dependent. Assert the four managed
names are present and pick the id by name. Also drop the call-site counts
from the 404-convention comment, which would go stale on any refactor.

* docs(route53resolver): correct the scoping limitation

The limitation claimed resources are visible regardless of the caller's
account. They are not: all four stores are created through StorageFactory,
which wraps every backend in AccountAwareStorageBackend, so keys are
prefixed with the calling credential's account id and both scan() and
keys() filter on that prefix. Region and VPC are what go unenforced, and
the AWS-managed lists are region-derived and globally visible by design.

* fix(route53resolver): validate Direction before the CreatorRequestId replay check

endpointIdPrefix ran only on the allocation path, so replaying a known
CreatorRequestId with an unrecognised Direction returned 200 and the
original endpoint instead of InvalidParametersException. Bind the prefix
right after the Direction is read, so every request is validated whether
or not it turns out to be a replay.

* fix(route53resolver): enforce the RuleType and ResolverEndpointType enums

CreateResolverRule stored any RuleType string it was given and UpdateResolverEndpoint
copied any ResolverEndpointType through, so Get/ListResolverRules and
GetResolverEndpoint reported values outside botocore's RuleTypeOption
(FORWARD/SYSTEM/RECURSIVE/DELEGATE) and ResolverEndpointType (IPV6/IPV4/DUALSTACK).
Both now reject with the same InvalidParametersException the Direction check uses.

* fix(route53resolver): reject an empty TargetIps list

The model pins TargetIps to list min 1; a present-but-empty array was
stored verbatim. Absent stays allowed for SYSTEM rules. Found by the
botocore-grounded review pipeline; the hand audit missed it.

* fix(route53resolver): make the CreatorRequestId replay check atomic

Two overlapping create retries with the same token could both pass the
replay scan before either put, persisting two resources with different
ids. The three create methods are now synchronized, making the
scan-then-put pair atomic on this ApplicationScoped singleton.

* fix(route53resolver): scope the CreatorRequestId replay to the request's region

replayOf matched purely on CreatorRequestId content across the whole
account-partitioned store, which carries no region in its keys. The same
account replaying a token in a second region got the first region's
resource and ARN back instead of the regional resource it asked for.
Route 53 Resolver is regional, so a token identifies one resource per
region: match the candidate's region too, taken from the ARN this service
builds rather than a stored field, so nothing new reaches the wire.

Also folds the two stacked javadoc blocks above replayOf into one; the
second was shadowing the first, which left the idempotency contract out
of the generated docs.

* docs: correct service count to 79 after the #2579 merge

The upstream/main merge (ca772bc72) added two new services
(servicequotas, ram) on top of this branch's own route53resolver
addition. The merge-base count was 76; three disjoint new services
(1 ours + 2 upstream) makes 79, not 78 as the merge commit left it.

* fix(config): restore the controltower enabled toggle in both application.yml files

The route53resolver key was inserted between controltower: and the
enabled: true that belonged to it, so controltower: became a bare key
binding nothing and route53resolver adopted its child. Control Tower kept
running only because ControlTowerServiceConfig.enabled() carries
@WithDefault("true"), which masked the break; the explicit toggle was
gone. Caught by ServiceConfigYamlCoverageTest, which names controltower
rather than route53resolver and made the CI failure read as unrelated.

* fix(route53resolver): raise the error codes the model actually names

InvalidParametersException (plural) is a Service Catalog shape and does
not exist anywhere in route53resolver's model. Checked every throw site
against the per-operation error lists in botocore route53resolver
2018-04-01 rather than renaming globally, because the service carries two
vocabularies: 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 therefore raises ValidationException; the other
eight sites raise InvalidParameterException. requireText and requireEnum
are shared across both families, so each caller now passes the code its
own operation models instead of the helper picking one. ResourceNotFound
usage was already correct and is untouched.

* fix(route53resolver): reject a CreatorRequestId replayed with different parameters

A replayed token was deduplicated on the token alone, so a retry carrying
different but individually valid parameters got a success response
describing the original resource rather than the one it asked for.

CreateResolverEndpoint and CreateResolverRule now compare the retry
against the stored resource and raise ResourceExistsException, which both
operations model. CreateFirewallDomainList is deliberately left lenient:
its modeled error list carries no conflict error at all, so reporting one
would mean inventing a shape real SDK clients cannot deserialize. That
divergence is pinned by a test and ledgered rather than guessed at.

* fix(route53resolver): compare IP request values, not just their count, on a replayed create

The conflict check compared IpAddressRequests by size, so a retry reusing
a CreatorRequestId with the same number of entries but a different subnet
or address was treated as an equivalent replay and returned the original
endpoint, dropping the configuration the caller actually asked for.

The modeled ResolverEndpoint shape carries IpAddressCount and no IP list,
and the handlers return the stored node verbatim, so the addresses are
recorded in a side store keyed by endpoint id rather than on the resource
itself; nothing new reaches the wire. Comparison is order-insensitive so a
reordered retry is still a replay, and endpoints created before this
record existed fall back to the count comparison instead of reporting a
conflict on every retry.

* fix(route53resolver): treat a missing IP-request record as a conflict, not a pass

The fallback for an endpoint with no recorded IpAddressRequests compared
IpAddressCount instead, which accepts a retry that keeps the count but
changes a subnet or address — exactly the case the record exists to catch.
That made it a silently wrong check rather than a lenient one.

With nothing to compare against, sameness cannot be established, so the
retry is now reported as ResourceExistsException. A spurious conflict is
loud and recoverable; a wrong success is neither. Nothing released can
reach this state: the endpoint store is new in the same change as the
record, so the only ways in are a write interrupted between the two stores
or state from an intermediate build of this branch.

Adds a package-private constructor so a hermetic test can create the
missing-record state the public API cannot, following the pattern in
Ec2IpamService. The cost of failing closed — an identical retry also
conflicting — is pinned as its own test rather than left implicit.

* fix(route53resolver): order IP requests by a member-order-independent key

The replay comparison sorted IpAddressRequests by JsonNode.toString, which
serialises members in insertion order. A retry carrying the same addresses
with the members written in a different order could sort the entries into a
different sequence, so an equivalent request was rejected as a conflict.

Sort by a canonical key that ignores member order instead. Both sides are
re-normalised at comparison time rather than trusting the stored order, so
a record written before this fix still compares as equal.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-27 14:16:38 -04:00
1 parent bd436eeea1
commit d60bd6ead2
16 files changed
+1882 -4

No files matched your search

@@ -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();
@@ -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(
@@ -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),
@@ -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 <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_Operations_Amazon_Route_53_Resolver.html">Route 53 Resolver API</a>
*/
@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();
}
}
@@ -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.
*
* <p>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.</p>
*
* <p>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).</p>
*/
@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 List<String> AWS_MANAGED_DOMAIN_LIST_NAMES = List.of(
"AWSManagedDomainsAggregateThreatList",
"AWSManagedDomainsAmazonGuardDutyThreatList",
"AWSManagedDomainsBotnetCommandandControl",
"AWSManagedDomainsMalwareDomainList");
/** botocore {@code RuleTypeOption}. */
private static final List<String> RULE_TYPES = List.of("FORWARD", "SYSTEM", "RECURSIVE", "DELEGATE");
/** botocore {@code ResolverEndpointType}. */
private static final List<String> ENDPOINT_TYPES = List.of("IPV6", "IPV4", "DUALSTACK");
public record FirewallDomainList(String id, String arn, String name, String managedOwnerName) {
}
private final StorageBackend<String, ObjectNode> domainListStore;
private final StorageBackend<String, ObjectNode> endpointStore;
private final StorageBackend<String, ObjectNode> ruleStore;
private final StorageBackend<String, ObjectNode> ruleAssociationStore;
/**
* The {@code IpAddressRequests} each endpoint was created with, keyed by endpoint id.
* Kept beside the endpoint rather than on it: the modeled {@code ResolverEndpoint} shape
* carries {@code IpAddressCount} and no IP list, and the handlers return the stored node
* verbatim, so holding the addresses on the resource would put an unmodeled member on the
* wire. Only the CreatorRequestId conflict check reads this.
*/
private final StorageBackend<String, ObjectNode> endpointIpRequestStore;
private final ObjectMapper objectMapper;
@Inject
public Route53ResolverService(StorageFactory storageFactory, ObjectMapper objectMapper) {
this.domainListStore = storageFactory.create("route53resolver", "route53resolver-domain-lists.json",
new TypeReference<java.util.Map<String, ObjectNode>>() {});
this.endpointStore = storageFactory.create("route53resolver", "route53resolver-endpoints.json",
new TypeReference<java.util.Map<String, ObjectNode>>() {});
this.ruleStore = storageFactory.create("route53resolver", "route53resolver-rules.json",
new TypeReference<java.util.Map<String, ObjectNode>>() {});
this.ruleAssociationStore = storageFactory.create("route53resolver",
"route53resolver-rule-associations.json", new TypeReference<java.util.Map<String, ObjectNode>>() {});
this.endpointIpRequestStore = storageFactory.create("route53resolver",
"route53resolver-endpoint-ip-requests.json",
new TypeReference<java.util.Map<String, ObjectNode>>() {});
this.objectMapper = objectMapper;
}
// Package-private for hermetic tests: pass in-memory StorageBackends directly, so a test
// can put a store into a state the public API cannot produce (e.g. an endpoint whose
// IpAddressRequests record is missing).
Route53ResolverService(StorageBackend<String, ObjectNode> domainListStore,
StorageBackend<String, ObjectNode> endpointStore,
StorageBackend<String, ObjectNode> ruleStore,
StorageBackend<String, ObjectNode> ruleAssociationStore,
StorageBackend<String, ObjectNode> endpointIpRequestStore,
ObjectMapper objectMapper) {
this.domainListStore = domainListStore;
this.endpointStore = endpointStore;
this.ruleStore = ruleStore;
this.ruleAssociationStore = ruleAssociationStore;
this.endpointIpRequestStore = endpointIpRequestStore;
this.objectMapper = objectMapper;
}
public List<FirewallDomainList> listFirewallDomainLists(String region) {
return AWS_MANAGED_DOMAIN_LIST_NAMES.stream()
.map(name -> managedList(region, name))
.toList();
}
public FirewallDomainList getFirewallDomainList(String region, String id) {
for (FirewallDomainList list : listFirewallDomainLists(region)) {
if (list.id().equals(id)) {
return list;
}
}
throw new AwsException("ResourceNotFoundException", "Firewall domain list not found: " + id, 404);
}
// ---------- Custom firewall domain lists ----------
public synchronized ObjectNode createFirewallDomainList(JsonNode request, String region, String accountId) {
String name = requireText(request, "Name", VALIDATION);
java.util.Optional<ObjectNode> replay = replayOf(domainListStore, request, region);
if (replay.isPresent()) {
return replay.get();
}
String id = id("rslvr-fdl");
ObjectNode list = objectMapper.createObjectNode();
list.put("Id", id);
list.put("Arn", "arn:aws:route53resolver:" + region + ":" + accountId + ":firewall-domain-list/" + id);
list.put("Name", name);
list.put("DomainCount", 0);
list.put("Status", "COMPLETE");
list.put("CreatorRequestId", text(request, "CreatorRequestId"));
list.put("ManagedOwnerName", (String) null);
list.put("CreationTime", Instant.now().toString());
list.put("ModificationTime", Instant.now().toString());
domainListStore.put(id, list);
return list.deepCopy();
}
public ObjectNode deleteFirewallDomainList(String id) {
ObjectNode list = require(domainListStore, id, "firewall domain list");
domainListStore.delete(id);
ObjectNode result = list.deepCopy();
result.put("Status", "DELETING");
return result;
}
public List<ObjectNode> listCustomFirewallDomainLists() {
return domainListStore.scan(key -> true).stream().map(ObjectNode::deepCopy).toList();
}
public java.util.Optional<ObjectNode> getCustomFirewallDomainList(String id) {
return domainListStore.get(id).map(ObjectNode::deepCopy);
}
// ---------- Resolver endpoints ----------
public synchronized ObjectNode createResolverEndpoint(JsonNode request, String region, String accountId) {
requireText(request, "Name", INVALID_PARAMETER);
String direction = requireText(request, "Direction", INVALID_PARAMETER);
String idPrefix = endpointIdPrefix(direction);
JsonNode ipAddresses = request.path("IpAddressRequests");
if (!ipAddresses.isArray() || ipAddresses.isEmpty()) {
throw new AwsException(INVALID_PARAMETER, "IpAddressRequests is required", 400);
}
java.util.Optional<ObjectNode> replay = replayOf(endpointStore, request, region);
if (replay.isPresent()) {
ObjectNode existing = replay.get();
requireReplayMatches(existing, request, "Name", "Direction", "SecurityGroupIds");
requireSameIpRequests(existing, request, ipAddresses);
return existing;
}
String id = id(idPrefix);
ObjectNode endpoint = objectMapper.createObjectNode();
endpoint.put("Id", id);
endpoint.put("Arn", "arn:aws:route53resolver:" + region + ":" + accountId + ":resolver-endpoint/" + id);
endpoint.put("Name", text(request, "Name"));
endpoint.put("Direction", direction);
endpoint.set("SecurityGroupIds", request.path("SecurityGroupIds").deepCopy());
endpoint.put("IpAddressCount", ipAddresses.size());
endpoint.put("HostVPCId", "vpc-" + deterministicHex(id, 8));
endpoint.put("Status", "OPERATIONAL");
endpoint.put("CreatorRequestId", text(request, "CreatorRequestId"));
endpoint.put("CreationTime", Instant.now().toString());
endpoint.put("ModificationTime", Instant.now().toString());
endpointStore.put(id, endpoint);
endpointIpRequestStore.put(id,
objectMapper.createObjectNode().set("IpAddressRequests", normalizedIpRequests(ipAddresses)));
return endpoint.deepCopy();
}
public ObjectNode deleteResolverEndpoint(String id) {
ObjectNode endpoint = require(endpointStore, id, "resolver endpoint");
endpointStore.delete(id);
endpointIpRequestStore.delete(id);
ObjectNode result = endpoint.deepCopy();
result.put("Status", "DELETING");
return result;
}
public ObjectNode getResolverEndpoint(String id) {
return require(endpointStore, id, "resolver endpoint").deepCopy();
}
public List<ObjectNode> listResolverEndpoints() {
return endpointStore.scan(key -> true).stream().map(ObjectNode::deepCopy).toList();
}
public ObjectNode updateResolverEndpoint(String id, JsonNode request) {
ObjectNode endpoint = require(endpointStore, id, "resolver endpoint");
String endpointType = text(request, "ResolverEndpointType");
if (endpointType != null) {
requireEnum(endpointType, "ResolverEndpointType", ENDPOINT_TYPES, INVALID_PARAMETER);
}
copyIfPresent(request, endpoint, "Name", "ResolverEndpointType");
endpoint.put("ModificationTime", Instant.now().toString());
endpointStore.put(id, endpoint);
return endpoint.deepCopy();
}
// ---------- Resolver rules ----------
public synchronized ObjectNode createResolverRule(JsonNode request, String region, String accountId) {
requireEnum(requireText(request, "RuleType", INVALID_PARAMETER), "RuleType", RULE_TYPES,
INVALID_PARAMETER);
// TargetIps is modeled list min 1: present-but-empty is invalid, absent is
// allowed (SYSTEM rules carry no targets).
JsonNode targetIps = request.path("TargetIps");
if (targetIps.isArray() && targetIps.isEmpty()) {
throw new AwsException(INVALID_PARAMETER,
"TargetIps must contain at least one target address.", 400);
}
String domainName = text(request, "DomainName");
java.util.Optional<ObjectNode> replay = replayOf(ruleStore, request, region);
if (replay.isPresent()) {
requireReplayMatches(replay.get(), request,
"Name", "RuleType", "DomainName", "TargetIps", "ResolverEndpointId");
return replay.get();
}
String id = id("rslvr-rr");
ObjectNode rule = objectMapper.createObjectNode();
rule.put("Id", id);
rule.put("Arn", "arn:aws:route53resolver:" + region + ":" + accountId + ":resolver-rule/" + id);
rule.put("DomainName", domainName);
rule.put("Status", "COMPLETE");
rule.put("RuleType", text(request, "RuleType"));
rule.put("Name", text(request, "Name"));
rule.set("TargetIps", request.path("TargetIps").deepCopy());
rule.put("ResolverEndpointId", text(request, "ResolverEndpointId"));
rule.put("OwnerId", accountId);
rule.put("ShareStatus", "NOT_SHARED");
rule.put("CreatorRequestId", text(request, "CreatorRequestId"));
rule.put("CreationTime", Instant.now().toString());
rule.put("ModificationTime", Instant.now().toString());
ruleStore.put(id, rule);
return rule.deepCopy();
}
public ObjectNode deleteResolverRule(String id) {
ObjectNode rule = require(ruleStore, id, "resolver rule");
ruleStore.delete(id);
ObjectNode result = rule.deepCopy();
result.put("Status", "DELETING");
return result;
}
public ObjectNode getResolverRule(String id) {
return require(ruleStore, id, "resolver rule").deepCopy();
}
public List<ObjectNode> listResolverRules() {
return ruleStore.scan(key -> true).stream().map(ObjectNode::deepCopy).toList();
}
public ObjectNode updateResolverRule(String id, JsonNode config) {
ObjectNode rule = require(ruleStore, id, "resolver rule");
copyIfPresent(config, rule, "Name", "TargetIps", "ResolverEndpointId");
rule.put("ModificationTime", Instant.now().toString());
ruleStore.put(id, rule);
return rule.deepCopy();
}
// ---------- Resolver rule associations ----------
public ObjectNode associateResolverRule(JsonNode request) {
String ruleId = requireText(request, "ResolverRuleId", INVALID_PARAMETER);
String vpcId = requireText(request, "VPCId", INVALID_PARAMETER);
require(ruleStore, ruleId, "resolver rule");
String id = id("rslvr-rrassoc");
ObjectNode association = objectMapper.createObjectNode();
association.put("Id", id);
association.put("ResolverRuleId", ruleId);
association.put("Name", text(request, "Name"));
association.put("VPCId", vpcId);
association.put("Status", "COMPLETE");
ruleAssociationStore.put(id, association);
return association.deepCopy();
}
public ObjectNode disassociateResolverRule(JsonNode request) {
String ruleId = requireText(request, "ResolverRuleId", INVALID_PARAMETER);
String vpcId = requireText(request, "VPCId", INVALID_PARAMETER);
ObjectNode association = ruleAssociationStore.scan(key -> true).stream()
.filter(a -> ruleId.equals(text(a, "ResolverRuleId")) && vpcId.equals(text(a, "VPCId")))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No association between resolver rule " + ruleId + " and VPC " + vpcId, 400));
ruleAssociationStore.delete(text(association, "Id"));
ObjectNode result = association.deepCopy();
result.put("Status", "DELETING");
return result;
}
public ObjectNode getResolverRuleAssociation(String id) {
return require(ruleAssociationStore, id, "resolver rule association").deepCopy();
}
public List<ObjectNode> listResolverRuleAssociations() {
return ruleAssociationStore.scan(key -> true).stream().map(ObjectNode::deepCopy).toList();
}
/**
* AWS gives a resolver endpoint a direction-specific id prefix: {@code rslvr-in-} for
* inbound endpoints, {@code rslvr-out-} for outbound. {@code INBOUND_DELEGATION} is an
* inbound variant and shares the inbound prefix. Anything outside
* {@code ResolverEndpointDirection} is rejected rather than defaulted.
*/
private static String endpointIdPrefix(String direction) {
return switch (direction) {
case "INBOUND", "INBOUND_DELEGATION" -> "rslvr-in";
case "OUTBOUND" -> "rslvr-out";
default -> throw new AwsException(INVALID_PARAMETER,
"Direction must be one of INBOUND, OUTBOUND, INBOUND_DELEGATION: " + direction, 400);
};
}
// ---------- Shared helpers ----------
/**
* Route 53 Resolver creates are idempotent on {@code CreatorRequestId}: replaying a
* token returns the resource it originally created rather than allocating a second
* one. Called after the request's own validation so a replayed token never excuses a
* malformed body. A blank/absent token opts out — those creates always allocate.
*
* <p>The 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.</p>
*
* <p>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.</p>
*/
private java.util.Optional<ObjectNode> replayOf(StorageBackend<String, ObjectNode> store, JsonNode request,
String region) {
String creatorRequestId = text(request, "CreatorRequestId");
if (creatorRequestId == null || creatorRequestId.isBlank()) {
return java.util.Optional.empty();
}
String regionPrefix = "arn:aws:route53resolver:" + region + ":";
return store.scan(key -> true).stream()
.filter(existing -> creatorRequestId.equals(text(existing, "CreatorRequestId")))
.filter(existing -> {
String arn = text(existing, "Arn");
return arn != null && arn.startsWith(regionPrefix);
})
.findFirst()
.map(ObjectNode::deepCopy);
}
/**
* A retried create must describe the same resource it originally created. AWS models
* {@code ResourceExistsException} on {@code CreateResolverEndpoint} and
* {@code CreateResolverRule} for a {@code CreatorRequestId} replayed with different
* parameters, rather than returning the original and leaving the caller holding a
* success response whose attributes are not the ones it asked for.
*
* <p>Only members the retry actually supplies are compared, so omitting an optional
* one is not read as a disagreement.</p>
*
* <p>{@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.</p>
*/
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}.
*
* <p>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.</p>
*
* <p>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.</p>
*/
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.
*
* <p>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.</p>
*/
private ArrayNode normalizedIpRequests(JsonNode ipAddresses) {
List<JsonNode> entries = new java.util.ArrayList<>();
ipAddresses.forEach(entries::add);
entries.sort(java.util.Comparator.comparing(Route53ResolverService::canonicalKey));
ArrayNode normalized = objectMapper.createArrayNode();
entries.forEach(normalized::add);
return normalized;
}
/** A node's contents as a string that does not depend on the order its members were written in. */
private static String canonicalKey(JsonNode node) {
if (node.isObject()) {
List<String> names = new java.util.ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
java.util.Collections.sort(names);
StringBuilder key = new StringBuilder("{");
for (String name : names) {
key.append(name).append('=').append(canonicalKey(node.get(name))).append(';');
}
return key.append('}').toString();
}
if (node.isArray()) {
StringBuilder key = new StringBuilder("[");
node.forEach(element -> key.append(canonicalKey(element)).append(';'));
return key.append(']').toString();
}
return node.asText();
}
private AwsException replayConflict(JsonNode request, ObjectNode existing, String field) {
return new AwsException("ResourceExistsException",
"CreatorRequestId " + text(request, "CreatorRequestId") + " was already used to create "
+ text(existing, "Id") + " with a different " + field + ".", 400);
}
private ObjectNode require(StorageBackend<String, ObjectNode> store, String id, String type) {
return store.get(id).orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Unknown " + type + ": " + id, 400));
}
/**
* Rejects a value the botocore model does not list in the member's enum. Accepting one
* stores a resource AWS would never have created — a rule whose {@code RuleType} is not
* a {@code RuleTypeOption} is then handed back by Get/List as though it were real.
*
* <p>The 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}.</p>
*/
private static void requireEnum(String value, String field, List<String> allowed, String errorCode) {
if (!allowed.contains(value)) {
throw new AwsException(errorCode,
field + " must be one of " + String.join(", ", allowed) + ": " + value, 400);
}
}
private String requireText(JsonNode node, String field, String errorCode) {
String value = text(node, field);
if (value == null || value.isBlank()) {
throw new AwsException(errorCode, field + " is required", 400);
}
return value;
}
private String text(JsonNode node, String field) {
JsonNode value = node == null ? null : node.get(field);
return value == null || value.isNull() ? null : value.asText();
}
private void copyIfPresent(JsonNode source, ObjectNode target, String... fields) {
for (String field : fields) {
if (source.has(field)) {
target.set(field, source.get(field).deepCopy());
}
}
}
private String id(String prefix) {
return prefix + "-" + UUID.randomUUID().toString().replace("-", "").substring(0, 13);
}
private static FirewallDomainList managedList(String region, String name) {
String id = "rslvr-fdl-" + deterministicHex(region + "|" + name, 17);
// Managed lists are AWS-owned: their ARNs carry no account id.
String arn = "arn:aws:route53resolver:" + region + "::firewall-domain-list/" + id;
return new FirewallDomainList(id, arn, name, MANAGED_OWNER_NAME);
}
private static String deterministicHex(String seed, int length) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(seed.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest).substring(0, length);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 unavailable", e);
}
}
}