Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(apigateway): return stored method, policy, and stage settings (#3857)

Attila Kis004d562f3483
diff --git a/compatibility-tests/compat-terraform/test/apigateway-rest-readback-tf/main.tf b/compatibility-tests/compat-terraform/test/apigateway-rest-readback-tf/main.tf
new file mode 100644
index 0000000000..2adf0f93f0
--- /dev/null
+++ b/compatibility-tests/compat-terraform/test/apigateway-rest-readback-tf/main.tf
@@ -0,0 +1,104 @@
+# Verifies that a REST API gateway converges: a second plan reports no changes.
+#
+# GetMethod dropped requestParameters, GetRestApi dropped policy, and GetStage dropped
+# accessLogSettings, tracingEnabled and tags. Terraform planned the same three in-place
+# updates on every run, and because the deployment's redeployment trigger hashes the
+# method, the re-apply failed with "Provider produced inconsistent final plan".
+
+variable "extra_request_parameter" {
+ type = bool
+ default = false
+}
+
+variable "stage_env" {
+ type = string
+ default = "local"
+}
+
+resource "aws_api_gateway_rest_api" "api" {
+ name = "floci-apigw-rest-readback"
+}
+
+resource "aws_api_gateway_resource" "proxy" {
+ rest_api_id = aws_api_gateway_rest_api.api.id
+ parent_id = aws_api_gateway_rest_api.api.root_resource_id
+ path_part = "{proxy+}"
+}
+
+resource "aws_api_gateway_method" "proxy" {
+ rest_api_id = aws_api_gateway_rest_api.api.id
+ resource_id = aws_api_gateway_resource.proxy.id
+ http_method = "ANY"
+ authorization = "NONE"
+
+ request_parameters = merge(
+ { "method.request.path.proxy" = true },
+ var.extra_request_parameter ? { "method.request.header.X-Tenant" = false } : {},
+ )
+}
+
+resource "aws_api_gateway_integration" "proxy" {
+ rest_api_id = aws_api_gateway_rest_api.api.id
+ resource_id = aws_api_gateway_resource.proxy.id
+ http_method = aws_api_gateway_method.proxy.http_method
+ type = "MOCK"
+
+ request_templates = {
+ "application/json" = "{\"statusCode\": 200}"
+ }
+}
+
+resource "aws_api_gateway_rest_api_policy" "api" {
+ rest_api_id = aws_api_gateway_rest_api.api.id
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [{
+ Effect = "Allow"
+ Principal = "*"
+ Action = "execute-api:Invoke"
+ Resource = "${aws_api_gateway_rest_api.api.execution_arn}/*"
+ }]
+ })
+}
+
+# The common module pattern from the bug report: the trigger hashes the method, so a
+# method that reads back differently than it was written breaks the apply itself.
+resource "aws_api_gateway_deployment" "api" {
+ rest_api_id = aws_api_gateway_rest_api.api.id
+
+ triggers = {
+ redeployment = sha1(jsonencode([
+ aws_api_gateway_resource.proxy,
+ aws_api_gateway_method.proxy,
+ aws_api_gateway_integration.proxy,
+ ]))
+ }
+
+ lifecycle {
+ create_before_destroy = true
+ }
+}
+
+resource "aws_api_gateway_stage" "local" {
+ rest_api_id = aws_api_gateway_rest_api.api.id
+ deployment_id = aws_api_gateway_deployment.api.id
+ stage_name = "local"
+ xray_tracing_enabled = true
+
+ access_log_settings {
+ destination_arn = "arn:aws:logs:us-east-1:000000000000:log-group:floci-apigw-rest-readback"
+ format = "$context.requestId $context.status"
+ }
+
+ tags = {
+ env = var.stage_env
+ }
+}
+
+output "rest_api_id" {
+ value = aws_api_gateway_rest_api.api.id
+}
+
+output "resource_id" {
+ value = aws_api_gateway_resource.proxy.id
+}
diff --git a/compatibility-tests/compat-terraform/test/apigateway-rest-readback-tf/provider.tf b/compatibility-tests/compat-terraform/test/apigateway-rest-readback-tf/provider.tf
new file mode 100644
index 0000000000..3be9cd3b36
--- /dev/null
+++ b/compatibility-tests/compat-terraform/test/apigateway-rest-readback-tf/provider.tf
@@ -0,0 +1,28 @@
+terraform {
+ required_providers {
+ aws = {
+ source = "hashicorp/aws"
+ version = "~> 6.0"
+ }
+ }
+}
+
+variable "endpoint" {
+ type = string
+ default = "http://localhost:4566"
+}
+
+provider "aws" {
+ region = "us-east-1"
+ access_key = "test"
+ secret_key = "test"
+
+ skip_credentials_validation = true
+ skip_metadata_api_check = true
+ skip_requesting_account_id = true
+ s3_use_path_style = true
+
+ endpoints {
+ apigateway = var.endpoint
+ }
+}
diff --git a/compatibility-tests/compat-terraform/test/apigateway_rest_readback.bats b/compatibility-tests/compat-terraform/test/apigateway_rest_readback.bats
new file mode 100644
index 0000000000..774587134b
--- /dev/null
+++ b/compatibility-tests/compat-terraform/test/apigateway_rest_readback.bats
@@ -0,0 +1,140 @@
+#!/usr/bin/env bats
+# API Gateway REST Read-Back Compatibility Test
+#
+# GetMethod dropped requestParameters, GetRestApi dropped policy, and GetStage dropped
+# accessLogSettings, tracingEnabled and tags. Every write succeeded, but the reads came back
+# without the values, so each plan proposed the same three in-place updates forever. With a
+# deployment trigger that hashes the method, the re-apply failed outright with "Provider
+# produced inconsistent final plan". This verifies the module applies, reads back what it
+# wrote, converges on a re-apply, and survives an in-place method change.
+
+setup_file() {
+ load 'test_helper/common-setup'
+
+ APIGW_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/apigateway-rest-readback-tf" && pwd)"
+ cd "$APIGW_TF_DIR"
+
+ echo "# === API Gateway REST Read-Back Test ===" >&3
+ echo "# Endpoint: $FLOCI_ENDPOINT" >&3
+ echo "# Config: $APIGW_TF_DIR" >&3
+
+ rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true
+
+ echo "# --- terraform init ---" >&3
+ run terraform init -input=false -no-color
+ if [ "$status" -ne 0 ]; then
+ echo "# terraform init failed: $output" >&3
+ return 1
+ fi
+
+ echo "# --- terraform apply ---" >&3
+ run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color
+ if [ "$status" -ne 0 ]; then
+ echo "# terraform apply failed: $output" >&3
+ return 1
+ fi
+}
+
+teardown_file() {
+ load 'test_helper/common-setup'
+
+ APIGW_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/apigateway-rest-readback-tf" && pwd)"
+ cd "$APIGW_TF_DIR"
+
+ terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color || true
+ rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true
+}
+
+setup() {
+ load 'test_helper/common-setup'
+ APIGW_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/apigateway-rest-readback-tf" && pwd)"
+}
+
+@test "API Gateway read-back: GetMethod returns requestParameters" {
+ API_ID=$(terraform -chdir="$APIGW_TF_DIR" output -raw rest_api_id)
+ RESOURCE_ID=$(terraform -chdir="$APIGW_TF_DIR" output -raw resource_id)
+ run aws_cmd apigateway get-method --rest-api-id "$API_ID" --resource-id "$RESOURCE_ID" \
+ --http-method ANY --query 'requestParameters."method.request.path.proxy"' --output text
+ assert_success
+ assert_output "True"
+}
+
+@test "API Gateway read-back: GetRestApi returns the policy" {
+ API_ID=$(terraform -chdir="$APIGW_TF_DIR" output -raw rest_api_id)
+ run aws_cmd apigateway get-rest-api --rest-api-id "$API_ID" --query policy --output text
+ assert_success
+ assert_output --partial "execute-api:Invoke"
+}
+
+@test "API Gateway read-back: GetStage returns access logs, tracing and tags" {
+ API_ID=$(terraform -chdir="$APIGW_TF_DIR" output -raw rest_api_id)
+ run aws_cmd apigateway get-stage --rest-api-id "$API_ID" --stage-name local \
+ --query '[accessLogSettings.format, tracingEnabled, tags.env]' --output text
+ assert_success
+ assert_output "\$context.requestId \$context.status True local"
+}
+
+# The failure from the bug report: the method read back without requestParameters, so it
+# differed between plan and apply, the deployment trigger hash moved mid-apply, and the
+# re-apply died with "Provider produced inconsistent final plan".
+#
+# The re-apply may still replace the deployment once, whatever the server returns:
+# aws_api_gateway_method's create does not read the method back, so unset collections
+# (request_models, authorization_scopes) stay null in state until the first refresh fills
+# them in as empty, and that moves the trigger hash a single time. The stage then follows the
+# new deployment id, so only the method and the policy must stay untouched here.
+@test "API Gateway read-back: re-apply succeeds" {
+ cd "$APIGW_TF_DIR"
+ run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color
+ assert_success
+ refute_output --partial "inconsistent final plan"
+ refute_output --partial "aws_api_gateway_method.proxy: Modifying"
+ refute_output --partial "aws_api_gateway_rest_api_policy.api: Modifying"
+}
+
+# The critical assertion: before the fix every plan proposed the same three updates forever.
+@test "API Gateway read-back: plan after re-apply reports no changes" {
+ cd "$APIGW_TF_DIR"
+ run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode
+ assert_success
+ assert_output --partial "No changes"
+}
+
+# Changing a method request parameter goes through UpdateMethod patch operations and changes
+# the deployment trigger hash. This is where "inconsistent final plan" used to surface.
+@test "API Gateway read-back: changing a request parameter applies and re-plans clean" {
+ cd "$APIGW_TF_DIR"
+ run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -var="extra_request_parameter=true" \
+ -input=false -auto-approve -no-color
+ assert_success
+ refute_output --partial "inconsistent final plan"
+
+ run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -var="extra_request_parameter=true" \
+ -input=false -no-color -detailed-exitcode
+ assert_success
+ assert_output --partial "No changes"
+}
+
+# Stage tag changes go through TagResource on the stage ARN, which used to tag the REST API
+# instead, so the stage never showed the new value and the plan never settled.
+@test "API Gateway read-back: changing a stage tag lands on the stage and re-plans clean" {
+ cd "$APIGW_TF_DIR"
+ run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -var="extra_request_parameter=true" \
+ -var="stage_env=staging" -input=false -auto-approve -no-color
+ assert_success
+
+ API_ID=$(terraform -chdir="$APIGW_TF_DIR" output -raw rest_api_id)
+ run aws_cmd apigateway get-stage --rest-api-id "$API_ID" --stage-name local \
+ --query 'tags.env' --output text
+ assert_success
+ assert_output "staging"
+
+ run aws_cmd apigateway get-rest-api --rest-api-id "$API_ID" --query 'tags' --output text
+ assert_success
+ assert_output "None"
+
+ run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -var="extra_request_parameter=true" \
+ -var="stage_env=staging" -input=false -no-color -detailed-exitcode
+ assert_success
+ assert_output --partial "No changes"
+}
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 6915347fb0..5b2a82f0f7 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
@@ -10,6 +10,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
+import com.fasterxml.jackson.core.io.JsonStringEncoder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -2145,9 +2146,21 @@ public class ApiGatewayController {
node.put("apiKeySource", "HEADER");
node.put("disableExecuteApiEndpoint", false);
+ // AWS returns the policy JSON-escaped inside the string ({\"Version\":...}), and the
+ // Terraform provider unquotes it on read, so a raw document here would fail to parse.
+ if (api.getPolicy() != null) {
+ node.put("policy", escapePolicy(api.getPolicy()));
+ }
+
return node;
}
+ // Full JSON string escaping, not just quotes: a pretty-printed policy carries newlines, and
+ // those must be escaped too or the provider's quote-and-unquote step fails to parse it.
+ private static String escapePolicy(String policy) {
+ return new String(JsonStringEncoder.getInstance().quoteAsString(policy));
+ }
+
private ObjectNode toResourceNode(ApiGatewayResource r) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", r.getId());
@@ -2164,6 +2177,10 @@ public class ApiGatewayController {
node.put("apiKeyRequired", m.isApiKeyRequired());
if (m.getAuthorizerId() != null) node.put("authorizerId", m.getAuthorizerId());
if (m.getRequestValidatorId() != null) node.put("requestValidatorId", m.getRequestValidatorId());
+ if (m.getRequestParameters() != null && !m.getRequestParameters().isEmpty()) {
+ ObjectNode params = node.putObject("requestParameters");
+ m.getRequestParameters().forEach(params::put);
+ }
if (m.getRequestModels() != null && !m.getRequestModels().isEmpty()) {
ObjectNode models = objectMapper.createObjectNode();
m.getRequestModels().forEach(models::put);
@@ -2252,6 +2269,20 @@ public class ApiGatewayController {
node.put("cacheClusterEnabled", s.isCacheClusterEnabled());
node.put("cacheClusterStatus", s.getCacheClusterStatus());
if (s.getCacheClusterSize() != null) node.put("cacheClusterSize", s.getCacheClusterSize());
+ node.put("tracingEnabled", s.isTracingEnabled());
+ if (s.getAccessLogSettings() != null) {
+ ObjectNode logs = node.putObject("accessLogSettings");
+ if (s.getAccessLogSettings().destinationArn() != null) {
+ logs.put("destinationArn", s.getAccessLogSettings().destinationArn());
+ }
+ if (s.getAccessLogSettings().format() != null) {
+ logs.put("format", s.getAccessLogSettings().format());
+ }
+ }
+ if (!s.getTags().isEmpty()) {
+ ObjectNode tags = node.putObject("tags");
+ s.getTags().forEach(tags::put);
+ }
if (!s.getVariables().isEmpty()) {
ObjectNode vars = node.putObject("variables");
s.getVariables().forEach(vars::put);
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 d8e4a6dbe1..c42dea6375 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
@@ -232,6 +232,9 @@ public class ApiGatewayService {
api.setBinaryMediaTypes(binaryTypes.stream()
.filter(String.class::isInstance).map(String.class::cast).toList());
}
+ if (request.get("policy") instanceof String policy && !policy.isEmpty()) {
+ api.setPolicy(policy);
+ }
EndpointConfiguration endpointConfiguration = new EndpointConfiguration();
if (request.get(EPC_KEY) instanceof Map<?, ?> epMap) {
@@ -775,6 +778,18 @@ public class ApiGatewayService {
stage.setCacheClusterSize((String) request.getOrDefault("cacheClusterSize", "0.5"));
}
+ stage.setTracingEnabled(Boolean.TRUE.equals(request.get("tracingEnabled")));
+ if (request.get("tags") instanceof Map<?, ?> tags) {
+ tags.forEach((k, v) -> {
+ if (k instanceof String key && v instanceof String val) stage.getTags().put(key, val);
+ });
+ }
+ if (request.get("accessLogSettings") instanceof Map<?, ?> logs) {
+ stage.setAccessLogSettings(new Stage.AccessLogSettings(
+ logs.get("destinationArn") instanceof String arn ? arn : null,
+ logs.get("format") instanceof String format ? format : null));
+ }
+
stageStore.put(stageKey(region, apiId, stageName), stage);
LOG.infov("Created stage {0} for API {1}", stageName, apiId);
return stage;
@@ -803,12 +818,24 @@ public class ApiGatewayService {
String value = op.get("value");
LOG.infov("Patch operation: op={0}, path={1}, value={2}", opType, path, value);
+ if ("remove" .equals(opType) && "/accessLogSettings" .equals(path)) {
+ stage.setAccessLogSettings(null);
+ continue;
+ }
if (!"replace" .equals(opType) && !"add" .equals(opType)) continue;
if ("/description" .equals(path)) {
stage.setDescription(value);
} else if ("/deploymentId" .equals(path)) {
stage.setDeploymentId(value);
+ } else if ("/tracingEnabled" .equals(path)) {
+ stage.setTracingEnabled(Boolean.parseBoolean(value));
+ } else if ("/accessLogSettings/destinationArn" .equals(path)) {
+ Stage.AccessLogSettings logs = stage.getAccessLogSettings();
+ stage.setAccessLogSettings(new Stage.AccessLogSettings(value, logs != null ? logs.format() : null));
+ } else if ("/accessLogSettings/format" .equals(path)) {
+ Stage.AccessLogSettings logs = stage.getAccessLogSettings();
+ stage.setAccessLogSettings(new Stage.AccessLogSettings(logs != null ? logs.destinationArn() : null, value));
} else if (path.startsWith("/variables/")) {
String varKey = path.substring("/variables/" .length());
LOG.infov("Setting stage variable {0} = {1}", varKey, value);
@@ -2264,6 +2291,9 @@ public class ApiGatewayService {
String value = op.get("value");
if ("/name" .equals(path)) api.setName(value);
else if ("/description" .equals(path)) api.setDescription(value);
+ // aws_api_gateway_rest_api_policy writes the policy this way, and clears it by
+ // replacing it with an empty string.
+ else if ("/policy" .equals(path)) api.setPolicy(value == null || value.isEmpty() ? null : value);
}
}
apiStore.put(apiKey(region, apiId), api);
@@ -2418,14 +2448,44 @@ public class ApiGatewayService {
throw new AwsException("BadRequestException", "Invalid boolean value '" + value + "' for apiKeyRequired. Must be 'true' or 'false'", 400);
}
}
+ // Checked here, before anything is applied: the method is the live stored object,
+ // so a failure halfway through the apply loop would leave earlier ops in place.
+ if (path.startsWith("/requestParameters/") && ("add".equals(opType) || "replace".equals(opType))) {
+ validateRequestParameterNames(
+ Map.of(unescapeJsonPointer(path.substring("/requestParameters/".length())), Boolean.TRUE));
+ }
}
for (Map<String, String> op : patchOperations) {
- if (!"replace".equals(op.get("op"))) continue;
+ String opType = op.get("op");
String path = op.getOrDefault("path", "");
String value = op.get("value");
+ // Terraform patches request parameters and models one entry at a time with
+ // add/replace/remove, so those maps are handled before the replace-only members.
+ if (path.startsWith("/requestParameters/")) {
+ String name = unescapeJsonPointer(path.substring("/requestParameters/".length()));
+ if ("remove".equals(opType)) {
+ method.getRequestParameters().remove(name);
+ } else if ("add".equals(opType) || "replace".equals(opType)) {
+ method.getRequestParameters().put(name, Boolean.parseBoolean(value));
+ }
+ continue;
+ }
+ if (path.startsWith("/requestModels/")) {
+ String contentType = unescapeJsonPointer(path.substring("/requestModels/".length()));
+ if ("remove".equals(opType)) {
+ method.getRequestModels().remove(contentType);
+ } else if (("add".equals(opType) || "replace".equals(opType)) && value != null) {
+ method.getRequestModels().put(contentType, value);
+ }
+ continue;
+ }
+ if (!"replace".equals(opType)) continue;
if ("/authorizationType".equals(path)) method.setAuthorizationType(value);
else if ("/authorizerId".equals(path)) method.setAuthorizerId(value);
else if ("/apiKeyRequired".equals(path)) method.setApiKeyRequired(Boolean.parseBoolean(value));
+ else if ("/requestValidatorId".equals(path)) {
+ method.setRequestValidatorId(value == null || value.isEmpty() ? null : value);
+ }
}
}
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
@@ -2499,6 +2559,22 @@ public class ApiGatewayService {
apiStore.put(apiKey(region, apiId), api);
}
+ public Map<String, String> getStageTags(String region, String apiId, String stageName) {
+ return getStage(region, apiId, stageName).getTags();
+ }
+
+ public void tagStage(String region, String apiId, String stageName, Map<String, String> tags) {
+ Stage stage = getStage(region, apiId, stageName);
+ stage.getTags().putAll(tags);
+ stageStore.put(stageKey(region, apiId, stageName), stage);
+ }
+
+ public void untagStage(String region, String apiId, String stageName, List<String> tagKeys) {
+ Stage stage = getStage(region, apiId, stageName);
+ tagKeys.forEach(stage.getTags()::remove);
+ stageStore.put(stageKey(region, apiId, stageName), stage);
+ }
+
public Map<String, String> getDomainNameTags(String region, String domainName) {
synchronized (domainNameLock) {
Map<String, String> tags = getDomainName(region, domainName).getTags();
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java
index 452817d81d..2c2a0e0b1c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java
@@ -20,6 +20,7 @@ import java.util.Map;
public class ApiGatewayTagHandler implements TagHandler {
private static final String DOMAIN_NAMES = "/domainnames/";
+ private static final String STAGES = "/stages/";
private final ApiGatewayService service;
@@ -41,16 +42,23 @@ public class ApiGatewayTagHandler implements TagHandler {
@Override
public Map<String, String> listTags(String region, String arn) {
String domainName = domainNameFromArn(arn);
- return domainName != null
- ? service.getDomainNameTags(region, domainName)
+ if (domainName != null) {
+ return service.getDomainNameTags(region, domainName);
+ }
+ String stageName = stageNameFromArn(arn);
+ return stageName != null
+ ? service.getStageTags(region, apiIdFromArn(arn), stageName)
: service.getTags(region, apiIdFromArn(arn));
}
@Override
public void tagResource(String region, String arn, Map<String, String> tags) {
String domainName = domainNameFromArn(arn);
+ String stageName = stageNameFromArn(arn);
if (domainName != null) {
service.tagDomainName(region, domainName, tags);
+ } else if (stageName != null) {
+ service.tagStage(region, apiIdFromArn(arn), stageName, tags);
} else {
service.tagResource(region, apiIdFromArn(arn), tags);
}
@@ -59,8 +67,11 @@ public class ApiGatewayTagHandler implements TagHandler {
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
String domainName = domainNameFromArn(arn);
+ String stageName = stageNameFromArn(arn);
if (domainName != null) {
service.untagDomainName(region, domainName, tagKeys);
+ } else if (stageName != null) {
+ service.untagStage(region, apiIdFromArn(arn), stageName, tagKeys);
} else {
service.untagResource(region, apiIdFromArn(arn), tagKeys);
}
@@ -74,6 +85,19 @@ public class ApiGatewayTagHandler implements TagHandler {
return parts[1].split("/")[0];
}
+ /**
+ * The stage a {@code /restapis/<apiId>/stages/<stageName>} ARN names, or null for any other ARN.
+ * Stages carry their own tags; without this they would land on the REST API.
+ */
+ private static String stageNameFromArn(String arn) {
+ int at = arn.indexOf(STAGES);
+ if (at < 0 || !arn.contains("/restapis/")) {
+ return null;
+ }
+ String stageName = arn.substring(at + STAGES.length());
+ return stageName.isEmpty() || stageName.contains("/") ? null : stageName;
+ }
+
/**
* The domain a {@code /domainnames/<name>} ARN names, or null for any other ARN. A base path
* mapping ARN continues past the domain and is not taggable, so it falls through to the REST API
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java
index b22c250395..e680df8e57 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java
@@ -22,6 +22,16 @@ public class RestApi {
private EndpointConfiguration endpointConfiguration;
/** Content types treated as binary when applying integration contentHandling. */
private List<String> binaryMediaTypes = new ArrayList<>();
+ /** Resource policy document, stored exactly as the caller sent it. */
+ private String policy;
+
+ public String getPolicy() {
+ return policy;
+ }
+
+ public void setPolicy(String policy) {
+ this.policy = policy;
+ }
public List<String> getBinaryMediaTypes() {
return binaryMediaTypes;
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 550432f84e..d4a7d058c2 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
@@ -20,6 +20,36 @@ public class Stage {
private boolean cacheClusterEnabled;
private String cacheClusterSize;
private String cacheClusterStatus = "NOT_AVAILABLE";
+ private AccessLogSettings accessLogSettings;
+ private boolean tracingEnabled;
+ private Map<String, String> tags = new HashMap<>();
+
+ @RegisterForReflection
+ public record AccessLogSettings(String destinationArn, String format) {}
+
+ public AccessLogSettings getAccessLogSettings() {
+ return accessLogSettings;
+ }
+
+ public void setAccessLogSettings(AccessLogSettings accessLogSettings) {
+ this.accessLogSettings = accessLogSettings;
+ }
+
+ public boolean isTracingEnabled() {
+ return tracingEnabled;
+ }
+
+ public void setTracingEnabled(boolean tracingEnabled) {
+ this.tracingEnabled = tracingEnabled;
+ }
+
+ public Map<String, String> getTags() {
+ return tags;
+ }
+
+ public void setTags(Map<String, String> tags) {
+ this.tags = tags != null ? tags : new HashMap<>();
+ }
public boolean isCacheClusterEnabled() {
return cacheClusterEnabled;
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayConfigReadBackTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayConfigReadBackTest.java
new file mode 100644
index 0000000000..a6814ff379
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayConfigReadBackTest.java
@@ -0,0 +1,255 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+
+/**
+ * Round-trips method request parameters, the REST API resource policy and the stage's access log,
+ * tracing and tag settings through their getters.
+ *
+ * <p>Each write was accepted but the read came back without the value, so Terraform planned the
+ * same in-place update on every run, and a deployment whose redeployment trigger hashes the method
+ * failed with "Provider produced inconsistent final plan".
+ */
+@QuarkusTest
+class ApiGatewayConfigReadBackTest {
+
+ private static final String POLICY =
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\","
+ + "\"Action\":\"execute-api:Invoke\",\"Resource\":\"*\"}]}";
+
+ private String apiId;
+ private String resourceId;
+
+ @BeforeEach
+ void setup() {
+ apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"config-read-back\"}")
+ .when().post("/restapis")
+ .then().statusCode(201).body("id", notNullValue())
+ .extract().path("id");
+
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+
+ resourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"{proxy+}\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201).extract().path("id");
+ }
+
+ @AfterEach
+ void cleanup() {
+ if (apiId != null) {
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+ }
+
+ private String methodPath() {
+ return "/restapis/" + apiId + "/resources/" + resourceId + "/methods/ANY";
+ }
+
+ private String createStage(String body) {
+ String deploymentId = given().contentType(ContentType.JSON).body("{}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201).extract().path("id");
+ given().contentType(ContentType.JSON)
+ .body(body.replace("DEPLOYMENT", deploymentId))
+ .when().post("/restapis/" + apiId + "/stages")
+ .then().statusCode(201);
+ return "/restapis/" + apiId + "/stages/local";
+ }
+
+ @Test
+ void getMethodReturnsRequestParameters() {
+ given().contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\",\"requestParameters\":{\"method.request.path.proxy\":true}}")
+ .when().put(methodPath())
+ .then().statusCode(201)
+ .body("requestParameters.'method.request.path.proxy'", equalTo(true));
+
+ given().when().get(methodPath())
+ .then().statusCode(200)
+ .body("requestParameters.'method.request.path.proxy'", equalTo(true));
+ }
+
+ @Test
+ void updateMethodPatchesRequestParameters() {
+ given().contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\",\"requestParameters\":{\"method.request.path.proxy\":true}}")
+ .when().put(methodPath())
+ .then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("""
+ {"patchOperations":[
+ {"op":"add","path":"/requestParameters/method.request.header.X-Tenant","value":"false"},
+ {"op":"remove","path":"/requestParameters/method.request.path.proxy"}]}
+ """)
+ .when().patch(methodPath())
+ .then().statusCode(200);
+
+ given().when().get(methodPath())
+ .then().statusCode(200)
+ .body("requestParameters.'method.request.header.X-Tenant'", equalTo(false))
+ .body("requestParameters.'method.request.path.proxy'", nullValue());
+ }
+
+ @Test
+ void rejectedUpdateMethodLeavesRequestParametersUntouched() {
+ given().contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\",\"requestParameters\":{\"method.request.path.proxy\":true}}")
+ .when().put(methodPath())
+ .then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("""
+ {"patchOperations":[
+ {"op":"remove","path":"/requestParameters/method.request.path.proxy"},
+ {"op":"add","path":"/requestParameters/method.request.header.bad name!","value":"true"}]}
+ """)
+ .when().patch(methodPath())
+ .then().statusCode(400);
+
+ given().when().get(methodPath())
+ .then().statusCode(200)
+ .body("requestParameters.'method.request.path.proxy'", equalTo(true));
+ }
+
+ @Test
+ void getRestApiReturnsThePolicyEscapedAsAwsDoes() {
+ given().contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/policy\",\"value\":"
+ + quote(POLICY) + "}]}")
+ .when().patch("/restapis/" + apiId)
+ .then().statusCode(200);
+
+ String policy = given().when().get("/restapis/" + apiId)
+ .then().statusCode(200).extract().path("policy");
+ // AWS escapes the document's quotes inside the string; unescaping gives back the original.
+ assertEquals(POLICY, unquote(policy));
+
+ // A pretty-printed policy must come back with its newlines escaped as well, so that the
+ // escaped form is still a valid JSON string once a client wraps it in quotes.
+ String pretty = POLICY.replace(",", ",\n ");
+ given().contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/policy\",\"value\":"
+ + quote(pretty) + "}]}")
+ .when().patch("/restapis/" + apiId)
+ .then().statusCode(200);
+ String escaped = given().when().get("/restapis/" + apiId)
+ .then().statusCode(200).extract().path("policy");
+ assertFalse(escaped.contains("\n"), "raw newline in escaped policy");
+ assertEquals(pretty, unquote(escaped));
+
+ given().contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/policy\",\"value\":\"\"}]}")
+ .when().patch("/restapis/" + apiId)
+ .then().statusCode(200);
+
+ given().when().get("/restapis/" + apiId)
+ .then().statusCode(200).body("policy", nullValue());
+ }
+
+ @Test
+ void getStageReturnsAccessLogsTracingAndTags() {
+ String stagePath = createStage("""
+ {"stageName":"local","deploymentId":"DEPLOYMENT","tracingEnabled":true,
+ "tags":{"env":"local"}}
+ """);
+
+ given().contentType(ContentType.JSON)
+ .body("""
+ {"patchOperations":[
+ {"op":"replace","path":"/accessLogSettings/destinationArn","value":"arn:aws:logs:us-east-1:000000000000:log-group:api"},
+ {"op":"replace","path":"/accessLogSettings/format","value":"$context.requestId"}]}
+ """)
+ .when().patch(stagePath)
+ .then().statusCode(200);
+
+ given().when().get(stagePath)
+ .then().statusCode(200)
+ .body("accessLogSettings.destinationArn", equalTo("arn:aws:logs:us-east-1:000000000000:log-group:api"))
+ .body("accessLogSettings.format", equalTo("$context.requestId"))
+ .body("tracingEnabled", equalTo(true))
+ .body("tags.env", equalTo("local"));
+
+ given().when().get("/restapis/" + apiId + "/stages")
+ .then().statusCode(200)
+ .body("item[0].accessLogSettings.format", equalTo("$context.requestId"))
+ .body("item[0].tracingEnabled", equalTo(true));
+
+ given().contentType(ContentType.JSON)
+ .body("""
+ {"patchOperations":[
+ {"op":"remove","path":"/accessLogSettings"},
+ {"op":"replace","path":"/tracingEnabled","value":"false"}]}
+ """)
+ .when().patch(stagePath)
+ .then().statusCode(200);
+
+ given().when().get(stagePath)
+ .then().statusCode(200)
+ .body("accessLogSettings", nullValue())
+ .body("tracingEnabled", equalTo(false));
+ }
+
+ @Test
+ void tagResourceOnAStageArnTagsTheStageNotTheApi() {
+ String stagePath = createStage("{\"stageName\":\"local\",\"deploymentId\":\"DEPLOYMENT\"}");
+ String stageArn = "arn:aws:apigateway:us-east-1::/restapis/" + apiId + "/stages/local";
+
+ given().contentType(ContentType.JSON)
+ .body("{\"tags\":{\"team\":\"api\"}}")
+ .pathParam("resourceArn", stageArn)
+ .when().put("/tags/{resourceArn}")
+ .then().statusCode(204);
+
+ given().when().get(stagePath)
+ .then().statusCode(200).body("tags.team", equalTo("api"));
+ given().when().get("/restapis/" + apiId)
+ .then().statusCode(200).body("tags", nullValue());
+ given().pathParam("resourceArn", stageArn)
+ .when().get("/tags/{resourceArn}")
+ .then().statusCode(200).body("tags.team", equalTo("api"));
+
+ given().queryParam("tagKeys", "team")
+ .pathParam("resourceArn", stageArn)
+ .when().delete("/tags/{resourceArn}")
+ .then().statusCode(204);
+
+ given().when().get(stagePath)
+ .then().statusCode(200).body("tags", nullValue());
+ }
+
+ /** Decodes the escaped policy the way the Terraform provider does: wrap in quotes, parse as a JSON string. */
+ private static String unquote(String escaped) {
+ try {
+ return new ObjectMapper().readValue("\"" + escaped + "\"", String.class);
+ } catch (JsonProcessingException e) {
+ throw new AssertionError("escaped policy is not a valid JSON string body: " + escaped, e);
+ }
+ }
+
+ private static String quote(String s) {
+ try {
+ return new ObjectMapper().writeValueAsString(s);
+ } catch (JsonProcessingException e) {
+ throw new AssertionError(e);
+ }
+ }
+}