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:
Priamo Germosenanddchakrav-github authored and GitHub committed 2026-11-17 18:34:18 -04:00
1 parent 57c1704083
commit aa2a9f959e
10 files changed
+1319

No files matched your search

@@ -80,6 +80,35 @@ See [TLS / HTTPS](./tls.md) for SDK configuration examples and WebSocket (`wss:/
| `FLOCI_PROTOCOLS_STRICT_CLAIMING` | `false` | Reject RPC-signaled requests that no supported wire protocol claims, per the [Smithy wire-protocol-selection guide](https://smithy.io/2.0/guides/wire-protocol-selection.html) (e.g. an unknown `Smithy-Protocol` header value or an unimplemented `rpc-v2-json` request). When disabled such requests are logged and pass through, and are handled as the protocol of the route that serves them: one served by the JSON, CBOR or Query endpoint is an RPC call, and one served by a service's route is a REST request |
| `FLOCI_PROTOCOLS_REJECT_UNKNOWN_SERVICE_SCOPE` | `true` | Reject REST requests whose SigV4 credential scope names a service Floci does not implement, with `UnknownOperationException` instead of letting them fall through to S3's path-style routes and return a misleading `NoSuchBucket`. Set to `false` if Floci serves a route whose signing scope is not yet enumerated: the request then falls through as before instead of failing with a 404 |
---
## Request Log
| Variable | Default | Description |
|---|---|---|
| `FLOCI_REQUEST_LOG_ENABLED` | `false` | Write every request and its response to the request log, one JSON object per line |
| `FLOCI_REQUEST_LOG_FILE` | `./floci-requests.jsonl` | Where the request log is written |
Each line of the request log is one JSON object shaped like a HAR 1.2 `entry`: the request with its headers, query
string and body, the response with its status, headers and body, and the time taken. It also carries
`callerAccessKeyId`, the access key id the request was signed with, so each line can be tied to the caller that made
it, whether that is Terraform, CloudFormation or a direct SDK or CLI call. A request body is captured when its
declared length is 256 KiB or less; a larger one, and one sent without a declared length, is noted but not read. A
response body is cut at 256 KiB. A body that is not valid UTF-8 is stored base64 with `"encoding": "base64"`, and a
response streamed to the client is not read. Lines are written by a thread of their own, so a slow file never holds up
a response; when the writer falls 10,000 lines behind, new lines are dropped and Floci logs a warning.
!!! warning "The request log holds secrets"
Request and response bodies are written as plain text, and they can carry secrets: a secret access key in a
response, a password in a request, a secret value in a parameter. Floci redacts the `Authorization`,
`X-Amz-Security-Token`, `X-Amz-Content-Sha256`, `Cookie` and `Set-Cookie` headers and the `X-Amz-Signature`,
`X-Amz-Security-Token` and `X-Amz-Credential` query parameters, in the URL too, but a secret inside a body is
written as is. On a file system with POSIX permissions, Floci creates the file readable and writable by its owner
only; a file that already exists keeps its permissions. Floci writes only to a regular file, and refuses a symbolic
link, a named pipe or a directory at the path. Keep the log off in shared environments, and do not commit or share
the file.
---
## Storage
@@ -126,6 +126,22 @@ public interface EmulatorConfig {
ProtocolsConfig protocols();
/** The opt-in log of every request and response, one JSON object per line, for debugging. */
RequestLogConfig requestLog();
interface RequestLogConfig {
/** Write each request and its response to {@link #file()}. Env: FLOCI_REQUEST_LOG_ENABLED */
@WithDefault("false")
boolean enabled();
/**
* Where the log is written, one JSON object per line (JSONL); {@code ./floci-requests.jsonl} when unset. It
* holds request and response bodies as plain text, which can include secrets: known secret headers and query
* parameters are redacted, but a secret inside a body is not. Env: FLOCI_REQUEST_LOG_FILE
*/
Optional<String> file();
}
interface NetworkConfig {
SecurityGroupEnforcementConfig securityGroupEnforcement();
}
@@ -0,0 +1,100 @@
package io.floci.aws.core.common;
import io.floci.aws.core.common.RequestLogFilter.Body;
import io.quarkus.runtime.BlockingOperationControl;
import jakarta.annotation.Priority;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.function.BooleanSupplier;
/**
* Buffers the request body for {@link RequestLogFilter} and hands it over under {@link RequestLogFilter#BODY_PROPERTY}.
*
* <p>Separate from {@link RequestLogFilter} because of where each can run. {@link RequestLogFilter} is pre-matching,
* which on RESTEasy Reactive means the Vert.x IO thread, and reading the JAX-RS entity stream there fails with
* {@code BlockingNotAllowedException} instead of returning the body, which would drop the body of every AWS Query
* POST. This filter is post-matching, so it runs after the dispatch to a worker thread that a blocking resource method
* triggers, and the same read is legal. {@link io.floci.aws.services.iam.ResourceArnBuilder} and
* {@link io.floci.aws.services.s3.S3HeaderSignatureFilter} read the entity stream from that same position.
*
* <p>Priority 1 puts it ahead of every other post-matching filter, so a request that {@link IamEnforcementFilter}
* (default priority) aborts still has its body logged. It does nothing unless {@link RequestLogFilter} already opened
* a capture for the request, which only happens while the request log is enabled.
*
* <p>Like the rest of the request log, it never disturbs the request it observes: the stream is put back as an
* equivalent one for the resource method to read, and any failure is logged at warn and swallowed.
*/
@Provider
@Priority(1)
public class RequestLogBodyFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(RequestLogBodyFilter.class);
private final BooleanSupplier blockingAllowed;
public RequestLogBodyFilter() {
this(BlockingOperationControl::isBlockingAllowed);
}
/** {@code blockingAllowed} answers whether this thread may block, which only a running Quarkus can tell. */
RequestLogBodyFilter(BooleanSupplier blockingAllowed) {
this.blockingAllowed = blockingAllowed;
}
@Override
public void filter(ContainerRequestContext ctx) {
if (!(ctx.getProperty(RequestLogFilter.CAPTURE_PROPERTY) instanceof RequestLogFilter.RequestCapture)) {
return;
}
try {
Body body = captureRequestBody(ctx, blockingAllowed);
if (body != null) {
ctx.setProperty(RequestLogFilter.BODY_PROPERTY, body);
}
} catch (Exception e) {
LOG.warnv(e, "Request log: could not capture request body for {0} {1}",
ctx.getMethod(), ctx.getUriInfo().getPath());
}
}
/**
* Buffers the request body for logging when its declared {@code Content-Length} is within
* {@link RequestLogFilter#MAX_BODY_BYTES}, and puts an equivalent stream back so the resource method still reads
* the whole body. Returns {@code null} when there is no body, and a placeholder when the body is not read.
*
* <p>Only a declared length is read, and only that many bytes, which the resource would wait for anyway. A body
* over the cap, and one with no declared length (chunked), is not read at all: reading it would make this filter
* wait on the client, holding a worker thread before the resource runs, and on a blocking route enough slow
* uploads could exhaust the worker pool.
*/
static Body captureRequestBody(ContainerRequestContext ctx, BooleanSupplier blockingAllowed) throws IOException {
if (!ctx.hasEntity()) {
return null;
}
int length = ctx.getLength();
if (length > RequestLogFilter.MAX_BODY_BYTES) {
return Body.placeholder(RequestLogFilter.TRUNCATED, length);
}
if (length < 0) {
return Body.placeholder(RequestLogFilter.UNKNOWN_LENGTH, -1);
}
if (!blockingAllowed.getAsBoolean()) {
return Body.placeholder(RequestLogFilter.NOT_BUFFERED_IO_THREAD, length);
}
InputStream entityStream = ctx.getEntityStream();
if (entityStream == null) {
return null;
}
byte[] declared = entityStream.readNBytes(length);
// Whatever follows a declared length that undercounts still reaches the resource.
ctx.setEntityStream(new SequenceInputStream(new ByteArrayInputStream(declared), entityStream));
return declared.length == 0 ? null : Body.bytes(declared);
}
}
@@ -0,0 +1,488 @@
package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import jakarta.annotation.Priority;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.StreamingOutput;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import java.io.File;
import java.io.InputStream;
import java.io.Writer;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Records every request and response as one line of JSON (JSONL) when {@code floci.request-log.enabled} is true
* ({@code FLOCI_REQUEST_LOG_ENABLED=true}). Each line is appended to {@code floci.request-log.file}, by default
* {@code ./floci-requests.jsonl}, and is a self-contained JSON object shaped like a HAR 1.2 {@code entry}
* (request, response and timings) with the caller's access key id added. The file streams and tails cleanly, and a
* partial write can only affect its last line. {@link RequestLogWriter} writes the lines from a thread of its own.
*
* <p>Request capture runs pre-matching at priority 1000, ahead of every other Floci filter, such as
* {@link AwsProtocolClaimFilter} (pre-matching, 6000) and {@link IamEnforcementFilter} (default priority), so a
* request one of them aborts is still captured. Response filters run in reverse priority order, so this one runs last
* on the way out and sees the final status and headers, including those {@link AwsRequestIdFilter} adds.
*
* <p>The log is opt-in debug tooling, so it never disturbs the response it observes: a failure to capture or record
* an entry is logged at warn and swallowed.
*
* <p>Pre-matching runs on the Vert.x IO thread, where reading the JAX-RS entity stream is a blocking operation that
* RESTEasy Reactive refuses with {@code BlockingNotAllowedException}. The request body is therefore buffered by
* {@link RequestLogBodyFilter}, a post-matching filter that runs on the worker thread, and handed over on the request
* context. A request no post-matching filter sees, one that matches no resource or that a pre-matching filter aborts,
* is still recorded, without {@code postData}.
*/
@Provider
@PreMatching
@Priority(1000)
public class RequestLogFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static final Logger LOG = Logger.getLogger(RequestLogFilter.class);
static final String CAPTURE_PROPERTY = "floci.request-log.capture";
static final String BODY_PROPERTY = "floci.request-log.body";
/** Stands in for a body {@link RequestLogBodyFilter} declined to buffer because of its size. */
static final String TRUNCATED = "<floci: body not captured, too large>";
/** Stands in for a body sent without a declared length, which could only be read by waiting on the client. */
static final String UNKNOWN_LENGTH = "<floci: body not captured, no declared length>";
/** Stands in for a body unreadable because the request was handled on the Vert.x IO thread. */
static final String NOT_BUFFERED_IO_THREAD =
"<floci: body not captured, request handled on the IO thread>";
/** Stands in for a response body streamed to the client, which reading here would consume. */
static final String STREAMED = "<floci: streamed body not captured>";
/** Header and query values carrying replayable secrets are stored as this instead of the value. */
static final String REDACTED = "<floci: redacted>";
/** Bodies larger than this are not buffered, so a multi-gigabyte upload is never mirrored. */
static final int MAX_BODY_BYTES = 256 * 1024;
static final String DEFAULT_FILE = "./floci-requests.jsonl";
private static final String HTTP_VERSION = "HTTP/1.1";
/**
* Header names whose values are replayable secrets: the SigV4 signature, any session token, and session cookies.
* Redacted before anything is written, so a reader of the log cannot replay a still-valid request. Matched
* case-insensitively.
*/
private static final Set<String> SECRET_HEADERS = Set.of(
"authorization", "x-amz-security-token", "x-amz-content-sha256", "cookie", "set-cookie");
/**
* Query parameter names carrying replayable secrets on a presigned URL, lower-cased and matched against the
* decoded name. The credential's access key id is captured separately as {@code callerAccessKeyId}, as it is no
* secret, but the signature, the security token and the full credential string are redacted here.
*/
private static final Set<String> SECRET_QUERY_PARAMS = Set.of(
"x-amz-signature", "x-amz-security-token", "x-amz-credential");
private final ObjectMapper objectMapper;
private final Supplier<EmulatorConfig> config;
private final Supplier<RequestLogWriter> writer;
// jakarta.inject.Provider qualified inline: this file imports jakarta.ws.rs.ext.Provider, the JAX-RS annotation,
// and the two types collide. Read lazily, and once, as AwsProtocolClaimFilter does: JAX-RS providers are
// instantiated before runtime config mappings exist, and an invalid mapping already fails startup.
@Inject
public RequestLogFilter(ObjectMapper objectMapper, jakarta.inject.Provider<EmulatorConfig> configProvider) {
this.objectMapper = objectMapper;
this.config = new MemoizedSupplier<>(configProvider::get);
this.writer = new MemoizedSupplier<>(() -> new RequestLogWriter(logFile(config.get())));
}
@Override
public void filter(ContainerRequestContext ctx) {
if (!enabled()) {
return;
}
try {
String url = redactUrl(ctx.getUriInfo().getRequestUri().toString());
RequestCapture capture = new RequestCapture(
System.nanoTime(),
Instant.now(),
ctx.getMethod(),
url,
headerList(ctx.getHeaders()),
queryStringList(ctx.getUriInfo().getQueryParameters()),
mimeType(ctx.getMediaType()),
callerAccessKeyId(ctx));
ctx.setProperty(CAPTURE_PROPERTY, capture);
} catch (Exception e) {
LOG.warnv(e, "Request log: could not capture request {0} {1}", ctx.getMethod(),
ctx.getUriInfo().getPath());
}
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
if (!enabled()) {
return;
}
if (!(requestContext.getProperty(CAPTURE_PROPERTY) instanceof RequestCapture capture)) {
return;
}
try {
writer.get().append(objectMapper.writeValueAsString(
buildEntry(capture, requestBody(requestContext), responseContext)));
} catch (Exception e) {
LOG.warnv(e, "Request log: could not record response for {0} {1}",
capture.method(), capture.url());
}
}
private boolean enabled() {
return config.get().requestLog().enabled();
}
/**
* The body {@link RequestLogBodyFilter} buffered, or {@code null} when the request carried none and when no
* post-matching filter ran for it at all.
*/
private static Body requestBody(ContainerRequestContext ctx) {
return ctx.getProperty(BODY_PROPERTY) instanceof Body body ? body : null;
}
private Map<String, Object> buildEntry(RequestCapture capture, Body requestBody,
ContainerResponseContext response) {
long elapsedMs = Duration.ofNanos(System.nanoTime() - capture.startedNanos()).toMillis();
Body responseBody = responseBody(response.getEntity());
Map<String, Object> request = new LinkedHashMap<>();
request.put("method", capture.method());
request.put("url", capture.url());
request.put("httpVersion", HTTP_VERSION);
request.put("cookies", List.of());
request.put("headers", capture.headers());
request.put("queryString", capture.queryString());
request.put("headersSize", -1);
request.put("bodySize", requestBody == null ? 0 : requestBody.originalSize());
if (requestBody != null) {
Map<String, Object> postData = new LinkedHashMap<>();
postData.put("mimeType", capture.mimeType());
postData.put("params", List.of());
postData.put("text", requestBody.text());
if (requestBody.encoding() != null) {
postData.put("encoding", requestBody.encoding());
}
request.put("postData", postData);
}
Map<String, Object> content = new LinkedHashMap<>();
content.put("size", responseBody.originalSize());
content.put("mimeType", mimeType(response.getMediaType()));
content.put("text", responseBody.text());
if (responseBody.encoding() != null) {
content.put("encoding", responseBody.encoding());
}
Map<String, Object> responseNode = new LinkedHashMap<>();
responseNode.put("status", response.getStatus());
responseNode.put("statusText", statusText(response));
responseNode.put("httpVersion", HTTP_VERSION);
responseNode.put("cookies", List.of());
responseNode.put("headers", headerList(response.getStringHeaders()));
responseNode.put("content", content);
responseNode.put("redirectURL", "");
responseNode.put("headersSize", -1);
responseNode.put("bodySize", responseBody.originalSize());
Map<String, Object> timings = new LinkedHashMap<>();
timings.put("send", 0);
timings.put("wait", elapsedMs);
timings.put("receive", 0);
Map<String, Object> entry = new LinkedHashMap<>();
entry.put("startedDateTime", DateTimeFormatter.ISO_OFFSET_DATE_TIME
.format(capture.startedAt().atOffset(ZoneOffset.UTC)));
entry.put("time", elapsedMs);
if (capture.callerAccessKeyId() != null) {
entry.put("callerAccessKeyId", capture.callerAccessKeyId());
}
entry.put("request", request);
entry.put("response", responseNode);
entry.put("cache", Map.of());
entry.put("timings", timings);
return entry;
}
private static Path logFile(EmulatorConfig config) {
String configured = config.requestLog().file()
.map(String::strip)
.filter(path -> !path.isEmpty())
.orElse(DEFAULT_FILE);
return Path.of(configured);
}
/** The stored form of a response entity, which is never read when it streams to the client. */
Body responseBody(Object entity) {
return switch (entity) {
case null -> Body.EMPTY;
case String text -> Body.text(text);
case byte[] bytes -> Body.bytes(bytes);
case CharSequence text -> Body.text(text.toString());
// Reading these would consume or reopen what the client is about to receive; their size is unknown here.
case InputStream ignored -> Body.STREAMED_BODY;
case StreamingOutput ignored -> Body.STREAMED_BODY;
case File ignored -> Body.STREAMED_BODY;
case Path ignored -> Body.STREAMED_BODY;
default -> serialize(entity);
};
}
/**
* Serializes an entity no further than the cap, so a large response is never held whole a second time. When the
* cap is reached the body's full size is not known, and is recorded as -1.
*/
private Body serialize(Object entity) {
CappedWriter out = new CappedWriter(MAX_BODY_BYTES);
try {
objectMapper.writeValue(out, entity);
} catch (Exception e) {
if (!out.capped()) {
LOG.tracev(e, "Request log: entity of type {0} is not serializable to JSON",
entity.getClass().getName());
return Body.text(String.valueOf(entity));
}
}
return out.capped() ? new Body(out.text(), null, -1) : Body.text(out.text());
}
private static String statusText(ContainerResponseContext response) {
Response.StatusType statusInfo = response.getStatusInfo();
return statusInfo == null || statusInfo.getReasonPhrase() == null ? "" : statusInfo.getReasonPhrase();
}
private static String mimeType(MediaType mediaType) {
return mediaType == null ? "" : mediaType.toString();
}
static List<Map<String, String>> headerList(MultivaluedMap<String, String> headers) {
return nameValueList(headers, name -> SECRET_HEADERS.contains(name.toLowerCase(Locale.ROOT)));
}
static List<Map<String, String>> queryStringList(MultivaluedMap<String, String> params) {
return nameValueList(params, name -> SECRET_QUERY_PARAMS.contains(name.toLowerCase(Locale.ROOT)));
}
/** Each value as a {@code name}/{@code value} pair, with the value of a secret name redacted. */
private static List<Map<String, String>> nameValueList(MultivaluedMap<String, String> values,
Predicate<String> secret) {
List<Map<String, String>> result = new ArrayList<>();
if (values == null) {
return result;
}
for (Map.Entry<String, List<String>> entry : values.entrySet()) {
boolean redacted = secret.test(entry.getKey());
for (String value : entry.getValue()) {
String stored = redacted ? REDACTED : (value == null ? "" : value);
result.add(Map.of("name", entry.getKey(), "value", stored));
}
}
return result;
}
/**
* The request URL with the value of every presigned-secret query parameter redacted, so the stored URL cannot be
* replayed as a still-valid signed request. A parameter is matched by its decoded name, so a percent-encoded name
* is caught too. Other parameters are kept as they were sent.
*/
static String redactUrl(String url) {
if (url == null) {
return null;
}
int query = url.indexOf('?');
if (query < 0) {
return url;
}
int fragment = url.indexOf('#', query);
String parameters = fragment < 0 ? url.substring(query + 1) : url.substring(query + 1, fragment);
StringBuilder redacted = new StringBuilder(url.length()).append(url, 0, query + 1);
String[] pairs = parameters.split("&", -1);
for (int i = 0; i < pairs.length; i++) {
if (i > 0) {
redacted.append('&');
}
String pair = pairs[i];
int equals = pair.indexOf('=');
String name = equals < 0 ? pair : pair.substring(0, equals);
if (SECRET_QUERY_PARAMS.contains(decode(name).toLowerCase(Locale.ROOT))) {
redacted.append(name).append('=').append(REDACTED);
} else {
redacted.append(pair);
}
}
if (fragment >= 0) {
redacted.append(url, fragment, url.length());
}
return redacted.toString();
}
private static String decode(String name) {
try {
return URLDecoder.decode(name, StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
return name;
}
}
private static final Pattern CREDENTIAL_AKID = Pattern.compile("Credential=([^/]+)/");
/**
* The SigV4 access key id the request was signed with, which ties each line to the caller that made it. Read from
* the {@code Authorization} header, or from the {@code X-Amz-Credential} query parameter of a presigned request;
* {@code null} for an unsigned request. Terraform, CloudFormation and direct SDK or CLI calls all sign with it.
*/
private static String callerAccessKeyId(ContainerRequestContext ctx) {
String auth = ctx.getHeaderString("Authorization");
if (auth != null) {
Matcher matcher = CREDENTIAL_AKID.matcher(auth);
if (matcher.find()) {
return matcher.group(1);
}
}
String presigned = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
if (presigned != null && !presigned.isEmpty()) {
return presigned.split("/", 2)[0];
}
return null;
}
/**
* A captured body. {@code text} is the stored form (UTF-8 text, a placeholder, or base64 for binary content),
* {@code encoding} is {@code "base64"} for binary content and {@code null} otherwise, and {@code originalSize} is
* the byte count of the body the client sent or received, before the cap, or -1 when it is not known.
*/
record Body(String text, String encoding, int originalSize) {
static final Body EMPTY = new Body("", null, 0);
static final Body STREAMED_BODY = new Body(STREAMED, null, -1);
/** Text stored up to the cap, with the size of all of it. */
static Body text(String value) {
String full = value == null ? "" : value;
String stored = full.length() <= MAX_BODY_BYTES ? full : full.substring(0, MAX_BODY_BYTES);
return new Body(stored, null, full.getBytes(StandardCharsets.UTF_8).length);
}
/**
* Bytes stored up to the cap: as text when they are valid UTF-8, else base64 with {@code encoding=base64},
* since decoding non-text bytes as UTF-8 mangles them.
*/
static Body bytes(byte[] bytes) {
byte[] capped = bytes.length <= MAX_BODY_BYTES ? bytes : Arrays.copyOf(bytes, MAX_BODY_BYTES);
String text = Utf8.decodeStrictly(capped);
return text != null
? new Body(text, null, bytes.length)
: new Body(Base64.getEncoder().encodeToString(capped), "base64", bytes.length);
}
/** A placeholder standing in for a body that was not captured. */
static Body placeholder(String marker, int originalSize) {
return new Body(marker, null, originalSize);
}
}
/** Strict UTF-8 decoding, which refuses rather than replaces bytes that are not valid UTF-8. */
static final class Utf8 {
private Utf8() {
}
static String decodeStrictly(byte[] bytes) {
try {
return StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString();
} catch (CharacterCodingException e) {
return null;
}
}
}
/** A writer that keeps the first {@code limit} characters and stops the serializer once they are filled. */
static final class CappedWriter extends Writer {
private final StringBuilder text = new StringBuilder();
private final int limit;
private boolean capped;
CappedWriter(int limit) {
this.limit = limit;
}
@Override
public void write(char[] chars, int offset, int length) {
int room = limit - text.length();
if (length > room) {
text.append(chars, offset, Math.max(room, 0));
capped = true;
throw new IllegalStateException("The request log keeps no more of this body");
}
text.append(chars, offset, length);
}
@Override
public void flush() {
}
@Override
public void close() {
}
boolean capped() {
return capped;
}
String text() {
return text.toString();
}
}
/**
* The request leg of one entry, stashed on the request context so the response filter can complete it. The body
* is not part of it: {@link RequestLogBodyFilter} buffers it later and hands it over under {@link #BODY_PROPERTY}.
*/
record RequestCapture(long startedNanos,
Instant startedAt,
String method,
String url,
List<Map<String, String>> headers,
List<Map<String, String>> queryString,
String mimeType,
String callerAccessKeyId) {
}
}
@@ -0,0 +1,139 @@
package io.floci.aws.core.common;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
/**
* Appends request-log lines to the log file from a single thread of its own, so a slow or stalled file never holds the
* request threads that produce the lines. Lines wait in a bounded queue; when it is full a line is dropped and counted
* rather than waited for. 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, so the log cannot be redirected elsewhere.
*/
final class RequestLogWriter {
private static final Logger LOG = Logger.getLogger(RequestLogWriter.class);
/** Lines the writer may fall behind by before new ones are dropped. */
static final int QUEUE_CAPACITY = 10_000;
private final Path target;
private final BlockingQueue<String> lines = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
private final AtomicLong dropped = new AtomicLong();
private Thread worker;
private FileChannel channel;
RequestLogWriter(Path target) {
this.target = target;
}
/** Queues one line for the log, dropping it when the writer is too far behind. */
void append(String line) {
startIfNeeded();
if (!lines.offer(line)) {
long count = dropped.incrementAndGet();
if (count == 1 || count % 1_000 == 0) {
LOG.warnv("Request log: {0} lines dropped because {1} is not keeping up", count, target);
}
}
}
private synchronized void startIfNeeded() {
if (worker != null) {
return;
}
worker = new Thread(this::drain, "floci-request-log");
worker.setDaemon(true);
worker.start();
}
private void drain() {
while (!Thread.currentThread().isInterrupted()) {
String line;
try {
line = lines.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
write(line);
}
}
private void write(String line) {
try {
if (channel == null) {
channel = open(target);
}
ByteBuffer bytes = ByteBuffer.wrap((line + System.lineSeparator()).getBytes(StandardCharsets.UTF_8));
while (bytes.hasRemaining()) {
channel.write(bytes);
}
} catch (IOException | RuntimeException e) {
LOG.warnv(e, "Request log: could not write {0}", target);
closeQuietly();
}
}
/**
* Opens the log for appending, creating it owner-only first. The path must name a regular file once its symbolic
* links are not followed, and the open itself does not follow one either, so a link swapped in between is refused.
*/
static FileChannel open(Path target) throws IOException {
createOwnerOnly(target);
if (!Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("The request log path is not a regular file: " + target);
}
return FileChannel.open(target, StandardOpenOption.WRITE, StandardOpenOption.APPEND,
LinkOption.NOFOLLOW_LINKS);
}
/**
* Creates the log readable and writable by its owner alone where the file system supports POSIX permissions, since
* request and response bodies, secrets included, are written to it as plain text. Anything already at the path is
* left as it is.
*/
static void createOwnerOnly(Path target) throws IOException {
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
return;
}
Path parent = target.toAbsolutePath().getParent();
if (parent != null) {
Files.createDirectories(parent);
}
try {
if (target.getFileSystem().supportedFileAttributeViews().contains("posix")) {
Files.createFile(target, PosixFilePermissions.asFileAttribute(
PosixFilePermissions.fromString("rw-------")));
} else {
Files.createFile(target);
}
} catch (FileAlreadyExistsException e) {
// Created by someone else first; it keeps what it was created with.
}
}
private void closeQuietly() {
if (channel == null) {
return;
}
try {
channel.close();
} catch (IOException e) {
LOG.debugv(e, "Request log: could not close {0}", target);
}
channel = null;
}
}
+4
View File
@@ -393,6 +393,10 @@ floci:
strict-claiming: false # FLOCI_PROTOCOLS_STRICT_CLAIMING — reject RPC-signaled requests that no supported wire protocol claims
reject-unknown-service-scope: true # FLOCI_PROTOCOLS_REJECT_UNKNOWN_SERVICE_SCOPE — reject REST requests signed for a service Floci does not implement
request-log:
enabled: false # FLOCI_REQUEST_LOG_ENABLED: write every request and response as one JSON line (holds bodies, secrets included)
# file: ./floci-requests.jsonl # FLOCI_REQUEST_LOG_FILE
docker:
log-max-size: "10m"
log-max-file: "3"
@@ -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);
}
}
@@ -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; }