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 `` 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,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 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 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 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. 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 """ + + ref + %s + + """.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("HTTP10.0.0.1"), + settings("HTTP10.0.0.1" + + "303")); + assertNotEquals(settings("HTTP10.0.0.1"), + settings("HTTP10.0.0.110")); + } + + // Catches: requests that differ only in a setting Floci does not model passing as a retry. + @Test + void settingsFlociDoesNotModelStillCount() { + assertNotEquals(settings("HTTPSexample.com"), + settings("HTTPSexample.com" + + "false")); + } + + @Test + void regionsAreASet() { + assertEquals(settings("HTTPus-east-1eu-west-1"), + settings("HTTPeu-west-1us-east-1")); + } + + @Test + void recoveryControlGetsNoIntervalOrThresholdDefaults() { + assertEquals("RoutingControlArn=arn\nType=RECOVERY_CONTROL", + settings("RECOVERY_CONTROLarn")); + } + + @Test + void malformedXmlIsInvalidInput() { + AwsException e = assertThrows(AwsException.class, + () -> Route53Controller.healthCheckSettings("")); + 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 """ + + + %s + + HTTPS + example.com + 443 + %s + 30 + 3 + + + """.formatted(callerReference, resourcePath); + } + + @Test + @Order(26) + void createHealthCheck_nonNumericFailureThreshold_isInvalidInput() { + given() + .contentType(XML) + .body(healthCheckRequest("hc-bad-" + System.nanoTime(), "/health") + .replace("3", "three")) + .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("3", + "3false")) + .when().post("/2013-04-01/healthcheck") + .then().statusCode(409) + .body("ErrorResponse.Error.Code", equalTo("HealthCheckAlreadyExists")); + + given() + .contentType(XML) + .body(healthCheckRequest(reference, "/health") + .replace("30", "") + .replace("3", "")) + .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()); + } }