From 7f785fdc4cd618fbf404e2f3aa7ef77a772b1549 Mon Sep 17 00:00:00 2001 From: Aniket Shukla Date: Sat, 31 Oct 2026 15:06:44 +0530 Subject: [PATCH] feat(route53): support reusable delegation sets (#7020) * feat(route53): add reusable delegation set APIs * feat(route53): associate reusable delegation sets with hosted zones * fix(route53): preserve delegation ownership and assignments * fix(route53): authorize delegation set operations by matched route * fix(route53): filter hosted zones by reusable delegation set * fix(iam): select REST XML denials from the service catalog * perf(test): reuse Route53 IAM enforcement fixtures --- docs/services/index.md | 2 +- docs/services/route53.md | 34 +- .../core/common/IamEnforcementFilter.java | 28 +- .../floci/services/iam/IamActionRegistry.java | 19 ++ .../services/iam/ResourceArnBuilder.java | 15 + .../services/route53/Route53Controller.java | 93 +++++- .../services/route53/Route53Service.java | 179 ++++++++++- .../services/route53/model/DelegationSet.java | 12 + .../services/route53/model/HostedZone.java | 10 + .../core/common/IamEnforcementFilterTest.java | 50 +++ .../services/iam/IamActionRegistryTest.java | 17 + .../services/iam/ResourceArnBuilderTest.java | 18 ++ ...legationSetHostedZonesIntegrationTest.java | 216 +++++++++++++ ...tionSetsIamEnforcementIntegrationTest.java | 185 +++++++++++ .../Route53DelegationSetsIntegrationTest.java | 185 +++++++++++ .../Route53DelegationSetsServiceTest.java | 301 ++++++++++++++++++ .../floci/testing/AwsTestClients.java | 13 +- 17 files changed, 1343 insertions(+), 34 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/route53/model/DelegationSet.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetHostedZonesIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsIamEnforcementIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsServiceTest.java diff --git a/docs/services/index.md b/docs/services/index.md index a45f54038c..d14d0c2ef6 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -126,7 +126,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 | | [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 37 | | [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 | 27 | +| [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*`, `/2013-04-01/delegationset/*` | REST XML | 31 | | [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 22 | | [Amazon SageMaker](sagemaker.md) | `POST /` + `X-Amz-Target: SageMaker.*` | JSON 1.1 | 20 | | [SageMaker Runtime](sagemaker.md#endpoint-hosting) | `/endpoints/{EndpointName}/invocations` | REST (binary payload) | 1 | diff --git a/docs/services/route53.md b/docs/services/route53.md index 6d25d79e1f..9eda9d2f50 100644 --- a/docs/services/route53.md +++ b/docs/services/route53.md @@ -1,12 +1,16 @@ # Route53 -Route53 emulation supporting hosted zones, resource record sets, health checks, change tracking, and tagging. Private hosted zones provide embedded DNS resolution for cluster containers such as EKS and workloads wired to Floci's embedded DNS server. +Route53 emulation supporting hosted zones, reusable delegation sets, resource record sets, health checks, change tracking, and tagging. Private hosted zones provide embedded DNS resolution for cluster containers such as EKS and workloads wired to Floci's embedded DNS server. ## Supported Operations | Action | Description | | --- | --- | +| `CreateReusableDelegationSet` | `POST /2013-04-01/delegationset`. Optionally promotes an existing public zone with `HostedZoneId`. | +| `GetReusableDelegationSet` | `GET /2013-04-01/delegationset/{Id}` | +| `DeleteReusableDelegationSet` | `DELETE /2013-04-01/delegationset/{Id}`. Refuses to delete a set in use by a zone. | +| `ListReusableDelegationSets` | `GET /2013-04-01/delegationset`. Paginates with `marker` / `maxitems`. | | `CreateHostedZone` | `POST /2013-04-01/hostedzone`. A `` element in the request creates a private zone and records the first VPC association. | | `GetHostedZone` | `GET /2013-04-01/hostedzone/{Id}`. Private zones include their `` list. | | `UpdateHostedZoneComment` | `POST /2013-04-01/hostedzone/{Id}` | @@ -79,7 +83,7 @@ Public address routing, aliases, CNAME chasing, health-based or weighted record ## Default Nameservers -New zones use these nameservers (configurable via `floci.services.route53.*`): +New zones without a reusable delegation set use these nameservers (configurable via `floci.services.route53.*`): ``` ns-1.awsdns-01.org @@ -90,7 +94,30 @@ ns-4.awsdns-04.co.uk A configured name can be written with or without the final dot. The delegation set lists it without the dot, as Route 53 does. A new zone's apex NS records, and the primary server named in its SOA record (the first nameserver), use the fully qualified form with the dot. -The apex NS and SOA records are written when a zone is created, while the delegation set that `CreateHostedZone` and `GetHostedZone` return always reflects the current settings. A zone kept in persistent storage therefore keeps its original NS and SOA records after these settings change; update them with an `UPSERT` change. +For zones without a reusable delegation set, the apex NS and SOA records are written when a zone is created, while the delegation set that `CreateHostedZone` and `GetHostedZone` return reflects the current settings. A zone kept in persistent storage therefore keeps its original NS and SOA records after these settings change; update them with an `UPSERT` change. + +## Reusable Delegation Sets + +`CreateReusableDelegationSet`, `GetReusableDelegationSet`, `ListReusableDelegationSets`, and `DeleteReusableDelegationSet` implement the APIs used by the `aws_route53_delegation_set` Terraform resource. Sets are owned by the calling account and shared across regions. A duplicate live `CallerReference` returns `DelegationSetAlreadyCreated`. Listing uses `marker` / `maxitems`, returns at most 100 sets, and identifies the first set of the next page with `NextMarker`. + +The four delegation-set operations honor IAM policies when enforcement is enabled. Get and delete authorize the selected set's global ARN; create and list require wildcard resources. + +Pass `delegationsetid` to `ListHostedZones` to filter by a reusable set before pagination. An unknown set, including one owned by another account, returns `NoSuchDelegationSet`. + +Pass `DelegationSetId` to `CreateHostedZone` to reuse a set. The create/get responses include its ID, caller reference, and name servers; the new zone's apex NS records and SOA primary server use those same servers. Passing `HostedZoneId` to `CreateReusableDelegationSet` marks an existing public zone's delegation set as reusable. Private zones cannot use reusable sets. Deleting a set associated with any hosted zone returns `DelegationSetInUse`; delete its zones first. The default quotas are 100 sets per account and 100 hosted zones per set. + +A new standalone set snapshots the four configured local nameservers. Promotion reuses the zone's original assignment, even after configuration or apex NS changes. Older stored zones without a separate assignment recover it from their four apex NS entries, falling back to current settings when those entries are unavailable. Its servers and zone associations persist through the configured Route53 storage backend and remain stable after configuration changes. Floci does not allocate distinct AWS nameservers for each set, so different sets may contain the same servers. Requests selecting a reusable set reject equal, parent, or child public-zone names that share a nameserver with an existing public zone (`ConflictingDomainExists`). Sibling domains can share a set. This feature manages delegation metadata and apex records; public DNS delegation referrals remain unsupported. + +```bash +set_id=$(aws route53 create-reusable-delegation-set \ + --caller-reference local-delegation --query DelegationSet.Id --output text) +aws route53 create-hosted-zone \ + --name first.example.com --caller-reference first-zone \ + --delegation-set-id "$set_id" +aws route53 create-hosted-zone \ + --name second.example.com --caller-reference second-zone \ + --delegation-set-id "$set_id" +``` ## Configuration @@ -178,7 +205,6 @@ the record. DELETE still requires matching record values and routing properties. ## Not Supported (Phase 2) -- Reusable delegation sets - Traffic policies and traffic policy instances - Query logging configs - DNSSEC (key signing keys, enabling/disabling) diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index 4fd5ad8d41..7bfd052421 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -776,7 +776,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST; String servingScope = servingCredentialScope(claimedScope, ctx); if (rest) { - return new ResolvedAuthorization(servingScope, actionRegistry.resolveRoute(servingScope, ctx)); + return new ResolvedAuthorization(servingScope, routeAction(servingScope, ctx)); } String targetOperation = IamActionRegistry.targetOperation(ctx); String action = actionRegistry.resolve(servingScope, ctx); @@ -907,13 +907,18 @@ public class IamEnforcementFilter implements ContainerRequestFilter { && claim.protocol() != WireProtocol.REST; } + private String routeAction(String scope, ContainerRequestContext ctx) { + String matched = actionRegistry.resolveMatchedRoute(scope, resourceInfo); + return matched != null ? matched : actionRegistry.resolveRoute(scope, ctx); + } + private ResolvedAuthorization resolveRestAuthorization(ServiceDescriptor descriptor, ContainerRequestContext ctx) { return descriptor.credentialScopes().stream() .map(catalog::canonicalCredentialScope) .distinct() .sorted() - .map(scope -> new ResolvedAuthorization(scope, actionRegistry.resolveRoute(scope, ctx))) + .map(scope -> new ResolvedAuthorization(scope, routeAction(scope, ctx))) .filter(authorization -> authorization.action() != null) .findFirst() .orElse(null); @@ -1661,8 +1666,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { || "apigateway".equals(credentialScope)) { return arnBuilder.buildResources(credentialScope, ctx, region, accountId, requestPartition()); } - return arnBuilder.buildResources(credentialScope, operation, ctx, region, accountId, - AwsRegions.partitionFor(region)); + String partition = "route53".equals(credentialScope) ? requestPartition() : AwsRegions.partitionFor(region); + return arnBuilder.buildResources(credentialScope, operation, ctx, region, accountId, partition); } /** @@ -1775,11 +1780,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return accessDeniedResponse(action, credentialScope, requestMediaType, resourceArn, WireProtocol.REST); } - private static Response accessDeniedForRequest(String action, String credentialScope, ContainerRequestContext ctx) { + private Response accessDeniedForRequest(String action, String credentialScope, ContainerRequestContext ctx) { return accessDeniedForRequest(action, credentialScope, ctx, null); } - private static Response accessDeniedForRequest(String action, String credentialScope, + private Response accessDeniedForRequest(String action, String credentialScope, ContainerRequestContext ctx, String resourceArn) { WireProtocol protocol = claimedProtocol(ctx); if (isCbor(protocol)) { @@ -1792,7 +1797,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { if (IamActionRegistry.isS3ControlRequest(credentialScope, ctx)) { return s3ControlXmlAccessDenied(accessDeniedMessage(action)); } - return accessDeniedResponse(action, credentialScope, ctx.getMediaType(), resourceArn, protocol); + boolean restXml = catalog.byCredentialScope(credentialScope) + .filter(descriptor -> descriptor.supportsProtocol(ServiceProtocol.REST_XML)).isPresent(); + return accessDeniedResponse(action, credentialScope, ctx.getMediaType(), resourceArn, protocol, restXml); } private static String accessDeniedMessage(String action) { @@ -1801,12 +1808,17 @@ public class IamEnforcementFilter implements ContainerRequestFilter { static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType, String resourceArn, WireProtocol protocol) { + return accessDeniedResponse(action, credentialScope, requestMediaType, resourceArn, protocol, false); + } + + private static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType, + String resourceArn, WireProtocol protocol, boolean restXml) { String message = accessDeniedMessage(action); if ("s3".equals(credentialScope)) { String resourcePath = formatS3ResourcePath(resourceArn); return s3XmlAccessDenied(message, resourcePath); } - if (protocol == WireProtocol.AWS_QUERY || isFormEncoded(requestMediaType)) { + if (restXml || protocol == WireProtocol.AWS_QUERY || isFormEncoded(requestMediaType)) { return queryXmlError(queryAccessDeniedCode(credentialScope), message); } int status = protocol == WireProtocol.AWS_JSON_1_0 || protocol == WireProtocol.AWS_JSON_1_1 ? 400 : 403; diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java index 4360a80695..76aa562081 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java @@ -7,15 +7,18 @@ import io.github.hectorvent.floci.core.common.ProtocolClaim; import io.github.hectorvent.floci.core.common.WireProtocol; import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser; import io.github.hectorvent.floci.services.eks.EksController; +import io.github.hectorvent.floci.services.route53.Route53Controller; import io.github.hectorvent.floci.services.s3.S3ObjectActions; import jakarta.enterprise.context.ApplicationScoped; import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ResourceInfo; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.UriInfo; import org.jboss.logging.Logger; import java.util.List; +import java.util.Map; import java.util.regex.Pattern; /** @@ -30,6 +33,12 @@ import java.util.regex.Pattern; @ApplicationScoped public class IamActionRegistry { + private static final Map ROUTE53_DELEGATION_ACTIONS = Map.of( + "createReusableDelegationSet", "route53:CreateReusableDelegationSet", + "getReusableDelegationSet", "route53:GetReusableDelegationSet", + "listReusableDelegationSets", "route53:ListReusableDelegationSets", + "deleteReusableDelegationSet", "route53:DeleteReusableDelegationSet"); + private static final Logger LOG = Logger.getLogger(IamActionRegistry.class); private static final ObjectMapper MAPPER = new ObjectMapper(); @@ -631,6 +640,16 @@ public class IamActionRegistry { return IamAuthorizedActions.actionFor(credentialScope, operationName); } + /** The serving method identifies these actions even when path encoding or matrix parameters vary. */ + public String resolveMatchedRoute(String credentialScope, ResourceInfo resourceInfo) { + if ("route53".equals(credentialScope) && resourceInfo != null + && Route53Controller.class.equals(resourceInfo.getResourceClass()) + && resourceInfo.getResourceMethod() != null) { + return ROUTE53_DELEGATION_ACTIONS.get(resourceInfo.getResourceMethod().getName()); + } + return null; + } + /** * The action of a REST request, from its method and path alone. A REST request is the operation * whose route it reached, so neither an {@code X-Amz-Target} header nor a Query {@code Action} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index e845bf31cd..c5bde5e5ab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -203,6 +203,10 @@ public class ResourceArnBuilder { case "dsql" -> List.of(buildDsqlArn(path, ctx, region, accountId, partition)); case "eks" -> List.of(buildEksArn(path, ctx, region, accountId)); case "apigateway" -> List.of(buildApiGatewayArn(ctx, region, partition)); + case "route53" -> "route53:GetReusableDelegationSet".equals(operation) + || "route53:DeleteReusableDelegationSet".equals(operation) + ? List.of(buildRoute53DelegationSetArn(ctx, partition)) + : namedResources(credentialScope, operation, ctx, region, accountId, partition); default -> namedResources(credentialScope, operation, ctx, region, accountId, partition); }; } @@ -233,6 +237,17 @@ public class ResourceArnBuilder { return null; } + private String buildRoute53DelegationSetArn(ContainerRequestContext ctx, String partition) { + String id = ctx.getUriInfo().getPathParameters().getFirst("Id"); + if (id == null) { + return "*"; + } + if (id.startsWith("/delegationset/")) { + id = id.substring(15); + } + return AwsArnUtils.Arn.global(partition, "route53", "", "delegationset/" + id).toString(); + } + private String buildResourceGroupArn(ContainerRequestContext ctx, String region, String accountId) { JsonNode body = readJsonBody(ctx); if (body == null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Controller.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Controller.java index 224c920955..a2af827167 100644 --- a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Controller.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.XmlParser; import io.github.hectorvent.floci.services.route53.Route53Service.CreateZoneResult; import io.github.hectorvent.floci.services.route53.model.AliasTarget; import io.github.hectorvent.floci.services.route53.model.ChangeInfo; +import io.github.hectorvent.floci.services.route53.model.DelegationSet; import io.github.hectorvent.floci.services.route53.model.HealthCheck; import io.github.hectorvent.floci.services.route53.model.HealthCheckConfig; import io.github.hectorvent.floci.services.route53.model.HostedZone; @@ -45,6 +46,70 @@ public class Route53Controller { @Inject Route53Service service; + @POST + @Path("/delegationset") + public Response createReusableDelegationSet(String body) { + try { + if (!"CreateReusableDelegationSetRequest".equals(XmlParser.rootElementName(body))) { + throw new AwsException("InvalidInput", + "The request body must be a CreateReusableDelegationSetRequest document.", 400); + } + DelegationSet set = service.createReusableDelegationSet(XmlParser.extractFirst(body, "CallerReference", null), + XmlParser.extractFirst(body, "HostedZoneId", null)); + String xml = new XmlBuilder().start("CreateReusableDelegationSetResponse", NS) + .raw(xmlDelegationSet(set)).end("CreateReusableDelegationSetResponse").build(); + return Response.created(URI.create("/2013-04-01/delegationset/" + set.id())).type(XML).entity(xml).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/delegationset/{Id}") + public Response getReusableDelegationSet(@PathParam("Id") String id) { + try { + String xml = new XmlBuilder().start("GetReusableDelegationSetResponse", NS) + .raw(xmlDelegationSet(service.getReusableDelegationSet(id))) + .end("GetReusableDelegationSetResponse").build(); + return Response.ok(xml, XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/delegationset/{Id}") + public Response deleteReusableDelegationSet(@PathParam("Id") String id) { + try { + service.deleteReusableDelegationSet(id); + return Response.ok().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/delegationset") + public Response listReusableDelegationSets(@QueryParam("marker") String marker, + @QueryParam("maxitems") @DefaultValue("100") String maxItems) { + try { + Route53Pagination.Page page = service.pageReusableDelegationSets(marker, maxItems); + XmlBuilder xml = new XmlBuilder().start("ListReusableDelegationSetsResponse", NS).start("DelegationSets"); + for (DelegationSet set : page.items()) { + xml.raw(xmlDelegationSet(set)); + } + xml.end("DelegationSets").elem("Marker", marker == null ? "" : marker) + .elem("IsTruncated", page.isTruncated()); + if (page.isTruncated()) { + xml.elem("NextMarker", page.nextMarker()); + } + xml.elem("MaxItems", maxItems).end("ListReusableDelegationSetsResponse"); + return Response.ok(xml.build(), XML).build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + // ── Hosted Zones ────────────────────────────────────────────────────────── @POST @@ -63,12 +128,16 @@ public class Route53Controller { throw new AwsException("InvalidInput", "Name and CallerReference are required.", 400); } - CreateZoneResult result = service.createHostedZone(name, callerRef, comment, vpcAssociation); + String delegationSetId = XmlParser.extractFirst(body, "DelegationSetId", null); + if (delegationSetId != null && Boolean.parseBoolean(XmlParser.extractFirst(body, "PrivateZone", "false"))) { + throw new AwsException("InvalidInput", "A private hosted zone cannot use a reusable delegation set.", 400); + } + CreateZoneResult result = service.createHostedZone(name, callerRef, comment, vpcAssociation, delegationSetId); XmlBuilder xml = new XmlBuilder() .start("CreateHostedZoneResponse", NS) .raw(xmlHostedZone(result.zone())) .raw(xmlChangeInfo(result.change())) - .raw(xmlDelegationSet()); + .raw(xmlDelegationSet(service.getDelegationSet(result.zone()))); if (!result.zone().getVpcAssociations().isEmpty()) { xml.raw(xmlVpcAssociation(result.zone().getVpcAssociations().getFirst())); } @@ -91,7 +160,7 @@ public class Route53Controller { String xml = new XmlBuilder() .start("GetHostedZoneResponse", NS) .raw(xmlHostedZone(zone)) - .raw(xmlDelegationSet()) + .raw(xmlDelegationSet(service.getDelegationSet(zone))) .raw(xmlVpcAssociations(zone.getVpcAssociations())) .end("GetHostedZoneResponse") .build(); @@ -142,9 +211,10 @@ public class Route53Controller { @GET @Path("/hostedzone") public Response listHostedZones(@QueryParam("marker") String marker, - @QueryParam("maxitems") @DefaultValue("100") int maxItems) { + @QueryParam("maxitems") @DefaultValue("100") int maxItems, + @QueryParam("delegationsetid") String delegationSetId) { try { - Route53Pagination.Page page = service.pageHostedZones(marker, maxItems); + Route53Pagination.Page page = service.pageHostedZones(marker, maxItems, delegationSetId); XmlBuilder xml = new XmlBuilder() .start("ListHostedZonesResponse", NS) @@ -628,7 +698,7 @@ public class Route53Controller { .elem("Type", type) .elem("Value", value) .end("Limit") - .elem("Count", 0L) + .elem("Count", "MAX_REUSABLE_DELEGATION_SETS_BY_OWNER".equals(type) ? service.getReusableDelegationSetCount() : 0L) .end("GetAccountLimitResponse") .build(); return Response.ok(xml, XML).build(); @@ -735,15 +805,14 @@ public class Route53Controller { .build(); } - private String xmlDelegationSet() { - XmlBuilder xml = new XmlBuilder() - .start("DelegationSet") + private String xmlDelegationSet(DelegationSet set) { + XmlBuilder xml = new XmlBuilder().start("DelegationSet") + .elem("Id", set.id() == null ? null : "/delegationset/" + set.id()).elem("CallerReference", set.callerReference()) .start("NameServers"); - for (String ns : service.getNameServers()) { + for (String ns : set.nameServers()) { xml.elem("NameServer", ns); } - xml.end("NameServers").end("DelegationSet"); - return xml.build(); + return xml.end("NameServers").end("DelegationSet").build(); } private String xmlVpcAssociation(VpcAssociation association) { diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java index 792677cc72..300abc737c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java @@ -13,6 +13,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.route53.model.AliasTarget; import io.github.hectorvent.floci.services.route53.model.ChangeInfo; +import io.github.hectorvent.floci.services.route53.model.DelegationSet; import io.github.hectorvent.floci.services.route53.model.HealthCheck; import io.github.hectorvent.floci.services.route53.model.HealthCheckConfig; import io.github.hectorvent.floci.services.route53.model.HostedZone; @@ -22,6 +23,7 @@ import io.github.hectorvent.floci.services.route53.model.VpcAssociation; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.math.BigInteger; import java.security.SecureRandom; import java.time.Instant; import java.util.ArrayList; @@ -48,6 +50,7 @@ public class Route53Service implements Resettable { private record OwnedZone(String accountId, HostedZone zone) {} private final StorageBackend zoneStore; + private final StorageBackend delegationSetStore; private final StorageBackend> recordStore; private final StorageBackend healthCheckStore; private final StorageBackend changeStore; @@ -68,6 +71,8 @@ public class Route53Service implements Resettable { Ec2Service ec2Service) { this.zoneStore = factory.create("route53", "route53-zones.json", new TypeReference>() {}); + this.delegationSetStore = factory.create("route53", "route53-delegation-sets.json", + new TypeReference>() {}); this.recordStore = factory.create("route53", "route53-records.json", new TypeReference>>() {}); this.healthCheckStore = factory.create("route53", "route53-health-checks.json", @@ -96,10 +101,127 @@ public class Route53Service implements Resettable { } } + public synchronized DelegationSet createReusableDelegationSet(String callerReference, String hostedZoneId) { + if (callerReference == null || callerReference.isEmpty() || callerReference.length() > 128) { + throw new AwsException("InvalidInput", "CallerReference must contain between 1 and 128 characters.", 400); + } + for (DelegationSet existing : delegationSetStore.scan(k -> true)) { + if (existing.callerReference().equals(callerReference)) { + throw new AwsException("DelegationSetAlreadyCreated", + "A reusable delegation set with this caller reference already exists.", 400); + } + } + if (delegationSetStore.keys().size() >= 100) { + throw new AwsException("LimitsExceeded", "The reusable delegation set limit has been reached.", 400); + } + HostedZone source = null; + if (hostedZoneId != null) { + String zoneId = hostedZoneId.startsWith("/hostedzone/") ? hostedZoneId.substring(12) : hostedZoneId; + if (zoneId.isEmpty() || zoneId.length() > 32) { + throw new AwsException("InvalidInput", "HostedZoneId must contain between 1 and 32 characters.", 400); + } + try { + source = getHostedZoneOwnedByCaller(zoneId); + } catch (AwsException e) { + if (!"NoSuchHostedZone".equals(e.getErrorCode())) { + throw e; + } + throw new AwsException("HostedZoneNotFound", "The specified hosted zone cannot be found.", 400); + } + if (source.isPrivateZone()) { + throw new AwsException("InvalidArgument", "A private hosted zone cannot have a reusable delegation set.", 400); + } + if (source.getDelegationSetId() != null) { + throw new AwsException("DelegationSetAlreadyReusable", "The hosted zone's delegation set is already reusable.", 400); + } + } + String id = "N" + generateZoneId().substring(1); + DelegationSet set = new DelegationSet(id, callerReference, + source == null ? nameServers : assignedNameServers(source)); + delegationSetStore.put(id, set); + if (source != null) { + source.setDelegationSetId(id); + source.setDelegationNameServers(set.nameServers()); + zoneStore.put(source.getId(), source); + } + return set; + } + + public DelegationSet getReusableDelegationSet(String id) { + String cleanId = delegationSetId(id); + return delegationSetStore.get(cleanId).orElseThrow(() -> + new AwsException("NoSuchDelegationSet", "No reusable delegation set found with ID: " + cleanId, 400)); + } + + public synchronized void deleteReusableDelegationSet(String id) { + DelegationSet set = getReusableDelegationSet(id); + if (zoneStore.scan(k -> true).stream().anyMatch(zone -> set.id().equals(zone.getDelegationSetId()))) { + throw new AwsException("DelegationSetInUse", "The reusable delegation set is associated with a hosted zone.", 400); + } + delegationSetStore.delete(set.id()); + } + + public DelegationSet getDelegationSet(HostedZone zone) { + return zone.getDelegationSetId() == null ? new DelegationSet(null, null, nameServers) + : getReusableDelegationSet(zone.getDelegationSetId()); + } + + public long getReusableDelegationSetCount() { + return delegationSetStore.keys().size(); + } + + Route53Pagination.Page pageReusableDelegationSets(String marker, String maxItems) { + if (marker != null && marker.length() > 64) { + throw new AwsException("InvalidInput", "Marker must contain at most 64 characters.", 400); + } + int pageSize; + try { + BigInteger requested = new BigInteger(maxItems); + if (requested.signum() <= 0) { + throw new NumberFormatException("Nonpositive page size"); + } + pageSize = requested.min(BigInteger.valueOf(100)).intValueExact(); + } catch (NumberFormatException e) { + throw new AwsException("InvalidInput", "MaxItems must be a positive integer.", 400); + } + List sets = delegationSetStore.scan(k -> true).stream() + .filter(set -> marker == null || set.id().compareTo(marker) >= 0) + .sorted(Comparator.comparing(DelegationSet::id)).toList(); + return Route53Pagination.page(sets, null, pageSize, DelegationSet::id); + } + + private List assignedNameServers(HostedZone zone) { + if (zone.getDelegationSetId() != null) { + return getReusableDelegationSet(zone.getDelegationSetId()).nameServers(); + } + if (!zone.getDelegationNameServers().isEmpty()) { + return zone.getDelegationNameServers(); + } + // Older zones did not store their assignment separately from the apex NS records. + List stored = recordStore.get(zone.getId()).orElse(List.of()).stream() + .filter(record -> "NS".equals(record.getType()) && isApexSoaOrNs(record, zone.getName())) + .flatMap(record -> record.getRecords().stream()).map(ResourceRecord::getValue) + .map(Route53Service::delegationName).toList(); + return stored.size() == 4 ? stored : nameServers; + } + + private static String delegationSetId(String id) { + String cleanId = id == null ? "" : id.startsWith("/delegationset/") ? id.substring(15) : id; + if (cleanId.isEmpty() || cleanId.length() > 32) { + throw new AwsException("InvalidInput", "DelegationSetId must contain between 1 and 32 characters.", 400); + } + return cleanId; + } + // ── Hosted Zones ────────────────────────────────────────────────────────── public synchronized CreateZoneResult createHostedZone(String name, String callerReference, String comment, VpcAssociation vpcAssociation) { + return createHostedZone(name, callerReference, comment, vpcAssociation, null); + } + + public synchronized CreateZoneResult createHostedZone(String name, String callerReference, String comment, + VpcAssociation vpcAssociation, String delegationSetId) { String normalizedName = normalizeName(name); for (HostedZone existing : zoneStore.scan(k -> true)) { @@ -109,25 +231,57 @@ public class Route53Service implements Resettable { } } + DelegationSet set = null; + if (delegationSetId != null) { + if (vpcAssociation != null) { + throw new AwsException("InvalidInput", "A private hosted zone cannot use a reusable delegation set.", 400); + } + set = getReusableDelegationSet(delegationSetId); + validateDelegationSetForZone(set, normalizedName); + } String id = generateZoneId(); String callerAccountId = callerAccountId(); validateVpcOwnershipIfKnown(vpcAssociation, callerAccountId); HostedZone zone = new HostedZone(id, normalizedName, callerReference, comment, vpcAssociation); zone.setOwnerAccountId(callerAccountId); + zone.setDelegationSetId(set == null ? null : set.id()); + zone.setDelegationNameServers(set == null ? nameServers : set.nameServers()); if (vpcAssociation != null) { vpcAssociation.setOwnerAccountId(callerAccountId); } zoneNameCounts(zone.isPrivateZone()).merge(normalizedName.toLowerCase(), 1, Integer::sum); zoneStore.put(id, zone); - recordStore.put(id, buildDefaultRecords(normalizedName)); + recordStore.put(id, buildDefaultRecords(normalizedName, zone.getDelegationNameServers())); ChangeInfo change = newChange(null); return new CreateZoneResult(zone, change); } + private void validateDelegationSetForZone(DelegationSet set, String name) { + String accountId = callerAccountId(); + List zones = allHostedZonesAcrossAccounts().stream() + .filter(owned -> accountId.equals(owned.accountId()) && accountId.equals(ownerAccountId(owned.zone()))) + .map(OwnedZone::zone).toList(); + if (zones.stream().filter(zone -> set.id().equals(zone.getDelegationSetId())).count() >= 100) { + throw new AwsException("TooManyHostedZones", "The hosted zone limit for this reusable delegation set has been reached.", 400); + } + String normalizedName = normalizeRecordName(name); + for (HostedZone existing : zones) { + if (existing.isPrivateZone()) { + continue; + } + String existingName = normalizeRecordName(existing.getName()); + boolean related = DomainNames.isWithin(normalizedName, existingName) + || DomainNames.isWithin(existingName, normalizedName); + if (related && assignedNameServers(existing).stream().anyMatch(ns -> + set.nameServers().stream().anyMatch(candidate -> ns.equalsIgnoreCase(candidate)))) { + throw new AwsException("ConflictingDomainExists", + "The domain overlaps a public hosted zone that uses the same name servers.", 400); + } + } + } + public HostedZone getHostedZone(String id) { - HostedZone zone = zoneStore.get(id).orElseThrow(() -> - new AwsException("NoSuchHostedZone", - "No hosted zone found with ID: " + id, 404)); + HostedZone zone = getHostedZoneOwnedByCaller(id); zone.setResourceRecordSetCount(recordCount(id)); return zone; } @@ -167,7 +321,15 @@ public class Route53Service implements Resettable { } Route53Pagination.Page pageHostedZones(String marker, int maxItems) { + return pageHostedZones(marker, maxItems, null); + } + + Route53Pagination.Page pageHostedZones(String marker, int maxItems, String delegationSetId) { + String selected = delegationSetId == null ? null : getReusableDelegationSet(delegationSetId).id(); List all = new ArrayList<>(zoneStore.scan(k -> true)); + if (selected != null) { + all.removeIf(zone -> !selected.equals(zone.getDelegationSetId())); + } all.sort(Comparator.comparing(HostedZone::getName).thenComparing(HostedZone::getId)); for (HostedZone zone : all) { zone.setResourceRecordSetCount(recordCount(zone.getId())); @@ -831,7 +993,8 @@ public class Route53Service implements Resettable { return zone; } - HostedZone zone = getHostedZone(zoneId); + HostedZone zone = zoneStore.get(zoneId).orElseThrow(() -> + new AwsException("NoSuchHostedZone", "No hosted zone found with ID: " + zoneId, 404)); if (!ownerAccountId(zone).equals(callerAccountId)) { throw new AwsException("NoSuchHostedZone", "No hosted zone found with ID: " + zoneId, 404); @@ -952,7 +1115,7 @@ public class Route53Service implements Resettable { return change; } - private List buildDefaultRecords(String zoneName) { + private List buildDefaultRecords(String zoneName, List zoneNameServers) { List records = new ArrayList<>(); ResourceRecordSet soa = new ResourceRecordSet(); @@ -960,14 +1123,14 @@ public class Route53Service implements Resettable { soa.setType("SOA"); soa.setTtl(900L); soa.setRecords(List.of(new ResourceRecord( - normalizeName(nameServers.get(0)) + " awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400"))); + normalizeName(zoneNameServers.get(0)) + " awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400"))); records.add(soa); ResourceRecordSet ns = new ResourceRecordSet(); ns.setName(zoneName); ns.setType("NS"); ns.setTtl(172800L); - ns.setRecords(nameServers.stream() + ns.setRecords(zoneNameServers.stream() .map(n -> new ResourceRecord(normalizeName(n))) .toList()); records.add(ns); diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/model/DelegationSet.java b/src/main/java/io/github/hectorvent/floci/services/route53/model/DelegationSet.java new file mode 100644 index 0000000000..e1eb8ad07a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/route53/model/DelegationSet.java @@ -0,0 +1,12 @@ +package io.github.hectorvent.floci.services.route53.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +@RegisterForReflection +public record DelegationSet(String id, String callerReference, List nameServers) { + public DelegationSet { + nameServers = List.copyOf(nameServers); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/model/HostedZone.java b/src/main/java/io/github/hectorvent/floci/services/route53/model/HostedZone.java index c6ad1873b9..7f6fd106d4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/route53/model/HostedZone.java +++ b/src/main/java/io/github/hectorvent/floci/services/route53/model/HostedZone.java @@ -13,6 +13,8 @@ public class HostedZone { private String callerReference; private String comment; private String ownerAccountId; + private String delegationSetId; + private List delegationNameServers = List.of(); private boolean privateZone; private int resourceRecordSetCount; private List vpcAssociations = new ArrayList<>(); @@ -52,6 +54,14 @@ public class HostedZone { public String getOwnerAccountId() { return ownerAccountId; } public void setOwnerAccountId(String ownerAccountId) { this.ownerAccountId = ownerAccountId; } + public String getDelegationSetId() { return delegationSetId; } + public void setDelegationSetId(String delegationSetId) { this.delegationSetId = delegationSetId; } + + public List getDelegationNameServers() { return delegationNameServers; } + public void setDelegationNameServers(List delegationNameServers) { + this.delegationNameServers = delegationNameServers == null ? List.of() : List.copyOf(delegationNameServers); + } + public boolean isPrivateZone() { return privateZone; } public void setPrivateZone(boolean privateZone) { this.privateZone = privateZone; } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java index fb72285aaf..0953dd2725 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java @@ -149,6 +149,31 @@ class IamEnforcementFilterTest { catalog, scpProvider, sessionAccountLookup, null, null, clock, resourceInfo); } + @ParameterizedTest + @CsvSource({"aws-cn,GetReusableDelegationSet", "aws-cn,DeleteReusableDelegationSet", + "aws-us-gov,GetReusableDelegationSet", "aws-us-gov,DeleteReusableDelegationSet"}) + void delegationSetAuthorizationKeepsTheRequestPartitionForAnUnknownRegion(String partition, String operation) { + ContainerRequestContext request = mock(ContainerRequestContext.class); + String action = "route53:" + operation; + String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260629/future-1/route53/aws4_request, " + + "SignedHeaders=host, Signature=abc"; + requestContext.setAccountId("222233334444"); + requestContext.setRegion("future-1"); + requestContext.setPartition(partition); + when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION"); + when(request.getHeaderString("Authorization")).thenReturn(auth); + when(actionRegistry.resolve("route53", request)).thenReturn(action); + when(iamService.resolveCallerContext(eq("ASIASESSION"), any())).thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"route53:*","Resource":"*"}]} + """))); + when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(action), any(), isNull())) + .thenReturn(IamPolicyEvaluator.Decision.ALLOW); + + newFilter().filter(request); + + verify(arnBuilder).buildResources("route53", action, request, "future-1", "222233334444", partition); + } + @Test void filterBuildsResourceArnWithRequestContextAccount() { ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); @@ -2050,6 +2075,31 @@ class IamEnforcementFilterTest { assertTrue(body.contains(""), body); } + @ParameterizedTest + @CsvSource({"REST_XML, application/xml", "REST_JSON, application/json"}) + void restDenialUsesTheServiceCatalogProtocol(ServiceProtocol serviceProtocol, String expectedContentType) { + ContainerRequestContext request = mock(ContainerRequestContext.class); + String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20261030/us-east-1/catalog-service/aws4_request, " + + "SignedHeaders=host, Signature=abc"; + ServiceDescriptor descriptor = descriptor("catalog-service", serviceProtocol, Set.of("catalog-service"), null); + requestContext.setAccountId("000000000000"); + when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER"); + when(request.getHeaderString("Authorization")).thenReturn(auth); + stubClaim(request, WireProtocol.REST, descriptor); + when(catalog.byCredentialScope("catalog-service")).thenReturn(Optional.of(descriptor)); + when(actionRegistry.resolveRoute("catalog-service", request)).thenReturn("catalog-service:Read"); + when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of())); + when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq("catalog-service:Read"), any(), any())) + .thenReturn(IamPolicyEvaluator.Decision.DENY); + + newFilter().filter(request); + + ArgumentCaptor response = ArgumentCaptor.captor(); + verify(request).abortWith(response.capture()); + assertEquals(403, response.getValue().getStatus()); + assertEquals(MediaType.valueOf(expectedContentType), response.getValue().getMediaType()); + } + /** * SNS refuses with its own {@code AuthorizationError}, the 403 every SNS operation lists, whichever action is * denied (a role it is passed as well as its own); another Query service still answers {@code AccessDenied}. diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java index ea77bde73c..2833f10441 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java @@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.core.common.AwsProtocolClaimFilter; import io.github.hectorvent.floci.core.common.ProtocolClaim; import io.github.hectorvent.floci.core.common.WireProtocol; +import io.github.hectorvent.floci.services.route53.Route53Controller; import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ResourceInfo; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; @@ -18,6 +20,7 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicReference; @@ -38,6 +41,20 @@ class IamActionRegistryTest { private final IamActionRegistry registry = new IamActionRegistry(); + @ParameterizedTest + @CsvSource({"createReusableDelegationSet,CreateReusableDelegationSet", + "getReusableDelegationSet,GetReusableDelegationSet", + "listReusableDelegationSets,ListReusableDelegationSets", + "deleteReusableDelegationSet,DeleteReusableDelegationSet"}) + void matchedDelegationSetMethodsResolveTheirOwnActions(String method, String operation) { + ResourceInfo info = Mockito.mock(ResourceInfo.class); + Mockito.doReturn(Route53Controller.class).when(info).getResourceClass(); + when(info.getResourceMethod()).thenReturn(Arrays.stream(Route53Controller.class.getMethods()) + .filter(candidate -> candidate.getName().equals(method)).findFirst().orElseThrow()); + assertEquals("route53:" + operation, registry.resolveMatchedRoute("route53", info)); + assertNull(registry.resolveMatchedRoute("s3", info)); + } + @ParameterizedTest @CsvSource({"PUT,PutProvisionedConcurrencyConfig", "GET,GetProvisionedConcurrencyConfig", "DELETE,DeleteProvisionedConcurrencyConfig"}) diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index 9bcd860e87..ef16aac22b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -24,6 +24,8 @@ import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.UriInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -55,6 +57,22 @@ class ResourceArnBuilderTest { private MultivaluedMap queryParams; private Map contextProperties; + @ParameterizedTest + @CsvSource({"aws,us-east-1", "aws-us-gov,us-gov-west-1", "aws-cn,cn-north-1"}) + void delegationSetResourcesAreGlobalAndUseTheDecodedId(String partition, String region) { + for (String id : List.of("N1", "%2Fdelegationset%2FN1")) { + when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost/2013-04-01/delegationset/" + id)); + when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost/")); + MultivaluedMap parameters = new MultivaluedHashMap<>(); + parameters.putSingle("Id", id.equals("N1") ? "N1" : "/delegationset/N1"); + when(uriInfo.getPathParameters()).thenReturn(parameters); + for (String operation : List.of("GetReusableDelegationSet", "DeleteReusableDelegationSet")) { + assertEquals(List.of("arn:" + partition + ":route53:::delegationset/N1"), + builder.buildResources("route53", "route53:" + operation, ctx, region, ACCOUNT, partition)); + } + } + } + @BeforeEach void setUp() { builder = new ResourceArnBuilder(new ObjectMapper()); diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetHostedZonesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetHostedZonesIntegrationTest.java new file mode 100644 index 0000000000..02ba848acc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetHostedZonesIntegrationTest.java @@ -0,0 +1,216 @@ +package io.github.hectorvent.floci.services.route53; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.route53.Route53Client; +import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse; +import software.amazon.awssdk.services.route53.model.DelegationSet; +import software.amazon.awssdk.services.route53.model.ListHostedZonesResponse; +import software.amazon.awssdk.services.route53.model.RRType; +import software.amazon.awssdk.services.route53.model.ResourceRecord; +import software.amazon.awssdk.services.route53.model.ResourceRecordSet; +import software.amazon.awssdk.services.route53.model.Route53Exception; + +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class Route53DelegationSetHostedZonesIntegrationTest { + @Test + void zonesReuseTheSetInResponsesAndApexRecordsUntilAllZonesAreDeleted() { + try (Route53Client client = client("741686000010")) { + DelegationSet set = createSet(client); + String first = createZone(client, "first.example.", set.id()).hostedZone().id(); + String second = createZone(client, "second.example.", set.id()).hostedZone().id(); + String firstZone = first; + try { + assertEquals(set, client.getHostedZone(r -> r.id(firstZone)).delegationSet()); + assertEquals(set, client.getHostedZone(r -> r.id(second)).delegationSet()); + List records = client.listResourceRecordSets(r -> r.hostedZoneId(firstZone)) + .resourceRecordSets(); + assertEquals(set.nameServers().stream().map(ns -> ns + ".").sorted().toList(), records.stream() + .filter(r -> r.type() == RRType.NS).flatMap(r -> r.resourceRecords().stream()) + .map(ResourceRecord::value).sorted().toList()); + assertTrue(records.stream().filter(r -> r.type() == RRType.SOA).findFirst().orElseThrow() + .resourceRecords().getFirst().value().startsWith(set.nameServers().getFirst() + ". ")); + assertError("DelegationSetInUse", () -> client.deleteReusableDelegationSet(r -> r.id(set.id()))); + client.deleteHostedZone(r -> r.id(firstZone)); + first = null; + assertError("DelegationSetInUse", () -> client.deleteReusableDelegationSet(r -> r.id(set.id()))); + } finally { + if (first != null) { + String remaining = first; + client.deleteHostedZone(r -> r.id(remaining)); + } + client.deleteHostedZone(r -> r.id(second)); + client.deleteReusableDelegationSet(r -> r.id(set.id())); + } + } + } + + @Test + void createHostedZoneReturnsTheSelectedDelegationSet() { + try (Route53Client client = client("741686000011")) { + DelegationSet set = createSet(client); + CreateHostedZoneResponse zone = createZone(client, "created.example.", set.id()); + try { + assertEquals(set, zone.delegationSet()); + } finally { + client.deleteHostedZone(r -> r.id(zone.hostedZone().id())); + client.deleteReusableDelegationSet(r -> r.id(set.id())); + } + } + } + + @Test + void anExistingPublicZoneCanBePromotedOnlyOnceAndRemainsInUse() { + try (Route53Client client = client("741686000012")) { + CreateHostedZoneResponse zone = createZone(client, "promoted.example.", null); + String reference = UUID.randomUUID().toString(); + DelegationSet set = client.createReusableDelegationSet(r -> + r.callerReference(reference).hostedZoneId(zone.hostedZone().id())).delegationSet(); + try { + assertEquals(zone.delegationSet().nameServers(), set.nameServers()); + assertEquals(reference, set.callerReference()); + assertEquals(set, client.getHostedZone(r -> r.id(zone.hostedZone().id())).delegationSet()); + assertError("DelegationSetAlreadyReusable", () -> client.createReusableDelegationSet(r -> + r.callerReference(UUID.randomUUID().toString()).hostedZoneId(zone.hostedZone().id()))); + assertError("DelegationSetInUse", () -> client.deleteReusableDelegationSet(r -> r.id(set.id()))); + } finally { + client.deleteHostedZone(r -> r.id(zone.hostedZone().id())); + client.deleteReusableDelegationSet(r -> r.id(set.id())); + } + } + } + + @Test + void relatedPublicNamesCannotShareNameServersButSiblingDomainsCan() { + try (Route53Client client = client("741686000013")) { + DelegationSet set = createSet(client); + String zone = createZone(client, "a.example.com.", null).hostedZone().id(); + try { + for (String name : List.of("A.EXAMPLE.COM", "child.a.example.com.", "example.com.")) { + assertError("ConflictingDomainExists", () -> createZone(client, name, set.id())); + } + String sibling = createZone(client, "b.example.com.", set.id()).hostedZone().id(); + client.deleteHostedZone(r -> r.id(sibling)); + } finally { + client.deleteHostedZone(r -> r.id(zone)); + client.deleteReusableDelegationSet(r -> r.id(set.id())); + } + } + } + + @Test + void privateZonesCannotUseOrPromoteAReusableSet() { + try (Route53Client client = client("741686000014")) { + DelegationSet set = createSet(client); + String zone = client.createHostedZone(r -> r.name("private.example.") + .callerReference(UUID.randomUUID().toString()) + .vpc(v -> v.vpcId("vpc-delegation-private").vpcRegion("us-east-1"))).hostedZone().id(); + try { + assertError("InvalidArgument", () -> client.createReusableDelegationSet(r -> + r.callerReference(UUID.randomUUID().toString()).hostedZoneId(zone))); + assertError("InvalidInput", () -> client.createHostedZone(r -> r.name("other.private.example.") + .callerReference(UUID.randomUUID().toString()).delegationSetId(set.id()) + .vpc(v -> v.vpcId("vpc-delegation-private").vpcRegion("us-east-1")))); + assertEquals(1, client.getHostedZoneCount().hostedZoneCount()); + } finally { + client.deleteHostedZone(r -> r.id(zone)); + client.deleteReusableDelegationSet(r -> r.id(set.id())); + } + } + } + + @Test + void missingAndForeignResourcesFailWithoutCreatingZonesOrSets() { + try (Route53Client owner = client("741686000015"); Route53Client stranger = client("741686000016")) { + DelegationSet set = createSet(owner); + String zone = createZone(owner, "owned.example.", null).hostedZone().id(); + try { + assertError("NoSuchDelegationSet", () -> createZone(stranger, "stranger.example.", set.id())); + assertError("NoSuchDelegationSet", () -> createZone(owner, "missing.example.", "NMissing")); + assertError("HostedZoneNotFound", () -> stranger.createReusableDelegationSet(r -> + r.callerReference(UUID.randomUUID().toString()).hostedZoneId(zone))); + assertError("HostedZoneNotFound", () -> owner.createReusableDelegationSet(r -> + r.callerReference(UUID.randomUUID().toString()).hostedZoneId("ZMissing"))); + assertEquals(0, stranger.getHostedZoneCount().hostedZoneCount()); + assertTrue(stranger.listReusableDelegationSets().delegationSets().isEmpty()); + assertEquals(1, owner.getHostedZoneCount().hostedZoneCount()); + } finally { + owner.deleteHostedZone(r -> r.id(zone)); + owner.deleteReusableDelegationSet(r -> r.id(set.id())); + } + } + } + + @Test + void hostedZoneFilteringByDelegationSetHappensBeforePagination() { + try (Route53Client client = client("741686000040")) { + DelegationSet selected = createSet(client); + DelegationSet other = createSet(client); + String alpha = createZone(client, "alpha.example.", selected.id()).hostedZone().id(); + String beta = createZone(client, "beta.example.", selected.id()).hostedZone().id(); + String excluded = createZone(client, "excluded.example.", other.id()).hostedZone().id(); + String ordinary = createZone(client, "aardvark.example.", null).hostedZone().id(); + try { + ListHostedZonesResponse first = client.listHostedZones(r -> r.delegationSetId(selected.id()).maxItems("1")); + assertEquals(List.of(alpha), first.hostedZones().stream().map(zone -> zone.id()).toList()); + assertTrue(first.isTruncated()); + ListHostedZonesResponse second = client.listHostedZones(r -> r.delegationSetId(selected.id()) + .marker(first.nextMarker()).maxItems("1")); + assertEquals(List.of(beta), second.hostedZones().stream().map(zone -> zone.id()).toList()); + assertFalse(second.isTruncated()); + assertEquals(List.of(excluded), client.listHostedZones(r -> r.delegationSetId(other.id())) + .hostedZones().stream().map(zone -> zone.id()).toList()); + assertEquals(4, client.listHostedZones().hostedZones().size()); + } finally { + for (String id : List.of(alpha, beta, excluded, ordinary)) { + client.deleteHostedZone(r -> r.id(id)); + } + client.deleteReusableDelegationSet(r -> r.id(selected.id())); + client.deleteReusableDelegationSet(r -> r.id(other.id())); + } + } + } + + @Test + void hostedZoneFilteringValidatesTheSetEvenWhenNoZonesExist() { + try (Route53Client owner = client("741686000041"); Route53Client stranger = client("741686000042")) { + DelegationSet empty = createSet(owner); + try { + assertTrue(owner.listHostedZones(r -> r.delegationSetId(empty.id())).hostedZones().isEmpty()); + assertError("NoSuchDelegationSet", () -> owner.listHostedZones(r -> r.delegationSetId("NMissing"))); + assertError("NoSuchDelegationSet", () -> stranger.listHostedZones(r -> r.delegationSetId(empty.id()))); + } finally { + owner.deleteReusableDelegationSet(r -> r.id(empty.id())); + } + } + } + + private Route53Client client(String account) { + return AwsTestClients.create(Route53Client.builder(), account, Region.US_EAST_1); + } + + private DelegationSet createSet(Route53Client client) { + return client.createReusableDelegationSet(r -> r.callerReference(UUID.randomUUID().toString())).delegationSet(); + } + + private CreateHostedZoneResponse createZone(Route53Client client, String name, String delegationSetId) { + return client.createHostedZone(r -> r.name(name).callerReference(UUID.randomUUID().toString()) + .delegationSetId(delegationSetId)); + } + + private void assertError(String code, Runnable action) { + Route53Exception error = assertThrows(Route53Exception.class, action::run); + assertEquals(400, error.statusCode()); + assertEquals(code, error.awsErrorDetails().errorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsIamEnforcementIntegrationTest.java new file mode 100644 index 0000000000..d81447ae70 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsIamEnforcementIntegrationTest.java @@ -0,0 +1,185 @@ +package io.github.hectorvent.floci.services.route53; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.route53.Route53Client; +import software.amazon.awssdk.services.route53.model.Route53Exception; + +import java.net.URI; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class Route53DelegationSetsIamEnforcementIntegrationTest { + private static final String ACCOUNT = "741686000030"; + + @TestHTTPResource("/") + URI baseUri; + + private final PartitionCleanup CLEANUP = new PartitionCleanup(); + @RegisterExtension + final AfterAllCallback classCleanup = CLEANUP::afterEach; + private String implicitDenyKey; + private String explicitDenyKey; + private String allowKey; + private String scopedAllowKey; + private String scopedDenyKey; + private String selectedSet; + private String otherSet; + + @BeforeAll + void createSharedFixtures() { + implicitDenyKey = userWithPolicy(null); + explicitDenyKey = userWithPolicy(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"*","Resource":"*"}, + {"Effect":"Deny","Action":"route53:*","Resource":"*"}]} + """); + allowKey = userWithPolicy(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"route53:*","Resource":"*"}]} + """); + Route53Client root = client(ACCOUNT); + CLEANUP.register(root::close); + selectedSet = createSet(root); + CLEANUP.register(() -> root.deleteReusableDelegationSet(r -> r.id(selectedSet))); + otherSet = createSet(root); + CLEANUP.register(() -> root.deleteReusableDelegationSet(r -> r.id(otherSet))); + scopedAllowKey = userWithPolicy(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":["route53:GetReusableDelegationSet","route53:DeleteReusableDelegationSet"], + "Resource":"arn:aws:route53:::delegationset/%s"}]} + """.formatted(selectedSet)); + scopedDenyKey = userWithPolicy(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"*","Resource":"*"}, + {"Effect":"Deny","Action":["route53:GetReusableDelegationSet","route53:DeleteReusableDelegationSet"], + "Resource":"arn:aws:route53:::delegationset/%s"}]} + """.formatted(selectedSet)); + } + + @ParameterizedTest + @CsvSource({"Create,true", "Get,true", "List,true", "Delete,true", + "Create,false", "Get,false", "List,false", "Delete,false"}) + void missingPermissionsAndExplicitDeniesApplyToEveryOperation(String operation, boolean explicitDeny) { + try (Route53Client client = client(explicitDeny ? explicitDenyKey : implicitDenyKey)) { + Runnable call = switch (operation) { + case "Create" -> () -> client.createReusableDelegationSet(r -> r.callerReference(UUID.randomUUID().toString())); + case "Get" -> () -> client.getReusableDelegationSet(r -> r.id("NMissing")); + case "List" -> () -> client.listReusableDelegationSets(); + case "Delete" -> () -> client.deleteReusableDelegationSet(r -> r.id("NMissing")); + default -> throw new IllegalArgumentException(operation); + }; + assertDenied(call); + } + } + + @Test + void anAllowedCallerCanCompleteTheDelegationSetLifecycle() { + try (Route53Client client = client(allowKey)) { + String id = createSet(client); + try { + assertEquals(id, client.getReusableDelegationSet(r -> r.id(id)).delegationSet().id()); + assertEquals(id, client.listReusableDelegationSets().delegationSets().stream() + .filter(set -> set.id().equals(id)).findFirst().orElseThrow().id()); + } finally { + client.deleteReusableDelegationSet(r -> r.id(id)); + } + } + } + + @Test + void resourceScopedAllowsGrantOnlyTheSelectedSet() { + try (Route53Client reader = client(scopedAllowKey)) { + assertEquals(selectedSet, reader.getReusableDelegationSet(r -> r.id(selectedSet)).delegationSet().id()); + assertDenied(() -> reader.getReusableDelegationSet(r -> r.id(otherSet))); + assertDenied(() -> reader.deleteReusableDelegationSet(r -> r.id(otherSet))); + } + } + + @ParameterizedTest + @ValueSource(strings = {"plain", "encodedPrefix", "matrix", "matrixEncodedId"}) + void aScopedDenyCannotBeBypassedByEncodedIdsOrOperationHeaders(String variant) { + String selected = selectedSet; + String other = otherSet; + String key = scopedDenyKey; + String path = "/2013-04-01/delegationset/" + + (variant.contains("Prefix") ? "%2Fdelegationset%2F" : "") + + (variant.equals("matrixEncodedId") ? "%4E" + selected.substring(1) : selected) + + (variant.startsWith("matrix") ? ";ignored=1" : ""); + given().urlEncodingEnabled(false).header("Authorization", auth(ACCOUNT, "route53")) + .get(path).then().statusCode(200).body(containsString(selected)); + try (Route53Client reader = client(key)) { + assertEquals(other, reader.getReusableDelegationSet(r -> r.id(other)).delegationSet().id()); + for (String method : new String[]{"GET", "DELETE"}) { + given().urlEncodingEnabled(false).header("Authorization", auth(key, "route53")) + .header("X-Amz-Target", "Route53.ListReusableDelegationSets") + .queryParam("Action", "ListReusableDelegationSets") + .request(method, path) + .then().statusCode(403).body(containsString("AccessDenied")); + } + } + } + + @ParameterizedTest + @CsvSource({"Create,literal", "Get,literal", "List,literal", "Delete,literal", + "Create,separator", "Get,separator", "List,separator", "Delete,separator"}) + void percentEncodedRouteLiteralsStillEnforceTheSelectedOperation(String operation, String variant) { + String key = explicitDenyKey; + String method = switch (operation) { + case "Create" -> "POST"; + case "Delete" -> "DELETE"; + default -> "GET"; + }; + String path = (variant.equals("literal") ? "/2013-04-01/%64elegationset" + : "/2013-04-01%2Fdelegationset;ignored=1") + + (operation.equals("Get") || operation.equals("Delete") ? "/NMissing" : ""); + given().urlEncodingEnabled(false).header("Authorization", auth(key, "route53")) + .contentType("application/xml").body("" + + UUID.randomUUID() + "") + .request(method, path).then().statusCode(403).body(containsString("AccessDenied")); + } + + private String userWithPolicy(String policy) { + String user = "r53-delegation-" + UUID.randomUUID(); + String key = EnforcementFixtures.createUser(CLEANUP, baseUri.getPort(), auth(ACCOUNT, "iam"), user).accessKeyId(); + if (policy != null) { + EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "delegation", policy); + } + return key; + } + + private Route53Client client(String key) { + return AwsTestClients.create(Route53Client.builder(), key, Region.US_EAST_1, baseUri); + } + + private String createSet(Route53Client client) { + return client.createReusableDelegationSet(r -> r.callerReference(UUID.randomUUID().toString())).delegationSet().id(); + } + + private void assertDenied(Runnable call) { + Route53Exception error = assertThrows(Route53Exception.class, call::run); + assertEquals(403, error.statusCode()); + assertEquals("AccessDenied", error.awsErrorDetails().errorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsIntegrationTest.java new file mode 100644 index 0000000000..e91ec455fd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsIntegrationTest.java @@ -0,0 +1,185 @@ +package io.github.hectorvent.floci.services.route53; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.route53.Route53Client; +import software.amazon.awssdk.services.route53.model.CreateReusableDelegationSetResponse; +import software.amazon.awssdk.services.route53.model.DelegationSet; +import software.amazon.awssdk.services.route53.model.ListReusableDelegationSetsResponse; +import software.amazon.awssdk.services.route53.model.Route53Exception; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class Route53DelegationSetsIntegrationTest { + @Test + void createGetAndDeleteRoundTripThroughAwsSdk() { + try (Route53Client client = client("741686000001", Region.US_EAST_1)) { + String reference = "delegation<&>" + UUID.randomUUID(); + CreateReusableDelegationSetResponse response = client.createReusableDelegationSet(r -> r.callerReference(reference)); + DelegationSet created = response.delegationSet(); + try { + assertTrue(created.id().startsWith("N")); + assertEquals(reference, created.callerReference()); + assertEquals(201, response.sdkHttpResponse().statusCode()); + assertEquals("/2013-04-01/delegationset/" + created.id(), + URI.create(response.sdkHttpResponse().firstMatchingHeader("Location").orElseThrow()).getPath()); + given().header("Authorization", "AWS4-HMAC-SHA256 Credential=741686000001" + + "/20261030/us-east-1/route53/aws4_request, SignedHeaders=host, Signature=abc") + .get("/2013-04-01/delegationset/" + created.id()).then().statusCode(200) + .body(containsString("/delegationset/" + created.id() + "")) + .body(containsString("delegation<&>")); + assertEquals(4, created.nameServers().size()); + assertEquals(1, client.getAccountLimit(r -> r.type("MAX_REUSABLE_DELEGATION_SETS_BY_OWNER")).count()); + assertEquals(created, client.getReusableDelegationSet(r -> r.id(created.id())).delegationSet()); + } finally { + client.deleteReusableDelegationSet(r -> r.id(created.id())); + } + assertError("NoSuchDelegationSet", () -> client.getReusableDelegationSet(r -> r.id(created.id()))); + } + } + + @Test + void duplicateCallerReferenceIsRejectedWithoutCreatingAnotherSet() { + try (Route53Client client = client("741686000002", Region.US_EAST_1)) { + String reference = UUID.randomUUID().toString(); + String id = client.createReusableDelegationSet(r -> r.callerReference(reference)).delegationSet().id(); + try { + assertError("DelegationSetAlreadyCreated", () -> + client.createReusableDelegationSet(r -> r.callerReference(reference))); + assertEquals(1, client.listReusableDelegationSets().delegationSets().size()); + } finally { + client.deleteReusableDelegationSet(r -> r.id(id)); + } + } + } + + @Test + void listIncludesEverySetOnceUsingFirstUnseenId() { + try (Route53Client client = client("741686000003", Region.US_EAST_1)) { + List ids = new ArrayList<>(); + try { + for (int i = 0; i < 3; i++) { + ids.add(client.createReusableDelegationSet(r -> r.callerReference(UUID.randomUUID().toString())) + .delegationSet().id()); + } + List pages = new ArrayList<>(); + String marker = null; + do { + String next = marker; + ListReusableDelegationSetsResponse page = client.listReusableDelegationSets(r -> + r.maxItems("1").marker(next)); + pages.add(page); + marker = page.nextMarker(); + } while (pages.getLast().isTruncated() && pages.size() < 4); + assertEquals(3, pages.size()); + assertEquals(ids.stream().sorted().toList(), pages.stream() + .flatMap(p -> p.delegationSets().stream()).map(DelegationSet::id).toList()); + assertTrue(pages.getFirst().isTruncated()); + assertEquals(pages.get(1).delegationSets().getFirst().id().replace("/delegationset/", ""), + pages.getFirst().nextMarker()); + assertFalse(pages.getLast().isTruncated()); + assertEquals(null, pages.getLast().nextMarker()); + } finally { + ids.forEach(id -> client.deleteReusableDelegationSet(r -> r.id(id))); + } + } + } + + @Test + void setsAreAccountScopedAndGlobalAcrossRegions() { + try (Route53Client owner = client("741686000004", Region.US_EAST_1); + Route53Client otherRegion = client("741686000004", Region.EU_WEST_1); + Route53Client stranger = client("741686000005", Region.US_EAST_1)) { + String reference = UUID.randomUUID().toString(); + DelegationSet set = owner.createReusableDelegationSet(r -> r.callerReference(reference)).delegationSet(); + try { + assertEquals(set, otherRegion.getReusableDelegationSet(r -> r.id(set.id())).delegationSet()); + assertTrue(stranger.listReusableDelegationSets().delegationSets().isEmpty()); + assertError("NoSuchDelegationSet", () -> stranger.getReusableDelegationSet(r -> r.id(set.id()))); + assertError("NoSuchDelegationSet", () -> stranger.deleteReusableDelegationSet(r -> r.id(set.id()))); + String foreignId = stranger.createReusableDelegationSet(r -> r.callerReference(reference)) + .delegationSet().id(); + stranger.deleteReusableDelegationSet(r -> r.id(foreignId)); + } finally { + owner.deleteReusableDelegationSet(r -> r.id(set.id())); + } + } + } + + @ParameterizedTest + @ValueSource(ints = {0, 129}) + void callerReferenceLengthIsValidated(int length) { + try (Route53Client client = client("741686000006", Region.US_EAST_1)) { + assertError("InvalidInput", () -> client.createReusableDelegationSet(r -> r.callerReference("x".repeat(length)))); + } + } + + @ParameterizedTest + @ValueSource(strings = {"0", "-1", "no"}) + void invalidPageSizeHasAnAwsXmlError(String size) { + given().queryParam("maxitems", size).when().get("/2013-04-01/delegationset") + .then().statusCode(400).body(containsString("InvalidInput")); + } + + @Test + void positivePageSizeBeyondIntegerRangeIsAccepted() { + try (Route53Client client = client("741686000007", Region.US_EAST_1)) { + ListReusableDelegationSetsResponse page = client.listReusableDelegationSets(r -> r.maxItems("2147483648")); + assertEquals("2147483648", page.maxItems()); + assertFalse(page.isTruncated()); + } + } + + @ParameterizedTest + @ValueSource(strings = { + "wrong", + "", + "xbroken" + }) + void malformedCreateRequestsReturnXmlErrors(String body) { + given().contentType("application/xml").body(body).post("/2013-04-01/delegationset") + .then().statusCode(400).body(containsString("InvalidInput")); + } + + @Test + void callerReferenceMaximumLengthIsAccepted() { + try (Route53Client client = client("741686000008", Region.US_EAST_1)) { + String id = client.createReusableDelegationSet(r -> r.callerReference("x".repeat(128))).delegationSet().id(); + client.deleteReusableDelegationSet(r -> r.id(id)); + } + } + + @Test + void overlongIdsAndMarkersReturnXmlErrors() { + try (Route53Client client = client("741686000009", Region.US_EAST_1)) { + assertError("InvalidInput", () -> client.getReusableDelegationSet(r -> r.id("N".repeat(33)))); + assertError("InvalidInput", () -> client.deleteReusableDelegationSet(r -> r.id("N".repeat(33)))); + assertError("InvalidInput", () -> client.listReusableDelegationSets(r -> r.marker("N".repeat(65)))); + } + } + + private Route53Client client(String account, Region region) { + return AwsTestClients.create(Route53Client.builder(), account, region); + } + + private void assertError(String code, Runnable action) { + Route53Exception error = assertThrows(Route53Exception.class, action::run); + assertEquals(400, error.statusCode()); + assertEquals(code, error.awsErrorDetails().errorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsServiceTest.java new file mode 100644 index 0000000000..da8fa7ea1f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53DelegationSetsServiceTest.java @@ -0,0 +1,301 @@ +package io.github.hectorvent.floci.services.route53; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.route53.model.DelegationSet; +import io.github.hectorvent.floci.services.route53.model.HostedZone; +import io.github.hectorvent.floci.services.route53.model.ResourceRecord; +import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet; +import io.github.hectorvent.floci.testing.StorageFactories; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class Route53DelegationSetsServiceTest { + private static final String ACCOUNT = "741686000020"; + + @TempDir + Path directory; + + @ParameterizedTest + @ValueSource(strings = {"persistent", "hybrid", "wal"}) + void setsAndZoneLinksSurviveStorageReloadAndConfigurationChanges(String mode) { + DelegationSet set; + String zoneId; + try (Fixture fixture = fixture(mode, "original")) { + HostedZone zone = fixture.service().createHostedZone("saved.example.", "source", null, null).zone(); + zoneId = zone.getId(); + set = fixture.service().createReusableDelegationSet("saved", "/hostedzone/" + zoneId); + } + try (Fixture reloaded = fixture(mode, "changed")) { + Route53Service service = reloaded.service(); + assertEquals(set, service.getReusableDelegationSet("/delegationset/" + set.id())); + assertEquals(set, service.getDelegationSet(service.getHostedZone(zoneId))); + assertError("DelegationSetInUse", () -> service.deleteReusableDelegationSet(set.id())); + assertError("DelegationSetAlreadyCreated", () -> service.createReusableDelegationSet("saved", null)); + HostedZone next = service.createHostedZone("next.example.", "next", null, null, set.id()).zone(); + assertEquals(set, service.getDelegationSet(next)); + assertTrue(service.listResourceRecordSets(next.getId(), null, null, 100).stream() + .filter(record -> "SOA".equals(record.getType())).findFirst().orElseThrow() + .getRecords().getFirst().getValue().startsWith(set.nameServers().getFirst() + ". ")); + service.deleteHostedZone(next.getId()); + service.deleteHostedZone(zoneId); + service.deleteReusableDelegationSet(set.id()); + } + try (Fixture reloaded = fixture(mode, "changed")) { + assertEquals(0, reloaded.service().getReusableDelegationSetCount()); + assertEquals(0, reloaded.service().getHostedZoneCount()); + } + } + + @Test + void aForeignReadCannotClaimAnOwnerlessLegacyZoneBeforePromotion() { + RequestContext context = new RequestContext(); + context.setAccountId("741686000099"); + @SuppressWarnings("unchecked") + Instance instance = mock(Instance.class); + when(instance.get()).thenReturn(context); + InMemoryStorage legacy = new InMemoryStorage<>(); + legacy.put("ZLEGACY", new HostedZone("ZLEGACY", "legacy.example.", "legacy", null, false)); + AccountAwareStorageBackend zones = new AccountAwareStorageBackend<>(legacy, instance, ACCOUNT); + StorageFactory factory = mock(StorageFactory.class); + when(factory.create(anyString(), anyString(), any())).thenAnswer(invocation -> + "route53-zones.json".equals(invocation.getArgument(1)) ? zones : AccountAwareStorageBackend.inMemory(ACCOUNT)); + RegionResolver resolver = mock(RegionResolver.class); + when(resolver.getAccountId()).thenAnswer(ignored -> context.getAccountId()); + Route53Service service = new Route53Service(factory, config("original"), resolver, mock(Ec2Service.class)); + AwsException read = assertThrows(AwsException.class, () -> service.getHostedZone("ZLEGACY")); + assertEquals("NoSuchHostedZone", read.getErrorCode()); + assertEquals(404, read.getHttpStatus()); + assertError("HostedZoneNotFound", () -> service.createReusableDelegationSet("foreign", "ZLEGACY")); + context.setAccountId(ACCOUNT); + service.createReusableDelegationSet("owner", "ZLEGACY"); + assertEquals(1, service.getReusableDelegationSetCount()); + } + + @Test + void aForeignCallerCannotPromoteAnUnscopedLegacyZone() throws Exception { + seedLegacyZone(); + try (Fixture fixture = fixture("persistent", "original", "741686000099")) { + assertError("HostedZoneNotFound", () -> fixture.service().createReusableDelegationSet("foreign", "ZLEGACY")); + assertEquals(0, fixture.service().getReusableDelegationSetCount()); + } + } + + @Test + void legacyPublicZonesParticipateInConflictsBeforeTheirFirstRead() throws Exception { + seedLegacyZone(); + try (Fixture fixture = fixture("persistent", "original")) { + DelegationSet set = fixture.service().createReusableDelegationSet("set", null); + assertError("ConflictingDomainExists", () -> fixture.service() + .createHostedZone("child.legacy.example.", "child", null, null, set.id())); + } + } + + @Test + void promotionAfterConfigurationChangePreservesTheOriginalZoneAssignment() { + String zoneId; + try (Fixture fixture = fixture("persistent", "original")) { + zoneId = fixture.service().createHostedZone("original.example.", "original", null, null).zone().getId(); + ResourceRecordSet ns = fixture.service().listResourceRecordSets(zoneId, null, null, 100).stream() + .filter(record -> "NS".equals(record.getType())).findFirst().orElseThrow(); + ns.setRecords(List.of(new ResourceRecord("custom.nameserver.test."))); + fixture.service().changeResourceRecordSets(zoneId, List.of(Map.of("action", "UPSERT", "rrs", ns)), null); + } + try (Fixture fixture = fixture("persistent", "changed")) { + DelegationSet set = fixture.service().createReusableDelegationSet("promoted", zoneId); + assertEquals(List.of("original-1.test", "original-2.test", "original-3.test", "original-4.test"), + set.nameServers()); + } + } + + @Test + void promotionRecoversAnOlderZonesNameserversFromItsPersistedApexRecords() throws Exception { + seedLegacyZone(); + try (Fixture fixture = fixture("persistent", "changed")) { + DelegationSet set = fixture.service().createReusableDelegationSet("promoted", "ZLEGACY"); + assertEquals(List.of("original-1.test", "original-2.test", "original-3.test", "original-4.test"), + set.nameServers()); + } + } + + @Test + void setQuotaAndMaximumPageSizeAreEnforcedAndDeletionFreesCapacity() { + try (Fixture fixture = fixture("memory", "quota")) { + Route53Service service = fixture.service(); + List ids = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + ids.add(service.createReusableDelegationSet("ref-" + i, null).id()); + } + assertError("LimitsExceeded", () -> service.createReusableDelegationSet("overflow", null)); + assertEquals(100, service.getReusableDelegationSetCount()); + assertEquals(100, service.pageReusableDelegationSets(null, "2147483648").items().size()); + String first = ids.stream().sorted().findFirst().orElseThrow(); + service.deleteReusableDelegationSet(first); + assertEquals(99, service.pageReusableDelegationSets(first, "100").items().size()); + service.createReusableDelegationSet("replacement", null); + assertEquals(100, service.getReusableDelegationSetCount()); + } + } + + @Test + void hostedZoneQuotaCountsOnlyZonesAssociatedWithThatSet() { + try (Fixture fixture = fixture("memory", "quota")) { + Route53Service service = fixture.service(); + DelegationSet set = service.createReusableDelegationSet("set", null); + String first = null; + for (int i = 0; i < 100; i++) { + HostedZone zone = service.createHostedZone("zone-" + i + ".example.", "zone-" + i, + null, null, set.id()).zone(); + if (first == null) { + first = zone.getId(); + } + } + assertError("TooManyHostedZones", () -> + service.createHostedZone("overflow.example.", "overflow", null, null, set.id())); + DelegationSet other = service.createReusableDelegationSet("other", null); + service.createHostedZone("other.example.", "other", null, null, other.id()); + service.deleteHostedZone(first); + service.createHostedZone("replacement.example.", "replacement", null, null, set.id()); + assertEquals(101, service.getHostedZoneCount()); + } + } + + @Test + void concurrentDuplicateReferencesCreateExactlyOneSet() throws Exception { + try (Fixture fixture = fixture("memory", "concurrent"); + ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + Route53Service service = fixture.service(); + CountDownLatch start = new CountDownLatch(1); + List> calls = new ArrayList<>(); + for (int i = 0; i < 16; i++) { + calls.add(() -> { + start.await(); + return outcome(() -> service.createReusableDelegationSet("shared", null)); + }); + } + List> futures = calls.stream().map(executor::submit).toList(); + start.countDown(); + List results = new ArrayList<>(); + for (Future future : futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + assertEquals(1, results.stream().filter("success"::equals).count()); + assertEquals(15, results.stream().filter("DelegationSetAlreadyCreated"::equals).count()); + assertEquals(1, service.getReusableDelegationSetCount()); + } + } + + @Test + void racingDeleteAndZoneCreationCannotLeaveADanglingSetReference() throws Exception { + try (Fixture fixture = fixture("memory", "concurrent"); + ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + Route53Service service = fixture.service(); + DelegationSet set = service.createReusableDelegationSet("racing", null); + CountDownLatch start = new CountDownLatch(1); + Future create = executor.submit(() -> { + start.await(); + return outcome(() -> service.createHostedZone("racing.example.", "racing", null, null, set.id())); + }); + Future delete = executor.submit(() -> { + start.await(); + return outcome(() -> service.deleteReusableDelegationSet(set.id())); + }); + start.countDown(); + String createResult = create.get(10, TimeUnit.SECONDS); + String deleteResult = delete.get(10, TimeUnit.SECONDS); + if ("success".equals(createResult)) { + assertEquals("DelegationSetInUse", deleteResult); + assertEquals(set, service.getReusableDelegationSet(set.id())); + assertEquals(1, service.getHostedZoneCount()); + } else { + assertEquals("NoSuchDelegationSet", createResult); + assertEquals("success", deleteResult); + assertEquals(0, service.getHostedZoneCount()); + assertEquals(0, service.getReusableDelegationSetCount()); + } + } + } + + private String outcome(Runnable action) { + try { + action.run(); + return "success"; + } catch (AwsException e) { + return e.getErrorCode(); + } + } + + private void assertError(String code, Runnable action) { + AwsException error = assertThrows(AwsException.class, action::run); + assertEquals(code, error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + } + + private void seedLegacyZone() throws Exception { + Files.writeString(directory.resolve("route53-zones.json"), """ + {"ZLEGACY":{"id":"ZLEGACY","name":"legacy.example.","callerReference":"legacy", + "ownerAccountId":"741686000020","privateZone":false}} + """); + Files.writeString(directory.resolve("route53-records.json"), """ + {"ZLEGACY":[{"name":"legacy.example.","type":"NS","ttl":172800,"records":[ + {"value":"original-1.test."},{"value":"original-2.test."}, + {"value":"original-3.test."},{"value":"original-4.test."}]}]} + """); + } + + private Fixture fixture(String mode, String prefix) { + return fixture(mode, prefix, ACCOUNT); + } + + private Fixture fixture(String mode, String prefix, String callerAccount) { + EmulatorConfig config = config(prefix); + StorageFactory factory = StorageFactories.open(config, mode); + return new Fixture(factory, new Route53Service(factory, config, new RegionResolver("us-east-1", callerAccount), + mock(Ec2Service.class))); + } + + private EmulatorConfig config(String prefix) { + EmulatorConfig config = StorageFactories.config(directory, ACCOUNT); + when(config.services().route53().defaultNameserver1()).thenReturn(prefix + "-1.test."); + when(config.services().route53().defaultNameserver2()).thenReturn(prefix + "-2.test."); + when(config.services().route53().defaultNameserver3()).thenReturn(prefix + "-3.test."); + when(config.services().route53().defaultNameserver4()).thenReturn(prefix + "-4.test."); + return config; + } + + private record Fixture(StorageFactory factory, Route53Service service) implements AutoCloseable { + @Override + public void close() { + factory.shutdownAll(); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/testing/AwsTestClients.java b/src/test/java/io/github/hectorvent/floci/testing/AwsTestClients.java index 253497f05c..3bc1f876c2 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/AwsTestClients.java +++ b/src/test/java/io/github/hectorvent/floci/testing/AwsTestClients.java @@ -25,7 +25,18 @@ public final class AwsTestClients { /** Selects a transport explicitly for operations requiring methods such as PATCH. */ public static & AwsSyncClientBuilder, C> C create( B builder, String account, Region region, SdkHttpClient.Builder httpClientBuilder) { - return builder.endpointOverride(URI.create("http://localhost:" + RestAssured.port)) + return create(builder, account, region, httpClientBuilder, URI.create("http://localhost:" + RestAssured.port)); + } + + /** Explicit endpoint for class fixtures created before RestAssured's per-test port is installed. */ + public static & AwsSyncClientBuilder, C> C create( + B builder, String account, Region region, URI endpoint) { + return create(builder, account, region, UrlConnectionHttpClient.builder(), endpoint); + } + + private static & AwsSyncClientBuilder, C> C create( + B builder, String account, Region region, SdkHttpClient.Builder httpClientBuilder, URI endpoint) { + return builder.endpointOverride(endpoint) .httpClientBuilder(httpClientBuilder).region(region) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test"))) .build();