fix(gateway): never log request bodies
The gateway logged every POST and PUT body with only credentials masked, so lead, member, user and forgot-password personal data reached the log. It now logs method, masked path and masked headers only, and no longer reads or rebuilds the body. The body-masking code and its tests go. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
f81202f46c
commit
0562689c6e
5 files changed
+56
-285
No files matched your search
@@ -1,56 +1,27 @@
|
||||
package com.solvway.gateway.filter;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
|
||||
/**
|
||||
* Security finding F47: builds the copy of a request that the gateway may write to its log (shipped to
|
||||
* Elasticsearch) with credentials masked. Runs on every request, on the event loop, before authentication, so every
|
||||
* method is linear in its input (no regular expressions) and never throws. The request itself is never changed.
|
||||
* Security finding F47: masks credentials in the header and path copy that the gateway writes to its log (shipped to
|
||||
* Elasticsearch). Request bodies are never logged. Runs on every request, on the event loop, before authentication,
|
||||
* so every method is linear in its input (no regular expressions) and never throws. The request itself is never changed.
|
||||
*/
|
||||
final class LogRedactor {
|
||||
|
||||
static final String MASK = "***";
|
||||
/** Bodies larger than this are not parsed or logged, only their size. */
|
||||
static final int MAX_PARSE_BYTES = 64 * 1024;
|
||||
/** A logged (masked) body is cut to this many characters. */
|
||||
static final int MAX_LOGGED_CHARS = 4096;
|
||||
|
||||
/** Header values that carry credentials; compared lower-case. */
|
||||
private static final Set<String> SENSITIVE_HEADERS = Set.of("authorization", "proxy-authorization", "api-key",
|
||||
"x-api-key", "cookie", "set-cookie", "x-xsrf-token", "x-csrf-token");
|
||||
/** A body field is sensitive when its name contains one of these (lower-case). */
|
||||
private static final List<String> SENSITIVE_NAME_PARTS = List.of("password", "pwd", "secret", "token");
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private LogRedactor() {
|
||||
}
|
||||
|
||||
static boolean isSensitiveName(String name) {
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
for (String part : SENSITIVE_NAME_PARTS) {
|
||||
if (lower.contains(part)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** "Name:[v1, v2], Name2:[v]" with credential header values replaced by the mask. */
|
||||
static String headers(HttpHeaders headers) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
@@ -86,92 +57,4 @@ final class LogRedactor {
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** The body as it may be logged: JSON and form bodies with credentials masked; anything else only by size. */
|
||||
static String body(byte[] bytes, MediaType contentType) {
|
||||
if (bytes.length > MAX_PARSE_BYTES) {
|
||||
return notLogged("body", bytes.length);
|
||||
}
|
||||
String text = new String(bytes, StandardCharsets.UTF_8);
|
||||
String masked;
|
||||
if (contentType != null && MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) {
|
||||
masked = maskForm(text);
|
||||
} else if (contentType == null || contentType.getSubtype().toLowerCase(Locale.ROOT).contains("json")) {
|
||||
masked = maskJson(text);
|
||||
if (masked == null) {
|
||||
return notLogged(contentType == null ? "body" : "unparseable JSON body", bytes.length);
|
||||
}
|
||||
} else {
|
||||
return notLogged(contentType.getType() + "/" + contentType.getSubtype() + " body", bytes.length);
|
||||
}
|
||||
return masked.length() > MAX_LOGGED_CHARS
|
||||
? masked.substring(0, MAX_LOGGED_CHARS) + "...(truncated, " + masked.length() + " chars)"
|
||||
: masked;
|
||||
}
|
||||
|
||||
private static String notLogged(String what, int length) {
|
||||
return "(" + what + " of " + length + " bytes, not logged)";
|
||||
}
|
||||
|
||||
/** The JSON with sensitive fields masked, or null when the text is not JSON. */
|
||||
private static String maskJson(String text) {
|
||||
try {
|
||||
JsonNode tree = MAPPER.readTree(text);
|
||||
if (tree == null) {
|
||||
return null;
|
||||
}
|
||||
mask(tree);
|
||||
return MAPPER.writeValueAsString(tree);
|
||||
} catch (Exception | StackOverflowError e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void mask(JsonNode node) {
|
||||
if (node instanceof ObjectNode object) {
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = object.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
if (isSensitiveName(field.getKey())) {
|
||||
field.setValue(TextNode.valueOf(MASK));
|
||||
} else {
|
||||
mask(field.getValue());
|
||||
}
|
||||
}
|
||||
} else if (node instanceof ArrayNode array) {
|
||||
for (JsonNode element : array) {
|
||||
mask(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String maskForm(String text) {
|
||||
StringBuilder sb = new StringBuilder(text.length());
|
||||
int start = 0;
|
||||
while (start <= text.length()) {
|
||||
int amp = text.indexOf('&', start);
|
||||
int end = amp < 0 ? text.length() : amp;
|
||||
String pair = text.substring(start, end);
|
||||
int eq = pair.indexOf('=');
|
||||
if (eq >= 0 && isSensitiveName(decode(pair.substring(0, eq)))) {
|
||||
sb.append(pair, 0, eq + 1).append(MASK);
|
||||
} else {
|
||||
sb.append(pair);
|
||||
}
|
||||
if (amp < 0) {
|
||||
break;
|
||||
}
|
||||
sb.append('&');
|
||||
start = amp + 1;
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String decode(String name) {
|
||||
try {
|
||||
return URLDecoder.decode(name, StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-61
@@ -4,15 +4,9 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||
import org.springframework.cloud.gateway.filter.GlobalFilter;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.List;
|
||||
@@ -33,65 +27,17 @@ public class RequestBodyLoggerFilter implements GlobalFilter, Ordered {
|
||||
if (requestUri.startsWith("/actuator")) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
// F47: credentials (headers, body fields, JWTs in the path) are masked in the logged copy only
|
||||
String headerString = LogRedactor.headers(request.getHeaders());
|
||||
String loggedPath = LogRedactor.path(request.getURI().getPath());
|
||||
final HttpMethod method = request.getMethod();
|
||||
if (method == HttpMethod.GET) {
|
||||
log.info("Method: {}, Path: {}, Body: {}, Headers: {}", method, loggedPath, "{}", headerString);
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
return DataBufferUtils.join(request.getBody())
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
log.info("Method: {}, Path: {}, Body: {}, Headers: {}", method, loggedPath, "(empty)", headerString);
|
||||
return chain.filter(exchange).then(Mono.empty());
|
||||
}))
|
||||
.flatMap(dataBuffer -> {
|
||||
// 1. Read the body into a byte array and release the buffer
|
||||
byte[] bytes = new byte[dataBuffer.readableByteCount()];
|
||||
dataBuffer.read(bytes);
|
||||
DataBufferUtils.release(dataBuffer);
|
||||
|
||||
// 2. Log the captured body
|
||||
log.info("Method: {}, Path: {}, Body: {}, Headers: {}", method, loggedPath,
|
||||
LogRedactor.body(bytes, request.getHeaders().getContentType()), headerString);
|
||||
|
||||
// 3. Create a decorated request with the cached body and updated headers
|
||||
ServerHttpRequestDecorator decoratedRequest = new ServerHttpRequestDecorator(request) {
|
||||
@Override
|
||||
public Flux<DataBuffer> getBody() {
|
||||
// Return a new Flux with the cached body
|
||||
return Flux.just(exchange.getResponse().bufferFactory().wrap(bytes));
|
||||
}
|
||||
|
||||
// THIS IS THE CRITICAL FIX:
|
||||
// We must provide new headers that accurately reflect the cached body.
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
// Create a mutable copy of the original headers
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.putAll(super.getHeaders());
|
||||
|
||||
// If the original request was chunked, the Transfer-Encoding header will be present.
|
||||
// We must remove it as we are now providing a fixed-length body.
|
||||
httpHeaders.remove(HttpHeaders.TRANSFER_ENCODING);
|
||||
|
||||
// Set the content length to the exact size of our cached body.
|
||||
httpHeaders.setContentLength(bytes.length);
|
||||
|
||||
return httpHeaders;
|
||||
}
|
||||
};
|
||||
|
||||
// 4. Continue the filter chain with the new exchange containing the decorated request
|
||||
return chain.filter(exchange.mutate().request(decoratedRequest).build());
|
||||
});
|
||||
// F47: credentials (headers, JWTs in the path) are masked in the logged copy only. The body is never read or
|
||||
// logged (spec gateway-request-logging): it carries personal data. Content-Length in the headers shows its size,
|
||||
// except for chunked requests.
|
||||
log.info("Method: {}, Path: {}, Headers: {}", request.getMethod(),
|
||||
LogRedactor.path(request.getURI().getPath()), LogRedactor.headers(request.getHeaders()));
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
// This must run before the JWTAuthFilter (-100)
|
||||
// Runs before the JWTAuthFilter (-100), so rejected requests are logged too.
|
||||
return -200;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user