diff --git a/openspec/changes/stop-gateway-body-logging/tasks.md b/openspec/changes/stop-gateway-body-logging/tasks.md index f042ec1..e6e878f 100644 --- a/openspec/changes/stop-gateway-body-logging/tasks.md +++ b/openspec/changes/stop-gateway-body-logging/tasks.md @@ -4,7 +4,7 @@ Design: `design.md`. One serial task: the filter and its redactor change togethe ## 1. Gateway -- [ ] 1.1 Stop logging request bodies (design decisions 1 to 3). +- [x] 1.1 Stop logging request bodies (design decisions 1 to 3). Tests first, in `RequestBodyLoggerFilterTest`: - a lead update PUT (name, mobile, email, notes): none of the values in the log, method and path present, downstream body unchanged; diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java index e7d6d16..e83bd1b 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java @@ -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 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 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> fields = object.fields(); - while (fields.hasNext()) { - Map.Entry 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; - } - } } diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/RequestBodyLoggerFilter.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/RequestBodyLoggerFilter.java index 73d73e9..bf4cf02 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/RequestBodyLoggerFilter.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/RequestBodyLoggerFilter.java @@ -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 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; } } \ No newline at end of file diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java index 348a9e6..9c93f0b 100644 --- a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java @@ -9,12 +9,9 @@ import java.util.Locale; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; - -import com.fasterxml.jackson.databind.ObjectMapper; /** - * F47: what the gateway may write to its request log. Every method here runs on every request, on a Netty event-loop + * F47: the header and path copy the gateway writes to its request log. Every method here runs on every request, on a Netty event-loop * thread, before authentication, so each must be linear in the input and must never throw. */ class LogRedactorTest { @@ -22,85 +19,6 @@ class LogRedactorTest { private static final String SECRET = "S3cret#Pw"; private static final String JWT = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyIn0.c2lnbmF0dXJl"; - private static String body(String body, MediaType type) { - return LogRedactor.body(body.getBytes(java.nio.charset.StandardCharsets.UTF_8), type); - } - - @Test - @DisplayName("JSON: values of any type under a sensitive key are masked, at any depth; other fields kept") - void jsonAnyValueTypeMasked() throws Exception { - String logged = body("{\"username\":\"u1\",\"password\":\"" + SECRET + "\",\"otpToken\":123456," - + "\"pwdHistory\":[\"" + SECRET + "\"],\"profile\":{\"clientSecret\":{\"v\":\"" + SECRET + "\"},\"name\":\"Ali\"}," - + "\"items\":[{\"refreshToken\":\"" + JWT + "\"}],\"newPassword\":null}", MediaType.APPLICATION_JSON); - - assertThat(logged).doesNotContain(SECRET).doesNotContain(JWT).doesNotContain("123456"); - assertThat(new ObjectMapper().readTree(logged).path("username").asText()).isEqualTo("u1"); - assertThat(new ObjectMapper().readTree(logged).path("profile").path("name").asText()).isEqualTo("Ali"); - assertThat(new ObjectMapper().readTree(logged).path("password").asText()).isEqualTo("***"); - } - - @Test - @DisplayName("JSON: a unicode-escaped key is still recognised") - void jsonEscapedKeyMasked() { - assertThat(body("{\"\\u0070assword\":\"" + SECRET + "\"}", MediaType.APPLICATION_JSON)).doesNotContain(SECRET); - } - - @Test - @DisplayName("JSON body without a content type is still parsed and masked") - void jsonWithoutContentType() { - assertThat(body("{\"password\":\"" + SECRET + "\"}", null)).doesNotContain(SECRET).contains("***"); - } - - @Test - @DisplayName("unparseable JSON is not logged, only its size") - void brokenJsonNotLogged() { - assertThat(body("{\"password\":\"" + SECRET, MediaType.APPLICATION_JSON)) - .doesNotContain(SECRET).contains("not logged"); - } - - @Test - @DisplayName("form: sensitive fields masked, including URL-encoded names; others kept") - void formMasked() { - String logged = body("username=u1&password=" + SECRET + "&pass%77ord=" + SECRET + "&user%5Bpwd%5D=" + SECRET - + "&remember=1", MediaType.APPLICATION_FORM_URLENCODED); - - assertThat(logged).doesNotContain(SECRET).contains("username=u1").contains("remember=1").contains("password=***"); - } - - @Test - @DisplayName("multipart and other content types are not logged, only their size") - void otherBodiesNotLogged() { - assertThat(body("--b\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n" + SECRET + "\r\n--b--", - MediaType.MULTIPART_FORM_DATA)).doesNotContain(SECRET).contains("not logged"); - assertThat(body("" + SECRET + "", MediaType.APPLICATION_XML)) - .doesNotContain(SECRET).contains("not logged"); - } - - @Test - @DisplayName("bodies over the parse limit are not logged; logged bodies are capped") - void sizeLimits() { - String big = "{\"note\":\"" + "x".repeat(LogRedactor.MAX_PARSE_BYTES) + "\"}"; - assertThat(body(big, MediaType.APPLICATION_JSON)).contains("not logged").hasSizeLessThan(200); - - String medium = "{\"note\":\"" + "y".repeat(LogRedactor.MAX_LOGGED_CHARS * 2) + "\"}"; - assertThat(body(medium, MediaType.APPLICATION_JSON)).hasSizeLessThan(LogRedactor.MAX_LOGGED_CHARS + 100) - .contains("truncated"); - } - - @Test - @DisplayName("adversarial bodies (long secret value, keyword floods) finish fast and never throw") - void adversarialBodiesAreLinear() { - String longToken = "{\"token\":\"" + "A".repeat(60_000) + "\"}"; - String keywordFloodJson = "{\"" + "password".repeat(7_000) + "\":1}"; - String keywordFloodForm = "password".repeat(7_000); - assertTimeoutPreemptively(Duration.ofSeconds(2), () -> { - assertThat(body(longToken, MediaType.APPLICATION_JSON)).doesNotContain("AAAAAAAAAA"); - body(keywordFloodJson, MediaType.APPLICATION_JSON); - body(keywordFloodForm, MediaType.APPLICATION_FORM_URLENCODED); - body(keywordFloodForm, null); - }); - } - @Test @DisplayName("headers: credential values masked case-insensitively, also under a Turkish default locale") void headersMasked() { diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/RequestBodyLoggerFilterTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/RequestBodyLoggerFilterTest.java index 12a423c..337d0bb 100644 --- a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/RequestBodyLoggerFilterTest.java +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/RequestBodyLoggerFilterTest.java @@ -22,10 +22,9 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; /** - * The gateway logs every request (method, path, body, headers) and ships the log to Elasticsearch. Credentials must - * not reach that log: the customer login body (/auth/webCustomerAuthenticate is not on the skip list), password - * change/registration bodies, and the Authorization / api-key headers sent on every call. The downstream request - * must still receive the original, unmasked body. + * The gateway logs every request (method, path, headers) and ships the log to Elasticsearch. No request body may + * reach that log (personal data and credentials alike), credential headers and JWTs in the path are masked, and the + * downstream request must still receive the original body (spec gateway-request-logging). */ class RequestBodyLoggerFilterTest { @@ -74,8 +73,8 @@ class RequestBodyLoggerFilterTest { } @Test - @DisplayName("customer login: the password is masked in the log and passed unchanged downstream") - void customerLoginPasswordMasked() { + @DisplayName("customer login: no body content in the log, body passed unchanged downstream") + void customerLoginBodyNotLogged() { String body = "{\"username\":\"cust@example.com\",\"password\":\"" + PASSWORD + "\"}"; String downstream = run(MockServerHttpRequest.post("/auth/webCustomerAuthenticate") @@ -85,15 +84,14 @@ class RequestBodyLoggerFilterTest { String line = loggedLine(); assertThat(line).doesNotContain(PASSWORD).doesNotContain(API_KEY) - .contains("/auth/webCustomerAuthenticate") - .contains("\"username\":\"cust@example.com\"") - .contains("\"password\":\"***\""); + .contains("POST").contains("/auth/webCustomerAuthenticate") + .doesNotContain("cust@example.com").doesNotContain("username").doesNotContain("password"); assertThat(downstream).isEqualTo(body); } @Test - @DisplayName("password change and token fields are masked, other fields kept") - void sensitiveFieldsMasked() { + @DisplayName("password change: no body field name or value in the log") + void passwordChangeBodyNotLogged() { String body = "{\"id\":7,\"oldPassword\":\"old" + PASSWORD + "\",\"newPassword\":\"new" + PASSWORD + "\",\"confirmPassword\":\"new" + PASSWORD + "\",\"refreshToken\":\"" + JWT + "\",\"clientSecret\":\"x" + PASSWORD + "\",\"name\":\"Ali\"}"; @@ -103,19 +101,22 @@ class RequestBodyLoggerFilterTest { String line = loggedLine(); assertThat(line).doesNotContain(PASSWORD).doesNotContain(JWT) - .contains("\"id\":7").contains("\"name\":\"Ali\"") - .contains("\"oldPassword\":\"***\"").contains("\"refreshToken\":\"***\""); + .doesNotContain("Ali").doesNotContain("oldPassword").doesNotContain("refreshToken") + .contains("/user/changePassword"); assertThat(downstream).isEqualTo(body); } @Test - @DisplayName("form-encoded password is masked") - void formPasswordMasked() { - run(MockServerHttpRequest.post("/auth/stockistAuthenticate") + @DisplayName("form body: no field name or value in the log, body passed unchanged downstream") + void formBodyNotLogged() { + String body = "username=u1&password=" + PASSWORD + "&remember=1"; + String downstream = run(MockServerHttpRequest.post("/auth/stockistAuthenticate") .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .body("username=u1&password=" + PASSWORD + "&remember=1")); + .body(body)); - assertThat(loggedLine()).doesNotContain(PASSWORD).contains("password=***").contains("remember=1"); + assertThat(loggedLine()).doesNotContain(PASSWORD).doesNotContain("username").doesNotContain("password=") + .doesNotContain("remember").contains("/auth/stockistAuthenticate"); + assertThat(downstream).isEqualTo(body); } @Test @@ -152,11 +153,34 @@ class RequestBodyLoggerFilterTest { } @Test - @DisplayName("an empty POST body is logged as (empty) and still forwarded") + @DisplayName("an empty POST is logged and still forwarded") void emptyBody() { String downstream = run(MockServerHttpRequest.post("/user/ping").header("api-key", API_KEY).build()); - assertThat(loggedLine()).contains("(empty)").doesNotContain(API_KEY); + assertThat(loggedLine()).contains("POST").contains("/user/ping").doesNotContain(API_KEY); assertThat(downstream).isEmpty(); } + + @Test + @DisplayName("lead update: name, mobile, email and notes stay out of the log, body passed unchanged") + void leadUpdateBodyNotLogged() { + String body = "{\"leadUuid\":\"3312900963345457152\",\"name\":\"Aisyah Rahman\",\"mobile\":\"+60123456701\"," + + "\"email\":\"aisyah@example.test\",\"notes\":\"Prefers weekend calls\"}"; + + String downstream = run(MockServerHttpRequest.put("/counter/lead/update") + .contentType(MediaType.APPLICATION_JSON).body(body)); + + assertThat(loggedLine()).contains("PUT").contains("/counter/lead/update") + .doesNotContain("Aisyah").doesNotContain("60123456701").doesNotContain("aisyah@example.test") + .doesNotContain("weekend").doesNotContain("3312900963345457152"); + assertThat(downstream).isEqualTo(body); + } + + @Test + @DisplayName("the query string is not logged") + void queryStringNotLogged() { + run(MockServerHttpRequest.get("/counter/lead/list?q=aisyah&page=0").build()); + + assertThat(loggedLine()).contains("/counter/lead/list").doesNotContain("aisyah"); + } }