fix(apigateway): support integration connection patches (#6645)

* fix(apigateway): support integration connection patches

* test(apigateway): cover connection patches through AWS SDK

* fix(apigateway): accept V2 VPC links in integration patches

* fix(apigateway): resolve V2 VPC links during REST execution

* fix(apigateway): resolve VPC link stage variables at execution

* fix(apigateway): share VPC link stage variable pattern
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-26 17:05:35 -04:00
1 parent 2fd74eaf08
commit 4d0dfe9919
6 files changed
+345 -8

No files matched your search

@@ -784,25 +784,35 @@ public class ApiGatewayExecuteController {
return null;
}
String connectionId = integration.getConnectionId();
if (connectionId != null) {
Matcher stageVariable = ApiGatewayService.VPC_LINK_STAGE_VARIABLE.matcher(connectionId);
if (stageVariable.matches()) {
connectionId = scope.stage().getVariables().get(stageVariable.group(1));
}
}
if (connectionId == null || connectionId.isBlank()) {
return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
"VPC_LINK integration is missing a connectionId");
}
String status;
try {
io.github.hectorvent.floci.services.apigateway.model.VpcLink link =
apiGatewayService.getVpcLink(region, connectionId);
if (!"AVAILABLE".equalsIgnoreCase(link.getStatus())) {
status = apiGatewayService.getVpcLink(region, connectionId).getStatus();
} catch (AwsException e) {
try {
status = apiGatewayV2Service.getVpcLink(region, connectionId).getVpcLinkStatus();
} catch (AwsException ignored) {
LOG.warnv("VPC_LINK integration references unknown link {0} in {1}", connectionId, region);
return Response.status(502)
.entity(jsonMessage("VPC link is not available: " + link.getStatus()))
.entity(jsonMessage("Invalid VPC link identifier specified: " + connectionId))
.type(MediaType.APPLICATION_JSON).build();
}
return null;
} catch (AwsException e) {
LOG.warnv("VPC_LINK integration references unknown link {0} in {1}", connectionId, region);
}
if (!"AVAILABLE".equalsIgnoreCase(status)) {
return Response.status(502)
.entity(jsonMessage("Invalid VPC link identifier specified: " + connectionId))
.entity(jsonMessage("VPC link is not available: " + status))
.type(MediaType.APPLICATION_JSON).build();
}
return null;
}
// ──────────────────────────── Binary payloads ────────────────────────────
@@ -164,6 +164,8 @@ public class ApiGatewayService implements ResourceProvider {
"EDGE endpoint type is not supported for APIGatewayV2 domainName";
/** The characters AWS allows in an API mapping key, its level separator included, and the most it takes. */
private static final Pattern API_MAPPING_KEY = Pattern.compile("[A-Za-z0-9$\\-_.+!*'(),/]+");
static final Pattern VPC_LINK_STAGE_VARIABLE =
Pattern.compile("\\$\\{stageVariables\\.([A-Za-z0-9_]+)\\}");
private static final int MAX_API_MAPPING_KEY_LENGTH = 300;
private static final String MAPPING_KEY_SLASHES_MESSAGE =
"API mapping key should not start with a '/' or have consecutive '/'s.";
@@ -3425,6 +3427,10 @@ public class ApiGatewayService implements ResourceProvider {
if (patchOperations != null) {
String nextType = integration.getType();
String nextTransferMode = integration.getResponseTransferMode();
String nextConnectionType = integration.getConnectionType();
String nextConnectionId = integration.getConnectionId();
boolean connectionPatched = false;
boolean connectionIdPatched = false;
for (Map<String, String> op : patchOperations) {
String opType = op.get("op");
if (!"add".equals(opType) && !"replace".equals(opType)) {
@@ -3449,11 +3455,46 @@ public class ApiGatewayService implements ResourceProvider {
case "/responseTransferMode":
nextTransferMode = transferMode(value);
break;
case "/connectionType":
if (!"replace".equals(opType)) {
throw new AwsException("BadRequestException", "Invalid operation", 400);
}
nextConnectionType = value;
connectionPatched = true;
break;
case "/connectionId":
if (!"replace".equals(opType)) {
throw new AwsException("BadRequestException", "Invalid operation", 400);
}
nextConnectionId = value;
connectionPatched = true;
connectionIdPatched = true;
break;
default:
throw new AwsException("BadRequestException", "Unsupported path: " + path, 400);
}
}
validateTransferMode(nextTransferMode, nextType);
if (connectionPatched) {
if ("VPC_LINK".equals(nextConnectionType)) {
if (nextConnectionId == null || nextConnectionId.isBlank()
|| (!VPC_LINK_STAGE_VARIABLE.matcher(nextConnectionId).matches()
&& vpcLinkStore.get(vpcLinkKey(region, nextConnectionId)).isEmpty()
&& !apiGatewayV2Service.hasVpcLink(region, nextConnectionId))) {
throw new AwsException("BadRequestException",
"Invalid VPC link identifier specified: " + nextConnectionId, 400);
}
} else if ("INTERNET".equals(nextConnectionType)) {
if (connectionIdPatched) {
throw new AwsException("BadRequestException",
"Connection ID requires VPC_LINK", 400);
}
nextConnectionId = null;
} else {
throw new AwsException("BadRequestException",
"Invalid connection type: " + nextConnectionType, 400);
}
}
for (Map<String, String> op : patchOperations) {
String path = op.get("path");
String value = op.get("value");
@@ -3476,10 +3517,17 @@ public class ApiGatewayService implements ResourceProvider {
case "/responseTransferMode":
integration.setResponseTransferMode(transferMode(value));
break;
case "/connectionType":
case "/connectionId":
break;
default:
throw new IllegalStateException("Unreachable: validated above");
}
}
if (connectionPatched) {
integration.setConnectionType(nextConnectionType);
integration.setConnectionId(nextConnectionId);
}
}
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
return integration;
@@ -1178,6 +1178,10 @@ public class ApiGatewayV2Service {
.orElseThrow(() -> new AwsException("NotFoundException", "VpcLink not found", 404));
}
public boolean hasVpcLink(String region, String vpcLinkId) {
return vpcLinkStore.get(vpcLinkKey(region, vpcLinkId)).isPresent();
}
public List<VpcLink> getVpcLinks(String region) {
String prefix = region + "::";
return vpcLinkStore.scan(k -> k.startsWith(prefix));
@@ -0,0 +1,110 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
import software.amazon.awssdk.services.apigateway.model.ConnectionType;
import software.amazon.awssdk.services.apigateway.model.GetIntegrationResponse;
import software.amazon.awssdk.services.apigateway.model.IntegrationType;
import software.amazon.awssdk.services.apigateway.model.PatchOperation;
import software.amazon.awssdk.services.apigateway.model.UpdateIntegrationResponse;
import java.net.URI;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
class ApiGatewayIntegrationConnectionPatchSdkIntegrationTest {
@Inject
ApiGatewayV2Service apiGatewayV2Service;
@TestHTTPResource("/")
URI endpoint;
private ApiGatewayClient client() {
return ApiGatewayClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.httpClientBuilder(Apache5HttpClient.builder())
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.build();
}
@Test
void sdkUpdatesVpcLinkConnectionAndReadsItBack() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("integration-connection-patch-sdk")).id();
try {
String rootId = client.getResources(request -> request.restApiId(apiId)).items().get(0).id();
String resourceId = client.createResource(request -> request.restApiId(apiId)
.parentId(rootId).pathPart("widget")).id();
client.putMethod(request -> request.restApiId(apiId).resourceId(resourceId)
.httpMethod("POST").authorizationType("NONE"));
client.putIntegration(request -> request.restApiId(apiId).resourceId(resourceId)
.httpMethod("POST").type(IntegrationType.HTTP_PROXY).integrationHttpMethod("POST")
.uri("http://example.invalid/widget"));
String linkId = client.createVpcLink(request -> request.name("integration-patch-sdk-link")
.targetArns("arn:aws:elasticloadbalancing:us-east-1:000000000000:"
+ "loadbalancer/net/test/abc")).id();
try {
UpdateIntegrationResponse updated = client.updateIntegration(request -> request
.restApiId(apiId).resourceId(resourceId).httpMethod("POST")
.patchOperations(
PatchOperation.builder().op("replace").path("/connectionType")
.value("VPC_LINK").build(),
PatchOperation.builder().op("replace").path("/connectionId")
.value(linkId).build()));
assertEquals(ConnectionType.VPC_LINK, updated.connectionType());
assertEquals(linkId, updated.connectionId());
GetIntegrationResponse read = client.getIntegration(request -> request
.restApiId(apiId).resourceId(resourceId).httpMethod("POST"));
assertEquals(ConnectionType.VPC_LINK, read.connectionType());
assertEquals(linkId, read.connectionId());
UpdateIntegrationResponse internet = client.updateIntegration(request -> request
.restApiId(apiId).resourceId(resourceId).httpMethod("POST")
.patchOperations(PatchOperation.builder().op("replace")
.path("/connectionType").value("INTERNET").build()));
assertEquals(ConnectionType.INTERNET, internet.connectionType());
assertNull(internet.connectionId());
assertNull(client.getIntegration(request -> request.restApiId(apiId)
.resourceId(resourceId).httpMethod("POST")).connectionId());
} finally {
client.deleteVpcLink(request -> request.vpcLinkId(linkId));
}
String v2LinkId = apiGatewayV2Service.createVpcLink(Region.US_EAST_1.id(), Map.of(
"name", "integration-patch-sdk-v2-link", "subnetIds", List.of("subnet-test"),
"securityGroupIds", List.of("sg-test"))).getVpcLinkId();
try {
UpdateIntegrationResponse v2Updated = client.updateIntegration(request -> request
.restApiId(apiId).resourceId(resourceId).httpMethod("POST")
.patchOperations(
PatchOperation.builder().op("replace").path("/connectionType")
.value("VPC_LINK").build(),
PatchOperation.builder().op("replace").path("/connectionId")
.value(v2LinkId).build()));
assertEquals(ConnectionType.VPC_LINK, v2Updated.connectionType());
assertEquals(v2LinkId, v2Updated.connectionId());
assertEquals(v2LinkId, client.getIntegration(request -> request
.restApiId(apiId).resourceId(resourceId).httpMethod("POST")).connectionId());
} finally {
apiGatewayV2Service.deleteVpcLink(Region.US_EAST_1.id(), v2LinkId);
}
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigateway;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import jakarta.inject.Inject;
@@ -7,12 +8,17 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* Round-trips the {@code PutIntegration} fields AWS documents that Floci previously accepted and
@@ -312,6 +318,133 @@ class ApiGatewayIntegrationFieldsRoundTripTest {
.body("passthroughBehavior", equalTo("WHEN_NO_MATCH"));
}
@Test
void updateIntegrationCanPatchVpcLinkConnection() {
given().contentType(ContentType.JSON)
.body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"POST\","
+ "\"uri\":\"http://example.invalid/widget\"}")
.when().put(integrationPath()).then().statusCode(201);
String linkId = given().contentType(ContentType.JSON)
.body("""
{"name":"integration-patch-link","targetArns":[
"arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/net/test/abc"
]}
""")
.when().post("/vpclinks").then().statusCode(202)
.extract().path("id");
try {
given().contentType(ContentType.JSON)
.body("""
{"patchOperations":[
{"op":"replace","path":"/connectionType","value":"VPC_LINK"},
{"op":"replace","path":"/connectionId","value":"%s"}
]}
""".formatted(linkId))
.when().patch(integrationPath()).then().statusCode(200)
.body("connectionType", equalTo("VPC_LINK"))
.body("connectionId", equalTo(linkId));
given().when().get(integrationPath()).then().statusCode(200)
.body("connectionType", equalTo("VPC_LINK"))
.body("connectionId", equalTo(linkId));
given().contentType(ContentType.JSON)
.body("""
{"patchOperations":[
{"op":"replace","path":"/uri","value":"http://changed.invalid/widget"},
{"op":"replace","path":"/connectionId","value":"missing-link"}
]}
""")
.when().patch(integrationPath()).then().statusCode(400);
given().when().get(integrationPath()).then().statusCode(200)
.body("uri", equalTo("http://example.invalid/widget"))
.body("connectionType", equalTo("VPC_LINK"))
.body("connectionId", equalTo(linkId));
given().contentType(ContentType.JSON)
.body("""
{"patchOperations":[
{"op":"replace","path":"/connectionType","value":"INTERNET"}
]}
""")
.when().patch(integrationPath()).then().statusCode(200)
.body("connectionType", equalTo("INTERNET"));
given().when().get(integrationPath()).then().statusCode(200)
.body("connectionType", equalTo("INTERNET"))
.body("connectionId", nullValue());
given().contentType(ContentType.JSON)
.body("""
{"patchOperations":[
{"op":"replace","path":"/connectionType","value":"VPC_LINK"},
{"op":"replace","path":"/connectionId","value":"${stageVariables.vpcLinkId}"}
]}
""")
.when().patch(integrationPath()).then().statusCode(200)
.body("connectionId", equalTo("${stageVariables.vpcLinkId}"));
} finally {
given().when().delete("/vpclinks/" + linkId).then().statusCode(202);
}
}
@Test
void updateIntegrationAcceptsVpcLinkV2Connection() throws IOException {
HttpServer backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backend.createContext("/widget", exchange -> {
byte[] response = "v2-link-ok".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, response.length);
exchange.getResponseBody().write(response);
exchange.close();
});
backend.start();
try {
given().contentType(ContentType.JSON)
.body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"POST\","
+ "\"uri\":\"http://127.0.0.1:" + backend.getAddress().getPort() + "/widget\"}")
.when().put(integrationPath()).then().statusCode(201);
String linkId = given().contentType(ContentType.JSON)
.body("""
{"name":"integration-patch-v2-link","subnetIds":["subnet-test"],
"securityGroupIds":["sg-test"]}
""")
.when().post("/v2/vpclinks").then().statusCode(201)
.extract().path("vpcLinkId");
try {
given().contentType(ContentType.JSON)
.body("""
{"patchOperations":[
{"op":"replace","path":"/connectionType","value":"VPC_LINK"},
{"op":"replace","path":"/connectionId","value":"%s"}
]}
""".formatted(linkId))
.when().patch(integrationPath()).then().statusCode(200)
.body("connectionType", equalTo("VPC_LINK"))
.body("connectionId", equalTo(linkId));
given().when().get(integrationPath()).then().statusCode(200)
.body("connectionId", equalTo(linkId));
String deploymentId = given().contentType(ContentType.JSON).body("{}")
.when().post("/restapis/" + apiId + "/deployments")
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages").then().statusCode(201);
given().when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200).body(equalTo("v2-link-ok"));
} finally {
given().when().delete("/v2/vpclinks/" + linkId).then().statusCode(202);
}
} finally {
backend.stop(0);
}
}
@Test
void getIntegrationResponseReturnsItsContentHandling() {
putFullIntegration();
@@ -225,6 +225,38 @@ class ApiGatewayVpcLinkAndCachingTest {
given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
}
@Test
void v1VpcLinkIntegrationResolvesStageVariable() {
String linkId = createVpcLink("stage-variable-v1-link");
String apiId = createApi("vpclink-stage-variable-v1",
",\"connectionType\":\"VPC_LINK\",\"connectionId\":\"${stageVariables.vpcLinkId}\"",
",\"variables\":{\"vpcLinkId\":\"" + linkId + "\"}");
given().when().get("/restapis/" + apiId + "/stages/test")
.then().statusCode(200).body("variables.vpcLinkId", equalTo(linkId));
given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
}
@Test
void v2VpcLinkIntegrationResolvesStageVariable() {
String linkId = given().contentType(ContentType.JSON)
.body("{\"name\":\"stage-variable-v2-link\",\"subnetIds\":[\"subnet-test\"],"
+ "\"securityGroupIds\":[\"sg-test\"]}")
.when().post("/v2/vpclinks").then().statusCode(201)
.extract().path("vpcLinkId");
try {
String apiId = createApi("vpclink-stage-variable-v2",
",\"connectionType\":\"VPC_LINK\",\"connectionId\":\"${stageVariables.vpcLinkId}\"",
",\"variables\":{\"vpcLinkId\":\"" + linkId + "\"}");
given().when().get("/restapis/" + apiId + "/stages/test")
.then().statusCode(200).body("variables.vpcLinkId", equalTo(linkId));
given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
} finally {
given().when().delete("/v2/vpclinks/" + linkId).then().statusCode(202);
}
}
@Test
void vpcLinkIntegrationIsRejectedWhenTheLinkIsUnknown() {
String apiId = createApi("vpclink-missing",