mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 17:58:05 -05:00
feat(core): log every request and response as JSONL behind floci.request-log (#8767)
Seeing what a client sent, and what Floci answered, meant reading service logs. floci.request-log.enabled (FLOCI_REQUEST_LOG_ENABLED), off by default, appends one JSON object per request and response to floci.request-log.file (./floci-requests.jsonl by default). Each line is shaped like a HAR 1.2 entry and carries callerAccessKeyId, the access key id the request was signed with, so every call can be tied to the caller that made it. The request is captured pre-matching, ahead of every other filter, so a request another filter aborts is still logged. Its body is read on the worker thread by a post-matching filter, only when its declared length is within 256 KiB, and handed back whole to the resource; a chunked body is not read, so a slow upload never holds a worker. A body that is not valid UTF-8 is stored base64, a response is cut at 256 KiB with its full size kept, and a response streamed to the client is never read. Signature, session-token, credential and cookie headers and presigned query parameters are redacted, matched by decoded name in the URL too. Lines are written by a thread of their own from a bounded queue, so a stalled file never holds a response. The file is created readable by its owner only, and only a regular file is written: a symbolic link, a named pipe or a directory at the path is refused. This is the request-log half of #4623, carried over from #4591. Refs #4623 Co-authored-by: dchakrav-github <42748809+dchakrav-github@users.noreply.github.com>
This commit is contained in:
1 parent
57c1704083
commit
aa2a9f959e
10 files changed
+1319
No files matched your search
@@ -0,0 +1,128 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.core.common.RequestLogFilter.Body;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link RequestLogBodyFilter} reads a body only when its declared length is within the cap, so a slow or endless
|
||||
* upload never holds a worker thread, and always hands the resource the complete body.
|
||||
*/
|
||||
class RequestLogBodyFilterTest {
|
||||
|
||||
@Test
|
||||
void aBodyWithNoDeclaredLengthIsNotRead() throws IOException {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
when(ctx.hasEntity()).thenReturn(true);
|
||||
// Undeclared, chunked length: reading it would wait on the client.
|
||||
when(ctx.getLength()).thenReturn(-1);
|
||||
|
||||
Body body = RequestLogBodyFilter.captureRequestBody(ctx, () -> true);
|
||||
|
||||
assertThat(body.text(), equalTo(RequestLogFilter.UNKNOWN_LENGTH));
|
||||
assertThat(body.originalSize(), equalTo(-1));
|
||||
verify(ctx, never()).getEntityStream();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeclaredLengthOverTheCapIsSkippedWithoutReading() throws IOException {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
when(ctx.hasEntity()).thenReturn(true);
|
||||
when(ctx.getLength()).thenReturn(RequestLogFilter.MAX_BODY_BYTES + 1);
|
||||
|
||||
Body body = RequestLogBodyFilter.captureRequestBody(ctx, () -> true);
|
||||
|
||||
assertThat(body.text(), equalTo(RequestLogFilter.TRUNCATED));
|
||||
assertThat(body.originalSize(), equalTo(RequestLogFilter.MAX_BODY_BYTES + 1));
|
||||
verify(ctx, never()).getEntityStream();
|
||||
}
|
||||
|
||||
@Test
|
||||
void smallBodyIsCapturedAndReplayed() throws IOException {
|
||||
byte[] small = "Action=ListQueues&Version=2012-11-05".getBytes(StandardCharsets.UTF_8);
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
when(ctx.hasEntity()).thenReturn(true);
|
||||
when(ctx.getLength()).thenReturn(small.length);
|
||||
when(ctx.getEntityStream()).thenReturn(new ByteArrayInputStream(small));
|
||||
ArgumentCaptor<InputStream> replaced = ArgumentCaptor.forClass(InputStream.class);
|
||||
|
||||
Body body = RequestLogBodyFilter.captureRequestBody(ctx, () -> true);
|
||||
|
||||
assertThat(body.text(), equalTo("Action=ListQueues&Version=2012-11-05"));
|
||||
assertThat(body.encoding(), is(nullValue()));
|
||||
verify(ctx).setEntityStream(replaced.capture());
|
||||
assertThat(replaced.getValue().readAllBytes(), equalTo(small));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBinaryBodyIsCapturedAsBase64AndReplayedWhole() throws IOException {
|
||||
byte[] binary = {(byte) 0xFF, (byte) 0xFE, 0x00, 0x10, (byte) 0xC3};
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
when(ctx.hasEntity()).thenReturn(true);
|
||||
when(ctx.getLength()).thenReturn(binary.length);
|
||||
when(ctx.getEntityStream()).thenReturn(new ByteArrayInputStream(binary));
|
||||
ArgumentCaptor<InputStream> replaced = ArgumentCaptor.forClass(InputStream.class);
|
||||
|
||||
Body body = RequestLogBodyFilter.captureRequestBody(ctx, () -> true);
|
||||
|
||||
assertThat(body.encoding(), equalTo("base64"));
|
||||
assertThat(Base64.getDecoder().decode(body.text()), equalTo(binary));
|
||||
assertThat(body.originalSize(), equalTo(binary.length));
|
||||
verify(ctx).setEntityStream(replaced.capture());
|
||||
assertThat(replaced.getValue().readAllBytes(), equalTo(binary));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whatFollowsAnUndercountingLengthStillReachesTheResource() throws IOException {
|
||||
byte[] sent = "declared-and-more".getBytes(StandardCharsets.UTF_8);
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
when(ctx.hasEntity()).thenReturn(true);
|
||||
when(ctx.getLength()).thenReturn(8);
|
||||
when(ctx.getEntityStream()).thenReturn(new ByteArrayInputStream(sent));
|
||||
ArgumentCaptor<InputStream> replaced = ArgumentCaptor.forClass(InputStream.class);
|
||||
|
||||
Body body = RequestLogBodyFilter.captureRequestBody(ctx, () -> true);
|
||||
|
||||
assertThat(body.text(), equalTo("declared"));
|
||||
verify(ctx).setEntityStream(replaced.capture());
|
||||
assertThat(replaced.getValue().readAllBytes(), equalTo(sent));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noEntityReturnsNull() throws IOException {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
when(ctx.hasEntity()).thenReturn(false);
|
||||
|
||||
assertThat(RequestLogBodyFilter.captureRequestBody(ctx, () -> true), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onTheIoThreadTheBodyIsLeftAlone() throws IOException {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
when(ctx.hasEntity()).thenReturn(true);
|
||||
when(ctx.getLength()).thenReturn(10);
|
||||
|
||||
Body body = RequestLogBodyFilter.captureRequestBody(ctx, () -> false);
|
||||
|
||||
assertThat(body.text(), equalTo(RequestLogFilter.NOT_BUFFERED_IO_THREAD));
|
||||
verify(ctx, never()).getEntityStream();
|
||||
verify(ctx, never()).setEntityStream(any());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import jakarta.annotation.Priority;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerResponseContext;
|
||||
import jakarta.ws.rs.container.PreMatching;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The request log's filters in the order JAX-RS runs them for one request: the pre-matching capture, the
|
||||
* post-matching body read, then the response, written to a real file. Floci's own filter chain is not booted for this,
|
||||
* so the order it relies on is checked on the annotations.
|
||||
*/
|
||||
class RequestLogChainTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* The body has to be read post-matching, on the worker thread: reading it pre-matching fails on the Vert.x IO
|
||||
* thread and drops every request body from the log. It runs ahead of every other post-matching filter, and the
|
||||
* capture runs ahead of every pre-matching one, so a request another filter aborts is still logged.
|
||||
*/
|
||||
@Test
|
||||
void theCaptureRunsFirstPreMatchingAndTheBodyIsReadPostMatching() {
|
||||
assertTrue(RequestLogFilter.class.isAnnotationPresent(PreMatching.class));
|
||||
assertThat(RequestLogFilter.class.getAnnotation(Priority.class).value(), equalTo(1000));
|
||||
assertFalse(RequestLogBodyFilter.class.isAnnotationPresent(PreMatching.class));
|
||||
assertThat(RequestLogBodyFilter.class.getAnnotation(Priority.class).value(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignedQueryPostIsLoggedWithItsBodyAndResponseAndItsSecretsRedacted(@TempDir Path dir) throws Exception {
|
||||
Path log = dir.resolve("requests.jsonl");
|
||||
RequestLogFilter capture = new RequestLogFilter(mapper, () -> config(log));
|
||||
byte[] body = "Action=ListQueues&Version=2012-11-05".getBytes(StandardCharsets.UTF_8);
|
||||
ContainerRequestContext request = request(body);
|
||||
ContainerResponseContext response = response();
|
||||
|
||||
capture.filter(request);
|
||||
new RequestLogBodyFilter(() -> true).filter(request);
|
||||
capture.filter(request, response);
|
||||
|
||||
JsonNode entry = await("the entry in " + log).atMost(Duration.ofSeconds(10))
|
||||
.until(() -> Files.exists(log) ? Files.readAllLines(log) : List.<String>of(), lines -> lines.size() == 1)
|
||||
.stream().map(this::parse).findFirst().orElseThrow();
|
||||
JsonNode logged = entry.path("request");
|
||||
assertThat(logged.path("method").asText(), equalTo("POST"));
|
||||
assertThat(logged.path("postData").path("text").asText(), equalTo("Action=ListQueues&Version=2012-11-05"));
|
||||
assertThat(logged.path("postData").path("mimeType").asText(),
|
||||
containsString("application/x-www-form-urlencoded"));
|
||||
assertThat(logged.path("bodySize").asInt(), equalTo(body.length));
|
||||
assertThat(entry.path("callerAccessKeyId").asText(), equalTo("AKIAEXAMPLE"));
|
||||
assertThat(header(logged, "Authorization"), equalTo(RequestLogFilter.REDACTED));
|
||||
assertThat(header(logged, "X-Amz-Security-Token"), equalTo(RequestLogFilter.REDACTED));
|
||||
assertThat(header(logged, "Cookie"), equalTo(RequestLogFilter.REDACTED));
|
||||
assertThat(header(logged, "Content-Type"), containsString("application/x-www-form-urlencoded"));
|
||||
assertThat(logged.path("url").asText(), not(containsString("deadbeef")));
|
||||
JsonNode answered = entry.path("response");
|
||||
assertThat(answered.path("status").asInt(), equalTo(200));
|
||||
assertThat(answered.path("content").path("text").asText(), containsString("ListQueuesResponse"));
|
||||
assertThat(header(answered, "Set-Cookie"), equalTo(RequestLogFilter.REDACTED));
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(Path log) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.requestLog().enabled()).thenReturn(true);
|
||||
when(config.requestLog().file()).thenReturn(Optional.of(log.toString()));
|
||||
return config;
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(byte[] body) {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
Map<String, Object> properties = new HashMap<>();
|
||||
doAnswer(invocation -> properties.put(invocation.getArgument(0), invocation.getArgument(1)))
|
||||
.when(ctx).setProperty(anyString(), any());
|
||||
when(ctx.getProperty(anyString())).thenAnswer(invocation -> properties.get(invocation.<String>getArgument(0)));
|
||||
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
|
||||
headers.add("Authorization", "AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/20260928/us-east-1/sqs/aws4_request, "
|
||||
+ "SignedHeaders=host;x-amz-date, Signature=deadbeef");
|
||||
headers.add("X-Amz-Security-Token", "FwoGZXIvYXdzEXAMPLETOKEN");
|
||||
headers.add("Cookie", "session=secret");
|
||||
headers.add("Content-Type", "application/x-www-form-urlencoded");
|
||||
when(ctx.getHeaders()).thenReturn(headers);
|
||||
when(ctx.getHeaderString(anyString())).thenAnswer(invocation -> headers.getFirst(invocation.getArgument(0)));
|
||||
UriInfo uri = mock(UriInfo.class);
|
||||
when(uri.getRequestUri()).thenReturn(URI.create("http://localhost:4566/?X-Amz-Signature=deadbeef"));
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("X-Amz-Signature", "deadbeef");
|
||||
when(uri.getQueryParameters()).thenReturn(query);
|
||||
when(uri.getPath()).thenReturn("/");
|
||||
when(ctx.getUriInfo()).thenReturn(uri);
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
when(ctx.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
when(ctx.hasEntity()).thenReturn(true);
|
||||
when(ctx.getLength()).thenReturn(body.length);
|
||||
InputStream[] stream = {new ByteArrayInputStream(body)};
|
||||
when(ctx.getEntityStream()).thenAnswer(invocation -> stream[0]);
|
||||
doAnswer(invocation -> stream[0] = invocation.getArgument(0)).when(ctx).setEntityStream(any());
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private static ContainerResponseContext response() {
|
||||
ContainerResponseContext ctx = mock(ContainerResponseContext.class);
|
||||
when(ctx.getEntity()).thenReturn("<ListQueuesResponse><ListQueuesResult/></ListQueuesResponse>");
|
||||
when(ctx.getStatus()).thenReturn(200);
|
||||
when(ctx.getStatusInfo()).thenReturn(Response.Status.OK);
|
||||
when(ctx.getMediaType()).thenReturn(MediaType.TEXT_XML_TYPE);
|
||||
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
|
||||
headers.add("Set-Cookie", "session=renewed; Path=/");
|
||||
headers.add("Content-Type", "text/xml");
|
||||
when(ctx.getStringHeaders()).thenReturn(headers);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private JsonNode parse(String line) {
|
||||
try {
|
||||
return mapper.readTree(line);
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError("not a JSON line: " + line, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String header(JsonNode side, String name) {
|
||||
for (JsonNode header : side.path("headers")) {
|
||||
if (name.equalsIgnoreCase(header.path("name").asText())) {
|
||||
return header.path("value").asText();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.RequestLogFilter.Body;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.lessThanOrEqualTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* {@link RequestLogFilter}'s helpers: how bodies are stored, redaction of headers, query parameters and URLs, and
|
||||
* {@link RequestLogWriter}'s handling of the log file.
|
||||
*/
|
||||
class RequestLogFilterTest {
|
||||
|
||||
private final RequestLogFilter filter = new RequestLogFilter(new ObjectMapper(), () -> null);
|
||||
|
||||
// ---- bodies ----
|
||||
|
||||
@Test
|
||||
void binaryBodyIsBase64WithOriginalSize() {
|
||||
byte[] cbor = new byte[] {(byte) 0xA1, 0x63, 0x66, 0x6F, 0x6F, (byte) 0xF6, 0x00, (byte) 0xFF};
|
||||
Body body = Body.bytes(cbor);
|
||||
|
||||
assertThat(body.encoding(), equalTo("base64"));
|
||||
assertThat(body.originalSize(), equalTo(cbor.length));
|
||||
// The stored text decodes back to the original bytes, lossless unlike a UTF-8 decode.
|
||||
assertThat(Base64.getDecoder().decode(body.text()), equalTo(cbor));
|
||||
}
|
||||
|
||||
@Test
|
||||
void largeBinaryBodyReportsOriginalSizeButCapsStoredBytes() {
|
||||
byte[] big = new byte[RequestLogFilter.MAX_BODY_BYTES + 4096];
|
||||
for (int i = 0; i < big.length; i++) {
|
||||
big[i] = (byte) (i % 256);
|
||||
}
|
||||
Body body = Body.bytes(big);
|
||||
|
||||
assertThat(body.encoding(), equalTo("base64"));
|
||||
assertThat(body.originalSize(), equalTo(big.length));
|
||||
assertThat(Base64.getDecoder().decode(body.text()).length, is(RequestLogFilter.MAX_BODY_BYTES));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bytesThatAreValidUtf8AreStoredAsText() {
|
||||
Body body = Body.bytes("Action=ListQueues&Version=2012-11-05".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertThat(body.encoding(), is(nullValue()));
|
||||
assertThat(body.text(), equalTo("Action=ListQueues&Version=2012-11-05"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void textBodyHasNoEncodingAndUtf8Size() {
|
||||
Body body = Body.text("<Response>ok</Response>");
|
||||
assertThat(body.encoding(), is(nullValue()));
|
||||
assertThat(body.originalSize(),
|
||||
equalTo("<Response>ok</Response>".getBytes(StandardCharsets.UTF_8).length));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTextBodyOverTheCapKeepsItsFullSize() {
|
||||
String large = "x".repeat(RequestLogFilter.MAX_BODY_BYTES + 100);
|
||||
Body body = filter.responseBody(large);
|
||||
|
||||
assertThat(body.text().length(), equalTo(RequestLogFilter.MAX_BODY_BYTES));
|
||||
assertThat(body.originalSize(), equalTo(large.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSerializedBodyStopsAtTheCapWithAnUnknownSize() {
|
||||
Map<String, String> large = Map.of("value", "x".repeat(RequestLogFilter.MAX_BODY_BYTES * 2));
|
||||
Body body = filter.responseBody(large);
|
||||
|
||||
assertThat(body.text().length(), lessThanOrEqualTo(RequestLogFilter.MAX_BODY_BYTES));
|
||||
assertThat(body.originalSize(), equalTo(-1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSmallSerializedBodyKeepsItsSize() {
|
||||
Body body = filter.responseBody(Map.of("QueueUrls", List.of()));
|
||||
|
||||
assertThat(body.text(), equalTo("{\"QueueUrls\":[]}"));
|
||||
assertThat(body.originalSize(), equalTo(body.text().length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStreamedBodyIsNeverReadAndItsSizeIsUnknown() {
|
||||
ByteArrayInputStream stream = new ByteArrayInputStream("object bytes".getBytes(StandardCharsets.UTF_8));
|
||||
Body body = filter.responseBody(stream);
|
||||
|
||||
assertThat(body.text(), equalTo(RequestLogFilter.STREAMED));
|
||||
assertThat(body.originalSize(), equalTo(-1));
|
||||
assertThat(stream.available(), equalTo(12));
|
||||
}
|
||||
|
||||
// ---- redaction ----
|
||||
|
||||
@Test
|
||||
void sessionCookiesAndSignaturesAreRedactedFromHeaders() {
|
||||
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
|
||||
headers.add("Cookie", "floci-quicksight=session-secret");
|
||||
headers.add("Set-Cookie", "floci-quicksight=new-secret; Path=/");
|
||||
headers.add("authorization", "AWS4-HMAC-SHA256 Credential=AKID/x, Signature=abc");
|
||||
headers.add("Content-Type", "application/json");
|
||||
|
||||
List<Map<String, String>> logged = RequestLogFilter.headerList(headers);
|
||||
|
||||
assertThat(value(logged, "Cookie"), equalTo(RequestLogFilter.REDACTED));
|
||||
assertThat(value(logged, "Set-Cookie"), equalTo(RequestLogFilter.REDACTED));
|
||||
assertThat(value(logged, "authorization"), equalTo(RequestLogFilter.REDACTED));
|
||||
assertThat(value(logged, "Content-Type"), equalTo("application/json"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignedSecretsAreRedactedFromTheQueryStringWhateverTheirCase() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("x-amz-signature", "deadbeef");
|
||||
params.add("X-Amz-Expires", "300");
|
||||
|
||||
List<Map<String, String>> logged = RequestLogFilter.queryStringList(params);
|
||||
|
||||
assertThat(value(logged, "x-amz-signature"), equalTo(RequestLogFilter.REDACTED));
|
||||
assertThat(value(logged, "X-Amz-Expires"), equalTo("300"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignedSecretsAreRedactedInUrl() {
|
||||
String url = "http://localhost:4566/bucket/key"
|
||||
+ "?X-Amz-Algorithm=AWS4-HMAC-SHA256"
|
||||
+ "&X-Amz-Credential=AKID%2F20260928%2Fus-east-1%2Fs3%2Faws4_request"
|
||||
+ "&X-Amz-Signature=deadbeefcafe"
|
||||
+ "&X-Amz-Security-Token=SESSIONTOKEN"
|
||||
+ "&partNumber=2";
|
||||
String redacted = RequestLogFilter.redactUrl(url);
|
||||
|
||||
assertThat(redacted, not(containsString("deadbeefcafe")));
|
||||
assertThat(redacted, not(containsString("SESSIONTOKEN")));
|
||||
assertThat(redacted, not(containsString("AKID")));
|
||||
assertThat(redacted, containsString("X-Amz-Algorithm=AWS4-HMAC-SHA256"));
|
||||
assertThat(redacted, containsString("partNumber=2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPercentEncodedSecretNameIsRedactedInUrlToo() {
|
||||
String url = "http://localhost:4566/bucket/key?%58-Amz-Signature=deadbeefcafe&x-amz-signature=cafe#frag";
|
||||
String redacted = RequestLogFilter.redactUrl(url);
|
||||
|
||||
assertThat(redacted, equalTo("http://localhost:4566/bucket/key?%58-Amz-Signature=" + RequestLogFilter.REDACTED
|
||||
+ "&x-amz-signature=" + RequestLogFilter.REDACTED + "#frag"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void urlWithoutSecretsIsUnchanged() {
|
||||
String url = "http://localhost:4566/?Action=ListQueues&Version=2012-11-05";
|
||||
assertThat(RequestLogFilter.redactUrl(url), equalTo(url));
|
||||
assertThat(RequestLogFilter.redactUrl("http://localhost:4566/health"), equalTo("http://localhost:4566/health"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullUrlIsHandled() {
|
||||
assertThat(RequestLogFilter.redactUrl(null), is(nullValue()));
|
||||
}
|
||||
|
||||
// ---- the log file ----
|
||||
|
||||
@Test
|
||||
void theLogIsCreatedReadableByItsOwnerOnly(@TempDir Path dir) throws IOException {
|
||||
Assumptions.assumeTrue(dir.getFileSystem().supportedFileAttributeViews().contains("posix"));
|
||||
Path log = dir.resolve("nested").resolve("requests.jsonl");
|
||||
|
||||
RequestLogWriter.createOwnerOnly(log);
|
||||
|
||||
assertThat(PosixFilePermissions.toString(Files.getPosixFilePermissions(log)), equalTo("rw-------"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExistingLogKeepsItsPermissions(@TempDir Path dir) throws IOException {
|
||||
Assumptions.assumeTrue(dir.getFileSystem().supportedFileAttributeViews().contains("posix"));
|
||||
Path log = Files.createFile(dir.resolve("requests.jsonl"),
|
||||
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-r-----")));
|
||||
|
||||
RequestLogWriter.createOwnerOnly(log);
|
||||
|
||||
assertThat(PosixFilePermissions.toString(Files.getPosixFilePermissions(log)), equalTo("rw-r-----"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSymbolicLinkAtTheLogPathIsRefused(@TempDir Path dir) throws IOException {
|
||||
Path elsewhere = Files.writeString(dir.resolve("someone-elses-file"), "theirs\n");
|
||||
Path log = Files.createSymbolicLink(dir.resolve("requests.jsonl"), elsewhere);
|
||||
|
||||
assertThrows(IOException.class, () -> RequestLogWriter.open(log));
|
||||
|
||||
assertThat(Files.readString(elsewhere), equalTo("theirs\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDirectoryAtTheLogPathIsRefused(@TempDir Path dir) throws IOException {
|
||||
Path log = Files.createDirectory(dir.resolve("requests.jsonl"));
|
||||
|
||||
assertThrows(IOException.class, () -> RequestLogWriter.open(log));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theWriterAppendsLinesFromItsOwnThread(@TempDir Path dir) throws IOException {
|
||||
Path log = dir.resolve("requests.jsonl");
|
||||
RequestLogWriter writer = new RequestLogWriter(log);
|
||||
|
||||
writer.append("{\"first\":1}");
|
||||
writer.append("{\"second\":2}");
|
||||
|
||||
await().atMost(Duration.ofSeconds(10))
|
||||
.until(() -> Files.exists(log) && Files.readAllLines(log).size() == 2);
|
||||
assertThat(Files.readAllLines(log), equalTo(List.of("{\"first\":1}", "{\"second\":2}")));
|
||||
try (FileChannel ignored = RequestLogWriter.open(log)) {
|
||||
assertThat(Files.isRegularFile(log), is(true));
|
||||
}
|
||||
}
|
||||
|
||||
private static String value(List<Map<String, String>> pairs, String name) {
|
||||
return pairs.stream().filter(pair -> pair.get("name").equals(name)).findFirst()
|
||||
.map(pair -> pair.get("value")).orElse(null);
|
||||
}
|
||||
}
|
||||
+2
@@ -360,6 +360,8 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
@Override
|
||||
public EmulatorConfig.InitHooksConfig initHooks() { return null; }
|
||||
@Override
|
||||
public RequestLogConfig requestLog() { return null; }
|
||||
@Override
|
||||
public ProtocolsConfig protocols() {
|
||||
return new ProtocolsConfig() {
|
||||
@Override public int maxRequestSize() { return 512; }
|
||||
|
||||
Reference in new issue
Block a user