mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
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:
1 parent
08656347c7
commit
f7565dff3e
14 files changed
+2338
-39
No files matched your search
+98
@@ -1431,6 +1431,80 @@ public class ApiGatewayController {
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── VPC Links (v1) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/vpclinks")
|
||||
public Response createV1VpcLink(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
io.github.hectorvent.floci.services.apigateway.model.VpcLink link =
|
||||
service.createVpcLink(region, request);
|
||||
// AWS provisions asynchronously and answers 202 Accepted.
|
||||
return Response.status(202).entity(toV1VpcLinkNode(link).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/vpclinks")
|
||||
public Response getV1VpcLinks(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
ArrayNode items = result.putArray("item");
|
||||
service.getVpcLinks(region).forEach(l -> items.add(toV1VpcLinkNode(l)));
|
||||
return Response.ok(result.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/vpclinks/{vpcLinkId}")
|
||||
public Response getV1VpcLink(@Context HttpHeaders headers,
|
||||
@PathParam("vpcLinkId") String vpcLinkId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toV1VpcLinkNode(service.getVpcLink(region, vpcLinkId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/vpclinks/{vpcLinkId}")
|
||||
public Response updateV1VpcLink(@Context HttpHeaders headers,
|
||||
@PathParam("vpcLinkId") String vpcLinkId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
io.github.hectorvent.floci.services.apigateway.model.VpcLink link =
|
||||
service.updateVpcLink(region, vpcLinkId, parsePatchOperations(body));
|
||||
return Response.ok(toV1VpcLinkNode(link).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/vpclinks/{vpcLinkId}")
|
||||
public Response deleteV1VpcLink(@Context HttpHeaders headers,
|
||||
@PathParam("vpcLinkId") String vpcLinkId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteVpcLink(region, vpcLinkId);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
private ObjectNode toV1VpcLinkNode(io.github.hectorvent.floci.services.apigateway.model.VpcLink link) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", link.getId());
|
||||
node.put("name", link.getName());
|
||||
if (link.getDescription() != null) node.put("description", link.getDescription());
|
||||
ArrayNode arns = node.putArray("targetArns");
|
||||
link.getTargetArns().forEach(arns::add);
|
||||
node.put("status", link.getStatus());
|
||||
if (link.getStatusMessage() != null) node.put("statusMessage", link.getStatusMessage());
|
||||
if (!link.getTags().isEmpty()) {
|
||||
ObjectNode tags = node.putObject("tags");
|
||||
link.getTags().forEach(tags::put);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
// ──────────────────────────── VPC Links (v2) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@@ -2032,6 +2106,11 @@ public class ApiGatewayController {
|
||||
node.set("tags", tagsNode);
|
||||
}
|
||||
|
||||
if (api.getBinaryMediaTypes() != null && !api.getBinaryMediaTypes().isEmpty()) {
|
||||
ArrayNode binaryTypes = node.putArray("binaryMediaTypes");
|
||||
api.getBinaryMediaTypes().forEach(binaryTypes::add);
|
||||
}
|
||||
|
||||
EndpointConfiguration epConfig = api.getEndpointConfiguration();
|
||||
if (epConfig == null) {
|
||||
epConfig = new EndpointConfiguration();
|
||||
@@ -2106,6 +2185,21 @@ public class ApiGatewayController {
|
||||
node.put("httpMethod", i.getHttpMethod());
|
||||
node.put("uri", i.getUri());
|
||||
node.put("passthroughBehavior", i.getPassthroughBehavior());
|
||||
if (i.getContentHandling() != null) node.put("contentHandling", i.getContentHandling());
|
||||
if (i.getTimeoutInMillis() != null) node.put("timeoutInMillis", i.getTimeoutInMillis());
|
||||
if (i.getConnectionType() != null) node.put("connectionType", i.getConnectionType());
|
||||
if (i.getConnectionId() != null) node.put("connectionId", i.getConnectionId());
|
||||
if (i.getCredentials() != null) node.put("credentials", i.getCredentials());
|
||||
if (i.getCacheNamespace() != null) node.put("cacheNamespace", i.getCacheNamespace());
|
||||
if (!i.getCacheKeyParameters().isEmpty()) {
|
||||
ArrayNode keys = node.putArray("cacheKeyParameters");
|
||||
i.getCacheKeyParameters().forEach(keys::add);
|
||||
}
|
||||
if (i.getTlsConfig() != null) {
|
||||
node.putObject("tlsConfig")
|
||||
.put("insecureSkipVerification", i.getTlsConfig().isInsecureSkipVerification());
|
||||
}
|
||||
// Mapping configuration is what IaC tools diff against — omitting it read as drift.
|
||||
if (!i.getRequestParameters().isEmpty()) {
|
||||
ObjectNode params = node.putObject("requestParameters");
|
||||
i.getRequestParameters().forEach(params::put);
|
||||
@@ -2126,6 +2220,7 @@ public class ApiGatewayController {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("statusCode", r.statusCode());
|
||||
node.put("selectionPattern", r.selectionPattern());
|
||||
if (r.contentHandling() != null) node.put("contentHandling", r.contentHandling());
|
||||
if (r.responseParameters() != null && !r.responseParameters().isEmpty()) {
|
||||
ObjectNode params = node.putObject("responseParameters");
|
||||
r.responseParameters().forEach(params::put);
|
||||
@@ -2152,6 +2247,9 @@ public class ApiGatewayController {
|
||||
if (s.getDescription() != null) node.put("description", s.getDescription());
|
||||
node.put("createdDate", s.getCreatedDate());
|
||||
node.put("lastUpdatedDate", s.getLastUpdatedDate());
|
||||
node.put("cacheClusterEnabled", s.isCacheClusterEnabled());
|
||||
node.put("cacheClusterStatus", s.getCacheClusterStatus());
|
||||
if (s.getCacheClusterSize() != null) node.put("cacheClusterSize", s.getCacheClusterSize());
|
||||
if (!s.getVariables().isEmpty()) {
|
||||
ObjectNode vars = node.putObject("variables");
|
||||
s.getVariables().forEach(vars::put);
|
||||
|
||||
+270
-17
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.apigateway.model.GatewayResponseType;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Integration;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.MethodSetting;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Stage;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
|
||||
@@ -433,7 +434,20 @@ public class ApiGatewayExecuteController {
|
||||
"No integration type configured");
|
||||
}
|
||||
|
||||
return switch (integrationType.toUpperCase(Locale.ROOT)) {
|
||||
Response vpcLinkError = validateVpcLink(scope, region, integration);
|
||||
if (vpcLinkError != null) return vpcLinkError;
|
||||
|
||||
String cacheKey = cacheKeyFor(stage, matched, httpMethod, path, integration, headers, uriInfo);
|
||||
if (cacheKey != null) {
|
||||
CachedResponse cached = responseCache.get(cacheKey);
|
||||
if (cached != null && cached.expiresAt() > System.currentTimeMillis()) {
|
||||
LOG.debugv("execute-api: cache hit for {0} {1}/{2}{3}", httpMethod, apiId, stageName, path);
|
||||
return fromCache(cached);
|
||||
}
|
||||
responseCache.remove(cacheKey);
|
||||
}
|
||||
|
||||
Response response = switch (integrationType.toUpperCase(Locale.ROOT)) {
|
||||
case "AWS_PROXY" -> invokeProxy(scope, region, apiId, httpMethod, path, proxy, stageName,
|
||||
matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey,
|
||||
iamIdentity);
|
||||
@@ -441,13 +455,20 @@ public class ApiGatewayExecuteController {
|
||||
matched, integration, headers, uriInfo, body, authorizerResult);
|
||||
case "HTTP_PROXY" -> invokeHttpProxy(scope, apiId, httpMethod, path, proxy, stageName,
|
||||
matched, integration, headers, uriInfo, body);
|
||||
case "HTTP" -> invokeHttpIntegration(scope, apiId, httpMethod, path, proxy, stageName,
|
||||
case "HTTP" -> invokeHttpIntegration(scope, region, apiId, httpMethod, path, proxy, stageName,
|
||||
matched, integration, headers, uriInfo, body, authorizerResult);
|
||||
case "MOCK" -> invokeMock(scope, region, httpMethod, path, stageName,
|
||||
matched, integration, headers, uriInfo, body, authorizerResult);
|
||||
default -> gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
|
||||
"Unsupported integration type: " + integration.getType());
|
||||
};
|
||||
|
||||
// Only successful responses are cached — AWS does not serve an error from the cache.
|
||||
if (cacheKey != null && response.getStatus() < 400) {
|
||||
responseCache.put(cacheKey,
|
||||
snapshotForCache(response, cacheTtlSeconds(methodSettingFor(stage, matched.getPath(), httpMethod))));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private void applyApiOwnerContext(ApiGatewayV2Service.ApiOwner owner) {
|
||||
@@ -585,7 +606,7 @@ public class ApiGatewayExecuteController {
|
||||
httpMethod, apiId, stageName, path, uri);
|
||||
|
||||
io.github.hectorvent.floci.services.apigatewayv2.proxy.ProxyResult result =
|
||||
httpProxyInvoker.invoke(target, ctx);
|
||||
httpProxyInvoker.invoke(target, ctx, proxyOptions(integration));
|
||||
|
||||
Response.ResponseBuilder rb = Response.status(result.statusCode());
|
||||
if (result.body() != null) rb.entity(result.body());
|
||||
@@ -601,6 +622,192 @@ public class ApiGatewayExecuteController {
|
||||
return rb.build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Response caching ────────────────────────────
|
||||
|
||||
/** AWS's default integration cache TTL when a method enables caching without naming one. */
|
||||
private static final int DEFAULT_CACHE_TTL_SECONDS = 300;
|
||||
|
||||
private record CachedResponse(int status, Object entity, Map<String, String> headers, long expiresAt) {}
|
||||
|
||||
private final Map<String, CachedResponse> responseCache = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* The cache key for this request, or {@code null} when caching does not apply. AWS caches only
|
||||
* when the stage has a cache cluster <em>and</em> the method — or the wildcard entry — enables
|
||||
* caching. The key is the integration's {@code cacheNamespace} plus the values of its
|
||||
* {@code cacheKeyParameters}, so two requests differing only in an uncached parameter share an
|
||||
* entry, which is exactly the behaviour that surprises people in production.
|
||||
*
|
||||
* <p>Nothing identifying the resource goes into the key beyond the namespace itself. AWS
|
||||
* documents {@code cacheNamespace} as shareable across resources precisely so those resources
|
||||
* can return the same cached data; mixing the method and request path back in would mean two
|
||||
* resources could never share an entry, which is the setting's whole purpose. The namespace
|
||||
* defaults to the resource id, so resources that did not opt into sharing stay separate.
|
||||
*/
|
||||
private String cacheKeyFor(Stage stage, ApiGatewayResource resource, String httpMethod,
|
||||
String path, Integration integration, HttpHeaders headers, UriInfo uriInfo) {
|
||||
if (stage == null || !stage.isCacheClusterEnabled()) return null;
|
||||
MethodSetting setting = methodSettingFor(stage, resource.getPath(), httpMethod);
|
||||
if (setting == null || !setting.isCachingEnabled()) return null;
|
||||
|
||||
StringBuilder key = new StringBuilder();
|
||||
key.append(integration.getCacheNamespace() != null
|
||||
? integration.getCacheNamespace() : resource.getId());
|
||||
for (String param : integration.getCacheKeyParameters()) {
|
||||
key.append('|').append(param).append('=')
|
||||
.append(cacheKeyParameterValue(param, headers, uriInfo, resource.getPath(), path));
|
||||
}
|
||||
return key.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method's own settings, falling back to the stage-wide wildcard entry. Settings are keyed
|
||||
* by the resource path without its leading slash ({@code pets/GET}), matching what AWS reports.
|
||||
*/
|
||||
private static MethodSetting methodSettingFor(Stage stage, String resourcePath, String httpMethod) {
|
||||
String normalized = resourcePath != null && resourcePath.startsWith("/")
|
||||
? resourcePath.substring(1) : resourcePath;
|
||||
MethodSetting exact = stage.getMethodSettings().get(normalized + "/" + httpMethod);
|
||||
return exact != null ? exact : stage.getMethodSettings().get("*/*");
|
||||
}
|
||||
|
||||
private String cacheKeyParameterValue(String param, HttpHeaders headers, UriInfo uriInfo,
|
||||
String resourcePath, String path) {
|
||||
if (param.startsWith("method.request.querystring.")) {
|
||||
return uriInfo.getQueryParameters()
|
||||
.getFirst(param.substring("method.request.querystring.".length()));
|
||||
}
|
||||
if (param.startsWith("method.request.header.")) {
|
||||
return headers.getHeaderString(param.substring("method.request.header.".length()));
|
||||
}
|
||||
if (param.startsWith("method.request.path.")) {
|
||||
return extractPathParams(resourcePath, path)
|
||||
.get(param.substring("method.request.path.".length()));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int cacheTtlSeconds(MethodSetting setting) {
|
||||
int ttl = setting != null ? setting.getCacheTtlInSeconds() : 0;
|
||||
return ttl > 0 ? ttl : DEFAULT_CACHE_TTL_SECONDS;
|
||||
}
|
||||
|
||||
private static CachedResponse snapshotForCache(Response response, int ttlSeconds) {
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
response.getStringHeaders().forEach((name, values) -> {
|
||||
if (!values.isEmpty()) headers.put(name, values.get(0));
|
||||
});
|
||||
return new CachedResponse(response.getStatus(), response.getEntity(), headers,
|
||||
System.currentTimeMillis() + ttlSeconds * 1000L);
|
||||
}
|
||||
|
||||
private static Response fromCache(CachedResponse cached) {
|
||||
Response.ResponseBuilder rb = Response.status(cached.status()).entity(cached.entity());
|
||||
cached.headers().forEach(rb::header);
|
||||
return rb.build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── VPC Link ────────────────────────────
|
||||
|
||||
/**
|
||||
* Checks that a {@code VPC_LINK} integration names a VPC link that exists and is available,
|
||||
* returning an error response when it does not and {@code null} when the request may proceed.
|
||||
*
|
||||
* <p>Floci has no real VPC, so a valid link routes straight to the integration URI. What this
|
||||
* catches is the misconfiguration AWS also rejects: pointing at a link that was deleted or
|
||||
* never created, which would otherwise silently behave like a plain internet integration.
|
||||
*/
|
||||
private Response validateVpcLink(GatewayResponseScope scope, String region, Integration integration) {
|
||||
if (!"VPC_LINK".equalsIgnoreCase(integration.getConnectionType())) {
|
||||
return null;
|
||||
}
|
||||
String connectionId = integration.getConnectionId();
|
||||
if (connectionId == null || connectionId.isBlank()) {
|
||||
return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
|
||||
"VPC_LINK integration is missing a connectionId");
|
||||
}
|
||||
try {
|
||||
io.github.hectorvent.floci.services.apigateway.model.VpcLink link =
|
||||
apiGatewayService.getVpcLink(region, connectionId);
|
||||
if (!"AVAILABLE".equalsIgnoreCase(link.getStatus())) {
|
||||
return Response.status(502)
|
||||
.entity(jsonMessage("VPC link is not available: " + link.getStatus()))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
return null;
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("VPC_LINK integration references unknown link {0} in {1}", connectionId, region);
|
||||
return Response.status(502)
|
||||
.entity(jsonMessage("Invalid VPC link identifier specified: " + connectionId))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Binary payloads ────────────────────────────
|
||||
|
||||
/**
|
||||
* True when {@code contentType} matches one of the API's configured {@code binaryMediaTypes}.
|
||||
* The charset parameter is ignored when comparing.
|
||||
*
|
||||
* <p>Entries are compared literally apart from the catch-all <code>*/*</code>, which is the
|
||||
* only wildcard AWS documents concretely: "To support all binary media types, specify
|
||||
* <code>*/*</code>." A subtype wildcard such as {@code image/*} is not expanded, because
|
||||
* nothing in the AWS documentation says API Gateway treats it as a pattern: every example there
|
||||
* names one exact media type at a time, and the browser walkthrough tells you to register the
|
||||
* concrete {@code image/webp} even though the request's {@code Accept} header carries
|
||||
* {@code image/*}.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html">Enabling binary support using the console</a>
|
||||
*/
|
||||
private boolean isBinaryMediaType(String region, String apiId, String contentType) {
|
||||
if (contentType == null || contentType.isBlank()) return false;
|
||||
List<String> binaryTypes;
|
||||
try {
|
||||
binaryTypes = apiGatewayService.getRestApi(region, apiId).getBinaryMediaTypes();
|
||||
} catch (AwsException e) {
|
||||
return false;
|
||||
}
|
||||
if (binaryTypes == null || binaryTypes.isEmpty()) return false;
|
||||
|
||||
String base = contentType.contains(";")
|
||||
? contentType.substring(0, contentType.indexOf(';')).trim() : contentType.trim();
|
||||
return binaryTypes.stream().anyMatch(configured -> mediaTypeMatches(configured, base));
|
||||
}
|
||||
|
||||
private static boolean mediaTypeMatches(String configured, String contentType) {
|
||||
if (configured == null) return false;
|
||||
String candidate = configured.trim();
|
||||
return "*/*".equals(candidate) || candidate.equalsIgnoreCase(contentType);
|
||||
}
|
||||
|
||||
/**
|
||||
* The request body as mapping templates should see it. {@code CONVERT_TO_TEXT} base64-encodes a
|
||||
* binary payload so it survives being handled as a string; otherwise the bytes are read as UTF-8.
|
||||
*/
|
||||
private static String templateBody(Integration integration, byte[] body, boolean binaryRequest) {
|
||||
if (body == null || body.length == 0) return null;
|
||||
if (binaryRequest && "CONVERT_TO_TEXT".equalsIgnoreCase(integration.getContentHandling())) {
|
||||
return Base64.getEncoder().encodeToString(body);
|
||||
}
|
||||
return new String(body, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* The payload actually sent to the backend. {@code CONVERT_TO_BINARY} treats the rendered body
|
||||
* as base64 and decodes it; anything else is sent as UTF-8 bytes.
|
||||
*/
|
||||
private static byte[] outgoingPayload(Integration integration, String renderedBody) {
|
||||
if (renderedBody == null) return new byte[0];
|
||||
if ("CONVERT_TO_BINARY".equalsIgnoreCase(integration.getContentHandling())) {
|
||||
try {
|
||||
return Base64.getDecoder().decode(renderedBody.trim());
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("CONVERT_TO_BINARY: body is not valid base64, sending it unchanged");
|
||||
}
|
||||
}
|
||||
return renderedBody.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
// ──────────────────────────── HTTP (non-proxy) ────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -613,7 +820,8 @@ public class ApiGatewayExecuteController {
|
||||
* {@code selectionPattern} is matched against the backend's HTTP status code (for
|
||||
* {@code AWS}/Lambda integrations it is matched against the error message instead).
|
||||
*/
|
||||
private Response invokeHttpIntegration(GatewayResponseScope scope, String apiId, String httpMethod, String path,
|
||||
private Response invokeHttpIntegration(GatewayResponseScope scope, String region, String apiId,
|
||||
String httpMethod, String path,
|
||||
String proxy, String stageName, ApiGatewayResource resource,
|
||||
Integration integration, HttpHeaders headers,
|
||||
UriInfo uriInfo, byte[] body,
|
||||
@@ -625,7 +833,9 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String bodyStr = body != null && body.length > 0 ? new String(body, StandardCharsets.UTF_8) : null;
|
||||
boolean binaryRequest = isBinaryMediaType(region, apiId,
|
||||
headers.getHeaderString(HttpHeaders.CONTENT_TYPE));
|
||||
String bodyStr = templateBody(integration, body, binaryRequest);
|
||||
|
||||
Map<String, String> headerMap = new HashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {
|
||||
@@ -691,8 +901,7 @@ public class ApiGatewayExecuteController {
|
||||
target.setIntegrationUri(uri);
|
||||
target.setIntegrationMethod(integration.getHttpMethod());
|
||||
|
||||
byte[] payload = transformedBody != null
|
||||
? transformedBody.getBytes(StandardCharsets.UTF_8) : new byte[0];
|
||||
byte[] payload = outgoingPayload(integration, transformedBody);
|
||||
|
||||
io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx =
|
||||
new io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext(
|
||||
@@ -705,7 +914,7 @@ public class ApiGatewayExecuteController {
|
||||
LOG.debugv("execute-api: {0} {1}/{2}{3} → HTTP {4}", httpMethod, apiId, stageName, path, uri);
|
||||
|
||||
io.github.hectorvent.floci.services.apigatewayv2.proxy.ProxyResult result =
|
||||
httpProxyInvoker.invoke(target, ctx);
|
||||
httpProxyInvoker.invoke(target, ctx, proxyOptions(integration));
|
||||
|
||||
String responseBodyStr = result.body() != null
|
||||
? new String(result.body(), StandardCharsets.UTF_8) : "";
|
||||
@@ -730,8 +939,8 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
// For HTTP integrations selectionPattern is matched against the backend's status code.
|
||||
return mapIntegrationResponse(integration, String.valueOf(result.statusCode()),
|
||||
responseBodyStr, result.statusCode(), responseHeaders, responseMappingCtx,
|
||||
defaultContentType);
|
||||
responseBodyStr, result.body(), result.statusCode(), responseHeaders,
|
||||
responseMappingCtx, defaultContentType);
|
||||
}
|
||||
|
||||
private boolean isGatewayGeneratedProxyFailure(InvokeResult result) {
|
||||
@@ -1130,8 +1339,13 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
if (body != null && body.length > 0) {
|
||||
event.put("body", new String(body));
|
||||
event.put("isBase64Encoded", false);
|
||||
// A payload whose content type is in the API's binaryMediaTypes must reach the function
|
||||
// base64-encoded; reading it as a UTF-8 string corrupts it.
|
||||
boolean binary = isBinaryMediaType(region, apiId, headers.getHeaderString(HttpHeaders.CONTENT_TYPE));
|
||||
event.put("body", binary
|
||||
? Base64.getEncoder().encodeToString(body)
|
||||
: new String(body, StandardCharsets.UTF_8));
|
||||
event.put("isBase64Encoded", binary);
|
||||
} else {
|
||||
event.putNull("body");
|
||||
event.put("isBase64Encoded", false);
|
||||
@@ -1316,11 +1530,11 @@ public class ApiGatewayExecuteController {
|
||||
// Build VTL context
|
||||
Map<String, String> headerMap = new HashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {
|
||||
if (!e.getValue().isEmpty()) headerMap.put(e.getKey(), e.getValue().get(0));
|
||||
if (!e.getValue().isEmpty()) headerMap.put(e.getKey(), e.getValue().getFirst());
|
||||
}
|
||||
Map<String, String> queryMap = new HashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
|
||||
if (!e.getValue().isEmpty()) queryMap.put(e.getKey(), e.getValue().get(0));
|
||||
if (!e.getValue().isEmpty()) queryMap.put(e.getKey(), e.getValue().getFirst());
|
||||
}
|
||||
Map<String, String> pathMap = new HashMap<>();
|
||||
pathMap.putAll(extractPathParams(resource.getPath(), path));
|
||||
@@ -1513,12 +1727,13 @@ public class ApiGatewayExecuteController {
|
||||
"Unsupported Media Type");
|
||||
Map<String, String> requestTemplates = integration.getRequestTemplates();
|
||||
|
||||
RequestTemplateResult requestTemplateResult = new RequestTemplateResult(bodyStr != null ? bodyStr : "", incomingContentType, null);
|
||||
if (requestTemplates == null || requestTemplates.isEmpty()) {
|
||||
// No templates defined at all
|
||||
if ("NEVER".equalsIgnoreCase(integration.getPassthroughBehavior())) {
|
||||
return new RequestTemplateResult(null, null, unsupportedMediaType);
|
||||
}
|
||||
return new RequestTemplateResult(bodyStr != null ? bodyStr : "", incomingContentType, null);
|
||||
return requestTemplateResult;
|
||||
}
|
||||
|
||||
// Try exact match first, then without charset: "application/json; charset=utf-8" → "application/json"
|
||||
@@ -1544,7 +1759,7 @@ public class ApiGatewayExecuteController {
|
||||
return new RequestTemplateResult(null, null, unsupportedMediaType);
|
||||
}
|
||||
// WHEN_NO_MATCH (default) — passthrough
|
||||
return new RequestTemplateResult(bodyStr != null ? bodyStr : "", incomingContentType, null);
|
||||
return requestTemplateResult;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1562,6 +1777,16 @@ public class ApiGatewayExecuteController {
|
||||
Map<String, String> integrationResponseHeaders,
|
||||
VtlTemplateEngine.VtlContext responseMappingCtx,
|
||||
String defaultContentType) {
|
||||
return mapIntegrationResponse(integration, selectionMatchString, responseBodyStr, null,
|
||||
fallbackStatus, integrationResponseHeaders, responseMappingCtx, defaultContentType);
|
||||
}
|
||||
|
||||
private Response mapIntegrationResponse(Integration integration, String selectionMatchString,
|
||||
String responseBodyStr, byte[] rawResponseBody,
|
||||
int fallbackStatus,
|
||||
Map<String, String> integrationResponseHeaders,
|
||||
VtlTemplateEngine.VtlContext responseMappingCtx,
|
||||
String defaultContentType) {
|
||||
Map<String, IntegrationResponse> integrationResponses = integration.getIntegrationResponses();
|
||||
IntegrationResponse matchedResponse = null;
|
||||
IntegrationResponse defaultResponse = null;
|
||||
@@ -1617,8 +1842,25 @@ public class ApiGatewayExecuteController {
|
||||
finalStatus = templateResult.statusOverride();
|
||||
}
|
||||
|
||||
// Integration-response contentHandling is an output conversion, applied after templates:
|
||||
// CONVERT_TO_TEXT base64-encodes a binary payload for the caller, CONVERT_TO_BINARY decodes
|
||||
// a base64 text payload back to bytes.
|
||||
Object entity = finalBody;
|
||||
String responseContentHandling = matchedResponse != null ? matchedResponse.contentHandling() : null;
|
||||
if ("CONVERT_TO_TEXT".equalsIgnoreCase(responseContentHandling)) {
|
||||
byte[] source = templateResult == null && rawResponseBody != null
|
||||
? rawResponseBody : finalBody.getBytes(StandardCharsets.UTF_8);
|
||||
entity = Base64.getEncoder().encodeToString(source);
|
||||
} else if ("CONVERT_TO_BINARY".equalsIgnoreCase(responseContentHandling)) {
|
||||
try {
|
||||
entity = Base64.getDecoder().decode(finalBody.trim());
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("CONVERT_TO_BINARY: response body is not valid base64, returning it unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
Response.ResponseBuilder rb = Response.status(finalStatus)
|
||||
.entity(finalBody);
|
||||
.entity(entity);
|
||||
|
||||
String contentType = null;
|
||||
|
||||
@@ -2083,6 +2325,17 @@ public class ApiGatewayExecuteController {
|
||||
private final io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker httpProxyInvoker =
|
||||
new io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker();
|
||||
|
||||
/** REST integrations default to AWS's 29s and may opt out of backend TLS verification. */
|
||||
private static io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker.ProxyOptions
|
||||
proxyOptions(Integration integration) {
|
||||
long timeoutMillis = integration.getTimeoutInMillis() != null
|
||||
? integration.getTimeoutInMillis() : 29_000L;
|
||||
boolean insecure = integration.getTlsConfig() != null
|
||||
&& integration.getTlsConfig().isInsecureSkipVerification();
|
||||
return new io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker.ProxyOptions(
|
||||
java.time.Duration.ofMillis(timeoutMillis), insecure);
|
||||
}
|
||||
|
||||
private Response dispatchHttpProxyV2(io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration,
|
||||
Route route, String httpMethod, String path,
|
||||
HttpHeaders headers, UriInfo uriInfo, byte[] body,
|
||||
|
||||
+150
-14
@@ -34,6 +34,7 @@ import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.MethodSetting;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.VpcLink;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
|
||||
@@ -82,6 +83,7 @@ public class ApiGatewayService {
|
||||
private final StorageBackend<String, RequestValidator> requestValidatorStore;
|
||||
private final StorageBackend<String, GatewayResponse> gatewayResponseStore;
|
||||
private final StorageBackend<String, Model> modelStore;
|
||||
private final StorageBackend<String, VpcLink> vpcLinkStore;
|
||||
private final StorageBackend<String, Account> accountStore;
|
||||
private final StorageBackend<String, CustomDomain> domainStore;
|
||||
private final StorageBackend<String, BasePathMapping> basePathMappingStore;
|
||||
@@ -136,6 +138,9 @@ public class ApiGatewayService {
|
||||
this.modelStore = storageFactory.create("apigateway", "apigateway-models.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.vpcLinkStore = storageFactory.create("apigateway", "apigateway-vpclinks.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.accountStore = storageFactory.create("apigateway", "apigateway-account.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
@@ -178,22 +183,19 @@ public class ApiGatewayService {
|
||||
"Unsupported patch operation: " + opType, 400);
|
||||
}
|
||||
|
||||
switch (path) {
|
||||
case "/cloudwatchRoleArn" -> {
|
||||
if ("remove".equals(opType)) {
|
||||
copy.setCloudwatchRoleArn(null);
|
||||
} else {
|
||||
copy.setCloudwatchRoleArn(value);
|
||||
}
|
||||
if (path.equals("/cloudwatchRoleArn")) {
|
||||
if ("remove".equals(opType)) {
|
||||
copy.setCloudwatchRoleArn(null);
|
||||
} else {
|
||||
copy.setCloudwatchRoleArn(value);
|
||||
}
|
||||
default -> {
|
||||
if (path.startsWith("/throttleSettings")) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"/throttleSettings value cannot be changed this way", 400);
|
||||
}
|
||||
} else {
|
||||
if (path.startsWith("/throttleSettings")) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Unsupported patch path: " + path, 400);
|
||||
"/throttleSettings value cannot be changed this way", 400);
|
||||
}
|
||||
throw new AwsException("BadRequestException",
|
||||
"Unsupported patch path: " + path, 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -226,6 +228,11 @@ public class ApiGatewayService {
|
||||
api.setCreatedDate(System.currentTimeMillis() / 1000L);
|
||||
api.setTags(ReservedTags.stripApiGatewayReservedTags(tags));
|
||||
|
||||
if (request.get("binaryMediaTypes") instanceof List<?> binaryTypes) {
|
||||
api.setBinaryMediaTypes(binaryTypes.stream()
|
||||
.filter(String.class::isInstance).map(String.class::cast).toList());
|
||||
}
|
||||
|
||||
EndpointConfiguration endpointConfiguration = new EndpointConfiguration();
|
||||
if (request.get(EPC_KEY) instanceof Map<?, ?> epMap) {
|
||||
epMap.forEach((k, v) -> {
|
||||
@@ -529,6 +536,34 @@ public class ApiGatewayService {
|
||||
integration.setPassthroughBehavior((String) request.get("passthroughBehavior"));
|
||||
}
|
||||
|
||||
integration.setContentHandling((String) request.get("contentHandling"));
|
||||
integration.setCredentials((String) request.get("credentials"));
|
||||
integration.setCacheNamespace((String) request.get("cacheNamespace"));
|
||||
if (request.get("connectionType") != null) {
|
||||
integration.setConnectionType((String) request.get("connectionType"));
|
||||
}
|
||||
integration.setConnectionId((String) request.get("connectionId"));
|
||||
|
||||
if (request.get("timeoutInMillis") instanceof Number timeout) {
|
||||
// AWS accepts 50ms upward; the 29s ceiling applies only to edge-optimized APIs, and
|
||||
// Regional/private APIs (Floci's default) may exceed it, so only the floor is enforced.
|
||||
if (timeout.intValue() < 50) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Invalid timeout value: " + timeout.intValue(), 400);
|
||||
}
|
||||
integration.setTimeoutInMillis(timeout.intValue());
|
||||
}
|
||||
|
||||
if (request.get("cacheKeyParameters") instanceof List<?> cacheKeys) {
|
||||
integration.setCacheKeyParameters(cacheKeys.stream()
|
||||
.filter(String.class::isInstance).map(String.class::cast).toList());
|
||||
}
|
||||
|
||||
if (request.get("tlsConfig") instanceof Map<?, ?> tls) {
|
||||
integration.setTlsConfig(new Integration.TlsConfig(
|
||||
Boolean.TRUE.equals(tls.get("insecureSkipVerification"))));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> reqParams = (Map<String, String>) request.get("requestParameters");
|
||||
if (reqParams != null) integration.setRequestParameters(reqParams);
|
||||
@@ -574,7 +609,8 @@ public class ApiGatewayService {
|
||||
|
||||
IntegrationResponse ir = new IntegrationResponse(statusCode, selectionPattern,
|
||||
respParams != null ? respParams : new HashMap<>(),
|
||||
respTemplates != null ? respTemplates : new HashMap<>());
|
||||
respTemplates != null ? respTemplates : new HashMap<>(),
|
||||
(String) request.get("contentHandling"));
|
||||
|
||||
integration.getIntegrationResponses().put(statusCode, ir);
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId),
|
||||
@@ -734,6 +770,11 @@ public class ApiGatewayService {
|
||||
Map<String, String> variables = (Map<String, String>) request.get("variables");
|
||||
if (variables != null) stage.setVariables(variables);
|
||||
|
||||
if (Boolean.TRUE.equals(request.get("cacheClusterEnabled"))) {
|
||||
stage.setCacheClusterEnabled(true);
|
||||
stage.setCacheClusterSize((String) request.getOrDefault("cacheClusterSize", "0.5"));
|
||||
}
|
||||
|
||||
stageStore.put(stageKey(region, apiId, stageName), stage);
|
||||
LOG.infov("Created stage {0} for API {1}", stageName, apiId);
|
||||
return stage;
|
||||
@@ -3036,6 +3077,12 @@ public class ApiGatewayService {
|
||||
integrationRequest.put("httpMethod", integrationExt.get("httpMethod"));
|
||||
integrationRequest.put("uri", integrationExt.get("uri"));
|
||||
integrationRequest.put("passthroughBehavior", integrationExt.get("passthroughBehavior"));
|
||||
for (String field : List.of("contentHandling", "timeoutInMillis", "connectionType",
|
||||
"connectionId", "credentials", "cacheNamespace", "cacheKeyParameters", "tlsConfig")) {
|
||||
if (integrationExt.get(field) != null) {
|
||||
integrationRequest.put(field, integrationExt.get(field));
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> reqParams = (Map<String, String>) integrationExt.get("requestParameters");
|
||||
if (reqParams != null) integrationRequest.put("requestParameters", reqParams);
|
||||
@@ -3126,6 +3173,95 @@ public class ApiGatewayService {
|
||||
return region + "::" + domainName + "::" + basePath;
|
||||
}
|
||||
|
||||
// ──────────────────────────── VPC Links (v1) ────────────────────────────
|
||||
|
||||
public VpcLink createVpcLink(String region, Map<String, Object> request) {
|
||||
String name = (String) request.get("name");
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "Vpc link name must be specified", 400);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> targetArns = request.get("targetArns") instanceof List<?> arns
|
||||
? (List<String>) arns : List.of();
|
||||
if (targetArns.isEmpty()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"At least one target ARN must be specified", 400);
|
||||
}
|
||||
|
||||
VpcLink link = new VpcLink();
|
||||
link.setId(shortId(10));
|
||||
link.setName(name);
|
||||
link.setDescription((String) request.get("description"));
|
||||
link.setTargetArns(targetArns);
|
||||
// Floci has no real VPC to provision against, so the link is immediately usable rather
|
||||
// than transitioning PENDING → AVAILABLE as it does in AWS.
|
||||
link.setStatus("AVAILABLE");
|
||||
|
||||
if (request.get("tags") instanceof Map<?, ?> tags) {
|
||||
Map<String, String> stringTags = new HashMap<>();
|
||||
tags.forEach((k, v) -> {
|
||||
if (k != null && v != null) stringTags.put(k.toString(), v.toString());
|
||||
});
|
||||
link.setTags(stringTags);
|
||||
}
|
||||
|
||||
vpcLinkStore.put(vpcLinkKey(region, link.getId()), link);
|
||||
LOG.infov("Created VPC Link: {0} ({1}) in {2}", link.getName(), link.getId(), region);
|
||||
return link;
|
||||
}
|
||||
|
||||
public VpcLink getVpcLink(String region, String vpcLinkId) {
|
||||
return vpcLinkStore.get(vpcLinkKey(region, vpcLinkId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid VPC link identifier specified", 404));
|
||||
}
|
||||
|
||||
public List<VpcLink> getVpcLinks(String region) {
|
||||
return vpcLinkStore.scan(k -> k.startsWith(region + "::"));
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS's patch-operation table for a VPC link supports only {@code replace}, and only on
|
||||
* {@code /name} and {@code /description}. Applying anything else is an error rather than a
|
||||
* no-op: silently accepting {@code op=remove,path=/name} would have set the name to the
|
||||
* supplied value, and silently ignoring an unknown path would report success for a change that
|
||||
* never happened.
|
||||
*/
|
||||
public VpcLink updateVpcLink(String region, String vpcLinkId, List<Map<String, String>> patchOperations) {
|
||||
VpcLink link = getVpcLink(region, vpcLinkId);
|
||||
if (patchOperations != null) {
|
||||
for (Map<String, String> op : patchOperations) {
|
||||
String operation = op.get("op");
|
||||
String path = op.get("path");
|
||||
String value = op.get("value");
|
||||
if (!"replace".equals(operation)) {
|
||||
throw new AwsException("BadRequestException", "Unsupported operation", 400);
|
||||
}
|
||||
if (path == null) {
|
||||
throw new AwsException("BadRequestException", "Missing path", 400);
|
||||
}
|
||||
switch (path) {
|
||||
case "/name" -> link.setName(value);
|
||||
case "/description" -> link.setDescription(value);
|
||||
default -> throw new AwsException("BadRequestException",
|
||||
"Invalid patch path '" + path + "' specified for op 'replace'. "
|
||||
+ "Must be one of: [/name, /description]", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
vpcLinkStore.put(vpcLinkKey(region, vpcLinkId), link);
|
||||
return link;
|
||||
}
|
||||
|
||||
public void deleteVpcLink(String region, String vpcLinkId) {
|
||||
getVpcLink(region, vpcLinkId);
|
||||
vpcLinkStore.delete(vpcLinkKey(region, vpcLinkId));
|
||||
}
|
||||
|
||||
private String vpcLinkKey(String region, String vpcLinkId) {
|
||||
return region + "::" + vpcLinkId;
|
||||
}
|
||||
|
||||
private static String shortId(int length) {
|
||||
return UUID.randomUUID().toString().replace("-", "").substring(0, length);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -15,10 +17,103 @@ public class Integration {
|
||||
private String uri;
|
||||
private String httpMethod;
|
||||
private String passthroughBehavior = "WHEN_NO_MATCH"; // WHEN_NO_MATCH, WHEN_NO_TEMPLATES, NEVER
|
||||
private String contentHandling; // CONVERT_TO_BINARY, CONVERT_TO_TEXT, or null to pass through
|
||||
private Integer timeoutInMillis; // 50–29000; AWS caps REST integrations at 29s
|
||||
private String connectionType = "INTERNET"; // INTERNET or VPC_LINK
|
||||
private String connectionId; // VpcLink id when connectionType is VPC_LINK
|
||||
private String credentials; // IAM role ARN assumed for AWS integrations
|
||||
private String cacheNamespace;
|
||||
private List<String> cacheKeyParameters = new ArrayList<>();
|
||||
private TlsConfig tlsConfig;
|
||||
private Map<String, String> requestParameters = new HashMap<>(); // integration.request.* → method.request.*
|
||||
private Map<String, String> requestTemplates = new HashMap<>();
|
||||
private Map<String, IntegrationResponse> integrationResponses = new HashMap<>();
|
||||
|
||||
/** Integration TLS settings. {@code insecureSkipVerification} skips backend cert validation. */
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@RegisterForReflection
|
||||
public static class TlsConfig {
|
||||
private boolean insecureSkipVerification;
|
||||
|
||||
public TlsConfig() {}
|
||||
|
||||
public TlsConfig(boolean insecureSkipVerification) {
|
||||
this.insecureSkipVerification = insecureSkipVerification;
|
||||
}
|
||||
|
||||
public boolean isInsecureSkipVerification() {
|
||||
return insecureSkipVerification;
|
||||
}
|
||||
|
||||
public void setInsecureSkipVerification(boolean insecureSkipVerification) {
|
||||
this.insecureSkipVerification = insecureSkipVerification;
|
||||
}
|
||||
}
|
||||
|
||||
public String getContentHandling() {
|
||||
return contentHandling;
|
||||
}
|
||||
|
||||
public void setContentHandling(String contentHandling) {
|
||||
this.contentHandling = contentHandling;
|
||||
}
|
||||
|
||||
public Integer getTimeoutInMillis() {
|
||||
return timeoutInMillis;
|
||||
}
|
||||
|
||||
public void setTimeoutInMillis(Integer timeoutInMillis) {
|
||||
this.timeoutInMillis = timeoutInMillis;
|
||||
}
|
||||
|
||||
public String getConnectionType() {
|
||||
return connectionType;
|
||||
}
|
||||
|
||||
public void setConnectionType(String connectionType) {
|
||||
this.connectionType = connectionType != null ? connectionType : "INTERNET";
|
||||
}
|
||||
|
||||
public String getConnectionId() {
|
||||
return connectionId;
|
||||
}
|
||||
|
||||
public void setConnectionId(String connectionId) {
|
||||
this.connectionId = connectionId;
|
||||
}
|
||||
|
||||
public String getCredentials() {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
public void setCredentials(String credentials) {
|
||||
this.credentials = credentials;
|
||||
}
|
||||
|
||||
public String getCacheNamespace() {
|
||||
return cacheNamespace;
|
||||
}
|
||||
|
||||
public void setCacheNamespace(String cacheNamespace) {
|
||||
this.cacheNamespace = cacheNamespace;
|
||||
}
|
||||
|
||||
public List<String> getCacheKeyParameters() {
|
||||
return cacheKeyParameters;
|
||||
}
|
||||
|
||||
public void setCacheKeyParameters(List<String> cacheKeyParameters) {
|
||||
this.cacheKeyParameters = cacheKeyParameters != null ? cacheKeyParameters : new ArrayList<>();
|
||||
}
|
||||
|
||||
public TlsConfig getTlsConfig() {
|
||||
return tlsConfig;
|
||||
}
|
||||
|
||||
public void setTlsConfig(TlsConfig tlsConfig) {
|
||||
this.tlsConfig = tlsConfig;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
+11
-2
@@ -12,5 +12,14 @@ public record IntegrationResponse(
|
||||
String statusCode,
|
||||
String selectionPattern,
|
||||
Map<String, String> responseParameters,
|
||||
Map<String, String> responseTemplates
|
||||
) {}
|
||||
Map<String, String> responseTemplates,
|
||||
/** CONVERT_TO_BINARY, CONVERT_TO_TEXT, or null to pass the payload through unchanged. */
|
||||
String contentHandling
|
||||
) {
|
||||
/** Backwards-compatible factory for responses that specify no content handling. */
|
||||
public IntegrationResponse(String statusCode, String selectionPattern,
|
||||
Map<String, String> responseParameters,
|
||||
Map<String, String> responseTemplates) {
|
||||
this(statusCode, selectionPattern, responseParameters, responseTemplates, null);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -18,6 +20,16 @@ public class RestApi {
|
||||
private String rootResourceId;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private EndpointConfiguration endpointConfiguration;
|
||||
/** Content types treated as binary when applying integration contentHandling. */
|
||||
private List<String> binaryMediaTypes = new ArrayList<>();
|
||||
|
||||
public List<String> getBinaryMediaTypes() {
|
||||
return binaryMediaTypes;
|
||||
}
|
||||
|
||||
public void setBinaryMediaTypes(List<String> binaryMediaTypes) {
|
||||
this.binaryMediaTypes = binaryMediaTypes != null ? binaryMediaTypes : new ArrayList<>();
|
||||
}
|
||||
|
||||
|
||||
public String getId() {
|
||||
|
||||
@@ -16,6 +16,35 @@ public class Stage {
|
||||
private String description;
|
||||
private Map<String, String> variables = new HashMap<>();
|
||||
private Map<String, MethodSetting> methodSettings = new HashMap<>();
|
||||
/** Stage-level cache switch; a method's own cachingEnabled only applies when this is on. */
|
||||
private boolean cacheClusterEnabled;
|
||||
private String cacheClusterSize;
|
||||
private String cacheClusterStatus = "NOT_AVAILABLE";
|
||||
|
||||
public boolean isCacheClusterEnabled() {
|
||||
return cacheClusterEnabled;
|
||||
}
|
||||
|
||||
public void setCacheClusterEnabled(boolean cacheClusterEnabled) {
|
||||
this.cacheClusterEnabled = cacheClusterEnabled;
|
||||
this.cacheClusterStatus = cacheClusterEnabled ? "AVAILABLE" : "NOT_AVAILABLE";
|
||||
}
|
||||
|
||||
public String getCacheClusterSize() {
|
||||
return cacheClusterSize;
|
||||
}
|
||||
|
||||
public void setCacheClusterSize(String cacheClusterSize) {
|
||||
this.cacheClusterSize = cacheClusterSize;
|
||||
}
|
||||
|
||||
public String getCacheClusterStatus() {
|
||||
return cacheClusterStatus;
|
||||
}
|
||||
|
||||
public void setCacheClusterStatus(String cacheClusterStatus) {
|
||||
this.cacheClusterStatus = cacheClusterStatus;
|
||||
}
|
||||
private long createdDate;
|
||||
private long lastUpdatedDate;
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A REST (v1) VPC Link: the private connection between an API and a Network Load Balancer, named
|
||||
* by an integration's {@code connectionId} when its {@code connectionType} is {@code VPC_LINK}.
|
||||
*
|
||||
* <p>Distinct from the v2 {@code VpcLink}, which is described by subnets and security groups rather
|
||||
* than by target ARNs.
|
||||
*/
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@RegisterForReflection
|
||||
public class VpcLink {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String description;
|
||||
private List<String> targetArns = new ArrayList<>();
|
||||
/** PENDING, AVAILABLE, DELETING or FAILED. */
|
||||
private String status = "AVAILABLE";
|
||||
private String statusMessage;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public List<String> getTargetArns() {
|
||||
return targetArns;
|
||||
}
|
||||
|
||||
public void setTargetArns(List<String> targetArns) {
|
||||
this.targetArns = targetArns != null ? targetArns : new ArrayList<>();
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getStatusMessage() {
|
||||
return statusMessage;
|
||||
}
|
||||
|
||||
public void setStatusMessage(String statusMessage) {
|
||||
this.statusMessage = statusMessage;
|
||||
}
|
||||
|
||||
public Map<String, String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags != null ? tags : new HashMap<>();
|
||||
}
|
||||
}
|
||||
+223
-5
@@ -3,6 +3,11 @@ package io.github.hectorvent.floci.services.apigatewayv2.proxy;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -15,6 +20,15 @@ import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.CertPath;
|
||||
import java.security.cert.CertPathValidator;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.PKIXParameters;
|
||||
import java.security.cert.TrustAnchor;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -48,6 +62,20 @@ public class HttpProxyInvoker {
|
||||
private static final Set<String> RESTRICTED = Set.of(
|
||||
"connection", "content-length", "expect", "host", "upgrade");
|
||||
|
||||
/**
|
||||
* Per-integration transport settings.
|
||||
*
|
||||
* @param timeout how long to wait for the backend response
|
||||
* @param insecureTls stop requiring the backend certificate to be issued by a trusted
|
||||
* certificate authority, for an integration configured with
|
||||
* {@code tlsConfig.insecureSkipVerification}. Expiration, hostname and the
|
||||
* presence of a root certificate authority are still checked, as in AWS.
|
||||
*/
|
||||
public record ProxyOptions(Duration timeout, boolean insecureTls) {
|
||||
/** HTTP API (v2) defaults: 30s, certificates verified. */
|
||||
public static final ProxyOptions DEFAULTS = new ProxyOptions(Duration.ofSeconds(30), false);
|
||||
}
|
||||
|
||||
// Pin to HTTP/1.1: the default HTTP_2 setting attempts cleartext-HTTP/2 negotiation
|
||||
// against http:// backends, which hangs against plain HTTP/1.1 servers (notably the
|
||||
// in-JVM Vertx HttpServer used by ELBv2 listeners for HttpAlbIntegration).
|
||||
@@ -57,9 +85,197 @@ public class HttpProxyInvoker {
|
||||
.followRedirects(HttpClient.Redirect.NEVER)
|
||||
.build();
|
||||
|
||||
/** Built on first use: an integration opting out of TLS verification is the exception. */
|
||||
private volatile HttpClient insecureClient;
|
||||
|
||||
private HttpClient clientFor(ProxyOptions options) {
|
||||
if (!options.insecureTls()) return client;
|
||||
HttpClient existing = insecureClient;
|
||||
if (existing != null) return existing;
|
||||
synchronized (this) {
|
||||
if (insecureClient == null) {
|
||||
insecureClient = buildInsecureClient();
|
||||
}
|
||||
return insecureClient;
|
||||
}
|
||||
}
|
||||
|
||||
private HttpClient buildInsecureClient() {
|
||||
try {
|
||||
TrustManager[] trustManagers = {new CaIssuanceSkippingTrustManager()};
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(null, trustManagers, new SecureRandom());
|
||||
// Hostname verification stays on. insecureSkipVerification waives only the "issued by a
|
||||
// supported CA" check; AWS documents that it still verifies the hostname, so a
|
||||
// certificate for the wrong host must fail here exactly as it would in AWS. Setting this
|
||||
// explicitly matters: SSLParameters defaults the algorithm to null, so handing
|
||||
// HttpClient a fresh instance without it would silently disable the check.
|
||||
SSLParameters sslParameters = new SSLParameters();
|
||||
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
|
||||
return HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.followRedirects(HttpClient.Redirect.NEVER)
|
||||
.sslContext(sslContext)
|
||||
.sslParameters(sslParameters)
|
||||
.build();
|
||||
} catch (GeneralSecurityException e) {
|
||||
LOG.warnv("Could not build insecure TLS client, falling back to verified: {0}", e.getMessage());
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The trust behaviour {@code tlsConfig.insecureSkipVerification} actually buys in AWS: API
|
||||
* Gateway stops checking that the endpoint's certificate was issued by a supported certificate
|
||||
* authority, so private-CA and self-signed certificates are accepted, but it still performs
|
||||
* basic certificate validation covering the expiration date, the hostname and the presence of a
|
||||
* root certificate authority. A trust-all manager is looser than that, and looser in the
|
||||
* direction that hides bugs: a backend whose certificate has expired, or whose chain is broken,
|
||||
* would work locally and fail in AWS.
|
||||
*
|
||||
* <p>For anything beyond a lone self-signed certificate the chain goes through the platform's
|
||||
* PKIX validator, anchored on the chain's own root, so the rules AWS keeps for a private
|
||||
* certificate authority (cA=true together with keyUsage keyCertSign, pathLenConstraint, and
|
||||
* name constraints on the intermediates) are enforced by the code that already implements them
|
||||
* correctly. The root's own constraints are checked here instead, because PKIX treats a trust
|
||||
* anchor as given and never reads its extensions.
|
||||
*
|
||||
* <p>Hostname verification is not done here, it is the SSL engine's endpoint identification.
|
||||
*/
|
||||
private static final class CaIssuanceSkippingTrustManager implements X509TrustManager {
|
||||
|
||||
/** X509v3 Name Constraints, RFC 5280 §4.2.1.10. */
|
||||
private static final String NAME_CONSTRAINTS_OID = "2.5.29.30";
|
||||
|
||||
|
||||
/** Position of {@code keyCertSign} in the KeyUsage bit string, RFC 5280 §4.2.1.3. */
|
||||
private static final int KEY_CERT_SIGN_BIT = 5;
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
||||
// This manager only ever verifies a backend as a client would; it never authenticates
|
||||
// an inbound peer. Accepting one silently would be a genuine trust-all.
|
||||
throw new CertificateException("client certificates are not accepted by this proxy");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
||||
if (chain == null || chain.length == 0) {
|
||||
throw new CertificateException("backend presented no certificate");
|
||||
}
|
||||
|
||||
// Expiration (and not-yet-valid), for every certificate in the chain. PKIX exempts a
|
||||
// trust anchor from this, and AWS does not, so it is checked here rather than left to
|
||||
// the validator below.
|
||||
for (X509Certificate certificate : chain) {
|
||||
certificate.checkValidity();
|
||||
}
|
||||
|
||||
// The chain has to terminate in a self-signed certificate: that trailing certificate is
|
||||
// the "root certificate authority" whose presence AWS still requires. What is skipped is
|
||||
// only whether that root is one we trust.
|
||||
X509Certificate root = chain[chain.length - 1];
|
||||
if (!root.getIssuerX500Principal().equals(root.getSubjectX500Principal())) {
|
||||
throw new CertificateException(
|
||||
"certificate chain does not terminate in a root certificate authority: "
|
||||
+ root.getSubjectX500Principal());
|
||||
}
|
||||
|
||||
if (chain.length == 1) {
|
||||
// A lone self-signed certificate 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: requiring them would reject what AWS documents as supported.
|
||||
// The signature still has to verify, so the certificate cannot have been tampered
|
||||
// with in flight.
|
||||
verifySignedBy(root, root);
|
||||
return;
|
||||
}
|
||||
|
||||
// A longer chain means a real certificate authority issued the leaf, and AWS states two
|
||||
// constraints such a root "must satisfy": the x509 extension keyUsage must have
|
||||
// keyCertSign, and the x509 extension basicConstraints must have CA:TRUE. These are
|
||||
// checked here rather than left to the validator below, which treats the trust anchor
|
||||
// as given and never looks at its extensions.
|
||||
//
|
||||
// A root carrying no keyUsage extension at all fails the first of those. Generic PKIX
|
||||
// would read the missing extension as leaving the key unrestricted (RFC 5280 §4.2.1.3),
|
||||
// but API Gateway states the extension as a requirement on the root rather than a bit
|
||||
// to inspect when present, so the looser reading would accept a certificate authority
|
||||
// that real API Gateway turns away.
|
||||
if (root.getBasicConstraints() < 0) {
|
||||
throw new CertificateException(
|
||||
"root certificate is not a certificate authority (BasicConstraints cA=false): "
|
||||
+ root.getSubjectX500Principal());
|
||||
}
|
||||
boolean[] keyUsage = root.getKeyUsage();
|
||||
if (keyUsage == null) {
|
||||
throw new CertificateException(
|
||||
"root certificate carries no keyUsage extension, which API Gateway requires "
|
||||
+ "on a private certificate authority: " + root.getSubjectX500Principal());
|
||||
}
|
||||
if (keyUsage.length <= KEY_CERT_SIGN_BIT || !keyUsage[KEY_CERT_SIGN_BIT]) {
|
||||
throw new CertificateException(
|
||||
"root certificate is not permitted to sign certificates "
|
||||
+ "(keyUsage without keyCertSign): " + root.getSubjectX500Principal());
|
||||
}
|
||||
|
||||
// Name constraints on the root itself cannot be honoured: the platform validator refuses
|
||||
// to process constraints handed to it with a trust anchor, as opposed to ones it reads
|
||||
// from a certificate inside the path, so a root carrying them can be rejected but never
|
||||
// evaluated. Rejecting is both 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.
|
||||
// Constraints on an intermediate sit in the path proper and are enforced normally.
|
||||
if (root.getExtensionValue(NAME_CONSTRAINTS_OID) != null) {
|
||||
throw new CertificateException(
|
||||
"root certificate carries X509v3 Name Constraints, which cannot be enforced "
|
||||
+ "for a privately trusted root: " + root.getSubjectX500Principal());
|
||||
}
|
||||
|
||||
// The rest of the rules AWS keeps are the ordinary PKIX ones. Handing them to the
|
||||
// platform validator, with this chain's own root as the trust anchor, is precisely the
|
||||
// "stop checking that the root is one we trust, keep checking everything else"
|
||||
// semantic: chain signatures, basicConstraints and keyCertSign on any intermediates,
|
||||
// pathLenConstraint, and the X509v3 name constraints AWS documents it enforces.
|
||||
try {
|
||||
CertPath path = CertificateFactory.getInstance("X.509")
|
||||
.generateCertPath(List.of(chain).subList(0, chain.length - 1));
|
||||
PKIXParameters parameters = new PKIXParameters(
|
||||
Set.of(new TrustAnchor(root, null)));
|
||||
// Revocation would mean CRL or OCSP fetches for an issuer we are deliberately not
|
||||
// trusting: AWS lists expiration, hostname and the presence of a root as what
|
||||
// survives insecureSkipVerification, not revocation.
|
||||
parameters.setRevocationEnabled(false);
|
||||
CertPathValidator.getInstance("PKIX").validate(path, parameters);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new CertificateException("certificate chain is not valid: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void verifySignedBy(X509Certificate certificate, X509Certificate issuer)
|
||||
throws CertificateException {
|
||||
try {
|
||||
certificate.verify(issuer.getPublicKey());
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new CertificateException("certificate chain signature does not verify: "
|
||||
+ e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return new X509Certificate[0];
|
||||
}
|
||||
}
|
||||
|
||||
private final RequestParameterMapper mapper = new RequestParameterMapper(new ContextValueResolver());
|
||||
|
||||
public ProxyResult invoke(Integration integration, RequestContext ctx) {
|
||||
return invoke(integration, ctx, ProxyOptions.DEFAULTS);
|
||||
}
|
||||
|
||||
public ProxyResult invoke(Integration integration, RequestContext ctx, ProxyOptions options) {
|
||||
// 1. Resolve target URL from IntegrationUri template + captured path params
|
||||
String resolvedUrl = PathTemplateResolver.resolve(integration.getIntegrationUri(), ctx.pathParams());
|
||||
|
||||
@@ -94,7 +310,7 @@ public class HttpProxyInvoker {
|
||||
String finalUrl = buildFinalUrl(builder);
|
||||
if (hasHeader(builder, "Host") && finalUrl.startsWith("http://")) {
|
||||
try {
|
||||
return invokeHttpWithHostOverride(finalUrl, method, builder);
|
||||
return invokeHttpWithHostOverride(finalUrl, method, builder, options.timeout());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("HTTP_PROXY backend call failed: {0}", e.getMessage());
|
||||
return errorResult("Bad Gateway: " + e.getMessage());
|
||||
@@ -105,7 +321,7 @@ public class HttpProxyInvoker {
|
||||
try {
|
||||
hrb = HttpRequest.newBuilder()
|
||||
.uri(URI.create(finalUrl))
|
||||
.timeout(Duration.ofSeconds(30));
|
||||
.timeout(options.timeout());
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.warnv("HTTP_PROXY: invalid target URL: {0}", e.getMessage());
|
||||
return errorResult("Bad Gateway: invalid target URL: " + e.getMessage());
|
||||
@@ -130,7 +346,8 @@ public class HttpProxyInvoker {
|
||||
}
|
||||
|
||||
try {
|
||||
HttpResponse<byte[]> resp = client.send(hrb.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
HttpResponse<byte[]> resp =
|
||||
clientFor(options).send(hrb.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
Map<String, List<String>> respHeaders = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : resp.headers().map().entrySet()) {
|
||||
if (HOP_BY_HOP.contains(e.getKey().toLowerCase())) continue;
|
||||
@@ -156,7 +373,8 @@ public class HttpProxyInvoker {
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ProxyResult invokeHttpWithHostOverride(String finalUrl, String method, ProxyRequestBuilder builder)
|
||||
private static ProxyResult invokeHttpWithHostOverride(String finalUrl, String method,
|
||||
ProxyRequestBuilder builder, Duration timeout)
|
||||
throws IOException {
|
||||
URI uri = URI.create(finalUrl);
|
||||
int port = uri.getPort() == -1 ? 80 : uri.getPort();
|
||||
@@ -170,7 +388,7 @@ public class HttpProxyInvoker {
|
||||
|
||||
try (Socket socket = new Socket()) {
|
||||
socket.connect(new InetSocketAddress(uri.getHost(), port), 10_000);
|
||||
socket.setSoTimeout(30_000);
|
||||
socket.setSoTimeout((int) Math.min(timeout.toMillis(), Integer.MAX_VALUE));
|
||||
|
||||
OutputStream out = socket.getOutputStream();
|
||||
byte[] body = builder.body() == null ? new byte[0] : builder.body();
|
||||
|
||||
Reference in new issue
Block a user