Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import org.apache.catalina.connector.ClientAbortException;
import org.slf4j.Logger;
import org.slf4j.MDC;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
Expand Down Expand Up @@ -44,6 +45,7 @@
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

private static final Logger RUNTIME_ERROR_LOGGER = LoggerFactory.getLogger("runtime.error");
private static final String REQUEST_ID_MDC_KEY = "requestId";
private static final String MASKED_HEADER_VALUE = "***";
private static final List<String> SENSITIVE_HEADER_NAMES = List.of(
"authorization",
Expand Down Expand Up @@ -209,19 +211,21 @@ public ResponseEntity<Object> handleException(HttpServletRequest request, Except
String exception = e.getClass().getSimpleName();
String location = String.format("%s:%d", origin.getFileName(), origin.getLineNumber());
String message = e.getMessage();
String requestId = getRequestId();

String slackMessage = String.format(
"""
Request ID: `%s`
URI: `%s`
Location: `%s`
Exception: `%s`
```%s```
""",
uri, location, exception, message
requestId, uri, location, exception, message
);

RUNTIME_ERROR_LOGGER.error(slackMessage);
requestDebugLogging(request);
requestDebugLogging(request, requestId);

return buildErrorResponse(ApiResponseCode.UNEXPECTED_SERVER_ERROR);
}
Expand Down Expand Up @@ -272,17 +276,25 @@ private void requestLogging(
String errorTraceId
) {
log.warn("[{}] {} | errorTraceId={}", httpStatus, errorMessage, errorTraceId);
requestDebugLogging(request);
requestDebugLogging(request, getRequestId());
}

private void requestDebugLogging(HttpServletRequest request) {
private void requestDebugLogging(HttpServletRequest request, String requestId) {
if (!log.isDebugEnabled()) {
return;
}
log.debug("Request: {} {}", request.getMethod(), request.getRequestURI());
log.debug("Headers: {}", getLoggableHeaders(request));
log.debug("Query String: {}", getQueryString(request));
log.debug("Body: {}", getRequestBody(request));
log.debug("Request [requestId: {}]: {} {}", requestId, request.getMethod(), request.getRequestURI());
log.debug("Headers [requestId: {}]: {}", requestId, getLoggableHeaders(request));
log.debug("Query String [requestId: {}]: {}", requestId, getQueryString(request));
log.debug("Body [requestId: {}]: {}", requestId, getRequestBody(request));
}

private String getRequestId() {
String requestId = MDC.get(REQUEST_ID_MDC_KEY);
if (requestId == null) {
return " - ";
}
return requestId;
}

private Map<String, Object> getLoggableHeaders(HttpServletRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.http.HttpStatus;
Expand All @@ -34,12 +35,14 @@ void setUp() {
@AfterEach
void tearDown() {
exceptionHandlerLogger.setLevel(originalLevel);
MDC.clear();
}

@Test
@DisplayName("예상하지 못한 예외도 디버그 로그에서 요청 본문을 확인할 수 있다")
void logsRequestBodyAtDebugLevelForUnexpectedException(CapturedOutput output) {
// given
MDC.put("requestId", "request-123");
GlobalExceptionHandler handler = new GlobalExceptionHandler();
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/clubs");
request.setContentType("application/json");
Expand All @@ -61,21 +64,23 @@ void logsRequestBodyAtDebugLevelForUnexpectedException(CapturedOutput output) {
// then
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(output)
.contains("Request: POST /clubs")
.contains("Request ID: `request-123`")
.contains("Request [requestId: request-123]: POST /clubs")
.contains("Authorization=***")
.contains("Cookie=***")
.contains("X-Request-ID=request-1")
.doesNotContain("secret-token")
.doesNotContain("secret-cookie")
.contains(
"Query String: access%5Ftoken=***&access_token=***&code=***&name=KONECT&token=***&token=***"
"Query String [requestId: request-123]: "
+ "access%5Ftoken=***&access_token=***&code=***&name=KONECT&token=***&token=***"
)
.doesNotContain("encoded-query-secret")
.doesNotContain("query-secret")
.doesNotContain("oauth-code")
.doesNotContain("repeat-secret-one")
.doesNotContain("repeat-secret-two")
.contains("Body: {\"name\":\"KONECT\"}");
.contains("Body [requestId: request-123]: {\"name\":\"KONECT\"}");
}

@Test
Expand All @@ -97,7 +102,7 @@ void skipsRequestDetailLoggingWhenDebugIsDisabled(CapturedOutput output) {
// then
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(output)
.doesNotContain("Request: POST /clubs")
.doesNotContain("Request [requestId:")
.doesNotContain("Body: {\"name\":\"KONECT\"}");
Comment on lines +105 to 106
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

[LEVEL: low] DEBUG 비활성화 테스트의 Body 검증 문자열이 현재 포맷과 불일치합니다.
문제: Line 106이 Body: {"name":"KONECT"} 구포맷만 검사해서 Body [requestId: ...] 형태의 본문 로그 누출을 직접 검출하지 못합니다.
영향: DEBUG OFF 회귀가 발생해도 테스트가 통과해 민감 정보 로깅 회귀를 놓칠 수 있습니다.
제안: 현재 포맷 기준으로 doesNotContain("Body [requestId:") 검증을 추가하거나 교체하세요.

최소 수정 예시
         assertThat(output)
             .doesNotContain("Request [requestId:")
-            .doesNotContain("Body: {\"name\":\"KONECT\"}");
+            .doesNotContain("Body [requestId:");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/test/java/gg/agit/konect/unit/global/exception/GlobalExceptionHandlerTest.java`
around lines 105 - 106, The test in GlobalExceptionHandlerTest currently checks
.doesNotContain("Body: {\"name\":\"KONECT\"}") which misses the actual log
format that can leak sensitive data; update the assertion on the logger output
(the chain containing .doesNotContain(...)) to either replace or add a check for
.doesNotContain("Body [requestId:") so the test fails if the log contains the
"Body [requestId:"-style payload; locate the assertion in
GlobalExceptionHandlerTest and modify the doesNotContain call(s) accordingly.

}
}
Loading