From 7ce83b73d949e510ac0e7150be1ccdcc943e24b3 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 22:17:02 +0900 Subject: [PATCH] =?UTF-8?q?fix(web):=20=EB=B3=B4=EC=95=88=20=ED=95=84?= =?UTF-8?q?=ED=84=B0=EA=B0=80=205xx=20=EC=9D=B8=EC=A6=9D=20=EC=8B=A4?= =?UTF-8?q?=ED=8C=A8=EB=A5=BC=20ERROR=EB=A1=9C=20=EB=82=A8=EA=B8=B4?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: AuthErrorResponseWriter는 보안 필터가 답한 실패를 모두 WARN으로 남긴다. AUTH_JWKS_UNAVAILABLE(503, 키 서버 장애)과 INTERNAL_AUTH_MISCONFIGURATION(500, 인증 설정 오류)은 서버 쪽 고장인데도 WARN이다. 다른 모든 경로는 5xx를 ERROR로 남기므로(ServerFailureLog) 규칙이 갈라져 있고, ERROR로 거르는 운영자는 이 둘을 놓친다. 고른 방법: 응답 상태로 레벨을 고른다. 5xx는 ERROR, 4xx는 WARN이다. 줄의 모양(code·category·method·path, 예외 없음)은 그대로다. 401 서명·issuer· audience 불일치는 WARN으로 둔다(소유자 결정 3, 2026-11-06). 테스트가 서명 실패 WARN도 고정한다. 버린 대안: 두 코드를 이름으로 나열하기 — 새 5xx 보안 코드가 생기면 조용히 WARN에 남는다. ServerFailureLog 줄로 바꾸기 — 예외를 붙이는 줄이라, 토큰이 섞일 수 있는 실패 메시지를 남기지 않는 이 writer의 계약과 맞지 않는다. 위험·한계: ERROR 수로 경보를 거는 곳에 JWKS 장애와 인증 설정 오류가 새로 잡힌다. upgrade 안내 5절에 적었다. 결정은 docs/superpowers/specs/2026-11-06-error-code-log-level-design.md 10절이다. 검증(desktop, 공유 잠금, 로그는 desktop ~/t3-loglevel-logs/): - RED: 기준 writer로 EnvelopeAuthenticationEntryPointTest 8건 중 2건 실패 (aKeyServiceOutageIsLoggedAtError, aDecoderMisconfigurationIsLoggedAtError — WARN이 나오고 ERROR를 기대). rc=1, red-web.log - GREEN: :adapter:inbound:web:check rc=0, 테스트 329건 실패 0. green-web-check.log - :adapter:inbound:web:testQualityCheck rc=0, green-quality.log --- docs/runbooks/auth-jwks-unavailable.md | 4 +- .../auth-public-path-misconfiguration.md | 4 +- docs/upgrade/2026-11-maturity-review.md | 1 + src/adapter/inbound/web/README.md | 4 + .../web/auth/AuthErrorResponseWriter.java | 18 ++-- .../EnvelopeAuthenticationEntryPointTest.java | 86 +++++++++++++++++++ 6 files changed, 108 insertions(+), 9 deletions(-) diff --git a/docs/runbooks/auth-jwks-unavailable.md b/docs/runbooks/auth-jwks-unavailable.md index 42bcc829..b7c529e4 100644 --- a/docs/runbooks/auth-jwks-unavailable.md +++ b/docs/runbooks/auth-jwks-unavailable.md @@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY error_codes: [AUTH_JWKS_UNAVAILABLE] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,6 +13,8 @@ status: stub ## Symptoms - HTTP 503 with `error.code=AUTH_JWKS_UNAVAILABLE` +- ERROR log line `security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY method=… path=…` + (logger `AuthErrorResponseWriter`) - All authentication failing; JWKS refresh attempts failing ## Diagnosis diff --git a/docs/runbooks/auth-public-path-misconfiguration.md b/docs/runbooks/auth-public-path-misconfiguration.md index df069a67..019a1976 100644 --- a/docs/runbooks/auth-public-path-misconfiguration.md +++ b/docs/runbooks/auth-public-path-misconfiguration.md @@ -4,7 +4,7 @@ category: INTERNAL error_codes: [INTERNAL_AUTH_MISCONFIGURATION] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,6 +13,8 @@ status: stub ## Symptoms - HTTP 500 with `error.code=INTERNAL_AUTH_MISCONFIGURATION` +- ERROR log line `security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL method=… path=…` + (logger `AuthErrorResponseWriter`) - Security filter misconfiguration detected at runtime ## Diagnosis diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index ef50f035..4c768e01 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -243,6 +243,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | | Flyway 잠금 | Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션 대신 세션에 둔다. Spring Boot의 Flyway는 module-defaults `spring.flyway.postgresql.transactional-lock: false`, 템플릿이 직접 만드는 Flyway(멱등성·알림·sample stream, schema-per-tenant, testkit `MigrationContractRunner`)는 `FlywaySchemaPolicy.configure()`, messaging inbox stream은 같은 값을 직접 넣는다. 운영 코드의 `Flyway.configure()` 직접 호출은 `JpaProductionArchitectureTest`가 거부한다 | Flyway 기본값에서는 동시 인덱스 마이그레이션이 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않았다. 이제 끝난다. 마이그레이션은 잠금을 잡은 연결 하나로 돈다. transaction 모드 PgBouncer 뒤에서는 잠금 해제가 다른 서버 연결로 가 다음 배포가 기다릴 수 있으니 마이그레이션은 직접 연결이나 session 모드 pool로 돌린다. 배포 도구는 이 repo 밖이라 2절 15번으로 맞춘다 | 재리뷰 round6 RR6-03-01 · `persistence-jpa.yml`, `.../migration/FlywaySchemaPolicy.java`, `docs/jpa/migration-guide.md` "Who may change the schema"·"Concurrent index builds" | | 성능 lane(HTTP client·Mongo) | httpclient `LargeBodyResourceTest`의 힙 상한(32 MiB 스트리밍 중 힙 증가 16 MiB 미만)을 매번 단언한다. 전에는 `-Pperformance.assertions.enabled=true`일 때만 단언하고 아니면 건너뛴다는 줄만 찍었다. Mongo `MongoResourceBudgetLaneTest`는 표준 gate 전체(p99 500ms, pool 대기 250ms, 힙 512 MiB, examined/returned 10, spill 금지)를 Gradle 밖 실행에서도 단언한다(B-43) | 손으로 돌린 `performanceCheck`가 상한을 실제로 재므로, 전에는 통과하던 느린 기계에서 실패할 수 있다 | B4(2026-11-06) · `LargeBodyResourceTest`, `MongoResourceBudgetLaneTest` | +| 보안 필터 로그 레벨 | 보안 필터(`AuthErrorResponseWriter`)의 `security failure` 줄을 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)면 ERROR, 4xx면 WARN으로 남긴다. 전에는 모두 WARN이었다. 다른 경로가 5xx를 ERROR로 남기는 규칙(`ServerFailureLog`)과 같아졌다 | ERROR로 거르는 로그 경보·대시보드에 JWKS 장애와 인증 설정 오류가 새로 잡힌다. 401·403은 그대로 WARN | 설계 메모 2026-11-06 7절 결정 2 · `src/adapter/inbound/web/.../auth/AuthErrorResponseWriter.java`, `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md` | ## 6. 따라오는 순서 diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 7b2336ca..6383ea21 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -115,6 +115,10 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 코드의 일반 `client_safe_message` 만 담고, 원시 예외 텍스트·`Authorization` 헤더·issuer·audience 는 절대 포함하지 않는다. 로그 라인엔 code/category/요청 path 만 기록하고 bearer token 은 절대 로깅하지 않는다(leak 테스트가 강제하는 계약). 전체 로그 마스킹 필터는 별도 log-management 영역에서 다룬다. +- **로그 레벨.** 4xx(토큰 누락·만료·서명·issuer·audience·kid 실패, 권한 부족)는 호출자 쪽 실패라 WARN이다. + 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)는 서버 쪽 고장이라 ERROR다. 다른 + 경로가 5xx를 ERROR로 남기는 규칙(shared-contract `ServerFailureLog`)과 같다. 레벨은 오류 코드 레지스트리의 + 칸이 아니라 이 코드가 정한다(설계 메모 `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md`). - **WWW-Authenticate(RFC 9110 §15.5.2).** 401 응답은 반드시 WWW-Authenticate 헤더를 갖되, `error_description` 으로 issuer/token 세부가 새지 않도록 최소한으로 유지한다. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java index 79068f66..7893d1ba 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java @@ -8,6 +8,7 @@ import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.event.Level; import org.springframework.http.HttpHeaders; import tools.jackson.databind.ObjectMapper; @@ -28,13 +29,16 @@ class AuthErrorResponseWriter { void write(HttpServletRequest request, HttpServletResponse response, OperationalError code) throws IOException { - // Log only safe metadata — never the token or the raw failure message. - log.warn( - "security failure: code={} category={} method={} path={}", - code.code(), - code.category(), - request.getMethod(), - request.getRequestURI()); + // Log only safe metadata — never the token or the raw failure message. A 5xx is the server's + // own failure (the key service is down, the decoder is misconfigured) and is an ERROR, as a 5xx + // is on every other path (ServerFailureLog); a 4xx is the caller's and stays a WARN. + log.atLevel(code.httpStatus() >= 500 ? Level.ERROR : Level.WARN) + .log( + "security failure: code={} category={} method={} path={}", + code.code(), + code.category(), + request.getMethod(), + request.getRequestURI()); // A 401 response carries a minimal WWW-Authenticate header (no issuer / token detail). if (code.httpStatus() == 401) { diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java index 3ad25ca3..d580043b 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java @@ -2,17 +2,23 @@ package dev.caskeleton.adapter.inbound.web.auth; import static org.assertj.core.api.Assertions.assertThat; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; +import java.io.IOException; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.LoggerFactory; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.http.HttpHeaders; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.InsufficientAuthenticationException; +import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.jwt.BadJwtException; @@ -106,6 +112,86 @@ class EnvelopeAuthenticationEntryPointTest { .isEqualTo("AUTH_JWKS_UNAVAILABLE"); } + @Test + void aKeyServiceOutageIsLoggedAtError() throws Exception { + // given + AuthenticationException outage = + new InvalidBearerTokenException( + "invalid", + new JwtDecoderConfig.AuthenticationKeyServiceUnavailableException( + new IOException("connect timed out"))); + + // when + List lines = writerLinesFor(outage); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "ERROR", + "security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY" + + " method=GET path=/v1/things"); + } + + @Test + void aDecoderMisconfigurationIsLoggedAtError() throws Exception { + // given + AuthenticationException misconfiguration = + new InvalidBearerTokenException( + "invalid", + new JwtDecoderConfig.AuthenticationDecoderMisconfigurationException( + new IllegalStateException("issuer metadata does not match"))); + + // when + List lines = writerLinesFor(misconfiguration); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "ERROR", + "security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL" + + " method=GET path=/v1/things"); + } + + @Test + void aRejectedSignatureStaysAtWarn() throws Exception { + // given + AuthenticationException rejected = + new InvalidBearerTokenException( + "invalid", new BadJwtException("Signed JWT rejected: Invalid signature")); + + // when + List lines = writerLinesFor(rejected); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "WARN", + "security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH" + + " method=GET path=/v1/things"); + } + + /** The lines the security writer logs while the entry point answers {@code failure}. */ + private List writerLinesFor(AuthenticationException failure) throws Exception { + Logger logger = (Logger) LoggerFactory.getLogger(AuthErrorResponseWriter.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + entryPoint.commence( + new MockHttpServletRequest("GET", "/v1/things"), new MockHttpServletResponse(), failure); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + return appender.list; + } + @Test void tokenValueNeverLeaksIntoResponseBodyOrLogs(CapturedOutput output) throws Exception { // §테스트 계약: a JWT value must never appear in the response or the log output.