Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(apigateway): persist UpdateStage methodSettings patch operations on v1 stages (#1004)

Ben Younes214d404733e2
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
index 21476ee39a..9a95b222a7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
@@ -1577,6 +1577,25 @@ public class ApiGatewayController {
ObjectNode vars = node.putObject("variables");
s.getVariables().forEach(vars::put);
}
+ if (!s.getMethodSettings().isEmpty()) {
+ ObjectNode methodSettings = node.putObject("methodSettings");
+ s.getMethodSettings().forEach((key, setting) -> methodSettings.set(key, toMethodSettingNode(setting)));
+ }
+ return node;
+ }
+
+ private ObjectNode toMethodSettingNode(io.github.hectorvent.floci.services.apigateway.model.MethodSetting setting) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("metricsEnabled", setting.isMetricsEnabled());
+ node.put("loggingLevel", setting.getLoggingLevel());
+ node.put("dataTraceEnabled", setting.isDataTraceEnabled());
+ node.put("throttlingBurstLimit", setting.getThrottlingBurstLimit());
+ node.put("throttlingRateLimit", setting.getThrottlingRateLimit());
+ node.put("cachingEnabled", setting.isCachingEnabled());
+ node.put("cacheTtlInSeconds", setting.getCacheTtlInSeconds());
+ node.put("cacheDataEncrypted", setting.isCacheDataEncrypted());
+ node.put("requireAuthorizationForCacheControl", setting.isRequireAuthorizationForCacheControl());
+ node.put("unauthorizedCacheControlHeaderStrategy", setting.getUnauthorizedCacheControlHeaderStrategy());
return node;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index 23fe8602c4..11678c0e76 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
+import io.github.hectorvent.floci.services.apigateway.model.MethodSetting;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
import io.github.hectorvent.floci.services.apigateway.model.Integration;
@@ -469,6 +470,8 @@ public class ApiGatewayService {
String varKey = path.substring("/variables/" .length());
LOG.infov("Setting stage variable {0} = {1}", varKey, value);
stage.getVariables().put(varKey, value);
+ } else {
+ applyMethodSettingPatch(stage, path, value);
}
}
}
@@ -477,6 +480,64 @@ public class ApiGatewayService {
return stage;
}
+ private static final List<String> METHOD_SETTING_KEYS = List.of(
+ "metrics/enabled",
+ "logging/loglevel",
+ "logging/dataTrace",
+ "throttling/burstLimit",
+ "throttling/rateLimit",
+ "caching/enabled",
+ "caching/ttlInSeconds",
+ "caching/dataEncrypted",
+ "caching/requireAuthorizationForCacheControl",
+ "caching/unauthorizedCacheControlHeaderStrategy"
+ );
+
+ /**
+ * Applies a method-settings patch operation in the form
+ * <code>/{resourcePath}/{httpMethod}/{settingKey}</code>, e.g.
+ * <code>/*&#47;*&#47;metrics/enabled</code> or
+ * <code>/pets/GET/throttling/burstLimit</code>. Unknown setting keys are
+ * silently ignored to match real API Gateway's lenient PATCH semantics.
+ */
+ private void applyMethodSettingPatch(Stage stage, String path, String value) {
+ for (String settingKey : METHOD_SETTING_KEYS) {
+ String suffix = "/" + settingKey;
+ if (!path.endsWith(suffix)) continue;
+
+ String prefix = path.substring(1, path.length() - suffix.length());
+ int lastSlash = prefix.lastIndexOf('/');
+ if (lastSlash < 0) return;
+ String resourcePath = prefix.substring(0, lastSlash);
+ String httpMethod = prefix.substring(lastSlash + 1);
+ String methodKey = resourcePath + "/" + httpMethod;
+
+ MethodSetting setting = stage.getMethodSettings()
+ .computeIfAbsent(methodKey, k -> new MethodSetting());
+ applyMethodSettingValue(setting, settingKey, value);
+ return;
+ }
+ }
+
+ private void applyMethodSettingValue(MethodSetting setting, String settingKey, String value) {
+ if (value == null) return;
+ switch (settingKey) {
+ case "metrics/enabled" -> setting.setMetricsEnabled(Boolean.parseBoolean(value));
+ case "logging/loglevel" -> setting.setLoggingLevel(value);
+ case "logging/dataTrace" -> setting.setDataTraceEnabled(Boolean.parseBoolean(value));
+ case "throttling/burstLimit" -> setting.setThrottlingBurstLimit(Integer.parseInt(value));
+ case "throttling/rateLimit" -> setting.setThrottlingRateLimit(Double.parseDouble(value));
+ case "caching/enabled" -> setting.setCachingEnabled(Boolean.parseBoolean(value));
+ case "caching/ttlInSeconds" -> setting.setCacheTtlInSeconds(Integer.parseInt(value));
+ case "caching/dataEncrypted" -> setting.setCacheDataEncrypted(Boolean.parseBoolean(value));
+ case "caching/requireAuthorizationForCacheControl" ->
+ setting.setRequireAuthorizationForCacheControl(Boolean.parseBoolean(value));
+ case "caching/unauthorizedCacheControlHeaderStrategy" ->
+ setting.setUnauthorizedCacheControlHeaderStrategy(value);
+ default -> { /* unreachable: caller pre-filters by METHOD_SETTING_KEYS */ }
+ }
+ }
+
public void deleteStage(String region, String apiId, String stageName) {
getStage(region, apiId, stageName);
stageStore.delete(stageKey(region, apiId, stageName));
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodSetting.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodSetting.java
new file mode 100644
index 0000000000..c17b6bd696
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodSetting.java
@@ -0,0 +1,63 @@
+package io.github.hectorvent.floci.services.apigateway.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * Per-method settings on an API Gateway v1 Stage, addressed by the
+ * <code>{resourcePath}/{httpMethod}</code> key in
+ * {@link Stage#getMethodSettings()}.
+ *
+ * <p>Mirrors the fields documented at
+ * <a href="https://docs.aws.amazon.com/apigateway/latest/api/API_MethodSetting.html">AWS
+ * MethodSetting</a>; the defaults match the values real API Gateway returns
+ * when the method has never been configured (throttling limits {@code -1}
+ * mean "no override").
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class MethodSetting {
+
+ private static final int UNSET_THROTTLING_BURST_LIMIT = -1;
+ private static final double UNSET_THROTTLING_RATE_LIMIT = -1.0d;
+ private static final int UNSET_CACHE_TTL_SECONDS = 0;
+
+ private boolean metricsEnabled;
+ private String loggingLevel = "OFF";
+ private boolean dataTraceEnabled;
+ private int throttlingBurstLimit = UNSET_THROTTLING_BURST_LIMIT;
+ private double throttlingRateLimit = UNSET_THROTTLING_RATE_LIMIT;
+ private boolean cachingEnabled;
+ private int cacheTtlInSeconds = UNSET_CACHE_TTL_SECONDS;
+ private boolean cacheDataEncrypted;
+ private boolean requireAuthorizationForCacheControl;
+ private String unauthorizedCacheControlHeaderStrategy = "SUCCEED_WITH_RESPONSE_HEADER";
+
+ public boolean isMetricsEnabled() { return metricsEnabled; }
+ public void setMetricsEnabled(boolean v) { this.metricsEnabled = v; }
+
+ public String getLoggingLevel() { return loggingLevel; }
+ public void setLoggingLevel(String v) { this.loggingLevel = v; }
+
+ public boolean isDataTraceEnabled() { return dataTraceEnabled; }
+ public void setDataTraceEnabled(boolean v) { this.dataTraceEnabled = v; }
+
+ public int getThrottlingBurstLimit() { return throttlingBurstLimit; }
+ public void setThrottlingBurstLimit(int v) { this.throttlingBurstLimit = v; }
+
+ public double getThrottlingRateLimit() { return throttlingRateLimit; }
+ public void setThrottlingRateLimit(double v) { this.throttlingRateLimit = v; }
+
+ public boolean isCachingEnabled() { return cachingEnabled; }
+ public void setCachingEnabled(boolean v) { this.cachingEnabled = v; }
+
+ public int getCacheTtlInSeconds() { return cacheTtlInSeconds; }
+ public void setCacheTtlInSeconds(int v) { this.cacheTtlInSeconds = v; }
+
+ public boolean isCacheDataEncrypted() { return cacheDataEncrypted; }
+ public void setCacheDataEncrypted(boolean v) { this.cacheDataEncrypted = v; }
+
+ public boolean isRequireAuthorizationForCacheControl() { return requireAuthorizationForCacheControl; }
+ public void setRequireAuthorizationForCacheControl(boolean v) { this.requireAuthorizationForCacheControl = v; }
+
+ public String getUnauthorizedCacheControlHeaderStrategy() { return unauthorizedCacheControlHeaderStrategy; }
+ public void setUnauthorizedCacheControlHeaderStrategy(String v) { this.unauthorizedCacheControlHeaderStrategy = v; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Stage.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Stage.java
index e4580654ac..9cce96c04a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Stage.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Stage.java
@@ -12,6 +12,7 @@ public class Stage {
private String deploymentId;
private String description;
private Map<String, String> variables = new HashMap<>();
+ private Map<String, MethodSetting> methodSettings = new HashMap<>();
private long createdDate;
private long lastUpdatedDate;
@@ -47,6 +48,14 @@ public class Stage {
this.variables = variables != null ? variables : new HashMap<>();
}
+ public Map<String, MethodSetting> getMethodSettings() {
+ return methodSettings;
+ }
+
+ public void setMethodSettings(Map<String, MethodSetting> methodSettings) {
+ this.methodSettings = methodSettings != null ? methodSettings : new HashMap<>();
+ }
+
public long getCreatedDate() {
return createdDate;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayStageMethodSettingsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayStageMethodSettingsIntegrationTest.java
new file mode 100644
index 0000000000..9c37d8bd99
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayStageMethodSettingsIntegrationTest.java
@@ -0,0 +1,170 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * UpdateStage method-settings patch operations (e.g. <code>/*&#47;*&#47;metrics/enabled</code>,
+ * <code>/*&#47;*&#47;logging/loglevel</code>, <code>/*&#47;*&#47;throttling/burstLimit</code>)
+ * must persist on the stage and round-trip through GetStage as the
+ * <code>methodSettings</code> map. This is what the Terraform AWS provider's
+ * <code>aws_api_gateway_method_settings</code> resource requires.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewayStageMethodSettingsIntegrationTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String STAGE_NAME = "test";
+ private static final String WILDCARD_KEY = "*/*";
+
+ private static String apiId;
+ private static String deploymentId;
+
+ @Test
+ @Order(0)
+ void setup_createRestApi() {
+ apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"methodSettings-test-api\"}")
+ .when().post("/restapis")
+ .then().statusCode(201)
+ .extract().path("id");
+ assertNotNull(apiId);
+ }
+
+ @Test
+ @Order(1)
+ void setup_createDeploymentAndStage() {
+ deploymentId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"description\":\"initial\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"" + STAGE_NAME + "\",\"deploymentId\":\"" + deploymentId + "\"}")
+ .when().post("/restapis/" + apiId + "/stages")
+ .then().statusCode(201);
+ }
+
+ @Test
+ @Order(2)
+ void updateStage_methodSettingsPatchOperations_persistOnGetStage() throws Exception {
+ String patchBody = """
+ {
+ "patchOperations": [
+ {"op":"replace","path":"/*/*/metrics/enabled","value":"true"},
+ {"op":"replace","path":"/*/*/logging/loglevel","value":"ERROR"},
+ {"op":"replace","path":"/*/*/logging/dataTrace","value":"true"},
+ {"op":"replace","path":"/*/*/throttling/burstLimit","value":"5000"},
+ {"op":"replace","path":"/*/*/throttling/rateLimit","value":"10000.0"}
+ ]
+ }
+ """;
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(patchBody)
+ .when().patch("/restapis/" + apiId + "/stages/" + STAGE_NAME)
+ .then().statusCode(200);
+
+ String response = given()
+ .when().get("/restapis/" + apiId + "/stages/" + STAGE_NAME)
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode stage = MAPPER.readTree(response);
+ JsonNode methodSettings = stage.path("methodSettings");
+ assertTrue(methodSettings.isObject() && methodSettings.has(WILDCARD_KEY),
+ "GetStage response must include methodSettings[\"" + WILDCARD_KEY + "\"], got: " + response);
+
+ JsonNode wildcard = methodSettings.path(WILDCARD_KEY);
+ assertEquals(true, wildcard.path("metricsEnabled").asBoolean(),
+ "metricsEnabled must persist as true");
+ assertEquals("ERROR", wildcard.path("loggingLevel").asText(),
+ "loggingLevel must persist as ERROR");
+ assertEquals(true, wildcard.path("dataTraceEnabled").asBoolean(),
+ "dataTraceEnabled must persist as true");
+ assertEquals(5000, wildcard.path("throttlingBurstLimit").asInt(),
+ "throttlingBurstLimit must persist as 5000");
+ assertEquals(10000.0, wildcard.path("throttlingRateLimit").asDouble(), 0.0001,
+ "throttlingRateLimit must persist as 10000.0");
+ }
+
+ @Test
+ @Order(3)
+ void updateStage_methodSettingsCachingPatchOperations_persist() throws Exception {
+ String patchBody = """
+ {
+ "patchOperations": [
+ {"op":"replace","path":"/*/*/caching/enabled","value":"true"},
+ {"op":"replace","path":"/*/*/caching/ttlInSeconds","value":"300"},
+ {"op":"replace","path":"/*/*/caching/dataEncrypted","value":"false"}
+ ]
+ }
+ """;
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(patchBody)
+ .when().patch("/restapis/" + apiId + "/stages/" + STAGE_NAME)
+ .then().statusCode(200);
+
+ String response = given()
+ .when().get("/restapis/" + apiId + "/stages/" + STAGE_NAME)
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode wildcard = MAPPER.readTree(response).path("methodSettings").path(WILDCARD_KEY);
+ assertEquals(true, wildcard.path("cachingEnabled").asBoolean(),
+ "cachingEnabled must persist as true");
+ assertEquals(300, wildcard.path("cacheTtlInSeconds").asInt(),
+ "cacheTtlInSeconds must persist as 300");
+ assertEquals(false, wildcard.path("cacheDataEncrypted").asBoolean(),
+ "cacheDataEncrypted must persist as false");
+ }
+
+ @Test
+ @Order(4)
+ void updateStage_perMethodPatchOperations_keyedByResourcePathAndMethod() throws Exception {
+ String patchBody = """
+ {
+ "patchOperations": [
+ {"op":"replace","path":"/pets/GET/metrics/enabled","value":"true"},
+ {"op":"replace","path":"/pets/GET/throttling/burstLimit","value":"42"}
+ ]
+ }
+ """;
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(patchBody)
+ .when().patch("/restapis/" + apiId + "/stages/" + STAGE_NAME)
+ .then().statusCode(200);
+
+ String response = given()
+ .when().get("/restapis/" + apiId + "/stages/" + STAGE_NAME)
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode petsGet = MAPPER.readTree(response).path("methodSettings").path("pets/GET");
+ assertTrue(petsGet.isObject(),
+ "GetStage response must include methodSettings[\"pets/GET\"], got: " + response);
+ assertEquals(true, petsGet.path("metricsEnabled").asBoolean());
+ assertEquals(42, petsGet.path("throttlingBurstLimit").asInt());
+ }
+}