feat(apigateway): honour the remaining REST integration settings (#3434)

* feat(apigateway): honour the remaining REST integration settings

PutIntegration persisted 6 of the 16 fields AWS documents. The rest were
accepted without error and silently dropped, so an integration could be created
exactly as intended and then behave as though the configuration were absent.

- timeoutInMillis is applied to the backend call and defaults to AWS's 29,000ms
  rather than the previously hardcoded 30s. Values below AWS's 50ms floor are
  rejected; the 29s ceiling is an edge-optimized limit, so Regional APIs may
  exceed it.
- tlsConfig.insecureSkipVerification skips backend certificate and hostname
  verification. Without it an HTTPS backend behind a private CA or a self-signed
  certificate was unreachable with no way to opt out.
- contentHandling converts payloads in both directions: CONVERT_TO_TEXT
  base64-encodes a binary request for mapping templates, CONVERT_TO_BINARY
  decodes a base64 text request before it is sent. Integration responses accept
  it too, applied as an output conversion after response templates.
- binaryMediaTypes on the RestApi marks content types as binary. A binary body
  now reaches an AWS_PROXY integration base64-encoded with isBase64Encoded set;
  previously it was read as a UTF-8 string, which corrupted it.
- connectionType VPC_LINK requires connectionId to name a link that exists and
  is available. The five REST VPC Link operations are implemented at /vpclinks.
  Floci has no real VPC, so a valid link routes straight to the integration URI;
  what is enforced is the misconfiguration AWS also rejects.
- cacheNamespace and cacheKeyParameters drive response caching, gated on both
  switches AWS requires: cacheClusterEnabled on the stage and caching/enabled on
  the method. Only successful responses are cached, expiring after the method's
  ttlInSeconds.
- credentials is persisted and returned. Floci does not enforce IAM, so the role
  is not actually assumed.

The same fields are now carried through an OpenAPI import, which previously
dropped them from x-amazon-apigateway-integration.

* fix(apigateway): align TLS, cache keys and VPC link patches with AWS

Three review findings on the REST integration settings, all cases where the
local behaviour was looser than the contract AWS documents.

tlsConfig.insecureSkipVerification installed a trust-all X509TrustManager, so an
expired certificate, a broken chain or a chain with no root reached the backend
happily. AWS skips only the check that the certificate was issued by a supported
certificate authority; it still performs basic validation of the expiration
date, the hostname and the presence of a root certificate authority. A backend
that would fail in AWS therefore worked here, which is the direction that hides
a production TLS misconfiguration. The trust manager now verifies validity,
checks that the chain holds together and terminates in a self-signed root, and
requires cA=true on that root when it actually issued a leaf. Hostname
verification is now requested explicitly rather than being switched off: note
that java.net.http.HttpClient always applies HTTPS endpoint identification and
ignored the previous null algorithm, so the hostname was in fact still checked,
but the code and its documentation both claimed otherwise.

The response cache key appended the method and request path to cacheNamespace.
AWS allows one cacheNamespace across several resources exactly so those
resources return the same cached data, and no two resources share a path, so the
setting could never do what it exists for. The key is now the namespace plus the
declared cacheKeyParameters. The namespace still defaults to the resource id, so
resources that did not opt into sharing stay separate.

UpdateVpcLink never looked at op. Any operation on /name or /description was
applied, so op=remove,path=/name set the name instead of being rejected, and
every other path was silently ignored and reported as success. AWS's patch table
supports only replace on those two paths; anything else is now a
BadRequestException.

Also removes the em dashes AGENTS.md disallows from the test files this branch
adds, which the Documentation Style check flagged.

* fix(apigateway): enforce keyCertSign and name constraints under insecureSkipVerification

The comment on CaIssuanceSkippingTrustManager claimed the root check matched
AWS's two requirements on a private root, cA=true together with a keyUsage
including keyCertSign, but only getBasicConstraints() was ever consulted. A root
with CA:TRUE and no keyCertSign was accepted here and rejected by real API
Gateway, which is the direction that hides a broken certificate authority until
deployment. The keyUsage bit is now checked alongside basicConstraints. An
absent keyUsage extension is still accepted: RFC 5280 leaves the key
unrestricted when it is missing, and PKIX reads it the same way.

The rest of the chain walk is now the platform's PKIX validator, anchored on the
chain's own root, which is exactly the "stop checking that the root is one we
trust, keep checking everything else" semantic this setting has in AWS. That
brings X509v3 name constraints with it, which the hand-rolled walk did not
implement at all, along with basicConstraints and keyCertSign on intermediates
and pathLenConstraint. The anchor's own extensions are not examined by PKIX, so
the root's checks stay explicit, and its NameConstraints extension is passed
through to the TrustAnchor. Expiration stays explicit too, because PKIX exempts
a trust anchor from it and AWS does not.

A lone self-signed certificate keeps its own path: it is its own root and is the
plain self-signed-server case the setting exists to enable, so CA extensions are
not demanded of it.

Three tests against real HTTPS backends: a well-formed private CA chain is
reached, a root declaring CA:TRUE without keyCertSign is rejected, and a root
that permits itself only internal.example while issuing for localhost is
rejected. The latter two return 200 without this change.

* fix(apigateway): require keyUsage on a private root and evaluate name constraints properly

Two corrections to the previous round's TLS work.

AWS states the root constraint as "x509 extension keyUsage must have
keyCertSign", which a root carrying no keyUsage extension at all does not
satisfy. The previous commit read a missing extension as leaving the key
unrestricted, which is generic RFC 5280 semantics but not this API
Gateway-specific requirement, and so accepted a certificate authority real API
Gateway turns away. A root without the extension is now rejected.

The name constraints handling was also wrong, in a way its own test hid.
Constraints were unwrapped from the root and handed to the TrustAnchor, but the
platform validator refuses to process anchor-supplied constraints and fails with
"name constraints in trust anchor not supported". So a root carrying the
extension was rejected blindly, never evaluated, and the test asserting a
violated constraint passed on that unrelated error.

Root-level constraints are now rejected deliberately, with an error that says
so, rather than as a side effect of a validator limitation. That is also the
documented behaviour: AWS tells operators hitting validation errors under
insecureSkipVerification to check their CA certificates for Name Constraints
extensions and reissue without them. Constraints on an intermediate sit inside
the certification path, where the validator does read them, and those are
enforced for real: the log now shows "name constraints check failed" rather than
"not supported".

Tests follow the same split. A three-certificate chain whose intermediate
permits only internal.example while issuing for localhost is rejected, a chain
whose intermediate permits localhost is reached, so the first is failing on the
constraint rather than on chain length, and a root carrying constraints is
rejected as its own documented case. Plus a root with CA:TRUE and no keyUsage
extension, which returns 200 without this change.

* fix(apigateway): match binaryMediaTypes literally apart from the catch-all

The matcher expanded a subtype wildcard, so an image/* entry covered
image/png. Nothing in the AWS documentation establishes that as a
pattern: */* is documented concretely ("To support all binary media
types, specify */*"), while every other example names one exact media
type at a time, and the browser walkthrough tells you to register the
concrete image/webp even though the request's Accept header carries
image/*. Expanding it made Floci treat a payload as binary where AWS
would compare the entry as a literal string and treat it as text.

Entries are now compared literally, ignoring the charset parameter,
with */* as the one wildcard. The wildcard branch keeps its coverage
through a */* test, and a second test pins the subtype wildcard as
not expanded so the behaviour cannot drift back silently.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-17 00:18:49 -04:00
1 parent 08656347c7
commit f7565dff3e
14 files changed
+2338 -39

No files matched your search

@@ -0,0 +1,284 @@
package io.github.hectorvent.floci.services.apigateway;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* Covers {@code binaryMediaTypes} on the RestApi together with {@code contentHandling} on the
* integration and its integration responses, AWS's mechanism for moving binary payloads through a
* REST API.
*
* <p>{@code CONVERT_TO_TEXT} base64-encodes a binary payload so it can be handled as a string;
* {@code CONVERT_TO_BINARY} decodes a base64 text payload back into bytes. Both are applied on the
* way out of the stage they belong to: request-side for the integration, response-side for the
* integration response.
*/
@QuarkusTest
class ApiGatewayBinaryContentHandlingTest {
/** Deliberately not valid UTF-8, so any string round-trip corrupts it detectably. */
private static final byte[] BINARY_PAYLOAD = {
(byte) 0x89, 0x50, 0x4E, 0x47, (byte) 0xFF, (byte) 0xD8, 0x00, 0x01, (byte) 0xFE, 0x7F
};
private static HttpServer backend;
private static int backendPort;
private static final AtomicReference<byte[]> receivedBody = new AtomicReference<>();
private final List<String> createdApis = new ArrayList<>();
@BeforeAll
static void startBackend() throws IOException {
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backend.createContext("/", ApiGatewayBinaryContentHandlingTest::handle);
backend.start();
backendPort = backend.getAddress().getPort();
}
@AfterAll
static void stopBackend() {
if (backend != null) backend.stop(0);
}
private static void handle(HttpExchange exchange) throws IOException {
receivedBody.set(exchange.getRequestBody().readAllBytes());
// ?echo=binary returns the raw binary payload; ?echo=base64 returns it base64-encoded.
String query = exchange.getRequestURI().getQuery();
byte[] response;
String contentType;
if (query != null && query.contains("echo=binary")) {
response = BINARY_PAYLOAD;
contentType = "image/jpeg";
} else if (query != null && query.contains("echo=base64")) {
response = Base64.getEncoder().encodeToString(BINARY_PAYLOAD)
.getBytes(StandardCharsets.UTF_8);
contentType = "text/plain";
} else {
response = "{\"ok\":true}".getBytes(StandardCharsets.UTF_8);
contentType = "application/json";
}
exchange.getResponseHeaders().add("Content-Type", contentType);
exchange.sendResponseHeaders(200, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
/**
* Builds a deployed REST API with {@code image/jpeg} as a binary media type and a POST
* /widget method backed by an HTTP (non-proxy) integration.
*/
private String createApi(String name, String integrationExtras, String integrationResponseBody) {
return createApi(name, "\"image/jpeg\"", integrationExtras, integrationResponseBody);
}
/** As above, but with an explicit {@code binaryMediaTypes} array body (JSON, without brackets). */
private String createApi(String name, String binaryMediaTypes, String integrationExtras,
String integrationResponseBody) {
String apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\",\"binaryMediaTypes\":[" + binaryMediaTypes + "]}")
.when().post("/restapis")
.then().statusCode(201).body("id", notNullValue())
.extract().path("id");
createdApis.add(apiId);
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String resourceId = given().contentType(ContentType.JSON)
.body("{\"pathPart\":\"widget\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"type\":\"HTTP\",\"httpMethod\":\"POST\","
+ "\"uri\":\"http://127.0.0.1:" + backendPort + "/widget\"" + integrationExtras + "}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
.then().statusCode(201);
if (integrationResponseBody != null) {
given().contentType(ContentType.JSON).body(integrationResponseBody)
.when().put("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/POST/integration/responses/200")
.then().statusCode(201);
}
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);
return apiId;
}
@AfterEach
void cleanup() {
for (String apiId : createdApis) {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
createdApis.clear();
}
@Test
void convertToTextBase64EncodesABinaryRequestForMappingTemplates() {
receivedBody.set(null);
// $input.body is the base64 text, so the backend receives it verbatim inside the template.
String apiId = createApi("binary-convert-to-text",
",\"contentHandling\":\"CONVERT_TO_TEXT\","
+ "\"requestTemplates\":{\"image/jpeg\":\"$input.body\"}", null);
given().contentType("image/jpeg").body(BINARY_PAYLOAD)
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
assertEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
new String(receivedBody.get(), StandardCharsets.UTF_8));
}
@Test
void convertToBinaryDecodesABase64RequestBeforeSendingIt() {
receivedBody.set(null);
String apiId = createApi("binary-convert-to-binary",
",\"contentHandling\":\"CONVERT_TO_BINARY\","
+ "\"requestTemplates\":{\"text/plain\":\"$input.body\"}", null);
given().contentType("text/plain")
.body(Base64.getEncoder().encodeToString(BINARY_PAYLOAD))
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
assertArrayEquals(BINARY_PAYLOAD, receivedBody.get());
}
@Test
void withoutContentHandlingABinaryRequestIsNotBase64Encoded() {
receivedBody.set(null);
String apiId = createApi("binary-passthrough",
",\"requestTemplates\":{\"image/jpeg\":\"$input.body\"}", null);
given().contentType("image/jpeg").body(BINARY_PAYLOAD)
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
// No conversion requested, so the payload is handled as text, decidedly not base64.
assertEquals(false,
Base64.getEncoder().encodeToString(BINARY_PAYLOAD)
.equals(new String(receivedBody.get(), StandardCharsets.UTF_8)));
}
/**
* The catch-all entry AWS documents: "To support all binary media types, specify
* <code>*&#47;*</code>." It covers {@code image/png}, which is never named explicitly.
*/
@Test
void theCatchAllBinaryMediaTypeCoversAnyContentType() {
receivedBody.set(null);
String apiId = createApi("binary-catch-all", "\"*/*\"",
",\"contentHandling\":\"CONVERT_TO_TEXT\","
+ "\"requestTemplates\":{\"image/png\":\"$input.body\"}", null);
given().contentType("image/png").body(BINARY_PAYLOAD)
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
// Treated as binary purely via the catch-all, so CONVERT_TO_TEXT base64-encoded it.
assertEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
new String(receivedBody.get(), StandardCharsets.UTF_8));
}
/**
* A subtype wildcard is not a pattern. AWS documents only <code>*&#47;*</code> as a wildcard
* entry and names one exact media type at a time everywhere else, so {@code image/}<code>*</code>
* matches nothing but a request that literally declares that content type.
*/
@Test
void aSubtypeWildcardIsNotExpanded() {
receivedBody.set(null);
String apiId = createApi("binary-subtype-wildcard", "\"image/*\"",
",\"contentHandling\":\"CONVERT_TO_TEXT\","
+ "\"requestTemplates\":{\"image/png\":\"$input.body\"}", null);
given().contentType("image/png").body(BINARY_PAYLOAD)
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
// Not binary, so no base64 conversion happened.
assertNotEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
new String(receivedBody.get(), StandardCharsets.UTF_8));
}
/** The charset parameter must not defeat the match: {@code image/jpeg; charset=x} is still binary. */
@Test
void aCharsetParameterDoesNotDefeatTheBinaryMediaTypeMatch() {
receivedBody.set(null);
String apiId = createApi("binary-charset-param",
",\"contentHandling\":\"CONVERT_TO_TEXT\","
+ "\"requestTemplates\":{\"image/jpeg\":\"$input.body\"}", null);
given().contentType("image/jpeg; charset=utf-8").body(BINARY_PAYLOAD)
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
assertEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
new String(receivedBody.get(), StandardCharsets.UTF_8));
}
/** A non-proxy HTTP integration forwards only mapped query params, so ?echo must be mapped. */
private static final String ECHO_QUERY_MAPPING =
",\"requestParameters\":{\"integration.request.querystring.echo\":"
+ "\"method.request.querystring.echo\"}";
@Test
void integrationResponseConvertToTextBase64EncodesABinaryBackendBody() {
String apiId = createApi("binary-resp-to-text", ECHO_QUERY_MAPPING,
"{\"selectionPattern\":\"\",\"contentHandling\":\"CONVERT_TO_TEXT\"}");
byte[] received = given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget?echo=binary")
.then().statusCode(200)
.extract().asByteArray();
assertEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
new String(received, StandardCharsets.UTF_8));
}
@Test
void integrationResponseConvertToBinaryDecodesABase64BackendBody() {
String apiId = createApi("binary-resp-to-binary", ECHO_QUERY_MAPPING,
"{\"selectionPattern\":\"\",\"contentHandling\":\"CONVERT_TO_BINARY\"}");
byte[] received = given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget?echo=base64")
.then().statusCode(200)
.extract().asByteArray();
assertArrayEquals(BINARY_PAYLOAD, received);
}
}
@@ -0,0 +1,137 @@
package io.github.hectorvent.floci.services.apigateway;
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.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
/**
* Round-trips the {@code PutIntegration} fields AWS documents that Floci previously accepted and
* silently dropped: {@code contentHandling}, {@code timeoutInMillis}, {@code connectionType},
* {@code connectionId}, {@code credentials}, {@code cacheNamespace}, {@code cacheKeyParameters} and
* {@code tlsConfig}, plus {@code contentHandling} on an integration response and
* {@code binaryMediaTypes} on the RestApi.
*
* <p>The mapping configuration these sit alongside ({@code requestParameters},
* {@code requestTemplates}, {@code integrationResponses}) is covered by
* {@link ApiGatewayIntegrationReadBackTest}.
*/
@QuarkusTest
class ApiGatewayIntegrationFieldsRoundTripTest {
private String apiId;
private String resourceId;
@BeforeEach
void setup() {
apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"integration-fields-roundtrip\",\"binaryMediaTypes\":[\"image/jpeg\",\"application/octet-stream\"]}")
.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\":\"widget\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
.then().statusCode(201);
}
@AfterEach
void cleanup() {
if (apiId != null) {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
}
private String integrationPath() {
return "/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration";
}
private void putFullIntegration() {
given().contentType(ContentType.JSON)
.body("""
{"type":"HTTP","httpMethod":"POST","uri":"http://backend.internal/widget",
"contentHandling":"CONVERT_TO_BINARY",
"timeoutInMillis":12000,
"connectionType":"VPC_LINK",
"connectionId":"abc123",
"credentials":"arn:aws:iam::000000000000:role/ApiGatewayRole",
"cacheNamespace":"widget-ns",
"cacheKeyParameters":["method.request.querystring.tenant"],
"tlsConfig":{"insecureSkipVerification":true}}
""")
.when().put(integrationPath())
.then().statusCode(201);
}
@Test
void putIntegrationEchoesEveryConfiguredField() {
given().contentType(ContentType.JSON)
.body("""
{"type":"HTTP","httpMethod":"POST","uri":"http://backend.internal/widget",
"contentHandling":"CONVERT_TO_TEXT","timeoutInMillis":9000,
"connectionType":"VPC_LINK","connectionId":"abc123",
"tlsConfig":{"insecureSkipVerification":true}}
""")
.when().put(integrationPath())
.then().statusCode(201)
.body("type", equalTo("HTTP"))
.body("contentHandling", equalTo("CONVERT_TO_TEXT"))
.body("timeoutInMillis", equalTo(9000))
.body("connectionType", equalTo("VPC_LINK"))
.body("connectionId", equalTo("abc123"))
.body("tlsConfig.insecureSkipVerification", equalTo(true));
}
@Test
void getIntegrationReturnsTheSettingsItStores() {
putFullIntegration();
given().when().get(integrationPath())
.then().statusCode(200)
.body("cacheNamespace", equalTo("widget-ns"))
.body("cacheKeyParameters", contains("method.request.querystring.tenant"))
.body("credentials", equalTo("arn:aws:iam::000000000000:role/ApiGatewayRole"))
.body("contentHandling", equalTo("CONVERT_TO_BINARY"))
.body("timeoutInMillis", equalTo(12000));
}
@Test
void getIntegrationResponseReturnsItsContentHandling() {
putFullIntegration();
given().contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"5\\\\d{2}\",\"contentHandling\":\"CONVERT_TO_TEXT\"}")
.when().put(integrationPath() + "/responses/502")
.then().statusCode(201);
given().when().get(integrationPath() + "/responses/502")
.then().statusCode(200)
.body("statusCode", equalTo("502"))
.body("contentHandling", equalTo("CONVERT_TO_TEXT"));
}
@Test
void restApiRoundTripsBinaryMediaTypes() {
given().when().get("/restapis/" + apiId)
.then().statusCode(200)
.body("binaryMediaTypes", containsInAnyOrder("image/jpeg", "application/octet-stream"));
}
}
@@ -0,0 +1,567 @@
package io.github.hectorvent.floci.services.apigateway;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralSubtree;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.NameConstraints;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
/**
* Covers the two REST integration transport settings AWS documents that Floci previously accepted
* and ignored: {@code timeoutInMillis} and {@code tlsConfig.insecureSkipVerification}.
*
* <p>The TLS case matters because {@code HttpProxyInvoker} uses a default {@code HttpClient}: an
* HTTPS backend presenting a self-signed certificate was unreachable with no way to opt out, which
* is the common shape for an internal service behind a private CA.
*/
@QuarkusTest
class ApiGatewayIntegrationTransportOptionsTest {
private static HttpServer slowServer;
private static HttpsServer tlsServer;
private static HttpsServer wrongHostTlsServer;
private static HttpsServer expiredTlsServer;
private static HttpsServer privateCaTlsServer;
private static HttpsServer nonSigningRootTlsServer;
private static HttpsServer keyUsagelessRootTlsServer;
private static HttpsServer nameConstrainedRootTlsServer;
private static HttpsServer nameConstrainedIntermediateTlsServer;
private static HttpsServer permissiveIntermediateTlsServer;
private static int slowPort;
private static int tlsPort;
private static int wrongHostTlsPort;
private static int expiredTlsPort;
private static int privateCaTlsPort;
private static int nonSigningRootTlsPort;
private static int keyUsagelessRootTlsPort;
private static int nameConstrainedRootTlsPort;
private static int nameConstrainedIntermediateTlsPort;
private static int permissiveIntermediateTlsPort;
private final List<String> createdApis = new ArrayList<>();
@BeforeAll
static void startBackends() throws Exception {
slowServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
slowServer.createContext("/", ApiGatewayIntegrationTransportOptionsTest::slowHandler);
slowServer.start();
slowPort = slowServer.getAddress().getPort();
tlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
tlsServer.setHttpsConfigurator(new HttpsConfigurator(selfSignedContext()));
tlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
tlsServer.start();
tlsPort = tlsServer.getAddress().getPort();
// Same self-signed shape, but the certificate names a host this server is not reachable at,
// so only hostname verification can reject it.
wrongHostTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
wrongHostTlsServer.setHttpsConfigurator(new HttpsConfigurator(
selfSignedContextFor("wrong.example", List.of("wrong.example"))));
wrongHostTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
wrongHostTlsServer.start();
wrongHostTlsPort = wrongHostTlsServer.getAddress().getPort();
// Correct hostname, self-signed, but expired two days ago.
expiredTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
expiredTlsServer.setHttpsConfigurator(new HttpsConfigurator(expiredSelfSignedContext()));
expiredTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
expiredTlsServer.start();
expiredTlsPort = expiredTlsServer.getAddress().getPort();
// A leaf issued by a private root, the shape insecureSkipVerification exists for beyond the
// single self-signed certificate. Serves the root alongside the leaf, as a real backend does.
privateCaTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
privateCaTlsServer.setHttpsConfigurator(new HttpsConfigurator(
privateCaContext(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign, null)));
privateCaTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
privateCaTlsServer.start();
privateCaTlsPort = privateCaTlsServer.getAddress().getPort();
// Same chain, except the root declares cA=true without keyCertSign. AWS requires both
// together, so this root cannot issue the leaf it just issued.
nonSigningRootTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
nonSigningRootTlsServer.setHttpsConfigurator(new HttpsConfigurator(
privateCaContext(KeyUsage.digitalSignature | KeyUsage.cRLSign, null)));
nonSigningRootTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
nonSigningRootTlsServer.start();
nonSigningRootTlsPort = nonSigningRootTlsServer.getAddress().getPort();
// Same chain again, except the root carries no keyUsage extension at all. AWS states the
// extension itself as a requirement on a private root, not just the bit inside it.
keyUsagelessRootTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
keyUsagelessRootTlsServer.setHttpsConfigurator(new HttpsConfigurator(privateCaContext(null, null)));
keyUsagelessRootTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
keyUsagelessRootTlsServer.start();
keyUsagelessRootTlsPort = keyUsagelessRootTlsServer.getAddress().getPort();
// A fully-formed root that additionally carries Name Constraints of its own.
NameConstraints internalOnly = permittedDnsSubtree("internal.example");
nameConstrainedRootTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
nameConstrainedRootTlsServer.setHttpsConfigurator(new HttpsConfigurator(privateCaContext(
KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign, internalOnly)));
nameConstrainedRootTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
nameConstrainedRootTlsServer.start();
nameConstrainedRootTlsPort = nameConstrainedRootTlsServer.getAddress().getPort();
// Three certificates, with the constraints on the intermediate where the validator actually
// reads them: the intermediate permits itself internal.example and issued for localhost.
nameConstrainedIntermediateTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
nameConstrainedIntermediateTlsServer.setHttpsConfigurator(new HttpsConfigurator(
intermediateCaContext(permittedDnsSubtree("internal.example"))));
nameConstrainedIntermediateTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
nameConstrainedIntermediateTlsServer.start();
nameConstrainedIntermediateTlsPort = nameConstrainedIntermediateTlsServer.getAddress().getPort();
// The same three-certificate shape whose intermediate permits localhost. Without this, the
// test above would pass for any three-certificate chain rather than because of the
// constraint it names.
permissiveIntermediateTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
permissiveIntermediateTlsServer.setHttpsConfigurator(new HttpsConfigurator(
intermediateCaContext(permittedDnsSubtree("localhost"))));
permissiveIntermediateTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
permissiveIntermediateTlsServer.start();
permissiveIntermediateTlsPort = permissiveIntermediateTlsServer.getAddress().getPort();
}
@AfterAll
static void stopBackends() {
if (slowServer != null) slowServer.stop(0);
if (tlsServer != null) tlsServer.stop(0);
if (wrongHostTlsServer != null) wrongHostTlsServer.stop(0);
if (expiredTlsServer != null) expiredTlsServer.stop(0);
if (privateCaTlsServer != null) privateCaTlsServer.stop(0);
if (nonSigningRootTlsServer != null) nonSigningRootTlsServer.stop(0);
if (keyUsagelessRootTlsServer != null) keyUsagelessRootTlsServer.stop(0);
if (nameConstrainedRootTlsServer != null) nameConstrainedRootTlsServer.stop(0);
if (nameConstrainedIntermediateTlsServer != null) nameConstrainedIntermediateTlsServer.stop(0);
if (permissiveIntermediateTlsServer != null) permissiveIntermediateTlsServer.stop(0);
}
/** Sleeps when asked to, so a configured timeout can be observed firing. */
private static void slowHandler(HttpExchange exchange) throws IOException {
String query = exchange.getRequestURI().getQuery();
if (query != null && query.contains("slow=true")) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
respond(exchange, 200, "{\"from\":\"backend\"}");
}
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(status, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
}
/** An SSLContext serving a genuinely self-signed cert no default trust store will accept. */
private static SSLContext selfSignedContext() throws Exception {
return selfSignedContextFor("localhost", List.of("localhost", "127.0.0.1"));
}
/**
* A self-signed certificate for localhost whose validity window closed two days ago. Trusting
* everything accepts it; AWS does not, because expiration is part of the basic validation that
* survives insecureSkipVerification.
*/
private static SSLContext expiredSelfSignedContext() throws Exception {
CertificateGenerator generator = new CertificateGenerator();
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
X500Name dn = new X500Name("CN=localhost");
Instant now = Instant.now();
X509Certificate certificate = generator.signCertificate(
dn, keyPair.getPublic(), dn, keyPair.getPrivate(),
List.of("localhost", "127.0.0.1"), false, CertificateGenerator.LeafUsage.SERVER,
now.minus(10, ChronoUnit.DAYS), now.minus(2, ChronoUnit.DAYS));
return contextFor(certificate, keyPair.getPrivate());
}
private static SSLContext selfSignedContextFor(String commonName, List<String> sans) throws Exception {
CertificateGenerator generator = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate generated = generator.generateSelfSignedCertificate(
commonName, sans, KeyAlgorithm.RSA_2048);
X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
.generateCertificate(new ByteArrayInputStream(
generated.certificatePem().getBytes(StandardCharsets.UTF_8)));
// RSA keys are emitted as PKCS#1 ("RSA PRIVATE KEY"), not PKCS#8, so use the generator's
// own parser rather than PKCS8EncodedKeySpec.
PrivateKey privateKey = generator.parsePrivateKey(generated.privateKeyPem());
return contextFor(certificate, privateKey);
}
/**
* A two-certificate chain: a {@code localhost} leaf issued by a self-signed root built with
* exactly {@code rootKeyUsageBits} and, optionally, {@code nameConstraints}. Both are what a
* private certificate authority looks like on the wire, and both are the knobs AWS documents as
* still mattering under {@code insecureSkipVerification}.
*/
/** Permitted subtrees naming a single DNS name, the usual private-CA scoping shape. */
private static NameConstraints permittedDnsSubtree(String dnsName) {
return new NameConstraints(
new GeneralSubtree[]{new GeneralSubtree(new GeneralName(GeneralName.dNSName, dnsName))},
null);
}
/**
* A three-certificate chain, root to intermediate to {@code localhost} leaf, where the
* intermediate carries {@code nameConstraints}. Constraints belong on the intermediate to be
* enforced: it sits inside the certification path, where the validator reads extensions, rather
* than being the trust anchor, whose extensions are never looked at.
*/
private static SSLContext intermediateCaContext(NameConstraints nameConstraints) throws Exception {
KeyPairGenerator keys = KeyPairGenerator.getInstance("RSA");
keys.initialize(2048);
KeyPair rootKeyPair = keys.generateKeyPair();
KeyPair intermediateKeyPair = keys.generateKeyPair();
KeyPair leafKeyPair = keys.generateKeyPair();
Instant now = Instant.now();
int caKeyUsage = KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign;
X500Name rootDn = new X500Name("CN=Floci Test Root");
X509Certificate root = buildCa(rootDn, rootKeyPair.getPublic(), rootDn, rootKeyPair.getPrivate(),
caKeyUsage, null, now);
X500Name intermediateDn = new X500Name("CN=Floci Test Intermediate");
X509Certificate intermediate = buildCa(intermediateDn, intermediateKeyPair.getPublic(),
rootDn, rootKeyPair.getPrivate(), caKeyUsage, nameConstraints, now);
X509Certificate leaf = new CertificateGenerator().signCertificate(
new X500Name("CN=localhost"), leafKeyPair.getPublic(), intermediateDn,
intermediateKeyPair.getPrivate(), List.of("localhost", "127.0.0.1"), false,
CertificateGenerator.LeafUsage.SERVER, now.minus(1, ChronoUnit.DAYS),
now.plus(30, ChronoUnit.DAYS));
return contextFor(leafKeyPair.getPrivate(), leaf, intermediate, root);
}
/** A CA certificate, self-signed when {@code issuerDn} is its own subject. */
private static X509Certificate buildCa(X500Name subjectDn, java.security.PublicKey subjectKey,
X500Name issuerDn, PrivateKey issuerKey, Integer keyUsageBits,
NameConstraints nameConstraints, Instant now) throws Exception {
JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
issuerDn, new BigInteger(128, new SecureRandom()),
Date.from(now.minus(1, ChronoUnit.DAYS)), Date.from(now.plus(365, ChronoUnit.DAYS)),
subjectDn, subjectKey);
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
// A null bit set means the extension is left off entirely, which is its own case: AWS
// requires the extension to be there, not merely to have the right bit when present.
if (keyUsageBits != null) {
builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageBits));
}
if (nameConstraints != null) {
builder.addExtension(Extension.nameConstraints, true, nameConstraints);
}
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(issuerKey);
return new JcaX509CertificateConverter().getCertificate(builder.build(signer));
}
private static SSLContext privateCaContext(Integer rootKeyUsageBits, NameConstraints nameConstraints)
throws Exception {
KeyPairGenerator keys = KeyPairGenerator.getInstance("RSA");
keys.initialize(2048);
KeyPair rootKeyPair = keys.generateKeyPair();
KeyPair leafKeyPair = keys.generateKeyPair();
Instant now = Instant.now();
X500Name rootDn = new X500Name("CN=Floci Test Root");
X509Certificate root = buildCa(rootDn, rootKeyPair.getPublic(), rootDn,
rootKeyPair.getPrivate(), rootKeyUsageBits, nameConstraints, now);
X509Certificate leaf = new CertificateGenerator().signCertificate(
new X500Name("CN=localhost"), leafKeyPair.getPublic(), rootDn, rootKeyPair.getPrivate(),
List.of("localhost", "127.0.0.1"), false, CertificateGenerator.LeafUsage.SERVER,
now.minus(1, ChronoUnit.DAYS), now.plus(30, ChronoUnit.DAYS));
return contextFor(leafKeyPair.getPrivate(), leaf, root);
}
private static SSLContext contextFor(X509Certificate certificate, PrivateKey privateKey) throws Exception {
return contextFor(privateKey, certificate);
}
private static SSLContext contextFor(PrivateKey privateKey, X509Certificate... chain) throws Exception {
char[] password = "floci-test".toCharArray();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, null);
keyStore.setKeyEntry("backend", privateKey, password, (Certificate[]) chain);
KeyManagerFactory keyManagers = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
keyManagers.init(keyStore, password);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers.getKeyManagers(), null, null);
return sslContext;
}
/** Builds a deployed REST API whose /{proxy+} ANY method is an HTTP_PROXY to {@code targetUri}. */
private String createApi(String name, String targetUri, String integrationExtras) {
String apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\"}")
.when().post("/restapis")
.then().statusCode(201).body("id", notNullValue())
.extract().path("id");
createdApis.add(apiId);
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String resourceId = given().contentType(ContentType.JSON)
.body("{\"pathPart\":\"{proxy+}\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/ANY")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"ANY\",\"uri\":\"" + targetUri + "\""
+ integrationExtras + "}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/ANY/integration")
.then().statusCode(201);
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);
return apiId;
}
@AfterEach
void cleanup() {
for (String apiId : createdApis) {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
createdApis.clear();
}
@Test
void configuredTimeoutCutsOffASlowBackend() {
String apiId = createApi("timeout-short", "http://127.0.0.1:" + slowPort + "/{proxy}",
",\"timeoutInMillis\":300");
// Backend sleeps 2s; the 300ms integration timeout must fire and surface as 502.
given().when().get("/execute-api/" + apiId + "/test/thing?slow=true")
.then().statusCode(502);
}
@Test
void aGenerousTimeoutLetsTheSameSlowBackendThrough() {
String apiId = createApi("timeout-long", "http://127.0.0.1:" + slowPort + "/{proxy}",
",\"timeoutInMillis\":10000");
given().when().get("/execute-api/" + apiId + "/test/thing?slow=true")
.then().statusCode(200);
}
@Test
void rejectsATimeoutBelowTheAwsMinimum() {
String apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"timeout-invalid\"}")
.when().post("/restapis").then().statusCode(201).extract().path("id");
createdApis.add(apiId);
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + rootId + "/methods/GET")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"GET\","
+ "\"uri\":\"http://example.internal\",\"timeoutInMillis\":10}")
.when().put("/restapis/" + apiId + "/resources/" + rootId + "/methods/GET/integration")
.then().statusCode(400);
}
@Test
void selfSignedHttpsBackendIsRejectedWithoutTlsConfig() {
String apiId = createApi("tls-verified", "https://localhost:" + tlsPort + "/{proxy}", "");
// Default trust store cannot verify the backend's self-signed cert → 502 Bad Gateway.
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(502);
}
@Test
void insecureSkipVerificationReachesTheSelfSignedHttpsBackend() {
String apiId = createApi("tls-insecure", "https://localhost:" + tlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(200)
.body("tls", org.hamcrest.Matchers.equalTo("ok"));
}
@Test
void insecureSkipVerificationStillVerifiesTheHostname() {
String apiId = createApi("tls-insecure-wrong-host",
"https://localhost:" + wrongHostTlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
// AWS documents insecureSkipVerification as skipping only the check that the certificate
// was issued by a supported CA: expiration, hostname and the presence of a root CA are
// still verified. A certificate issued for wrong.example must therefore fail against a
// backend addressed as localhost.
// See https://docs.aws.amazon.com/apigateway/latest/api/API_TlsConfig.html
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(502);
}
@Test
void insecureSkipVerificationStillRejectsAnExpiredCertificate() {
String apiId = createApi("tls-insecure-expired",
"https://localhost:" + expiredTlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
// Expiration is the other half of the basic validation AWS keeps. A backend whose
// certificate has lapsed has to fail here too, or it works locally and breaks in AWS.
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(502);
}
@Test
void insecureSkipVerificationReachesABackendBehindAPrivateCa() {
String apiId = createApi("tls-insecure-private-ca",
"https://localhost:" + privateCaTlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
// The case the setting exists for beyond a lone self-signed certificate: a well-formed
// private root that no public trust store knows. Everything else about the chain is
// correct, so it has to be accepted.
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(200)
.body("tls", org.hamcrest.Matchers.equalTo("ok"));
}
@Test
void insecureSkipVerificationStillRequiresKeyCertSignOnAPrivateRoot() {
String apiId = createApi("tls-insecure-root-without-key-cert-sign",
"https://localhost:" + nonSigningRootTlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
// AWS states the two requirements on a private root together: the keyUsage extension has
// to include keyCertSign and basicConstraints has to say CA:TRUE. Checking only the second
// accepts a root that real API Gateway rejects, which is the direction that hides a broken
// certificate authority until deployment.
// See https://docs.aws.amazon.com/apigateway/latest/api/API_TlsConfig.html
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(502);
}
@Test
void insecureSkipVerificationRejectsAPrivateRootWithNoKeyUsageExtension() {
String apiId = createApi("tls-insecure-root-without-key-usage",
"https://localhost:" + keyUsagelessRootTlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
// AWS states the constraint as "x509 extension keyUsage must have keyCertSign", which a
// root carrying no keyUsage extension does not satisfy. Generic PKIX would read the absent
// extension as leaving the key unrestricted, and that looser reading accepts a certificate
// authority real API Gateway turns away.
// See https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-extensions-integration-tls-config.html
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(502);
}
@Test
void insecureSkipVerificationEnforcesNameConstraintsOnAnIntermediate() {
String apiId = createApi("tls-insecure-name-constrained-intermediate",
"https://localhost:" + nameConstrainedIntermediateTlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
// The intermediate permits itself only internal.example and issued for localhost anyway.
// AWS documents certificate chain validation as including X509v3 Name Constraints
// enforcement, so an issuer overreaching its own declared scope must not be honoured here.
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(502);
}
@Test
void insecureSkipVerificationReachesABackendWhoseIntermediatePermitsIt() {
String apiId = createApi("tls-insecure-permissive-intermediate",
"https://localhost:" + permissiveIntermediateTlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
// Same three-certificate shape, same code path, with the constraint satisfied. Without this
// the test above would be satisfied by any rejection of a three-certificate chain rather
// than by the constraint it names.
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(200)
.body("tls", org.hamcrest.Matchers.equalTo("ok"));
}
@Test
void insecureSkipVerificationRejectsARootCarryingNameConstraints() {
String apiId = createApi("tls-insecure-name-constrained-root",
"https://localhost:" + nameConstrainedRootTlsPort + "/{proxy}",
",\"tlsConfig\":{\"insecureSkipVerification\":true}");
// Constraints on the trust anchor itself are a separate case from the one above, and they
// cannot be evaluated: the platform validator refuses to process constraints supplied with
// an anchor rather than read from a certificate in the path. Rejecting is the safe
// direction and the documented one. AWS tells operators hitting validation errors under
// insecureSkipVerification to check that their CA certificates carry no Name Constraints
// extension and to reissue them without it, so such a certificate does not work in AWS
// either.
given().when().get("/execute-api/" + apiId + "/test/thing")
.then().statusCode(502);
}
}
@@ -0,0 +1,346 @@
package io.github.hectorvent.floci.services.apigateway;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Covers the REST (v1) VPC Link operations and stage-level response caching, both previously absent.
*
* <p>Floci has no real VPC, so a VPC_LINK integration routes straight to its URI. What is enforced
* is the misconfiguration AWS also rejects: naming a link that does not exist.
*
* <p>Caching follows AWS's two-level switch: the stage needs a cache cluster and the method needs
* caching enabled, and the entry is keyed by the integration's {@code cacheKeyParameters}.
*/
@QuarkusTest
class ApiGatewayVpcLinkAndCachingTest {
private static HttpServer backend;
private static int backendPort;
/** Counts backend hits, so a cache hit is observable as the absence of one. */
private static final AtomicInteger backendHits = new AtomicInteger();
private final List<String> createdApis = new ArrayList<>();
private final List<String> createdLinks = new ArrayList<>();
@BeforeAll
static void startBackend() throws IOException {
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backend.createContext("/", ApiGatewayVpcLinkAndCachingTest::handle);
backend.start();
backendPort = backend.getAddress().getPort();
}
@AfterAll
static void stopBackend() {
if (backend != null) backend.stop(0);
}
private static void handle(HttpExchange exchange) throws IOException {
int hit = backendHits.incrementAndGet();
byte[] response = ("{\"hit\":" + hit + "}").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
@AfterEach
void cleanup() {
for (String apiId : createdApis) {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
createdApis.clear();
for (String linkId : createdLinks) {
given().when().delete("/vpclinks/" + linkId);
}
createdLinks.clear();
}
private String createVpcLink(String name) {
String id = given().contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\",\"targetArns\":"
+ "[\"arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/net/nlb/abc\"]}")
.when().post("/vpclinks")
.then().statusCode(202).body("id", notNullValue())
.extract().path("id");
createdLinks.add(id);
return id;
}
/** A deployed API with a GET /widget method; caller supplies integration and stage extras. */
private String createApi(String name, String integrationExtras, String stageExtras) {
String apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\"}")
.when().post("/restapis").then().statusCode(201).extract().path("id");
createdApis.add(apiId);
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String resourceId = given().contentType(ContentType.JSON)
.body("{\"pathPart\":\"widget\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"GET\","
+ "\"uri\":\"http://127.0.0.1:" + backendPort + "/widget\"" + integrationExtras + "}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
.then().statusCode(201);
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 + "\"" + stageExtras + "}")
.when().post("/restapis/" + apiId + "/stages")
.then().statusCode(201);
return apiId;
}
/**
* A deployed API with GET /alpha and GET /beta, both proxying to the same backend with caching
* on. When {@code cacheNamespace} is non-null both integrations declare it, which is how AWS
* lets separate resources return the same cached data.
*/
private String createTwoResourceApi(String name, String cacheNamespace) {
String apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\"}")
.when().post("/restapis").then().statusCode(201).extract().path("id");
createdApis.add(apiId);
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String namespaceField = cacheNamespace == null
? "" : ",\"cacheNamespace\":\"" + cacheNamespace + "\"";
for (String pathPart : List.of("alpha", "beta")) {
String resourceId = given().contentType(ContentType.JSON)
.body("{\"pathPart\":\"" + pathPart + "\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"GET\","
+ "\"uri\":\"http://127.0.0.1:" + backendPort + "/widget\""
+ namespaceField + "}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/GET/integration")
.then().statusCode(201);
}
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 + "\","
+ "\"cacheClusterEnabled\":true}")
.when().post("/restapis/" + apiId + "/stages")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"patchOperations\":["
+ "{\"op\":\"replace\",\"path\":\"/~1alpha/GET/caching/enabled\",\"value\":\"true\"},"
+ "{\"op\":\"replace\",\"path\":\"/~1beta/GET/caching/enabled\",\"value\":\"true\"}]}")
.when().patch("/restapis/" + apiId + "/stages/test")
.then().statusCode(200);
return apiId;
}
/** Turns on caching for GET /widget on the stage. */
private void enableMethodCaching(String apiId, int ttlSeconds) {
given().contentType(ContentType.JSON)
.body("{\"patchOperations\":["
+ "{\"op\":\"replace\",\"path\":\"/~1widget/GET/caching/enabled\",\"value\":\"true\"},"
+ "{\"op\":\"replace\",\"path\":\"/~1widget/GET/caching/ttlInSeconds\",\"value\":\""
+ ttlSeconds + "\"}]}")
.when().patch("/restapis/" + apiId + "/stages/test")
.then().statusCode(200);
}
@Test
void vpcLinkCrudRoundTrips() {
String linkId = createVpcLink("crud-link");
given().when().get("/vpclinks/" + linkId)
.then().statusCode(200)
.body("name", equalTo("crud-link"))
.body("status", equalTo("AVAILABLE"))
.body("targetArns", contains(
"arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/net/nlb/abc"));
given().when().get("/vpclinks").then().statusCode(200).body("item.id", contains(linkId));
given().contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"renamed\"}]}")
.when().patch("/vpclinks/" + linkId)
.then().statusCode(200).body("name", equalTo("renamed"));
given().when().delete("/vpclinks/" + linkId).then().statusCode(202);
given().when().get("/vpclinks/" + linkId).then().statusCode(404);
createdLinks.remove(linkId);
}
@Test
void createVpcLinkRequiresATargetArn() {
given().contentType(ContentType.JSON).body("{\"name\":\"no-targets\"}")
.when().post("/vpclinks").then().statusCode(400);
}
@Test
void vpcLinkIntegrationRoutesWhenTheLinkExists() {
String linkId = createVpcLink("routing-link");
String apiId = createApi("vpclink-ok",
",\"connectionType\":\"VPC_LINK\",\"connectionId\":\"" + linkId + "\"", "");
given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
}
@Test
void vpcLinkIntegrationIsRejectedWhenTheLinkIsUnknown() {
String apiId = createApi("vpclink-missing",
",\"connectionType\":\"VPC_LINK\",\"connectionId\":\"does-not-exist\"", "");
given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(502);
}
@Test
void cachingServesTheSecondRequestWithoutHittingTheBackend() {
backendHits.set(0);
String apiId = createApi("cache-on", "", ",\"cacheClusterEnabled\":true");
enableMethodCaching(apiId, 300);
given().when().get("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200).body("hit", equalTo(1));
given().when().get("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200).body("hit", equalTo(1));
assertEquals(1, backendHits.get(), "second request should have been served from the cache");
}
@Test
void cachingIsOffWhenTheStageHasNoCacheCluster() {
backendHits.set(0);
// Method-level caching alone is not enough: AWS needs the stage's cache cluster too.
String apiId = createApi("cache-no-cluster", "", "");
enableMethodCaching(apiId, 300);
given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
assertEquals(2, backendHits.get(), "without a cache cluster every request reaches the backend");
}
@Test
void cacheKeyParametersSeparateEntries() {
backendHits.set(0);
String apiId = createApi("cache-keys",
",\"cacheKeyParameters\":[\"method.request.querystring.tenant\"]",
",\"cacheClusterEnabled\":true");
enableMethodCaching(apiId, 300);
given().when().get("/execute-api/" + apiId + "/test/widget?tenant=a").then().statusCode(200);
given().when().get("/execute-api/" + apiId + "/test/widget?tenant=a").then().statusCode(200);
// A different value for a declared cache key parameter is a different entry.
given().when().get("/execute-api/" + apiId + "/test/widget?tenant=b").then().statusCode(200);
assertEquals(2, backendHits.get(), "tenant=a should be cached, tenant=b should miss");
}
@Test
void aSharedCacheNamespaceLetsTwoResourcesReturnTheSameCachedData() {
backendHits.set(0);
String apiId = createTwoResourceApi("cache-shared-ns", "reports");
given().when().get("/execute-api/" + apiId + "/test/alpha")
.then().statusCode(200).body("hit", equalTo(1));
// AWS documents cacheNamespace as shareable across resources so that those resources can
// return the same cached data. Folding the method and request path into the key would make
// that impossible, since two resources never share a path.
given().when().get("/execute-api/" + apiId + "/test/beta")
.then().statusCode(200).body("hit", equalTo(1));
assertEquals(1, backendHits.get(),
"the second resource shares the namespace, so it should read the first one's entry");
}
@Test
void resourcesKeepSeparateEntriesWithoutASharedNamespace() {
backendHits.set(0);
// cacheNamespace defaults to the resource id, so resources that did not opt into sharing
// still get an entry each.
String apiId = createTwoResourceApi("cache-default-ns", null);
given().when().get("/execute-api/" + apiId + "/test/alpha").then().statusCode(200);
given().when().get("/execute-api/" + apiId + "/test/beta").then().statusCode(200);
assertEquals(2, backendHits.get(), "distinct default namespaces should not share an entry");
}
@Test
void updateVpcLinkRejectsAnUnsupportedOperation() {
String linkId = createVpcLink("patch-op-link");
// AWS's patch-operation table supports only replace on a VPC link, and applying an
// unsupported operation returns an error. Accepting remove here would have set the name to
// the supplied value instead.
given().contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/name\",\"value\":\"gone\"}]}")
.when().patch("/vpclinks/" + linkId)
.then().statusCode(400);
given().when().get("/vpclinks/" + linkId)
.then().statusCode(200).body("name", equalTo("patch-op-link"));
}
@Test
void updateVpcLinkRejectsAnUnsupportedPath() {
String linkId = createVpcLink("patch-path-link");
// Only /name and /description are patchable. Silently ignoring /targetArns would report
// success for a change that never happened.
given().contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/targetArns\",\"value\":\"x\"}]}")
.when().patch("/vpclinks/" + linkId)
.then().statusCode(400);
}
@Test
void stageReportsItsCacheClusterState() {
String apiId = createApi("cache-reported", "", ",\"cacheClusterEnabled\":true");
given().when().get("/restapis/" + apiId + "/stages/test")
.then().statusCode(200)
.body("cacheClusterEnabled", equalTo(true))
.body("cacheClusterStatus", equalTo("AVAILABLE"));
}
}