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

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

CreateHealthCheck refused any CallerReference already in use with
HealthCheckAlreadyExists. AWS treats the same reference with the same
settings as a retry and returns the health check it already created;
only different settings are refused. The Go SDK resends the same input
after a transient failure, so a Terraform or OpenTofu apply failed on
Floci where it succeeds on AWS. A matching retry now returns the
existing health check, and the docs note that a deleted health check's
reference is reusable at once here, while AWS keeps refusing it.

* fix(route53): compare a CreateHealthCheck retry on every setting it sends

The retry check compared only the seven HealthCheckConfig fields Floci
models, so two requests that differed in an unmodelled setting such as
EnableSNI passed as a retry, and a retry stating RequestInterval or
FailureThreshold at its default was refused as different from one that
omitted it. The controller now records the request's settings in a
canonical form, every value under HealthCheckConfig sorted (Regions and
ChildHealthChecks are sets), with an omitted RequestInterval or
FailureThreshold counted as AWS's default of 30 or 3 except for
RECOVERY_CONTROL, and a retry must match it. A non-numeric Port,
RequestInterval or FailureThreshold is now InvalidInput instead of being
dropped.

* refactor(route53): read the health check settings with XmlParser.extractElementTree
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-08 11:39:52 -04:00
1 parent 4927f71ce1
commit 0d4b8cda74
7 files changed
+249 -16

No files matched your search

+1
View File
@@ -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`.
@@ -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,23 +1107,65 @@ 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) {}
}
String ftStr = XmlParser.extractFirst(body, "FailureThreshold", null);
if (ftStr != null) {
try { cfg.setFailureThreshold(Integer.parseInt(ftStr)); } 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;
}
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);
}
}
/**
* Parses Key elements that appear inside a RemoveTagKeys block only.
* Uses StAX to avoid matching Key elements from AddTags.
@@ -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;
}
@@ -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; }
}
@@ -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());
}
}
@@ -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() {
@@ -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());
}
}