Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(route53): return the health check on a CreateHealthCheck retry (#5298)

Hector Ventura0d4b8cda742a
diff --git a/docs/services/route53.md b/docs/services/route53.md
index 619bc162af..dabb4d2b25 100644
--- a/docs/services/route53.md
+++ b/docs/services/route53.md
@@ -45,6 +45,7 @@ Route53 emulation supporting hosted zones, resource record sets, health checks,
- Supported change actions: `CREATE`, `UPSERT`, `DELETE`.
- Hosted zone IDs are returned with the `/hostedzone/` prefix in XML responses (e.g. `/hostedzone/Z1PA6795UKMFR9`). The AWS SDK strips this prefix client-side.
- Health check IDs are plain UUIDs without a prefix.
+- `CreateHealthCheck` with a `CallerReference` already in use returns that health check when the settings match, so an SDK retry succeeds, and fails with `HealthCheckAlreadyExists` when they differ. A deleted health check's reference can be reused at once; AWS keeps refusing it for some days.
- Tags are supported for both `hostedzone` and `healthcheck` resource types.
- A hosted zone is private when `CreateHostedZone` carries a `<VPC>` element; `HostedZoneConfig.PrivateZone` is response-only.
- `AssociateVPCWithHostedZone` rejects public zones with `PublicZoneVPCAssociation`, and `DisassociateVPCFromHostedZone` rejects removing the last VPC with `LastVPCAssociation`.
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 2bf1f92d2d..95a990f7f0 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
@@ -464,7 +464,7 @@ public class Route53Controller {
throw new AwsException("InvalidInput", "CallerReference is required.", 400);
}
HealthCheckConfig cfg = parseHealthCheckConfig(body);
- HealthCheck hc = service.createHealthCheck(callerRef, cfg);
+ HealthCheck hc = service.createHealthCheck(callerRef, cfg, healthCheckSettings(body));
String xml = new XmlBuilder()
.start("CreateHealthCheckResponse", NS)
.raw(xmlHealthCheck(hc))
@@ -1107,21 +1107,63 @@ public class Route53Controller {
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.setPort(integerElement(body, "Port"));
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) {}
+ cfg.setRequestInterval(integerElement(body, "RequestInterval"));
+ cfg.setFailureThreshold(integerElement(body, "FailureThreshold"));
+ return cfg;
+ }
+
+ private static Integer integerElement(String body, String name) {
+ String value = XmlParser.extractFirst(body, name, null);
+ if (value == null) {
+ return null;
}
- String ftStr = XmlParser.extractFirst(body, "FailureThreshold", null);
- if (ftStr != null) {
- try { cfg.setFailureThreshold(Integer.parseInt(ftStr)); } catch (NumberFormatException ignored) {}
+ try {
+ return Integer.parseInt(value.trim());
+ } catch (NumberFormatException e) {
+ throw new AwsException("InvalidInput", "Invalid value for " + name + ": " + value, 400);
+ }
+ }
+
+ /**
+ * The create request's settings in a canonical form, so a retry can be told from a different
+ * request: every value under {@code HealthCheckConfig} as {@code path=value}, sorted, because
+ * {@code Regions} and {@code ChildHealthChecks} are sets. An omitted {@code RequestInterval} or
+ * {@code FailureThreshold} counts as AWS's default (30 and 3), except for {@code RECOVERY_CONTROL},
+ * which takes neither, so stating the default explicitly is still the same request.
+ */
+ static String healthCheckSettings(String body) {
+ // Null for malformed XML as well as a missing element; HealthCheckConfig is required either way.
+ XmlParser.XmlElement config = XmlParser.extractElementTree(body, "HealthCheckConfig");
+ if (config == null) {
+ throw new AwsException("InvalidInput", "Could not parse the request body.", 400);
+ }
+ List<String> entries = new ArrayList<>();
+ collectSettings(config, "", entries);
+ if (!entries.contains("Type=RECOVERY_CONTROL")) {
+ addDefault(entries, "RequestInterval", "30");
+ addDefault(entries, "FailureThreshold", "3");
+ }
+ entries.sort(null);
+ return String.join("\n", entries);
+ }
+
+ private static void collectSettings(XmlParser.XmlElement element, String prefix, List<String> entries) {
+ for (XmlParser.XmlElement child : element.children()) {
+ String path = prefix + child.name();
+ if (!child.text().isEmpty()) {
+ entries.add(path + "=" + child.text());
+ }
+ collectSettings(child, path + "/", entries);
+ }
+ }
+
+ private static void addDefault(List<String> entries, String name, String value) {
+ if (entries.stream().noneMatch(entry -> entry.startsWith(name + "="))) {
+ entries.add(name + "=" + value);
}
- return cfg;
}
/**
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 0ceac25227..36a16a4202 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
@@ -468,15 +468,24 @@ public class Route53Service implements Resettable {
// ── Health Checks ─────────────────────────────────────────────────────────
- public synchronized HealthCheck createHealthCheck(String callerReference, HealthCheckConfig cfg) {
+ /**
+ * A caller reference makes the create safe to retry: the same reference with the same settings
+ * (the request's canonical {@code requestSettings}) returns the health check it already created,
+ * and different settings are refused.
+ */
+ public synchronized HealthCheck createHealthCheck(String callerReference, HealthCheckConfig cfg,
+ String requestSettings) {
for (HealthCheck existing : healthCheckStore.scan(k -> true)) {
if (existing.getCallerReference().equals(callerReference)) {
+ if (requestSettings.equals(existing.getRequestSettings())) {
+ return existing;
+ }
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);
+ HealthCheck hc = new HealthCheck(id, callerReference, cfg, requestSettings);
healthCheckStore.put(id, hc);
return hc;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/model/HealthCheck.java b/src/main/java/io/github/hectorvent/floci/services/route53/model/HealthCheck.java
index 5a887d6067..c3222c44f1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/route53/model/HealthCheck.java
+++ b/src/main/java/io/github/hectorvent/floci/services/route53/model/HealthCheck.java
@@ -9,13 +9,15 @@ public class HealthCheck {
private String callerReference;
private HealthCheckConfig config;
private long healthCheckVersion;
+ private String requestSettings;
public HealthCheck() {}
- public HealthCheck(String id, String callerReference, HealthCheckConfig config) {
+ public HealthCheck(String id, String callerReference, HealthCheckConfig config, String requestSettings) {
this.id = id;
this.callerReference = callerReference;
this.config = config;
+ this.requestSettings = requestSettings;
this.healthCheckVersion = 1;
}
@@ -30,4 +32,8 @@ public class HealthCheck {
public long getHealthCheckVersion() { return healthCheckVersion; }
public void setHealthCheckVersion(long healthCheckVersion) { this.healthCheckVersion = healthCheckVersion; }
+
+ /** The create request's settings in canonical form, which a retry with the same reference must match. */
+ public String getRequestSettings() { return requestSettings; }
+ public void setRequestSettings(String requestSettings) { this.requestSettings = requestSettings; }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53HealthCheckSettingsTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53HealthCheckSettingsTest.java
new file mode 100644
index 0000000000..7498627c20
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53HealthCheckSettingsTest.java
@@ -0,0 +1,62 @@
+package io.github.hectorvent.floci.services.route53;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class Route53HealthCheckSettingsTest {
+
+ private static String request(String config) {
+ return """
+ <CreateHealthCheckRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <CallerReference>ref</CallerReference>
+ <HealthCheckConfig>%s</HealthCheckConfig>
+ </CreateHealthCheckRequest>
+ """.formatted(config);
+ }
+
+ private static String settings(String config) {
+ return Route53Controller.healthCheckSettings(request(config));
+ }
+
+ // Catches: a retry that states RequestInterval or FailureThreshold at its default refused as a
+ // different request from one that omitted them.
+ @Test
+ void omittedIntervalAndThresholdEqualTheirDefaults() {
+ assertEquals(settings("<Type>HTTP</Type><IPAddress>10.0.0.1</IPAddress>"),
+ settings("<Type>HTTP</Type><IPAddress>10.0.0.1</IPAddress>"
+ + "<RequestInterval>30</RequestInterval><FailureThreshold>3</FailureThreshold>"));
+ assertNotEquals(settings("<Type>HTTP</Type><IPAddress>10.0.0.1</IPAddress>"),
+ settings("<Type>HTTP</Type><IPAddress>10.0.0.1</IPAddress><RequestInterval>10</RequestInterval>"));
+ }
+
+ // Catches: requests that differ only in a setting Floci does not model passing as a retry.
+ @Test
+ void settingsFlociDoesNotModelStillCount() {
+ assertNotEquals(settings("<Type>HTTPS</Type><FullyQualifiedDomainName>example.com</FullyQualifiedDomainName>"),
+ settings("<Type>HTTPS</Type><FullyQualifiedDomainName>example.com</FullyQualifiedDomainName>"
+ + "<EnableSNI>false</EnableSNI>"));
+ }
+
+ @Test
+ void regionsAreASet() {
+ assertEquals(settings("<Type>HTTP</Type><Regions><Region>us-east-1</Region><Region>eu-west-1</Region></Regions>"),
+ settings("<Type>HTTP</Type><Regions><Region>eu-west-1</Region><Region>us-east-1</Region></Regions>"));
+ }
+
+ @Test
+ void recoveryControlGetsNoIntervalOrThresholdDefaults() {
+ assertEquals("RoutingControlArn=arn\nType=RECOVERY_CONTROL",
+ settings("<Type>RECOVERY_CONTROL</Type><RoutingControlArn>arn</RoutingControlArn>"));
+ }
+
+ @Test
+ void malformedXmlIsInvalidInput() {
+ AwsException e = assertThrows(AwsException.class,
+ () -> Route53Controller.healthCheckSettings("<CreateHealthCheckRequest><HealthCheckConfig>"));
+ assertEquals("InvalidInput", e.getErrorCode());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53IntegrationTest.java
index 411f921fbd..126e6082db 100644
--- a/src/test/java/io/github/hectorvent/floci/services/route53/Route53IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53IntegrationTest.java
@@ -387,6 +387,81 @@ class Route53IntegrationTest {
// ── Health Checks ─────────────────────────────────────────────────────────
+ private static String healthCheckRequest(String callerReference, String resourcePath) {
+ return """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <CreateHealthCheckRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <CallerReference>%s</CallerReference>
+ <HealthCheckConfig>
+ <Type>HTTPS</Type>
+ <FullyQualifiedDomainName>example.com</FullyQualifiedDomainName>
+ <Port>443</Port>
+ <ResourcePath>%s</ResourcePath>
+ <RequestInterval>30</RequestInterval>
+ <FailureThreshold>3</FailureThreshold>
+ </HealthCheckConfig>
+ </CreateHealthCheckRequest>
+ """.formatted(callerReference, resourcePath);
+ }
+
+ @Test
+ @Order(26)
+ void createHealthCheck_nonNumericFailureThreshold_isInvalidInput() {
+ given()
+ .contentType(XML)
+ .body(healthCheckRequest("hc-bad-" + System.nanoTime(), "/health")
+ .replace("<FailureThreshold>3</FailureThreshold>", "<FailureThreshold>three</FailureThreshold>"))
+ .when().post("/2013-04-01/healthcheck")
+ .then().statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
+ }
+
+ // Catches: an SDK retry of CreateHealthCheck (same caller reference and settings) answered with
+ // HealthCheckAlreadyExists instead of the health check it already created.
+ @Test
+ @Order(25)
+ void createHealthCheck_retryWithSameReferenceAndSettings_returnsTheSameHealthCheck() {
+ String reference = "hc-retry-" + System.nanoTime();
+ String firstId = given()
+ .contentType(XML).body(healthCheckRequest(reference, "/health"))
+ .when().post("/2013-04-01/healthcheck")
+ .then().statusCode(201)
+ .extract().path("CreateHealthCheckResponse.HealthCheck.Id");
+ try {
+ given()
+ .contentType(XML).body(healthCheckRequest(reference, "/health"))
+ .when().post("/2013-04-01/healthcheck")
+ .then().statusCode(201)
+ .body("CreateHealthCheckResponse.HealthCheck.Id", equalTo(firstId));
+
+ given()
+ .contentType(XML).body(healthCheckRequest(reference, "/other"))
+ .when().post("/2013-04-01/healthcheck")
+ .then().statusCode(409)
+ .body("ErrorResponse.Error.Code", equalTo("HealthCheckAlreadyExists"));
+
+ given()
+ .contentType(XML)
+ .body(healthCheckRequest(reference, "/health")
+ .replace("<FailureThreshold>3</FailureThreshold>",
+ "<FailureThreshold>3</FailureThreshold><EnableSNI>false</EnableSNI>"))
+ .when().post("/2013-04-01/healthcheck")
+ .then().statusCode(409)
+ .body("ErrorResponse.Error.Code", equalTo("HealthCheckAlreadyExists"));
+
+ given()
+ .contentType(XML)
+ .body(healthCheckRequest(reference, "/health")
+ .replace("<RequestInterval>30</RequestInterval>", "")
+ .replace("<FailureThreshold>3</FailureThreshold>", ""))
+ .when().post("/2013-04-01/healthcheck")
+ .then().statusCode(201)
+ .body("CreateHealthCheckResponse.HealthCheck.Id", equalTo(firstId));
+ } finally {
+ given().when().delete("/2013-04-01/healthcheck/" + firstId).then().statusCode(200);
+ }
+ }
+
@Test
@Order(16)
void createHealthCheck_returns201() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java
index 643d9e48f7..e12de5be20 100644
--- a/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java
@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
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.HealthCheck;
+import io.github.hectorvent.floci.services.route53.model.HealthCheckConfig;
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
import io.github.hectorvent.floci.services.route53.model.VpcAssociation;
@@ -365,4 +367,40 @@ class Route53ServiceTest {
assertFalse(service.isCoveredByPrivateZone("othercorp.internal"));
assertFalse(service.isCoveredByPrivateZone("example.org"));
}
+
+ private static HealthCheckConfig httpsCheck(String path) {
+ HealthCheckConfig cfg = new HealthCheckConfig();
+ cfg.setType("HTTPS");
+ cfg.setFullyQualifiedDomainName("example.com");
+ cfg.setPort(443);
+ cfg.setResourcePath(path);
+ cfg.setRequestInterval(30);
+ cfg.setFailureThreshold(3);
+ return cfg;
+ }
+
+ // Catches: an SDK retry of CreateHealthCheck (same caller reference, same settings) refused with
+ // HealthCheckAlreadyExists, which fails a Terraform or OpenTofu apply.
+ @Test
+ void createHealthCheck_retryWithSameReferenceAndSettings_returnsTheExistingHealthCheck() {
+ Route53Service service = newService();
+ HealthCheck first = service.createHealthCheck("tf-ref-1", httpsCheck("/health"), "ResourcePath=/health");
+
+ HealthCheck retried = service.createHealthCheck("tf-ref-1", httpsCheck("/health"), "ResourcePath=/health");
+
+ assertEquals(first.getId(), retried.getId());
+ assertThat(service.listHealthChecks(null, 0), hasSize(1));
+ }
+
+ @Test
+ void createHealthCheck_sameReferenceWithDifferentSettings_isHealthCheckAlreadyExists() {
+ Route53Service service = newService();
+ service.createHealthCheck("tf-ref-2", httpsCheck("/health"), "ResourcePath=/health");
+
+ AwsException e = assertThrows(AwsException.class,
+ () -> service.createHealthCheck("tf-ref-2", httpsCheck("/other"), "ResourcePath=/other"));
+
+ assertEquals("HealthCheckAlreadyExists", e.getErrorCode());
+ assertEquals(409, e.getHttpStatus());
+ }
}