Compare commits

...
3 Commits
Author SHA1 Message Date
ngqile 076548bd5f Merge pull request 'fix(gateway): never log request bodies' (#11) from stop-gateway-body-logging into main 2026-11-30 01:24:43 +00:00
ngqileandClaude Opus 5.5 0562689c6e 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
2026-11-30 09:24:31 +08:00
ngqileandClaude Opus 5.5 f81202f46c docs(openspec): propose stop-gateway-body-logging
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 18:18:37 +08:00
9 changed files with 206 additions and 284 deletions

No files matched your search

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-27
@@ -0,0 +1,28 @@
# Design
## Context
`RequestBodyLoggerFilter` is a global gateway filter (order -200, before `JWTAuthFilter` at -100). For a GET it logs method, path and headers. For any other method it reads the whole body into memory, logs it through `LogRedactor.body` (JSON and form fields whose names contain password, pwd, secret or token are masked; other content types and bodies over 64 KB are logged by size only), then re-wraps the cached bytes in a request decorator with a fixed Content-Length. No other gateway filter reads the body. See proposal.md for why bodies must go.
## Goals / Non-Goals
**Goals:** no request body content in the gateway log, for every method and content type; downstream requests unchanged.
**Non-Goals:** changing what mobile-api or the services log; changing the skip list or the header and path masking.
## Decisions
1. **Log every method the way GET is logged today.** One line, `Method`, masked `Path`, masked `Headers`, then pass the exchange on untouched. Content-Length is part of the headers, so the body size stays visible.
- Alternative: keep reading the body to log its size. Rejected: the header already carries the size for non-chunked bodies, and reading the body is the only reason the filter buffers whole requests in memory and rebuilds them.
- Alternative: mask known PII field names (name, mobile, email). Rejected by the user: a denylist misses fields it does not name.
2. **Delete the body-masking code.** `LogRedactor.body`, the JSON and form maskers, `isSensitiveName`, the size constants and their tests have no callers once the filter stops logging bodies. `headers` and `path` stay. The deleted `LogRedactorTest` cases test only removed code: `jsonAnyValueTypeMasked`, `jsonEscapedKeyMasked`, `jsonWithoutContentType`, `brokenJsonNotLogged`, `formMasked`, `otherBodiesNotLogged`, `sizeLimits`, `adversarialBodiesAreLinear`.
3. **Rewrite the body assertions in `RequestBodyLoggerFilterTest`.** `customerLoginPasswordMasked`, `sensitiveFieldsMasked` and `formPasswordMasked` assert a masked body today. They become "no body content in the log" tests, which also forbid the non-secret fields (username, name) the old tests required. Each still checks the downstream body is unchanged. `emptyBody` asserted the `(empty)` marker; it now asserts the line is logged and the request is forwarded. A new test covers a lead update body and a query string.
## Risks / Trade-offs
- [Bodies are no longer available in the log for debugging] → Method, path, headers and size remain. A service can log a specific, non-PII field itself where it needs one.
- [A future change re-adds body logging] → The spec forbids it, and the filter test fails if any body content reaches the log.
## Migration Plan
Deploy the gateway. Rollback is redeploying the previous gateway image. No data or contract changes. Bodies already in Elasticsearch are not touched by this change; whether to purge them is a separate operational decision.
@@ -0,0 +1,36 @@
# Proposal
## Why
The API gateway logs the body of every POST and PUT request, and the log is shipped to Elasticsearch. Only credentials are masked (passwords, tokens, keys). Every other field is logged as sent, so personal data reaches the log:
- lead capture, lead update and lead search (names, mobiles, emails, notes);
- member calls;
- admin user create and edit;
- forgot-password.
The project rules forbid logging customer PII. The `add-lead-listing-export` branch review found this, and it has to be fixed before go-live on 2027-01-15.
## What Changes
- The gateway request log keeps one line per request with the method, the path and the headers, and never the request body. Credential header values and JWT-shaped path segments stay masked, as today.
- The gateway no longer reads the request body to log it, so the body passes to the downstream service untouched. No other gateway filter reads the body.
- The body-masking code (JSON and form field masking, size limits) has no callers left and is removed, together with its unit tests. Header and path masking and their tests stay.
- The filter tests that asserted a masked body now assert that no body content reaches the log at all, and that the downstream service still receives the original body. These tests get stricter, not weaker.
- The skip list (`/log/save`, `/log/saveMemberLog`, `/auth/authenticate`, `/auth/webMemberAuthenticate`) and the `/actuator` skip stay as they are.
Not in this change: logging elsewhere (mobile-api and service logs), log retention, and access logs.
## Capabilities
### New Capabilities
- `gateway-request-logging`: what the gateway writes to its request log, and what it must never write there.
### Modified Capabilities
None.
## Impact
- `solvway-api-gateway`: `RequestBodyLoggerFilter` (logs without reading the body), `LogRedactor` (body masking removed), and their tests.
- **Debugging**: request bodies are no longer in the gateway log. Content-Length is still logged with the headers, so the size of each body stays visible.
- No API, database or dependency change. Downstream services see the same requests.
@@ -0,0 +1,61 @@
## Purpose
The gateway keeps a log line for each request it routes, so operators can trace traffic, without ever writing request bodies, personal data or credentials to that log.
## ADDED Requirements
### Requirement: Request log carries no request body
The gateway SHALL log each routed request, except skip-listed and `/actuator` paths, as one line with the method, the path and the request headers. It MUST NOT write any part of the request body to the log, for any method or content type. The downstream service MUST receive the original request body unchanged.
#### Scenario: Lead update body stays out of the log
- **GIVEN** a PUT or POST with a JSON body holding a lead's name, mobile, email and notes
- **WHEN** the gateway routes it
- **THEN** the log line holds the method and the path
- **AND** none of the name, mobile, email or notes appears in the log
- **AND** the downstream service receives the body byte for byte
#### Scenario: Login body stays out of the log
- **GIVEN** a customer login POST with a username and a password in a JSON body
- **WHEN** the gateway routes it
- **THEN** neither the username nor the password appears in the log
#### Scenario: Form body stays out of the log
- **GIVEN** a form-encoded POST with a username and a password
- **WHEN** the gateway routes it
- **THEN** no field name or value from the body appears in the log
#### Scenario: Empty body is still routed
- **GIVEN** a POST with no body
- **WHEN** the gateway routes it
- **THEN** the request is logged and reaches the downstream service with no body
#### Scenario: Skip-listed path is not logged
- **WHEN** a request to `/auth/authenticate` passes through the gateway
- **THEN** nothing about it is written to the request log
### Requirement: Credentials in headers and paths are masked
The gateway SHALL mask the values of credential headers (Authorization, Proxy-Authorization, api-key, x-api-key, Cookie, Set-Cookie, X-XSRF-TOKEN, X-CSRF-TOKEN) and any JWT-shaped path segment in the request log. Header names and other header values MUST stay readable. The query string MUST NOT be logged.
#### Scenario: Authorization and api-key are masked
- **GIVEN** a request with an Authorization bearer token, an api-key and an Accept header
- **WHEN** the gateway logs it
- **THEN** the token and the key do not appear in the log
- **AND** the Accept header value does
#### Scenario: JWT in the path is masked
- **WHEN** a request to `/auth/findUserByToken/M/<jwt>` is logged
- **THEN** the log shows `/auth/findUserByToken/M/***`
#### Scenario: Search term in the query string is not logged
- **WHEN** a GET with the query string `?q=aisyah` is logged
- **THEN** the log shows the path without `aisyah`
@@ -0,0 +1,24 @@
# Tasks
Design: `design.md`. One serial task: the filter and its redactor change together.
## 1. Gateway
- [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;
- customer login, password change and form login: no body field name or value in the log, downstream body unchanged (rewrites the three masked-body tests);
- an empty POST is logged and forwarded (rewrites `emptyBody`);
- a GET with `?q=aisyah`: the term is not in the log;
- header and JWT-path masking and the skip list keep their existing tests unchanged.
Run them red, then change the filter to log method, masked path and masked headers for every method without reading the body. Delete `LogRedactor.body` and everything only it uses, with the eight body-only `LogRedactorTest` cases named in design decision 2.
Live check: rebuild the gateway, capture and update a made-up lead through the portal, and confirm with `docker compose logs api-gateway` that the lead's name, mobile and email are absent while the request lines are present.
- Scope: `solvway-api-gateway/src/**/filter/RequestBodyLoggerFilter*`, `solvway-api-gateway/src/**/filter/LogRedactor*`
- Verify: `mvn -T 1C -B -q -pl solvway-api-gateway -am verify`.
## Workflow follow-up
- Whole-branch review, push, PR to main and merge, then archive on its own branch.
@@ -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;
}
}
}
@@ -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;
}
}
@@ -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("<req><password>" + SECRET + "</password></req>", 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() {
@@ -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");
}
}