mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(cloudfront): stream origin responses and viewer request bodies (#5278)
A distribution read every origin response whole before answering the viewer: an S3 origin's object through getObject, a custom origin's body through the HTTP client into a byte array. A viewer's POST, PUT, PATCH or DELETE body was likewise read whole before it was forwarded. So an object or upload of about 2 GiB or more failed, and a smaller one could run the heap out of memory. S3 origins now open the object as a stream, the snapshot GetObject serves, and custom origins return their response before its body is read; either body is written to the viewer as it arrives, with its Content-Length, or chunked as the origin sent it. A viewer's body is streamed to the custom origin with its Content-Length, or chunked when the viewer sent it chunked or, as HTTP/2 allows, with no length. An origin response closed before its end, as when the viewer goes away or a custom error page replaces it, cancels its request instead of reading the rest of the body to reuse the connection. Since a streamed response holds its connection for the whole transfer, one origin may now use the whole connection pool, as CloudFront sets no per-origin limit.
This commit is contained in:
1 parent
f5d48bb5e0
commit
1f1d4f94dd
8 files changed
+774
-169
No files matched your search
+151
-78
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudfront;
|
||||
import io.github.hectorvent.floci.core.common.SsrfProtection;
|
||||
import org.apache.hc.client5.http.DnsResolver;
|
||||
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.ConnectionConfig;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.config.TlsConfig;
|
||||
@@ -13,32 +14,32 @@ import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
||||
import org.apache.hc.client5.http.impl.routing.DefaultRoutePlanner;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.client5.http.routing.RoutingSupport;
|
||||
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpVersion;
|
||||
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
|
||||
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
|
||||
import org.apache.hc.core5.http2.HttpVersionPolicy;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.net.UnknownHostException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpHeaders;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
@@ -51,8 +52,11 @@ import java.util.stream.Collectors;
|
||||
*/
|
||||
final class CloudFrontOriginHttpClient implements AutoCloseable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFrontOriginHttpClient.class);
|
||||
|
||||
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
|
||||
private static final Duration RESPONSE_TIMEOUT = Duration.ofSeconds(30);
|
||||
static final int MAX_CONNECTIONS = 100;
|
||||
|
||||
private final CloseableHttpClient client;
|
||||
|
||||
@@ -86,8 +90,10 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
|
||||
.setDnsResolver(validatingResolver)
|
||||
.setDefaultConnectionConfig(connectionConfig)
|
||||
.setDefaultTlsConfig(tlsConfig)
|
||||
.setMaxConnTotal(100)
|
||||
.setMaxConnPerRoute(20);
|
||||
// CloudFront has no per-origin connection limit, and a streamed response holds its
|
||||
// connection for the whole transfer, so one origin may use the whole pool.
|
||||
.setMaxConnTotal(MAX_CONNECTIONS)
|
||||
.setMaxConnPerRoute(MAX_CONNECTIONS);
|
||||
if (sslContext != null) {
|
||||
connectionManagerBuilder.setTlsSocketStrategy(ClientTlsStrategyBuilder.create()
|
||||
.setSslContext(sslContext)
|
||||
@@ -113,39 +119,139 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
|
||||
.build();
|
||||
}
|
||||
|
||||
HttpResponse<byte[]> send(HttpRequest request, HttpResponse.BodyHandler<byte[]> bodyHandler)
|
||||
throws IOException, InterruptedException {
|
||||
return send(request, Map.of(), bodyHandler);
|
||||
}
|
||||
|
||||
HttpResponse<byte[]> send(HttpRequest request, Map<String, String> originHeaders,
|
||||
HttpResponse.BodyHandler<byte[]> bodyHandler)
|
||||
throws IOException, InterruptedException {
|
||||
return send(request, List.of(), originHeaders, null, bodyHandler);
|
||||
/**
|
||||
* An origin response whose body has not been read. The caller reads {@code body} as it needs it
|
||||
* and closes it, which releases the connection. {@code contentLength} is the length the body
|
||||
* arrives with, {@code -1} when it comes chunked or with none.
|
||||
*/
|
||||
record OpenResponse(int statusCode, HttpHeaders headers, long contentLength, InputStream body) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends {@code request} with {@code forwardedHeaders} added and {@code requestBody} as its
|
||||
* entity, or with no entity when it is {@code null}. Each origin header replaces every
|
||||
* same-named request or forwarded header, so a viewer cannot repeat a header to smuggle its own
|
||||
* value past an origin custom header. The request's own body publisher must be empty: the body
|
||||
* travels as bytes so its {@code Content-Length} is exact.
|
||||
* Sends {@code request} with {@code forwardedHeaders} added and {@code requestBody}, when it is
|
||||
* not {@code null}, streamed as the entity, with {@code requestBodyLength} as its
|
||||
* {@code Content-Length}, or chunked when the length is negative. Each origin header replaces
|
||||
* every same-named request or forwarded header, so a viewer cannot repeat a header to smuggle its
|
||||
* own value past an origin custom header. The response comes back before its body is read, so
|
||||
* neither body has to fit in memory.
|
||||
*/
|
||||
HttpResponse<byte[]> send(HttpRequest request,
|
||||
List<CloudFrontOriginRequestBuilder.Header> forwardedHeaders,
|
||||
Map<String, String> originHeaders, byte[] requestBody,
|
||||
HttpResponse.BodyHandler<byte[]> bodyHandler)
|
||||
OpenResponse open(HttpRequest request,
|
||||
List<CloudFrontOriginRequestBuilder.Header> forwardedHeaders,
|
||||
Map<String, String> originHeaders, InputStream requestBody, long requestBodyLength)
|
||||
throws IOException, InterruptedException {
|
||||
// No entity content type: the caller's Content-Type request header is sent as is.
|
||||
HttpUriRequestBase originRequest = originRequest(request, forwardedHeaders, originHeaders,
|
||||
requestBody != null ? new InputStreamEntity(requestBody, requestBodyLength, null) : null);
|
||||
ClassicHttpResponse response;
|
||||
try {
|
||||
response = client.executeOpen(RoutingSupport.determineHost(originRequest), originRequest, context(request));
|
||||
} catch (HttpException e) {
|
||||
throw new IOException("CloudFront origin request has no target host", e);
|
||||
} catch (InterruptedIOException e) {
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
throw new InterruptedException("CloudFront origin request interrupted");
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
InputStream body = entity != null
|
||||
? new ResponseBody(entity.getContent(), originRequest, response)
|
||||
: new ResponseBody(InputStream.nullInputStream(), null, response);
|
||||
// The entity's length follows the framing the body arrives with; with no entity, as for a
|
||||
// HEAD, the header describes the body a GET would get.
|
||||
long contentLength = entity != null ? entity.getContentLength() : headerContentLength(response);
|
||||
return new OpenResponse(response.getCode(), responseHeaders(response), contentLength, body);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
originRequest.cancel();
|
||||
closeAborted(response);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An origin response body that releases its connection when it is closed. Closed at its end, the
|
||||
* connection goes back to the pool. Closed before its end, as when a viewer goes away or a custom
|
||||
* error page replaces it, the request is cancelled and the connection closed, since closing the
|
||||
* response normally reads the rest of the body to reuse the connection, however long it is.
|
||||
*/
|
||||
private static final class ResponseBody extends FilterInputStream {
|
||||
|
||||
private final HttpUriRequestBase request;
|
||||
private final ClassicHttpResponse response;
|
||||
private boolean finished;
|
||||
|
||||
ResponseBody(InputStream content, HttpUriRequestBase request, ClassicHttpResponse response) {
|
||||
super(content);
|
||||
this.request = request;
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
int b = super.read();
|
||||
finished |= b < 0;
|
||||
return b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] buffer, int offset, int length) throws IOException {
|
||||
int read = super.read(buffer, offset, length);
|
||||
finished |= read < 0;
|
||||
return read;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
if (finished || request == null) {
|
||||
try {
|
||||
super.close();
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
request.cancel();
|
||||
closeAborted(response);
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes a response whose request was cancelled; reading the rest of it fails, as it should. */
|
||||
private static void closeAborted(ClassicHttpResponse response) {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv("Closed an unfinished CloudFront origin response: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static long headerContentLength(ClassicHttpResponse response) {
|
||||
Header header = response.getFirstHeader("Content-Length");
|
||||
if (header == null) {
|
||||
return -1;
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(header.getValue().trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("Ignoring an invalid custom-origin Content-Length: {0}", e.getMessage());
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private HttpUriRequestBase originRequest(HttpRequest request,
|
||||
List<CloudFrontOriginRequestBuilder.Header> forwardedHeaders,
|
||||
Map<String, String> originHeaders, HttpEntity entity)
|
||||
throws IOException, InterruptedException {
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
throw new InterruptedException("CloudFront origin request interrupted");
|
||||
}
|
||||
if (request.bodyPublisher().filter(publisher -> publisher.contentLength() != 0).isPresent()) {
|
||||
throw new IOException("CloudFront origin request bodies must be passed as bytes");
|
||||
throw new IOException("CloudFront origin request bodies must be passed separately");
|
||||
}
|
||||
|
||||
ClassicRequestBuilder builder = ClassicRequestBuilder.create(request.method())
|
||||
.setUri(request.uri())
|
||||
.setVersion(HttpVersion.HTTP_1_1);
|
||||
// A request that can be cancelled, so a response closed before its end is not read to the end.
|
||||
HttpUriRequestBase builder = new HttpUriRequestBase(request.method(), request.uri());
|
||||
builder.setVersion(HttpVersion.HTTP_1_1);
|
||||
Set<String> replaced = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
|
||||
replaced.addAll(originHeaders.keySet());
|
||||
request.headers().map().forEach((name, values) -> {
|
||||
@@ -159,11 +265,13 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
originHeaders.forEach(builder::addHeader);
|
||||
if (requestBody != null) {
|
||||
// No entity content type: the caller's Content-Type request header is sent as is.
|
||||
builder.setEntity(new ByteArrayEntity(requestBody, null));
|
||||
if (entity != null) {
|
||||
builder.setEntity(entity);
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
|
||||
private static HttpClientContext context(HttpRequest request) {
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
Duration responseTimeout = request.timeout().orElse(RESPONSE_TIMEOUT);
|
||||
context.setRequestConfig(RequestConfig.custom()
|
||||
@@ -173,28 +281,16 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
|
||||
.setContentCompressionEnabled(false)
|
||||
.setProtocolUpgradeEnabled(false)
|
||||
.build());
|
||||
return context;
|
||||
}
|
||||
|
||||
try {
|
||||
return client.execute(builder.build(), context, response -> {
|
||||
Map<String, List<String>> responseHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
for (Header header : response.getHeaders()) {
|
||||
responseHeaders.computeIfAbsent(header.getName(), ignored -> new ArrayList<>())
|
||||
.add(header.getValue());
|
||||
}
|
||||
byte[] body = response.getEntity() != null
|
||||
? EntityUtils.toByteArray(response.getEntity())
|
||||
: new byte[0];
|
||||
return new PinnedHttpResponse(
|
||||
response.getCode(), request,
|
||||
HttpHeaders.of(responseHeaders, (name, value) -> true),
|
||||
body, request.uri());
|
||||
});
|
||||
} catch (InterruptedIOException e) {
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
throw new InterruptedException("CloudFront origin request interrupted");
|
||||
}
|
||||
throw e;
|
||||
private static HttpHeaders responseHeaders(ClassicHttpResponse response) {
|
||||
Map<String, List<String>> responseHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
for (Header header : response.getHeaders()) {
|
||||
responseHeaders.computeIfAbsent(header.getName(), ignored -> new ArrayList<>())
|
||||
.add(header.getValue());
|
||||
}
|
||||
return HttpHeaders.of(responseHeaders, (name, value) -> true);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -202,29 +298,6 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
|
||||
client.close();
|
||||
}
|
||||
|
||||
private record PinnedHttpResponse(
|
||||
int statusCode,
|
||||
HttpRequest request,
|
||||
HttpHeaders headers,
|
||||
byte[] body,
|
||||
URI uri) implements HttpResponse<byte[]> {
|
||||
|
||||
@Override
|
||||
public Optional<HttpResponse<byte[]>> previousResponse() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SSLSession> sslSession() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpClient.Version version() {
|
||||
return HttpClient.Version.HTTP_1_1;
|
||||
}
|
||||
}
|
||||
|
||||
private record ValidatingDnsResolver(DnsResolver delegate, Set<String> allowedHosts)
|
||||
implements DnsResolver {
|
||||
|
||||
|
||||
+157
-63
@@ -30,13 +30,16 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.StreamingOutput;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.PushbackInputStream;
|
||||
import java.net.IDN;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -170,7 +173,7 @@ public class CloudFrontServingController {
|
||||
@Path("/{proxy:.*}")
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response post(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo, byte[] body) {
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo, InputStream body) {
|
||||
return serveWithBody(distId, "POST", headers, uriInfo, body);
|
||||
}
|
||||
|
||||
@@ -178,7 +181,7 @@ public class CloudFrontServingController {
|
||||
@Path("/{proxy:.*}")
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response put(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo, byte[] body) {
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo, InputStream body) {
|
||||
return serveWithBody(distId, "PUT", headers, uriInfo, body);
|
||||
}
|
||||
|
||||
@@ -186,7 +189,7 @@ public class CloudFrontServingController {
|
||||
@Path("/{proxy:.*}")
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response patch(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo, byte[] body) {
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo, InputStream body) {
|
||||
return serveWithBody(distId, "PATCH", headers, uriInfo, body);
|
||||
}
|
||||
|
||||
@@ -194,12 +197,12 @@ public class CloudFrontServingController {
|
||||
@Path("/{proxy:.*}")
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response delete(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo, byte[] body) {
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo, InputStream body) {
|
||||
return serveWithBody(distId, "DELETE", headers, uriInfo, body);
|
||||
}
|
||||
|
||||
private Response serveWithBody(String distId, String method, HttpHeaders headers,
|
||||
UriInfo uriInfo, byte[] body) {
|
||||
UriInfo uriInfo, InputStream body) {
|
||||
HttpServerRequest request = currentVertxRequest.getCurrent().request();
|
||||
String rawViewerPath = rawViewerPath(request.uri());
|
||||
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
|
||||
@@ -208,7 +211,41 @@ public class CloudFrontServingController {
|
||||
headers.getHeaderString(HttpHeaders.AUTHORIZATION),
|
||||
request.getHeader("Origin"), method, null, null,
|
||||
request.getHeader("Pragma"),
|
||||
body != null ? body : new byte[0]);
|
||||
viewerBody(body, headers.getHeaderString("Transfer-Encoding"),
|
||||
headers.getHeaderString(HttpHeaders.CONTENT_LENGTH)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The viewer's request body and its length. It is {@code -1} when the body comes chunked, which
|
||||
* takes precedence over any {@code Content-Length} as HTTP has it, and otherwise the
|
||||
* {@code Content-Length}. With neither header an HTTP/1.1 request has no body, but an HTTP/2 one
|
||||
* can still send one, so the body is looked at: one that is already at its end is empty, and one
|
||||
* that is not is forwarded chunked.
|
||||
*/
|
||||
static ViewerBody viewerBody(InputStream body, String transferEncoding, String contentLength) {
|
||||
InputStream stream = body != null ? body : InputStream.nullInputStream();
|
||||
if (transferEncoding != null) {
|
||||
return new ViewerBody(stream, -1);
|
||||
}
|
||||
if (contentLength != null && !contentLength.isBlank()) {
|
||||
try {
|
||||
return new ViewerBody(stream, Long.parseLong(contentLength.trim()));
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("Treating an invalid viewer Content-Length as chunked: {0}", e.getMessage());
|
||||
return new ViewerBody(stream, -1);
|
||||
}
|
||||
}
|
||||
PushbackInputStream peekable = new PushbackInputStream(stream, 1);
|
||||
try {
|
||||
int first = peekable.read();
|
||||
if (first < 0) {
|
||||
return new ViewerBody(InputStream.nullInputStream(), 0);
|
||||
}
|
||||
peekable.unread(first);
|
||||
} catch (IOException e) {
|
||||
LOG.debugv("Could not read the start of a viewer request body: {0}", e.getMessage());
|
||||
}
|
||||
return new ViewerBody(peekable, -1);
|
||||
}
|
||||
|
||||
private Response serve(String distId, String rawViewerPath, String decodedViewerPath,
|
||||
@@ -218,7 +255,7 @@ public class CloudFrontServingController {
|
||||
String accessControlRequestMethod,
|
||||
String accessControlRequestHeaders,
|
||||
String pragma,
|
||||
byte[] viewerBody) {
|
||||
ViewerBody viewerBody) {
|
||||
boolean includeBody = !"HEAD".equals(method);
|
||||
boolean preflightRequest = "OPTIONS".equals(method)
|
||||
&& viewerOrigin != null && !viewerOrigin.isBlank()
|
||||
@@ -264,8 +301,14 @@ public class CloudFrontServingController {
|
||||
accessControlRequestMethod, accessControlRequestHeaders, viewerBody);
|
||||
|
||||
if (origin.status() >= 400) {
|
||||
Response fallback = applyCustomError(
|
||||
dist, origin, viewerScheme, viewerAuthorization, includeBody, directives);
|
||||
Response fallback;
|
||||
try {
|
||||
fallback = applyCustomError(
|
||||
dist, origin, viewerScheme, viewerAuthorization, includeBody, directives);
|
||||
} catch (RuntimeException e) {
|
||||
origin.closeStream();
|
||||
throw e;
|
||||
}
|
||||
if (fallback != null) {
|
||||
return fallback;
|
||||
}
|
||||
@@ -408,7 +451,7 @@ public class CloudFrontServingController {
|
||||
String method, String viewerOrigin,
|
||||
String accessControlRequestMethod,
|
||||
String accessControlRequestHeaders,
|
||||
byte[] viewerBody) {
|
||||
ViewerBody viewerBody) {
|
||||
DistributionConfig config = distribution.getConfig();
|
||||
String originId = CloudFrontRequestRouter.matchTargetOriginId(config, normalized);
|
||||
Origin origin = CloudFrontRequestRouter.findOrigin(config, originId);
|
||||
@@ -532,10 +575,12 @@ public class CloudFrontServingController {
|
||||
authorizeS3OriginRead(
|
||||
distribution, origin, bucket, key, viewerAuthorization);
|
||||
if (includeBody) {
|
||||
S3Object obj = s3Service.getObject(bucket, key);
|
||||
byte[] data = obj.getData() != null ? obj.getData() : new byte[0];
|
||||
// The body is streamed to the viewer, so an object of any size is served without
|
||||
// being read into the heap; the metadata and the stream come from one snapshot.
|
||||
S3Service.ObjectRead read = s3Service.openObject(bucket, key, null);
|
||||
S3Object obj = read.object();
|
||||
response = new OriginResponse(
|
||||
200, contentType(obj), data, data.length, s3ObjectHeaders(obj));
|
||||
200, contentType(obj), null, read.body(), obj.getSize(), s3ObjectHeaders(obj));
|
||||
} else {
|
||||
S3Object meta = s3Service.headObject(bucket, key);
|
||||
response = new OriginResponse(
|
||||
@@ -544,8 +589,13 @@ public class CloudFrontServingController {
|
||||
} catch (AwsException e) {
|
||||
response = OriginResponse.error(e.getHttpStatus(), e.getMessage());
|
||||
}
|
||||
return withS3CorsHeaders(
|
||||
bucket, origin, includeBody ? "GET" : "HEAD", response);
|
||||
try {
|
||||
return withS3CorsHeaders(
|
||||
bucket, origin, includeBody ? "GET" : "HEAD", response);
|
||||
} catch (RuntimeException e) {
|
||||
response.closeStream();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void authorizeS3OriginRead(
|
||||
@@ -642,7 +692,7 @@ public class CloudFrontServingController {
|
||||
*/
|
||||
private OriginResponse fetchFromCustomOrigin(Origin origin, String forwardUri,
|
||||
CloudFrontOriginRequestBuilder.OriginRequest originRequest,
|
||||
String viewerScheme, String method, byte[] viewerBody) {
|
||||
String viewerScheme, String method, ViewerBody viewerBody) {
|
||||
boolean includeBody = !"HEAD".equals(method);
|
||||
try {
|
||||
URI target = buildCustomOriginUri(
|
||||
@@ -665,15 +715,19 @@ public class CloudFrontServingController {
|
||||
}
|
||||
}
|
||||
rb.method(method, HttpRequest.BodyPublishers.noBody());
|
||||
// The transport derives Content-Length from the body itself.
|
||||
HttpResponse<byte[]> resp = httpClient.send(rb.build(), originRequest.headers(),
|
||||
originHeaders, originRequestBody(method, viewerBody),
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
// Both bodies are streamed, so neither has to fit in memory: the viewer's goes out with its
|
||||
// own Content-Length, or chunked as it came, and the origin's comes back as it arrives.
|
||||
ViewerBody requestBody = originRequestBody(method, viewerBody);
|
||||
CloudFrontOriginHttpClient.OpenResponse resp = httpClient.open(rb.build(), originRequest.headers(),
|
||||
originHeaders, requestBody != null ? requestBody.stream() : null,
|
||||
requestBody != null ? requestBody.length() : -1);
|
||||
String ct = resp.headers().firstValue("content-type").orElse(DEFAULT_CONTENT_TYPE);
|
||||
byte[] body = resp.body() != null ? resp.body() : new byte[0];
|
||||
long contentLength = includeBody ? body.length : responseContentLength(resp);
|
||||
return new OriginResponse(resp.statusCode(), ct, includeBody ? body : null,
|
||||
contentLength, resp.headers().map());
|
||||
long contentLength = resp.contentLength();
|
||||
if (!includeBody) {
|
||||
resp.body().close();
|
||||
return new OriginResponse(resp.statusCode(), ct, null, contentLength, resp.headers().map());
|
||||
}
|
||||
return new OriginResponse(resp.statusCode(), ct, null, resp.body(), contentLength, resp.headers().map());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv("CloudFront custom origin fetch was interrupted for host {0}",
|
||||
@@ -691,16 +745,20 @@ public class CloudFrontServingController {
|
||||
* The body CloudFront sends to the origin: POST, PUT and PATCH always carry one (possibly empty, so
|
||||
* the origin still sees {@code Content-Length: 0}); DELETE carries one only when the viewer sent it.
|
||||
*/
|
||||
private static byte[] originRequestBody(String method, byte[] viewerBody) {
|
||||
private static ViewerBody originRequestBody(String method, ViewerBody viewerBody) {
|
||||
if (viewerBody == null || !BODY_METHODS.contains(method)) {
|
||||
return null;
|
||||
}
|
||||
if ("DELETE".equals(method) && viewerBody.length == 0) {
|
||||
if ("DELETE".equals(method) && viewerBody.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
return viewerBody;
|
||||
}
|
||||
|
||||
/** A viewer request body, read as it is forwarded, and its length, {@code -1} when it comes chunked. */
|
||||
record ViewerBody(InputStream stream, long length) {
|
||||
}
|
||||
|
||||
private static String originAccessIdentityId(Origin origin) {
|
||||
Map<String, String> config = origin.getS3OriginConfig();
|
||||
String value = config != null ? config.get("OriginAccessIdentity") : null;
|
||||
@@ -798,15 +856,6 @@ public class CloudFrontServingController {
|
||||
return normalized.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private static long responseContentLength(HttpResponse<?> response) {
|
||||
try {
|
||||
return response.headers().firstValueAsLong("content-length").orElse(-1L);
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("Ignoring invalid custom-origin Content-Length: {0}", e.getMessage());
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
private static String safeOriginName(Origin origin) {
|
||||
try {
|
||||
return normalizeOriginHost(origin.getDomainName());
|
||||
@@ -847,8 +896,7 @@ public class CloudFrontServingController {
|
||||
String pagePath = str(cer.get("ResponsePagePath"));
|
||||
if (pagePath.isBlank()) {
|
||||
// ResponseCode override with no custom page: keep the origin body, change the status.
|
||||
return toResponse(new OriginResponse(responseCode, origin.contentType(), origin.body(),
|
||||
origin.contentLength(), origin.headers()), includeBody, directives);
|
||||
return toResponse(origin.withStatus(responseCode), includeBody, directives);
|
||||
}
|
||||
|
||||
String errNormalized = CloudFrontRequestRouter.normalizePath(pagePath);
|
||||
@@ -858,6 +906,8 @@ public class CloudFrontServingController {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The custom error page replaces the origin's error response, which is not sent.
|
||||
origin.closeStream();
|
||||
OriginResponse page;
|
||||
if (CloudFrontRequestRouter.isS3Origin(errOrigin)) {
|
||||
String key = CloudFrontRequestRouter.resolveOriginKey(errOrigin.getOriginPath(), errNormalized, null);
|
||||
@@ -874,8 +924,7 @@ public class CloudFrontServingController {
|
||||
// (AWS behavior), without recursively applying custom error handling.
|
||||
return toResponse(page, includeBody, directives);
|
||||
}
|
||||
return toResponse(new OriginResponse(responseCode, page.contentType(), page.body(),
|
||||
page.contentLength(), page.headers()), includeBody, directives);
|
||||
return toResponse(page.withStatus(responseCode), includeBody, directives);
|
||||
}
|
||||
|
||||
private Map<String, Object> matchCustomError(DistributionConfig config, int status) {
|
||||
@@ -893,21 +942,40 @@ public class CloudFrontServingController {
|
||||
|
||||
private Response toResponse(OriginResponse origin, boolean includeBody,
|
||||
ResponseHeadersPolicyConfigCodec.Directives directives) {
|
||||
Response.ResponseBuilder rb = Response.status(origin.status());
|
||||
HeaderCollection collected = collectResponseHeaders(origin, includeBody);
|
||||
applyResponseHeadersPolicy(collected.headers(), directives, collected.forbiddenPolicyHeaders());
|
||||
for (HeaderValues header : collected.headers().values()) {
|
||||
if ("date".equalsIgnoreCase(header.name())) {
|
||||
currentVertxRequest.getCurrent().response()
|
||||
.putHeader(header.name(), header.values());
|
||||
} else {
|
||||
header.values().forEach(value -> rb.header(header.name(), value));
|
||||
try {
|
||||
Response.ResponseBuilder rb = Response.status(origin.status());
|
||||
HeaderCollection collected = collectResponseHeaders(origin, includeBody);
|
||||
applyResponseHeadersPolicy(collected.headers(), directives, collected.forbiddenPolicyHeaders());
|
||||
for (HeaderValues header : collected.headers().values()) {
|
||||
if ("date".equalsIgnoreCase(header.name())) {
|
||||
currentVertxRequest.getCurrent().response()
|
||||
.putHeader(header.name(), header.values());
|
||||
} else {
|
||||
header.values().forEach(value -> rb.header(header.name(), value));
|
||||
}
|
||||
}
|
||||
if (includeBody && origin.stream() != null) {
|
||||
InputStream body = origin.stream();
|
||||
StreamingOutput entity = output -> {
|
||||
try (InputStream in = body) {
|
||||
in.transferTo(output);
|
||||
}
|
||||
};
|
||||
rb.entity(entity);
|
||||
} else {
|
||||
if (origin.stream() != null) {
|
||||
// A body that will not be sent, as for a HEAD, still holds its source open.
|
||||
origin.closeStream();
|
||||
}
|
||||
if (includeBody && origin.body() != null) {
|
||||
rb.entity(origin.body());
|
||||
}
|
||||
}
|
||||
return rb.build();
|
||||
} catch (RuntimeException e) {
|
||||
origin.closeStream();
|
||||
throw e;
|
||||
}
|
||||
if (includeBody && origin.body() != null) {
|
||||
rb.entity(origin.body());
|
||||
}
|
||||
return rb.build();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -943,7 +1011,8 @@ public class CloudFrontServingController {
|
||||
if (origin.contentType() != null) {
|
||||
setHeader(headers, "Content-Type", origin.contentType());
|
||||
}
|
||||
if (!includeBody && origin.contentLength() >= 0) {
|
||||
// A byte body sets its own length; a HEAD response and a streamed body need it stated.
|
||||
if ((!includeBody || origin.stream() != null) && origin.contentLength() >= 0) {
|
||||
setHeader(headers, "Content-Length", Long.toString(origin.contentLength()));
|
||||
}
|
||||
return new HeaderCollection(headers, forbiddenPolicyHeaders);
|
||||
@@ -1094,12 +1163,7 @@ public class CloudFrontServingController {
|
||||
"Access-Control-Request-Method"));
|
||||
}
|
||||
});
|
||||
return new OriginResponse(
|
||||
response.status(),
|
||||
response.contentType(),
|
||||
response.body(),
|
||||
response.contentLength(),
|
||||
headers);
|
||||
return response.withHeaders(headers);
|
||||
}
|
||||
|
||||
private static String originCustomHeader(Origin origin, String requestedName) {
|
||||
@@ -1192,12 +1256,42 @@ public class CloudFrontServingController {
|
||||
Set<String> forbiddenPolicyHeaders) {
|
||||
}
|
||||
|
||||
/** The result of fetching from an origin, including end-to-end response headers. */
|
||||
private record OriginResponse(int status, String contentType, byte[] body, long contentLength,
|
||||
Map<String, List<String>> headers) {
|
||||
/**
|
||||
* The result of fetching from an origin, including end-to-end response headers. An origin's
|
||||
* content, from an S3 object or a custom origin, is an open {@code stream} instead of
|
||||
* {@code body}, so it never passes through the heap; the viewer response writes and closes it.
|
||||
* {@code body} holds the bytes of a response Floci makes itself, such as an error.
|
||||
*/
|
||||
private record OriginResponse(int status, String contentType, byte[] body, InputStream stream,
|
||||
long contentLength, Map<String, List<String>> headers) {
|
||||
OriginResponse(int status, String contentType, byte[] body, long contentLength,
|
||||
Map<String, List<String>> headers) {
|
||||
this(status, contentType, body, null, contentLength, headers);
|
||||
}
|
||||
|
||||
static OriginResponse error(int status, String message) {
|
||||
byte[] b = message == null ? new byte[0] : message.getBytes(StandardCharsets.UTF_8);
|
||||
return new OriginResponse(status, MediaType.TEXT_PLAIN, b, b.length, Map.of());
|
||||
}
|
||||
|
||||
OriginResponse withStatus(int newStatus) {
|
||||
return new OriginResponse(newStatus, contentType, body, stream, contentLength, headers);
|
||||
}
|
||||
|
||||
OriginResponse withHeaders(Map<String, List<String>> newHeaders) {
|
||||
return new OriginResponse(status, contentType, body, stream, contentLength, newHeaders);
|
||||
}
|
||||
|
||||
/** Closes the stream of a response that will not be written. */
|
||||
void closeStream() {
|
||||
if (stream == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv("Could not close an unsent origin body: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user