mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(route53): add Route53 management-plane emulation (#715)
* feat(route53): add Route53 management-plane emulation Implements Route53 Phase 1 with 17 operations: hosted zones (Create, Get, Delete, List, ListByName, Count), resource record sets (ChangeResourceRecordSets, List), change tracking (GetChange), health checks (Create, Get, Delete, List, Update), tagging (ListTagsForResource, ChangeTagsForResource), and GetAccountLimit. Auto-creates SOA and NS apex records on zone creation. Rejects deletion of non-empty zones. All changes return INSYNC immediately. IDs are returned with path prefixes (/hostedzone/Z…, /change/C…) to satisfy the SDK Route53IdInterceptor. Nameservers are configurable via floci.services.route53.default-nameserver[1-4]. Adds OpenTofu and Terraform compatibility tests covering zone creation, A record, auto-created SOA/NS records, health check, and tag persistence. * feat(feat): adding missing endpoints * feat(route53): fix timeout when creating route dns from terraform
This commit is contained in:
1 parent
86eac926f9
commit
3b54255d7f
26 files changed
+2282
-6
No files matched your search
@@ -273,6 +273,24 @@ public interface EmulatorConfig {
|
||||
CodeBuildServiceConfig codebuild();
|
||||
CodeDeployServiceConfig codedeploy();
|
||||
AutoScalingServiceConfig autoscaling();
|
||||
Route53ServiceConfig route53();
|
||||
}
|
||||
|
||||
interface Route53ServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("ns-1.awsdns-01.org")
|
||||
String defaultNameserver1();
|
||||
|
||||
@WithDefault("ns-2.awsdns-02.net")
|
||||
String defaultNameserver2();
|
||||
|
||||
@WithDefault("ns-3.awsdns-03.com")
|
||||
String defaultNameserver3();
|
||||
|
||||
@WithDefault("ns-4.awsdns-04.co.uk")
|
||||
String defaultNameserver4();
|
||||
}
|
||||
|
||||
interface AutoScalingServiceConfig {
|
||||
|
||||
@@ -19,6 +19,7 @@ public final class AwsNamespaces {
|
||||
public static final String EC2 = "http://ec2.amazonaws.com/doc/2016-11-15/";
|
||||
public static final String ELB_V2 = "https://elasticloadbalancing.amazonaws.com/doc/2015-12-01/";
|
||||
public static final String AUTOSCALING = "https://autoscaling.amazonaws.com/doc/2011-01-01/";
|
||||
public static final String ROUTE53 = "https://route53.amazonaws.com/doc/2013-04-01/";
|
||||
|
||||
private AwsNamespaces() {}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.eks.EksController;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesController;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaController;
|
||||
import io.github.hectorvent.floci.services.opensearch.OpenSearchController;
|
||||
import io.github.hectorvent.floci.services.route53.Route53Controller;
|
||||
import io.github.hectorvent.floci.services.ses.SesController;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -224,7 +225,11 @@ public class ResolvedServiceCatalog {
|
||||
descriptor("ec2messages", "ec2messages", config.services().ssm().enabled(), false,
|
||||
null, null, 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("AmazonSSMMessageDeliveryService."), Set.of("ec2messages"), Set.of(), Set.of())
|
||||
Set.of("AmazonSSMMessageDeliveryService."), Set.of("ec2messages"), Set.of(), Set.of()),
|
||||
descriptor("route53", "route53", config.services().route53().enabled(), true,
|
||||
"route53", config.storage().mode(), 5000L, null, ServiceProtocol.REST_XML,
|
||||
protocols(ServiceProtocol.REST_XML),
|
||||
Set.of(), Set.of("route53"), Set.of(), Set.of(Route53Controller.class))
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,807 @@
|
||||
package io.github.hectorvent.floci.services.route53;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
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.HealthCheck;
|
||||
import io.github.hectorvent.floci.services.route53.model.HealthCheckConfig;
|
||||
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 jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.DELETE;
|
||||
import jakarta.ws.rs.DefaultValue;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import javax.xml.stream.XMLInputFactory;
|
||||
import javax.xml.stream.XMLStreamConstants;
|
||||
import javax.xml.stream.XMLStreamReader;
|
||||
import java.io.StringReader;
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Path("/2013-04-01")
|
||||
public class Route53Controller {
|
||||
|
||||
private static final String NS = AwsNamespaces.ROUTE53;
|
||||
private static final String XML = "application/xml";
|
||||
|
||||
private static final XMLInputFactory XML_FACTORY;
|
||||
|
||||
static {
|
||||
XML_FACTORY = XMLInputFactory.newInstance();
|
||||
XML_FACTORY.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
|
||||
XML_FACTORY.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
|
||||
XML_FACTORY.setProperty(XMLInputFactory.SUPPORT_DTD, false);
|
||||
}
|
||||
|
||||
@Inject
|
||||
Route53Service service;
|
||||
|
||||
// ── Hosted Zones ──────────────────────────────────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/hostedzone")
|
||||
public Response createHostedZone(String body) {
|
||||
try {
|
||||
String name = XmlParser.extractFirst(body, "Name", null);
|
||||
String callerRef = XmlParser.extractFirst(body, "CallerReference", null);
|
||||
String comment = XmlParser.extractFirst(body, "Comment", null);
|
||||
boolean privateZone = "true".equalsIgnoreCase(
|
||||
XmlParser.extractFirst(body, "PrivateZone", "false"));
|
||||
|
||||
if (name == null || callerRef == null) {
|
||||
throw new AwsException("InvalidInput", "Name and CallerReference are required.", 400);
|
||||
}
|
||||
|
||||
CreateZoneResult result = service.createHostedZone(name, callerRef, comment, privateZone);
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateHostedZoneResponse", NS)
|
||||
.raw(xmlHostedZone(result.zone()))
|
||||
.raw(xmlChangeInfo(result.change()))
|
||||
.raw(xmlDelegationSet())
|
||||
.end("CreateHostedZoneResponse")
|
||||
.build();
|
||||
|
||||
return Response.created(URI.create("/2013-04-01/hostedzone/" + result.zone().getId()))
|
||||
.type(XML)
|
||||
.entity(xml)
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/hostedzone/{Id}")
|
||||
public Response getHostedZone(@PathParam("Id") String id) {
|
||||
try {
|
||||
HostedZone zone = service.getHostedZone(id);
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetHostedZoneResponse", NS)
|
||||
.raw(xmlHostedZone(zone))
|
||||
.raw(xmlDelegationSet())
|
||||
.end("GetHostedZoneResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/hostedzone/{Id}")
|
||||
public Response deleteHostedZone(@PathParam("Id") String id) {
|
||||
try {
|
||||
ChangeInfo change = service.deleteHostedZone(id);
|
||||
String xml = new XmlBuilder()
|
||||
.start("DeleteHostedZoneResponse", NS)
|
||||
.raw(xmlChangeInfo(change))
|
||||
.end("DeleteHostedZoneResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/hostedzone")
|
||||
public Response listHostedZones(@QueryParam("marker") String marker,
|
||||
@QueryParam("maxitems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<HostedZone> zones = service.listHostedZones(marker, maxItems);
|
||||
long total = service.getHostedZoneCount();
|
||||
boolean truncated = zones.size() == maxItems && zones.size() < total;
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListHostedZonesResponse", NS)
|
||||
.start("HostedZones");
|
||||
for (HostedZone zone : zones) {
|
||||
xml.raw(xmlHostedZone(zone));
|
||||
}
|
||||
xml.end("HostedZones")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.elem("IsTruncated", String.valueOf(truncated));
|
||||
if (truncated && !zones.isEmpty()) {
|
||||
xml.elem("NextMarker", zones.get(zones.size() - 1).getId());
|
||||
}
|
||||
xml.elem("MaxItems", String.valueOf(maxItems))
|
||||
.end("ListHostedZonesResponse");
|
||||
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/hostedzonesbyname")
|
||||
public Response listHostedZonesByName(@QueryParam("dnsname") String dnsName,
|
||||
@QueryParam("maxitems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<HostedZone> zones = service.listHostedZonesByName(dnsName, maxItems);
|
||||
long total = service.getHostedZoneCount();
|
||||
boolean truncated = zones.size() == maxItems && zones.size() < total;
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListHostedZonesByNameResponse", NS)
|
||||
.start("HostedZones");
|
||||
for (HostedZone zone : zones) {
|
||||
xml.raw(xmlHostedZone(zone));
|
||||
}
|
||||
xml.end("HostedZones")
|
||||
.elem("IsTruncated", String.valueOf(truncated))
|
||||
.elem("MaxItems", String.valueOf(maxItems));
|
||||
if (dnsName != null && !dnsName.isEmpty()) {
|
||||
xml.elem("DNSName", dnsName);
|
||||
}
|
||||
xml.end("ListHostedZonesByNameResponse");
|
||||
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/hostedzonecount")
|
||||
public Response getHostedZoneCount() {
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetHostedZoneCountResponse", NS)
|
||||
.elem("HostedZoneCount", service.getHostedZoneCount())
|
||||
.end("GetHostedZoneCountResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
}
|
||||
|
||||
// ── Resource Record Sets ──────────────────────────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/hostedzone/{Id}/rrset")
|
||||
public Response changeResourceRecordSets(@PathParam("Id") String id, String body) {
|
||||
try {
|
||||
String comment = XmlParser.extractFirst(body, "Comment", null);
|
||||
List<Map<String, Object>> changes = parseChangeBatch(body);
|
||||
ChangeInfo change = service.changeResourceRecordSets(id, changes, comment);
|
||||
String xml = new XmlBuilder()
|
||||
.start("ChangeResourceRecordSetsResponse", NS)
|
||||
.raw(xmlChangeInfo(change))
|
||||
.end("ChangeResourceRecordSetsResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/hostedzone/{Id}/rrset")
|
||||
public Response listResourceRecordSets(@PathParam("Id") String id,
|
||||
@QueryParam("name") String startName,
|
||||
@QueryParam("type") String startType,
|
||||
@QueryParam("maxitems") @DefaultValue("300") int maxItems) {
|
||||
try {
|
||||
List<ResourceRecordSet> fetched = service.listResourceRecordSets(id, startName, startType, maxItems + 1);
|
||||
boolean truncated = fetched.size() > maxItems;
|
||||
List<ResourceRecordSet> records = truncated ? fetched.subList(0, maxItems) : fetched;
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListResourceRecordSetsResponse", NS)
|
||||
.start("ResourceRecordSets");
|
||||
for (ResourceRecordSet rrs : records) {
|
||||
xml.raw(xmlResourceRecordSet(rrs));
|
||||
}
|
||||
xml.end("ResourceRecordSets")
|
||||
.elem("IsTruncated", String.valueOf(truncated));
|
||||
if (truncated) {
|
||||
ResourceRecordSet next = fetched.get(maxItems);
|
||||
xml.elem("NextRecordName", next.getName())
|
||||
.elem("NextRecordType", next.getType());
|
||||
}
|
||||
xml.elem("MaxItems", String.valueOf(maxItems))
|
||||
.end("ListResourceRecordSetsResponse");
|
||||
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Changes ───────────────────────────────────────────────────────────────
|
||||
|
||||
@GET
|
||||
@Path("/change/{Id}")
|
||||
public Response getChange(@PathParam("Id") String id) {
|
||||
try {
|
||||
ChangeInfo change = service.getChange(id);
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetChangeResponse", NS)
|
||||
.raw(xmlChangeInfo(change))
|
||||
.end("GetChangeResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Health Checks ─────────────────────────────────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/healthcheck")
|
||||
public Response createHealthCheck(String body) {
|
||||
try {
|
||||
String callerRef = XmlParser.extractFirst(body, "CallerReference", null);
|
||||
if (callerRef == null) {
|
||||
throw new AwsException("InvalidInput", "CallerReference is required.", 400);
|
||||
}
|
||||
HealthCheckConfig cfg = parseHealthCheckConfig(body);
|
||||
HealthCheck hc = service.createHealthCheck(callerRef, cfg);
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateHealthCheckResponse", NS)
|
||||
.raw(xmlHealthCheck(hc))
|
||||
.end("CreateHealthCheckResponse")
|
||||
.build();
|
||||
return Response.created(URI.create("/2013-04-01/healthcheck/" + hc.getId()))
|
||||
.type(XML)
|
||||
.entity(xml)
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/healthcheck/{HealthCheckId}")
|
||||
public Response getHealthCheck(@PathParam("HealthCheckId") String id) {
|
||||
try {
|
||||
HealthCheck hc = service.getHealthCheck(id);
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetHealthCheckResponse", NS)
|
||||
.raw(xmlHealthCheck(hc))
|
||||
.end("GetHealthCheckResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/healthcheck/{HealthCheckId}")
|
||||
public Response deleteHealthCheck(@PathParam("HealthCheckId") String id) {
|
||||
try {
|
||||
service.deleteHealthCheck(id);
|
||||
return Response.ok("", XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/healthcheck")
|
||||
public Response listHealthChecks(@QueryParam("marker") String marker,
|
||||
@QueryParam("maxitems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<HealthCheck> checks = service.listHealthChecks(marker, maxItems);
|
||||
boolean truncated = checks.size() == maxItems;
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListHealthChecksResponse", NS)
|
||||
.start("HealthChecks");
|
||||
for (HealthCheck hc : checks) {
|
||||
xml.raw(xmlHealthCheck(hc));
|
||||
}
|
||||
xml.end("HealthChecks")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.elem("IsTruncated", String.valueOf(truncated))
|
||||
.elem("MaxItems", String.valueOf(maxItems))
|
||||
.end("ListHealthChecksResponse");
|
||||
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/healthcheck/{HealthCheckId}")
|
||||
public Response updateHealthCheck(@PathParam("HealthCheckId") String id, String body) {
|
||||
try {
|
||||
HealthCheckConfig cfg = parseHealthCheckConfig(body);
|
||||
HealthCheck hc = service.updateHealthCheck(id, cfg);
|
||||
String xml = new XmlBuilder()
|
||||
.start("UpdateHealthCheckResponse", NS)
|
||||
.raw(xmlHealthCheck(hc))
|
||||
.end("UpdateHealthCheckResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tags ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@GET
|
||||
@Path("/tags/{ResourceType}/{ResourceId}")
|
||||
public Response listTagsForResource(@PathParam("ResourceType") String type,
|
||||
@PathParam("ResourceId") String resourceId) {
|
||||
try {
|
||||
Map<String, String> tags = service.listTagsForResource(type, resourceId);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListTagsForResourceResponse", NS)
|
||||
.start("ResourceTagSet")
|
||||
.elem("ResourceType", type)
|
||||
.elem("ResourceId", resourceId)
|
||||
.start("Tags");
|
||||
for (Map.Entry<String, String> entry : tags.entrySet()) {
|
||||
xml.start("Tag")
|
||||
.elem("Key", entry.getKey())
|
||||
.elem("Value", entry.getValue())
|
||||
.end("Tag");
|
||||
}
|
||||
xml.end("Tags").end("ResourceTagSet").end("ListTagsForResourceResponse");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/tags/{ResourceType}/{ResourceId}")
|
||||
public Response changeTagsForResource(@PathParam("ResourceType") String type,
|
||||
@PathParam("ResourceId") String resourceId,
|
||||
String body) {
|
||||
try {
|
||||
List<Map<String, String>> addTags = XmlParser.extractGroups(body, "Tag").stream()
|
||||
.filter(g -> g.containsKey("Key"))
|
||||
.map(g -> Map.of("Key", g.get("Key"), "Value", g.getOrDefault("Value", "")))
|
||||
.toList();
|
||||
List<String> removeTagKeys = parseRemoveTagKeys(body);
|
||||
service.changeTagsForResource(type, resourceId, addTags, removeTagKeys);
|
||||
String xml = new XmlBuilder()
|
||||
.start("ChangeTagsForResourceResponse", NS)
|
||||
.end("ChangeTagsForResourceResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Limits ────────────────────────────────────────────────────────────────
|
||||
|
||||
@GET
|
||||
@Path("/accountlimit/{Type}")
|
||||
public Response getAccountLimit(@PathParam("Type") String type) {
|
||||
long value = switch (type) {
|
||||
case "MAX_HEALTH_CHECKS_BY_OWNER" -> 200L;
|
||||
case "MAX_HOSTED_ZONES_BY_OWNER" -> 500L;
|
||||
case "MAX_REUSABLE_DELEGATION_SETS_BY_OWNER" -> 100L;
|
||||
case "MAX_TRAFFIC_POLICY_INSTANCES_BY_OWNER" -> 5L;
|
||||
case "MAX_TRAFFIC_POLICIES_BY_OWNER" -> 50L;
|
||||
default -> 100L;
|
||||
};
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetAccountLimitResponse", NS)
|
||||
.start("Limit")
|
||||
.elem("Type", type)
|
||||
.elem("Value", value)
|
||||
.end("Limit")
|
||||
.elem("Count", 0L)
|
||||
.end("GetAccountLimitResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/healthcheck/{HealthCheckId}/status")
|
||||
public Response getHealthCheckStatus(@PathParam("HealthCheckId") String id) {
|
||||
try {
|
||||
service.getHealthCheck(id);
|
||||
String now = Instant.now().toString();
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetHealthCheckStatusResponse", NS)
|
||||
.start("HealthCheckObservations")
|
||||
.start("HealthCheckObservation")
|
||||
.elem("IPAddress", "1.2.3.4")
|
||||
.elem("Region", "us-east-1")
|
||||
.start("StatusReport")
|
||||
.elem("Status", "Success: HTTP Status Code 200, OK")
|
||||
.elem("CheckedTime", now)
|
||||
.end("StatusReport")
|
||||
.end("HealthCheckObservation")
|
||||
.end("HealthCheckObservations")
|
||||
.end("GetHealthCheckStatusResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/hostedzone/{Id}/dnssec")
|
||||
public Response getDnssec(@PathParam("Id") String id) {
|
||||
try {
|
||||
service.getHostedZone(id);
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetDNSSECResponse", NS)
|
||||
.start("Status")
|
||||
.elem("ServeSignature", "NOT_SIGNING")
|
||||
.elem("StatusMessage", "Zone is not signing")
|
||||
.end("Status")
|
||||
.start("KeySigningKeys")
|
||||
.end("KeySigningKeys")
|
||||
.end("GetDNSSECResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/hostedzonelimit/{HostedZoneId}/{Type}")
|
||||
public Response getHostedZoneLimit(@PathParam("HostedZoneId") String zoneId,
|
||||
@PathParam("Type") String type) {
|
||||
try {
|
||||
service.getHostedZone(zoneId);
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
}
|
||||
long value = switch (type) {
|
||||
case "MAX_RRSETS_BY_ZONE" -> 10000L;
|
||||
case "MAX_VPCS_ASSOCIATED_BY_ZONE" -> 100L;
|
||||
default -> 100L;
|
||||
};
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetHostedZoneLimitResponse", NS)
|
||||
.start("Limit")
|
||||
.elem("Type", type)
|
||||
.elem("Value", value)
|
||||
.end("Limit")
|
||||
.elem("Count", 0L)
|
||||
.end("GetHostedZoneLimitResponse")
|
||||
.build();
|
||||
return Response.ok(xml, XML).build();
|
||||
}
|
||||
|
||||
// ── XML builders ──────────────────────────────────────────────────────────
|
||||
|
||||
private String xmlHostedZone(HostedZone zone) {
|
||||
return new XmlBuilder()
|
||||
.start("HostedZone")
|
||||
.elem("Id", "/hostedzone/" + zone.getId())
|
||||
.elem("Name", zone.getName())
|
||||
.elem("CallerReference", zone.getCallerReference())
|
||||
.start("Config")
|
||||
.elem("Comment", zone.getComment())
|
||||
.elem("PrivateZone", String.valueOf(zone.isPrivateZone()))
|
||||
.end("Config")
|
||||
.elem("ResourceRecordSetCount", zone.getResourceRecordSetCount())
|
||||
.end("HostedZone")
|
||||
.build();
|
||||
}
|
||||
|
||||
private String xmlChangeInfo(ChangeInfo change) {
|
||||
return new XmlBuilder()
|
||||
.start("ChangeInfo")
|
||||
.elem("Id", "/change/" + change.getId())
|
||||
.elem("Status", change.getStatus())
|
||||
.elem("SubmittedAt", change.getSubmittedAt())
|
||||
.elem("Comment", change.getComment())
|
||||
.end("ChangeInfo")
|
||||
.build();
|
||||
}
|
||||
|
||||
private String xmlDelegationSet() {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DelegationSet")
|
||||
.start("NameServers");
|
||||
for (String ns : service.getNameServers()) {
|
||||
xml.elem("NameServer", ns);
|
||||
}
|
||||
xml.end("NameServers").end("DelegationSet");
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private String xmlResourceRecordSet(ResourceRecordSet rrs) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ResourceRecordSet")
|
||||
.elem("Name", rrs.getName())
|
||||
.elem("Type", rrs.getType());
|
||||
if (rrs.getSetIdentifier() != null) xml.elem("SetIdentifier", rrs.getSetIdentifier());
|
||||
if (rrs.getWeight() != null) xml.elem("Weight", rrs.getWeight());
|
||||
if (rrs.getRegion() != null) xml.elem("Region", rrs.getRegion());
|
||||
if (rrs.getFailover() != null) xml.elem("Failover", rrs.getFailover());
|
||||
if (rrs.getTtl() != null) xml.elem("TTL", rrs.getTtl());
|
||||
if (rrs.getRecords() != null && !rrs.getRecords().isEmpty()) {
|
||||
xml.start("ResourceRecords");
|
||||
for (ResourceRecord r : rrs.getRecords()) {
|
||||
xml.start("ResourceRecord").elem("Value", r.getValue()).end("ResourceRecord");
|
||||
}
|
||||
xml.end("ResourceRecords");
|
||||
}
|
||||
if (rrs.getAliasTarget() != null) {
|
||||
AliasTarget at = rrs.getAliasTarget();
|
||||
xml.start("AliasTarget")
|
||||
.elem("HostedZoneId", at.getHostedZoneId())
|
||||
.elem("DNSName", at.getDnsName())
|
||||
.elem("EvaluateTargetHealth", String.valueOf(at.isEvaluateTargetHealth()))
|
||||
.end("AliasTarget");
|
||||
}
|
||||
if (rrs.getHealthCheckId() != null) xml.elem("HealthCheckId", rrs.getHealthCheckId());
|
||||
xml.end("ResourceRecordSet");
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private String xmlHealthCheck(HealthCheck hc) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("HealthCheck")
|
||||
.elem("Id", hc.getId())
|
||||
.elem("CallerReference", hc.getCallerReference());
|
||||
if (hc.getConfig() != null) {
|
||||
HealthCheckConfig cfg = hc.getConfig();
|
||||
xml.start("HealthCheckConfig")
|
||||
.elem("Type", cfg.getType())
|
||||
.elem("IPAddress", cfg.getIpAddress())
|
||||
.elem("Port", cfg.getPort() != null ? String.valueOf(cfg.getPort()) : null)
|
||||
.elem("ResourcePath", cfg.getResourcePath())
|
||||
.elem("FullyQualifiedDomainName", cfg.getFullyQualifiedDomainName())
|
||||
.elem("RequestInterval",
|
||||
cfg.getRequestInterval() != null ? String.valueOf(cfg.getRequestInterval()) : null)
|
||||
.elem("FailureThreshold",
|
||||
cfg.getFailureThreshold() != null ? String.valueOf(cfg.getFailureThreshold()) : null)
|
||||
.end("HealthCheckConfig");
|
||||
}
|
||||
xml.elem("HealthCheckVersion", hc.getHealthCheckVersion())
|
||||
.end("HealthCheck");
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private Response xmlErrorResponse(AwsException e) {
|
||||
String xml = new XmlBuilder()
|
||||
.start("ErrorResponse", NS)
|
||||
.start("Error")
|
||||
.elem("Type", "Sender")
|
||||
.elem("Code", e.getErrorCode())
|
||||
.elem("Message", e.getMessage())
|
||||
.end("Error")
|
||||
.elem("RequestId", "00000000-0000-0000-0000-000000000000")
|
||||
.end("ErrorResponse")
|
||||
.build();
|
||||
return Response.status(e.getHttpStatus()).type(XML).entity(xml).build();
|
||||
}
|
||||
|
||||
// ── Request parsers ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Parses the ChangeBatch XML using StAX to correctly handle multiple Change elements,
|
||||
* each containing a ResourceRecordSet with its own set of ResourceRecord/Value children.
|
||||
*/
|
||||
private List<Map<String, Object>> parseChangeBatch(String body) {
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
if (body == null || body.isEmpty()) return result;
|
||||
|
||||
try {
|
||||
XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body));
|
||||
String currentAction = null;
|
||||
ResourceRecordSet currentRrs = null;
|
||||
List<ResourceRecord> currentRecords = null;
|
||||
AliasTarget currentAlias = null;
|
||||
int depth = 0;
|
||||
String currentElement = null;
|
||||
boolean inChangeBatch = false;
|
||||
boolean inChange = false;
|
||||
boolean inRrs = false;
|
||||
boolean inResourceRecords = false;
|
||||
boolean inAlias = false;
|
||||
boolean inHealthCheckConfig = false;
|
||||
|
||||
while (r.hasNext()) {
|
||||
int event = r.next();
|
||||
if (event == XMLStreamConstants.START_ELEMENT) {
|
||||
currentElement = r.getLocalName();
|
||||
switch (currentElement) {
|
||||
case "ChangeBatch" -> inChangeBatch = true;
|
||||
case "Change" -> {
|
||||
if (inChangeBatch) {
|
||||
inChange = true;
|
||||
currentAction = null;
|
||||
currentRrs = null;
|
||||
}
|
||||
}
|
||||
case "Action" -> {
|
||||
if (inChange && !inRrs) currentAction = r.getElementText();
|
||||
}
|
||||
case "ResourceRecordSet" -> {
|
||||
if (inChange) {
|
||||
inRrs = true;
|
||||
currentRrs = new ResourceRecordSet();
|
||||
currentRecords = new ArrayList<>();
|
||||
}
|
||||
}
|
||||
case "ResourceRecords" -> { if (inRrs) inResourceRecords = true; }
|
||||
case "AliasTarget" -> {
|
||||
if (inRrs) {
|
||||
inAlias = true;
|
||||
currentAlias = new AliasTarget();
|
||||
}
|
||||
}
|
||||
case "Name" -> {
|
||||
if (inRrs && !inAlias) {
|
||||
String n = r.getElementText();
|
||||
if (n != null && !n.endsWith(".")) n = n + ".";
|
||||
if (currentRrs != null) currentRrs.setName(n);
|
||||
}
|
||||
}
|
||||
case "Type" -> {
|
||||
if (inRrs && !inAlias && !inHealthCheckConfig && currentRrs != null) {
|
||||
currentRrs.setType(r.getElementText());
|
||||
}
|
||||
}
|
||||
case "TTL" -> {
|
||||
if (inRrs && currentRrs != null) {
|
||||
try { currentRrs.setTtl(Long.parseLong(r.getElementText())); }
|
||||
catch (NumberFormatException ignored) {}
|
||||
}
|
||||
}
|
||||
case "Value" -> {
|
||||
if (inResourceRecords && currentRecords != null) {
|
||||
currentRecords.add(new ResourceRecord(r.getElementText()));
|
||||
}
|
||||
}
|
||||
case "SetIdentifier" -> {
|
||||
if (inRrs && currentRrs != null) currentRrs.setSetIdentifier(r.getElementText());
|
||||
}
|
||||
case "Weight" -> {
|
||||
if (inRrs && currentRrs != null) {
|
||||
try { currentRrs.setWeight(Long.parseLong(r.getElementText())); }
|
||||
catch (NumberFormatException ignored) {}
|
||||
}
|
||||
}
|
||||
case "Region" -> {
|
||||
if (inRrs && !inAlias && currentRrs != null) currentRrs.setRegion(r.getElementText());
|
||||
}
|
||||
case "Failover" -> {
|
||||
if (inRrs && currentRrs != null) currentRrs.setFailover(r.getElementText());
|
||||
}
|
||||
case "HealthCheckId" -> {
|
||||
if (inRrs && !inHealthCheckConfig && currentRrs != null) {
|
||||
currentRrs.setHealthCheckId(r.getElementText());
|
||||
}
|
||||
}
|
||||
case "HostedZoneId" -> {
|
||||
if (inAlias && currentAlias != null) currentAlias.setHostedZoneId(r.getElementText());
|
||||
}
|
||||
case "DNSName" -> {
|
||||
if (inAlias && currentAlias != null) currentAlias.setDnsName(r.getElementText());
|
||||
}
|
||||
case "EvaluateTargetHealth" -> {
|
||||
if (inAlias && currentAlias != null) {
|
||||
currentAlias.setEvaluateTargetHealth(
|
||||
"true".equalsIgnoreCase(r.getElementText()));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (event == XMLStreamConstants.END_ELEMENT) {
|
||||
switch (r.getLocalName()) {
|
||||
case "ResourceRecords" -> inResourceRecords = false;
|
||||
case "AliasTarget" -> {
|
||||
if (inAlias && currentRrs != null && currentAlias != null) {
|
||||
currentRrs.setAliasTarget(currentAlias);
|
||||
}
|
||||
inAlias = false;
|
||||
currentAlias = null;
|
||||
}
|
||||
case "ResourceRecordSet" -> {
|
||||
if (inRrs && currentRrs != null && currentRecords != null) {
|
||||
if (!currentRecords.isEmpty()) currentRrs.setRecords(currentRecords);
|
||||
}
|
||||
inRrs = false;
|
||||
}
|
||||
case "Change" -> {
|
||||
if (inChange && currentAction != null && currentRrs != null) {
|
||||
Map<String, Object> change = new HashMap<>();
|
||||
change.put("action", currentAction);
|
||||
change.put("rrs", currentRrs);
|
||||
result.add(change);
|
||||
}
|
||||
inChange = false;
|
||||
currentAction = null;
|
||||
currentRrs = null;
|
||||
currentRecords = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
r.close();
|
||||
} catch (Exception ignored) {}
|
||||
return result;
|
||||
}
|
||||
|
||||
private HealthCheckConfig parseHealthCheckConfig(String body) {
|
||||
HealthCheckConfig cfg = new HealthCheckConfig();
|
||||
cfg.setType(XmlParser.extractFirst(body, "Type", null));
|
||||
cfg.setIpAddress(XmlParser.extractFirst(body, "IPAddress", null));
|
||||
String portStr = XmlParser.extractFirst(body, "Port", null);
|
||||
if (portStr != null) {
|
||||
try { cfg.setPort(Integer.parseInt(portStr)); } catch (NumberFormatException ignored) {}
|
||||
}
|
||||
cfg.setResourcePath(XmlParser.extractFirst(body, "ResourcePath", null));
|
||||
cfg.setFullyQualifiedDomainName(XmlParser.extractFirst(body, "FullyQualifiedDomainName", null));
|
||||
String riStr = XmlParser.extractFirst(body, "RequestInterval", null);
|
||||
if (riStr != null) {
|
||||
try { cfg.setRequestInterval(Integer.parseInt(riStr)); } catch (NumberFormatException ignored) {}
|
||||
}
|
||||
String ftStr = XmlParser.extractFirst(body, "FailureThreshold", null);
|
||||
if (ftStr != null) {
|
||||
try { cfg.setFailureThreshold(Integer.parseInt(ftStr)); } catch (NumberFormatException ignored) {}
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses Key elements that appear inside a RemoveTagKeys block only.
|
||||
* Uses StAX to avoid matching Key elements from AddTags.
|
||||
*/
|
||||
private List<String> parseRemoveTagKeys(String body) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (body == null || body.isEmpty()) return keys;
|
||||
try {
|
||||
XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body));
|
||||
boolean inRemove = false;
|
||||
while (r.hasNext()) {
|
||||
int event = r.next();
|
||||
if (event == XMLStreamConstants.START_ELEMENT) {
|
||||
if ("RemoveTagKeys".equals(r.getLocalName())) {
|
||||
inRemove = true;
|
||||
} else if (inRemove && "Key".equals(r.getLocalName())) {
|
||||
keys.add(r.getElementText());
|
||||
}
|
||||
} else if (event == XMLStreamConstants.END_ELEMENT) {
|
||||
if ("RemoveTagKeys".equals(r.getLocalName())) inRemove = false;
|
||||
}
|
||||
}
|
||||
r.close();
|
||||
} catch (Exception ignored) {}
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package io.github.hectorvent.floci.services.route53;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
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 io.github.hectorvent.floci.services.route53.model.ChangeInfo;
|
||||
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;
|
||||
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
|
||||
import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@ApplicationScoped
|
||||
public class Route53Service {
|
||||
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
public record CreateZoneResult(HostedZone zone, ChangeInfo change) {}
|
||||
|
||||
private final StorageBackend<String, HostedZone> zoneStore;
|
||||
private final StorageBackend<String, List<ResourceRecordSet>> recordStore;
|
||||
private final StorageBackend<String, HealthCheck> healthCheckStore;
|
||||
private final StorageBackend<String, ChangeInfo> changeStore;
|
||||
private final StorageBackend<String, Map<String, String>> tagStore;
|
||||
private final List<String> nameServers;
|
||||
|
||||
@Inject
|
||||
public Route53Service(StorageFactory factory, EmulatorConfig config) {
|
||||
this.zoneStore = factory.create("route53", "route53-zones.json",
|
||||
new TypeReference<Map<String, HostedZone>>() {});
|
||||
this.recordStore = factory.create("route53", "route53-records.json",
|
||||
new TypeReference<Map<String, List<ResourceRecordSet>>>() {});
|
||||
this.healthCheckStore = factory.create("route53", "route53-health-checks.json",
|
||||
new TypeReference<Map<String, HealthCheck>>() {});
|
||||
this.changeStore = factory.create("route53", "route53-changes.json",
|
||||
new TypeReference<Map<String, ChangeInfo>>() {});
|
||||
this.tagStore = factory.create("route53", "route53-tags.json",
|
||||
new TypeReference<Map<String, Map<String, String>>>() {});
|
||||
|
||||
EmulatorConfig.Route53ServiceConfig r53 = config.services().route53();
|
||||
this.nameServers = List.of(
|
||||
r53.defaultNameserver1(),
|
||||
r53.defaultNameserver2(),
|
||||
r53.defaultNameserver3(),
|
||||
r53.defaultNameserver4()
|
||||
);
|
||||
}
|
||||
|
||||
// ── Hosted Zones ──────────────────────────────────────────────────────────
|
||||
|
||||
public synchronized CreateZoneResult createHostedZone(String name, String callerReference,
|
||||
String comment, boolean privateZone) {
|
||||
String normalizedName = normalizeName(name);
|
||||
|
||||
for (HostedZone existing : zoneStore.scan(k -> true)) {
|
||||
if (existing.getCallerReference().equals(callerReference)) {
|
||||
throw new AwsException("HostedZoneAlreadyExists",
|
||||
"A hosted zone with caller reference " + callerReference + " already exists.", 409);
|
||||
}
|
||||
}
|
||||
|
||||
String id = generateZoneId();
|
||||
HostedZone zone = new HostedZone(id, normalizedName, callerReference, comment, privateZone);
|
||||
zoneStore.put(id, zone);
|
||||
recordStore.put(id, buildDefaultRecords(normalizedName));
|
||||
ChangeInfo change = newChange(null);
|
||||
return new CreateZoneResult(zone, change);
|
||||
}
|
||||
|
||||
public HostedZone getHostedZone(String id) {
|
||||
HostedZone zone = zoneStore.get(id).orElseThrow(() ->
|
||||
new AwsException("NoSuchHostedZone",
|
||||
"No hosted zone found with ID: " + id, 404));
|
||||
zone.setResourceRecordSetCount(recordCount(id));
|
||||
return zone;
|
||||
}
|
||||
|
||||
public synchronized ChangeInfo deleteHostedZone(String id) {
|
||||
HostedZone zone = getHostedZone(id);
|
||||
List<ResourceRecordSet> records = recordStore.get(id).orElse(List.of());
|
||||
long nonDefault = records.stream()
|
||||
.filter(r -> !isApexSoaOrNs(r, zone.getName()))
|
||||
.count();
|
||||
if (nonDefault > 0) {
|
||||
throw new AwsException("HostedZoneNotEmpty",
|
||||
"The hosted zone contains resource record sets in addition to the default NS and SOA records.", 400);
|
||||
}
|
||||
zoneStore.delete(id);
|
||||
recordStore.delete(id);
|
||||
tagStore.delete("hostedzone/" + id);
|
||||
return newChange(null);
|
||||
}
|
||||
|
||||
public List<HostedZone> listHostedZones(String marker, int maxItems) {
|
||||
List<HostedZone> all = new ArrayList<>(zoneStore.scan(k -> true));
|
||||
all.sort((a, b) -> a.getName().compareTo(b.getName()));
|
||||
for (HostedZone zone : all) {
|
||||
zone.setResourceRecordSetCount(recordCount(zone.getId()));
|
||||
}
|
||||
if (marker != null && !marker.isEmpty()) {
|
||||
int idx = 0;
|
||||
for (int i = 0; i < all.size(); i++) {
|
||||
if (all.get(i).getId().equals(marker)) {
|
||||
idx = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
all = all.subList(idx, all.size());
|
||||
}
|
||||
if (maxItems > 0 && all.size() > maxItems) {
|
||||
return all.subList(0, maxItems);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
public List<HostedZone> listHostedZonesByName(String dnsName, int maxItems) {
|
||||
List<HostedZone> all = new ArrayList<>(zoneStore.scan(k -> true));
|
||||
all.sort((a, b) -> a.getName().compareTo(b.getName()));
|
||||
for (HostedZone zone : all) {
|
||||
zone.setResourceRecordSetCount(recordCount(zone.getId()));
|
||||
}
|
||||
if (dnsName != null && !dnsName.isEmpty()) {
|
||||
String normalized = normalizeName(dnsName);
|
||||
all = all.stream()
|
||||
.filter(z -> z.getName().compareTo(normalized) >= 0)
|
||||
.toList();
|
||||
all = new ArrayList<>(all);
|
||||
}
|
||||
if (maxItems > 0 && all.size() > maxItems) {
|
||||
return all.subList(0, maxItems);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
public long getHostedZoneCount() {
|
||||
return zoneStore.keys().size();
|
||||
}
|
||||
|
||||
// ── Resource Record Sets ──────────────────────────────────────────────────
|
||||
|
||||
public synchronized ChangeInfo changeResourceRecordSets(String zoneId,
|
||||
List<Map<String, Object>> changes,
|
||||
String comment) {
|
||||
HostedZone zone = getHostedZone(zoneId);
|
||||
List<ResourceRecordSet> current = new ArrayList<>(
|
||||
recordStore.get(zoneId).orElse(new ArrayList<>()));
|
||||
|
||||
// Validate all changes before applying any
|
||||
for (Map<String, Object> change : changes) {
|
||||
String action = (String) change.get("action");
|
||||
ResourceRecordSet rrs = (ResourceRecordSet) change.get("rrs");
|
||||
validateChange(action, rrs, current, zone.getName());
|
||||
}
|
||||
|
||||
// Apply all changes
|
||||
for (Map<String, Object> change : changes) {
|
||||
String action = (String) change.get("action");
|
||||
ResourceRecordSet rrs = (ResourceRecordSet) change.get("rrs");
|
||||
applyChange(action, rrs, current);
|
||||
}
|
||||
|
||||
zone.setResourceRecordSetCount(current.size());
|
||||
zoneStore.put(zoneId, zone);
|
||||
recordStore.put(zoneId, current);
|
||||
return newChange(comment);
|
||||
}
|
||||
|
||||
public List<ResourceRecordSet> listResourceRecordSets(String zoneId, String startName,
|
||||
String startType, int maxItems) {
|
||||
getHostedZone(zoneId);
|
||||
List<ResourceRecordSet> records = new ArrayList<>(
|
||||
recordStore.get(zoneId).orElse(List.of()));
|
||||
|
||||
records.sort((a, b) -> {
|
||||
int cmp = a.getName().compareTo(b.getName());
|
||||
if (cmp != 0) return cmp;
|
||||
return a.getType().compareTo(b.getType());
|
||||
});
|
||||
|
||||
if (startName != null && !startName.isEmpty()) {
|
||||
String normalizedStart = normalizeName(startName);
|
||||
final String finalStartType = startType;
|
||||
records = records.stream()
|
||||
.filter(r -> {
|
||||
int cmp = r.getName().compareTo(normalizedStart);
|
||||
if (cmp > 0) return true;
|
||||
if (cmp == 0 && finalStartType != null && !finalStartType.isEmpty()) {
|
||||
return r.getType().compareTo(finalStartType) >= 0;
|
||||
}
|
||||
return cmp == 0;
|
||||
})
|
||||
.toList();
|
||||
records = new ArrayList<>(records);
|
||||
}
|
||||
|
||||
if (maxItems > 0 && records.size() > maxItems) {
|
||||
return records.subList(0, maxItems);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
// ── Changes ───────────────────────────────────────────────────────────────
|
||||
|
||||
public ChangeInfo getChange(String changeId) {
|
||||
return changeStore.get(changeId).orElseThrow(() ->
|
||||
new AwsException("NoSuchChange",
|
||||
"No change found with ID: " + changeId, 404));
|
||||
}
|
||||
|
||||
// ── Health Checks ─────────────────────────────────────────────────────────
|
||||
|
||||
public synchronized HealthCheck createHealthCheck(String callerReference, HealthCheckConfig cfg) {
|
||||
for (HealthCheck existing : healthCheckStore.scan(k -> true)) {
|
||||
if (existing.getCallerReference().equals(callerReference)) {
|
||||
throw new AwsException("HealthCheckAlreadyExists",
|
||||
"A health check with caller reference " + callerReference + " already exists.", 409);
|
||||
}
|
||||
}
|
||||
String id = UUID.randomUUID().toString();
|
||||
HealthCheck hc = new HealthCheck(id, callerReference, cfg);
|
||||
healthCheckStore.put(id, hc);
|
||||
return hc;
|
||||
}
|
||||
|
||||
public HealthCheck getHealthCheck(String id) {
|
||||
return healthCheckStore.get(id).orElseThrow(() ->
|
||||
new AwsException("NoSuchHealthCheck",
|
||||
"No health check found with ID: " + id, 404));
|
||||
}
|
||||
|
||||
public void deleteHealthCheck(String id) {
|
||||
getHealthCheck(id);
|
||||
healthCheckStore.delete(id);
|
||||
tagStore.delete("healthcheck/" + id);
|
||||
}
|
||||
|
||||
public List<HealthCheck> listHealthChecks(String marker, int maxItems) {
|
||||
List<HealthCheck> all = new ArrayList<>(healthCheckStore.scan(k -> true));
|
||||
if (marker != null && !marker.isEmpty()) {
|
||||
int idx = 0;
|
||||
for (int i = 0; i < all.size(); i++) {
|
||||
if (all.get(i).getId().equals(marker)) {
|
||||
idx = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
all = all.subList(idx, all.size());
|
||||
}
|
||||
if (maxItems > 0 && all.size() > maxItems) {
|
||||
return all.subList(0, maxItems);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
public HealthCheck updateHealthCheck(String id, HealthCheckConfig cfg) {
|
||||
HealthCheck hc = getHealthCheck(id);
|
||||
hc.setConfig(cfg);
|
||||
hc.setHealthCheckVersion(hc.getHealthCheckVersion() + 1);
|
||||
healthCheckStore.put(id, hc);
|
||||
return hc;
|
||||
}
|
||||
|
||||
// ── Tags ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceType, String resourceId) {
|
||||
return tagStore.get(resourceType + "/" + resourceId).orElse(Collections.emptyMap());
|
||||
}
|
||||
|
||||
public void changeTagsForResource(String resourceType, String resourceId,
|
||||
List<Map<String, String>> addTags, List<String> removeTagKeys) {
|
||||
String key = resourceType + "/" + resourceId;
|
||||
Map<String, String> tags = new LinkedHashMap<>(tagStore.get(key).orElse(new LinkedHashMap<>()));
|
||||
if (removeTagKeys != null) {
|
||||
removeTagKeys.forEach(tags::remove);
|
||||
}
|
||||
if (addTags != null) {
|
||||
addTags.forEach(t -> {
|
||||
if (t.get("Key") != null) {
|
||||
tags.put(t.get("Key"), t.getOrDefault("Value", ""));
|
||||
}
|
||||
});
|
||||
}
|
||||
tagStore.put(key, tags);
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
public List<String> getNameServers() {
|
||||
return nameServers;
|
||||
}
|
||||
|
||||
private static String normalizeName(String name) {
|
||||
if (name == null || name.isEmpty()) return name;
|
||||
return name.endsWith(".") ? name : name + ".";
|
||||
}
|
||||
|
||||
private static String generateZoneId() {
|
||||
StringBuilder sb = new StringBuilder("Z");
|
||||
for (int i = 0; i < 14; i++) {
|
||||
sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String generateChangeId() {
|
||||
StringBuilder sb = new StringBuilder("C");
|
||||
for (int i = 0; i < 13; i++) {
|
||||
sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private ChangeInfo newChange(String comment) {
|
||||
String id = generateChangeId();
|
||||
ChangeInfo change = new ChangeInfo(id, Instant.now().toString(), comment);
|
||||
changeStore.put(id, change);
|
||||
return change;
|
||||
}
|
||||
|
||||
private List<ResourceRecordSet> buildDefaultRecords(String zoneName) {
|
||||
List<ResourceRecordSet> records = new ArrayList<>();
|
||||
|
||||
ResourceRecordSet soa = new ResourceRecordSet();
|
||||
soa.setName(zoneName);
|
||||
soa.setType("SOA");
|
||||
soa.setTtl(900L);
|
||||
soa.setRecords(List.of(new ResourceRecord(
|
||||
nameServers.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()
|
||||
.map(n -> new ResourceRecord(n + "."))
|
||||
.toList());
|
||||
records.add(ns);
|
||||
|
||||
return records;
|
||||
}
|
||||
|
||||
private boolean isApexSoaOrNs(ResourceRecordSet rrs, String zoneName) {
|
||||
return rrs.getName().equals(zoneName) &&
|
||||
("SOA".equals(rrs.getType()) || "NS".equals(rrs.getType()));
|
||||
}
|
||||
|
||||
private int recordCount(String zoneId) {
|
||||
return recordStore.get(zoneId).map(List::size).orElse(0);
|
||||
}
|
||||
|
||||
private void validateChange(String action, ResourceRecordSet rrs,
|
||||
List<ResourceRecordSet> current, String zoneName) {
|
||||
if ("DELETE".equals(action) && isApexSoaOrNs(rrs, zoneName)) {
|
||||
throw new AwsException("InvalidChangeBatch",
|
||||
"Invalid resource record set: Deleting the SOA or NS record at the zone apex is not permitted.", 400);
|
||||
}
|
||||
if ("CREATE".equals(action)) {
|
||||
boolean exists = current.stream().anyMatch(r ->
|
||||
r.getName().equals(rrs.getName()) &&
|
||||
r.getType().equals(rrs.getType()) &&
|
||||
equalOrNull(r.getSetIdentifier(), rrs.getSetIdentifier()));
|
||||
if (exists) {
|
||||
throw new AwsException("InvalidChangeBatch",
|
||||
"Tried to create resource record set [name='" + rrs.getName() +
|
||||
"', type='" + rrs.getType() + "'] but it already exists.", 400);
|
||||
}
|
||||
}
|
||||
if ("DELETE".equals(action)) {
|
||||
boolean found = current.stream().anyMatch(r ->
|
||||
r.getName().equals(rrs.getName()) && r.getType().equals(rrs.getType()));
|
||||
if (!found) {
|
||||
throw new AwsException("InvalidChangeBatch",
|
||||
"Tried to delete resource record set [name='" + rrs.getName() +
|
||||
"', type='" + rrs.getType() + "'] but it was not found.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void applyChange(String action, ResourceRecordSet rrs, List<ResourceRecordSet> current) {
|
||||
switch (action) {
|
||||
case "CREATE" -> current.add(rrs);
|
||||
case "DELETE" -> current.removeIf(r ->
|
||||
r.getName().equals(rrs.getName()) && r.getType().equals(rrs.getType()) &&
|
||||
equalOrNull(r.getSetIdentifier(), rrs.getSetIdentifier()));
|
||||
case "UPSERT" -> {
|
||||
current.removeIf(r ->
|
||||
r.getName().equals(rrs.getName()) && r.getType().equals(rrs.getType()) &&
|
||||
equalOrNull(r.getSetIdentifier(), rrs.getSetIdentifier()));
|
||||
current.add(rrs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean equalOrNull(String a, String b) {
|
||||
if (a == null && b == null) return true;
|
||||
if (a == null || b == null) return false;
|
||||
return a.equals(b);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.github.hectorvent.floci.services.route53.model;
|
||||
|
||||
public class AliasTarget {
|
||||
|
||||
private String hostedZoneId;
|
||||
private String dnsName;
|
||||
private boolean evaluateTargetHealth;
|
||||
|
||||
public AliasTarget() {}
|
||||
|
||||
public String getHostedZoneId() { return hostedZoneId; }
|
||||
public void setHostedZoneId(String hostedZoneId) { this.hostedZoneId = hostedZoneId; }
|
||||
|
||||
public String getDnsName() { return dnsName; }
|
||||
public void setDnsName(String dnsName) { this.dnsName = dnsName; }
|
||||
|
||||
public boolean isEvaluateTargetHealth() { return evaluateTargetHealth; }
|
||||
public void setEvaluateTargetHealth(boolean evaluateTargetHealth) {
|
||||
this.evaluateTargetHealth = evaluateTargetHealth;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package io.github.hectorvent.floci.services.route53.model;
|
||||
|
||||
public class ChangeInfo {
|
||||
|
||||
private String id;
|
||||
private String status;
|
||||
private String submittedAt;
|
||||
private String comment;
|
||||
|
||||
public ChangeInfo() {}
|
||||
|
||||
public ChangeInfo(String id, String submittedAt, String comment) {
|
||||
this.id = id;
|
||||
this.status = "INSYNC";
|
||||
this.submittedAt = submittedAt;
|
||||
this.comment = comment;
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
|
||||
public String getSubmittedAt() { return submittedAt; }
|
||||
public void setSubmittedAt(String submittedAt) { this.submittedAt = submittedAt; }
|
||||
|
||||
public String getComment() { return comment; }
|
||||
public void setComment(String comment) { this.comment = comment; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package io.github.hectorvent.floci.services.route53.model;
|
||||
|
||||
public class HealthCheck {
|
||||
|
||||
private String id;
|
||||
private String callerReference;
|
||||
private HealthCheckConfig config;
|
||||
private long healthCheckVersion;
|
||||
|
||||
public HealthCheck() {}
|
||||
|
||||
public HealthCheck(String id, String callerReference, HealthCheckConfig config) {
|
||||
this.id = id;
|
||||
this.callerReference = callerReference;
|
||||
this.config = config;
|
||||
this.healthCheckVersion = 1;
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getCallerReference() { return callerReference; }
|
||||
public void setCallerReference(String callerReference) { this.callerReference = callerReference; }
|
||||
|
||||
public HealthCheckConfig getConfig() { return config; }
|
||||
public void setConfig(HealthCheckConfig config) { this.config = config; }
|
||||
|
||||
public long getHealthCheckVersion() { return healthCheckVersion; }
|
||||
public void setHealthCheckVersion(long healthCheckVersion) { this.healthCheckVersion = healthCheckVersion; }
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package io.github.hectorvent.floci.services.route53.model;
|
||||
|
||||
public class HealthCheckConfig {
|
||||
|
||||
private String type;
|
||||
private String ipAddress;
|
||||
private Integer port;
|
||||
private String resourcePath;
|
||||
private String fullyQualifiedDomainName;
|
||||
private Integer requestInterval;
|
||||
private Integer failureThreshold;
|
||||
|
||||
public HealthCheckConfig() {}
|
||||
|
||||
public String getType() { return type; }
|
||||
public void setType(String type) { this.type = type; }
|
||||
|
||||
public String getIpAddress() { return ipAddress; }
|
||||
public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; }
|
||||
|
||||
public Integer getPort() { return port; }
|
||||
public void setPort(Integer port) { this.port = port; }
|
||||
|
||||
public String getResourcePath() { return resourcePath; }
|
||||
public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; }
|
||||
|
||||
public String getFullyQualifiedDomainName() { return fullyQualifiedDomainName; }
|
||||
public void setFullyQualifiedDomainName(String fullyQualifiedDomainName) {
|
||||
this.fullyQualifiedDomainName = fullyQualifiedDomainName;
|
||||
}
|
||||
|
||||
public Integer getRequestInterval() { return requestInterval; }
|
||||
public void setRequestInterval(Integer requestInterval) { this.requestInterval = requestInterval; }
|
||||
|
||||
public Integer getFailureThreshold() { return failureThreshold; }
|
||||
public void setFailureThreshold(Integer failureThreshold) { this.failureThreshold = failureThreshold; }
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package io.github.hectorvent.floci.services.route53.model;
|
||||
|
||||
public class HostedZone {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String callerReference;
|
||||
private String comment;
|
||||
private boolean privateZone;
|
||||
private int resourceRecordSetCount;
|
||||
|
||||
public HostedZone() {}
|
||||
|
||||
public HostedZone(String id, String name, String callerReference,
|
||||
String comment, boolean privateZone) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.callerReference = callerReference;
|
||||
this.comment = comment;
|
||||
this.privateZone = privateZone;
|
||||
this.resourceRecordSetCount = 2;
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getCallerReference() { return callerReference; }
|
||||
public void setCallerReference(String callerReference) { this.callerReference = callerReference; }
|
||||
|
||||
public String getComment() { return comment; }
|
||||
public void setComment(String comment) { this.comment = comment; }
|
||||
|
||||
public boolean isPrivateZone() { return privateZone; }
|
||||
public void setPrivateZone(boolean privateZone) { this.privateZone = privateZone; }
|
||||
|
||||
public int getResourceRecordSetCount() { return resourceRecordSetCount; }
|
||||
public void setResourceRecordSetCount(int resourceRecordSetCount) {
|
||||
this.resourceRecordSetCount = resourceRecordSetCount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.route53.model;
|
||||
|
||||
public class ResourceRecord {
|
||||
|
||||
private String value;
|
||||
|
||||
public ResourceRecord() {}
|
||||
|
||||
public ResourceRecord(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getValue() { return value; }
|
||||
public void setValue(String value) { this.value = value; }
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.services.route53.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ResourceRecordSet {
|
||||
|
||||
private String name;
|
||||
private String type;
|
||||
private Long ttl;
|
||||
private List<ResourceRecord> records;
|
||||
private AliasTarget aliasTarget;
|
||||
private Long weight;
|
||||
private String region;
|
||||
private String setIdentifier;
|
||||
private String failover;
|
||||
private String healthCheckId;
|
||||
|
||||
public ResourceRecordSet() {}
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getType() { return type; }
|
||||
public void setType(String type) { this.type = type; }
|
||||
|
||||
public Long getTtl() { return ttl; }
|
||||
public void setTtl(Long ttl) { this.ttl = ttl; }
|
||||
|
||||
public List<ResourceRecord> getRecords() { return records; }
|
||||
public void setRecords(List<ResourceRecord> records) { this.records = records; }
|
||||
|
||||
public AliasTarget getAliasTarget() { return aliasTarget; }
|
||||
public void setAliasTarget(AliasTarget aliasTarget) { this.aliasTarget = aliasTarget; }
|
||||
|
||||
public Long getWeight() { return weight; }
|
||||
public void setWeight(Long weight) { this.weight = weight; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public String getSetIdentifier() { return setIdentifier; }
|
||||
public void setSetIdentifier(String setIdentifier) { this.setIdentifier = setIdentifier; }
|
||||
|
||||
public String getFailover() { return failover; }
|
||||
public void setFailover(String failover) { this.failover = failover; }
|
||||
|
||||
public String getHealthCheckId() { return healthCheckId; }
|
||||
public void setHealthCheckId(String healthCheckId) { this.healthCheckId = healthCheckId; }
|
||||
}
|
||||
Reference in new issue
Block a user