From 2f0aefadeeaab4d958a22ce395adb0d58dbe38b8 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 12:24:15 +0900 Subject: [PATCH 1/2] =?UTF-8?q?fix(security)!:=20=EB=AA=A8=EB=93=A0=20?= =?UTF-8?q?=EC=A0=84=EC=86=A1=EC=9D=B4=20=EA=B0=99=EC=9D=80=20=ED=98=B8?= =?UTF-8?q?=EC=B6=9C=EC=9E=90=EB=A1=9C=20=EA=B6=8C=ED=95=9C=EC=9D=84=20?= =?UTF-8?q?=ED=8C=90=EC=A0=95=ED=95=98=EA=B3=A0=20JWT=C2=B7tenant=20?= =?UTF-8?q?=EB=B9=88=ED=8B=88=EC=9D=84=20=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @RequiresPermission이 web 밖에서 늘 거부한다. gRPC·STOMP는 인증한 호출자를 SecurityContext에 넣지 않아 권한 있는 호출자도 거부되고, 거부는 web 403, gRPC INTERNAL+ERROR, GraphQL 가린 INTERNAL_ERROR+ERROR로 갈린다. GraphQL 정책은 하위 좌표(User.salary) 규칙을 받고 판정하지 않는다. 배포 jar가 SPRING_PROFILES_ACTIVE=test로 떠 prod 검사가 꺼진다. JWT 변환은 최상위 roles claim을 권한으로 읽고, sub 없는 token을 통과시켜 뒤에서 500이 되고, 틀린 tenant claim을 AUTH_TOKEN_MALFORMED로 본다. 모르는 profile의 알림 callback은 500+ERROR이고 공격자 문자열을 감사 WARN에 남긴다. patch 거부는 요청이 쓴 이름을 제한 없이 되풀이한다. tenant 입력 이름 거부가 web·GraphQL에서 갈리고, 익명 GraphQL tenant 출처가 SYSTEM이다. STOMP 거부는 자기 로그가 없고 설정 주석이 순서를 틀리게 적는다. - AuthorizationDeniedException을 AUTHZ_INSUFFICIENT_PERMISSION carrier로 만들고 method security가 그것을 그대로 던진다. 전송마다 이미 있는 carrier 대응이 같은 코드로 답한다(gRPC PERMISSION_DENIED, GraphQL FORBIDDEN). 버린 안: 전송마다 AccessDeniedException 대응 추가(네 곳에 같은 표를 둔다). - gRPC listener callback과 STOMP frame 처리 동안 호출자를 SecurityContext에 둔다(spring-security-core 의존, lockfile 갱신). Authentication이면 그대로, 아니면 권한 없는 인증 token이다. 역할은 AuthenticatedPrincipal 에서만 읽는다. - GraphQL 실행 전 판정이 fragment를 한 번씩 펼치며 typed parent로 좌표를 모은다. root는 늘, 하위 좌표는 규칙이 있을 때 판정하고 interface·구현 좌표의 규칙도 본다. - 배포 산출물은 test profile을 기동 실패로 거부한다. - JWT: 최상위 roles를 버리고, sub 없음·틀린 tenant는 401 AUTH_CLAIM_MAPPING_FAILED다. - callback은 profile을 먼저 찾고 없으면 감사 없이 400이다 (ProviderCallbackAdapterRegistry.require → find). - patch 거부는 이름을 16개·128자·안전 문자만 되풀이한다. - tenant 입력 이름 어휘를 TenantId.namesATenant 하나로 모으고, 익명 GraphQL 출처를 ANONYMOUS로 둔다(값 public, 거부는 하지 않는다 — 공개 DataLoader가 그 tenant로 돈다). - STOMP 거부는 사유·command만 담은 WARN 한 줄을 남긴다(session id는 SockJS가 client URL에서 받아 뺀다). - 고치며 찾음: decoder를 만든 뒤 JWKS 재조회를 IdP가 받지 않으면 라이브러리 문구("…decode the Jwt: ") 때문에 401 AUTH_TOKEN_MALFORMED로 분류됐다. 원인 사슬의 HTTP·I/O 실패를 먼저 보고 503 AUTH_JWKS_UNAVAILABLE로 답한다. 위험: 응답이 바뀐다(gRPC·GraphQL 거부 코드, sub 없음 401, JWKS 재조회 실패 503, 모르는 callback 400, test profile 기동 실패). 할 일은 docs/upgrade/2026-11-round9-authz.md 1~11행이다. registry 구현은 find를 구현해야 컴파일된다. 검증: desktop에서 바뀐 leaf check·systemTest, :app-bootstrap:test· architectureTest·documentContractTest, verifyDependencyLocks rc=0. 새 시험은 고치기 전 트리에서 실패했다(RED). Refs: RR9-02-02, RR9-02-16, RR9-02-17, RR9-02-18, RR9-02-20, RR9-02-23, RR9-02-25, RR9-02-28, RR9-02-29 BREAKING CHANGE: gRPC·GraphQL 권한 거부 코드, JWT sub 없음·틀린 tenant 응답, 모르는 알림 callback 응답, test profile 기동, registry require→find 가 바뀐다. 옮기는 법은 docs/upgrade/2026-11-round9-authz.md 1~11행. --- docs/ledger/estimates.jsonl | 1 + docs/manual/07-authorization.md | 3 +- docs/runbooks/auth-claim-mapping-failed.md | 26 +- docs/upgrade/2026-11-round9-authz.md | 31 ++ src/adapter/inbound/graphql/README.md | 11 + .../GraphQlPlatformAutoConfiguration.java | 7 +- .../GraphQlRequestContextConfiguration.java | 2 +- .../graphql/context/TenantContext.java | 14 +- .../GraphQlDocumentAuthorizationHandler.java | 227 ++++++++++-- .../GraphQlAuthorizationInterceptor.java | 13 + .../security/GraphQlAuthorizationPolicy.java | 22 +- .../security/GraphQlContextPropagator.java | 10 +- .../GraphQlTenantIsolationPolicy.java | 29 +- .../GraphQlPlatformExecutionPathTest.java | 7 +- .../context/GraphQlRequestContextTest.java | 3 +- .../error/GraphQlWireErrorMapperTest.java | 16 +- ...aphQlDocumentAuthorizationHandlerTest.java | 333 ++++++++++++++++++ .../GraphQlAuthorizationPolicyTest.java | 34 ++ .../GraphQlTenantIsolationPolicyTest.java | 36 ++ src/adapter/inbound/grpc/AGENTS.md | 4 + src/adapter/inbound/grpc/README.md | 12 + src/adapter/inbound/grpc/build.gradle | 4 + src/adapter/inbound/grpc/gradle.lockfile | 2 + .../grpc/GrpcAuthenticationInterceptor.java | 107 +++++- .../GrpcAuthenticationInterceptorTest.java | 183 ++++++++++ src/adapter/inbound/web-advanced/README.md | 3 + .../patch/PatchAuthorizationException.java | 43 ++- .../security/WebTenantContextResolver.java | 15 +- .../PatchAuthorizationExceptionTest.java | 50 +++ .../WebTenantContextResolverTest.java | 27 ++ src/adapter/inbound/web/README.md | 20 +- .../inbound/web/auth/JwtDecoderConfig.java | 7 +- .../JwtToAuthenticatedPrincipalConverter.java | 45 ++- .../web/auth/SecurityErrorClassifier.java | 16 +- ...equiresPermissionAuthorizationManager.java | 23 +- .../web/error/GlobalExceptionHandler.java | 6 +- .../JwtJwksSecurityFilterIntegrationTest.java | 40 ++- ...ToAuthenticatedPrincipalConverterTest.java | 42 ++- .../web/auth/SecurityErrorClassifierTest.java | 22 ++ ...resPermissionAuthorizationManagerTest.java | 48 ++- .../web/error/GlobalExceptionHandlerTest.java | 25 +- src/adapter/inbound/websocket/AGENTS.md | 6 + src/adapter/inbound/websocket/README.md | 15 + src/adapter/inbound/websocket/build.gradle | 4 + src/adapter/inbound/websocket/gradle.lockfile | 2 + .../websocket/stomp/WebSocketConfig.java | 9 +- ...SocketInboundAuthorizationInterceptor.java | 26 +- .../WebSocketSecurityContextInterceptor.java | 58 +++ ...etInboundAuthorizationInterceptorTest.java | 43 +++ ...bSocketSecurityContextInterceptorTest.java | 92 +++++ .../MapProviderCallbackAdapterRegistry.java | 22 +- .../ProviderCallbackAdapterRegistry.java | 9 +- .../NotificationProviderAssemblyTest.java | 2 +- src/application/core/README.md | 9 +- .../AuthorizationDeniedException.java | 22 +- .../application/tenant/TenantId.java | 45 +++ .../application/tenant/TenantIdTest.java | 22 ++ src/bootstrap/app/gradle.lockfile | 4 +- .../RuntimeEnvironmentProfileValidator.java | 18 +- ...untimeEnvironmentProfileValidatorTest.java | 20 +- .../ProviderCallbackIngressBridge.java | 9 +- .../ProviderCallbackIngressBridgeTest.java | 35 +- 62 files changed, 1862 insertions(+), 179 deletions(-) create mode 100644 docs/upgrade/2026-11-round9-authz.md create mode 100644 src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationExceptionTest.java create mode 100644 src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolverTest.java create mode 100644 src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSecurityContextInterceptor.java create mode 100644 src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSecurityContextInterceptorTest.java diff --git a/docs/ledger/estimates.jsonl b/docs/ledger/estimates.jsonl index a506c749..a56ba0ad 100644 --- a/docs/ledger/estimates.jsonl +++ b/docs/ledger/estimates.jsonl @@ -15,3 +15,4 @@ {"schema": 1, "kind": "actual", "task": "w2-be-ci-perf", "transcript": "a6b6b25f-a4f7-46c2-a746-5ab20a588c78", "minutes": 663, "active_minutes": 417, "calls": 464, "output_tokens": 438927, "cache_read_tokens": 256417797, "max_context": 911512, "within": "over", "result": "partial", "commits": ["ecc14004", "6325b518", "86488256", "c7aff0f4", "7054d179", "575aa1f7", "deeb1126", "96caf997", "cfc80ae8", "000a59ed", "5a95db45", "d237bacc", "7284b581", "14053060", "7dbf11ca", "2c180b90", "24dde586", "aeb60339", "083c6910"], "why": "시간이 p80을 넘었다: desktop 공유 잠금 대기자 10여 개(flock이 순서 없이 깨움)로 측정·검증이 2시간 넘게 밀렸고, runner 1대 대기열에서 늦게 풀린 job이 맨 뒤로 가 수동 실행 결과가 몇 시간씩 늦었다. 예측에 없던 결정: Gitea needs+if Blocked 재현(일회용 workflow 셋), Trivy가 처음 읽은 lockfile 라이선스와 이미지가 jar 라이선스를 못 읽는 것에 맞춘 판정 재설계. 결과는 partial: runner 초록은 NFS(소유자 sudo)·compose(수정 뒤 runner 미확인) 빼고 달성, 속도 목표 넷은 미달(캐시 효과는 병합 뒤, PG 컨테이너 159개 공유는 후속).", "recorded_at": "2026-11-12T08:34+09:00"} {"schema": 1, "kind": "actual", "task": "w2-be-ci-perf", "correction": true, "transcript": "a6b6b25f-a4f7-46c2-a746-5ab20a588c78", "minutes": 1266, "active_minutes": 555, "calls": 556, "output_tokens": 534063, "cache_read_tokens": 301335415, "max_context": 963079, "within": "over", "result": "partial", "commits": ["ecc14004", "6325b518", "86488256", "c7aff0f4", "7054d179", "575aa1f7", "deeb1126", "96caf997", "cfc80ae8", "000a59ed", "5a95db45", "d237bacc", "7284b581", "14053060", "7dbf11ca", "2c180b90", "24dde586", "aeb60339", "083c6910", "335fc967", "9682c52c", "3e06a809", "d17f8bcf", "7db40c9b"], "why": "앞 actual 줄을 고친다. 그 뒤 총괄 지시 둘(새 main 위로, main.yml concurrency와 취소 증거)과 main 두 번 병합으로 작업 중 138분·호출 92가 더 들었다. 대부분 runner 대기열(PR run이 한 번에 2~4시간 뒤로 밀림)과 desktop 공유 잠금 대기였다. 결과는 여전히 partial: runner PR 130 초록·release gate 125 초록, NFS는 소유자 sudo, 속도 목표 넷은 미달(PR 13.5→12.0분/목표 8, release gate 45.6→32.5분/목표 35는 이미지 job 포함), 캐시 효과는 병합 뒤 측정.", "recorded_at": "2026-11-12T18:36+09:00"} {"schema": 1, "kind": "estimate", "task": "w2-be-ci-perf-2", "transcript": "a6b6b25f-a4f7-46c2-a746-5ab20a588c78", "started_at": "2026-11-12T18:45+09:00", "base": "e7be517e", "task_kind": "improve", "size": "large", "minutes": {"p30": 150, "p50": 240, "p80": 400}, "calls": {"p30": 120, "p50": 200, "p80": 320}, "output_tokens": {"p30": 100000, "p50": 170000, "p80": 280000}, "basis": "직전 라운드 w2-be-ci-perf 실측 555분(p50 144의 3.9배, 대부분 runner·desktop 잠금 대기). 이번 판단 5개(B2·NFS·C2·job 합치기·main 줄 순서), desktop main 측정 1회(30분)+pr 1회, runner nightly 1회(2시간)+release 1회+PR 2회. 대기가 시간을 정한다", "recorded_at": "2026-11-12T18:58+09:00"} +{"schema": 1, "kind": "estimate", "task": "r9-group-a", "transcript": "70449164-6ab3-49a9-9bcd-a4281e2a0759", "started_at": "2026-11-13T07:00+09:00", "base": "d3a90479", "task_kind": "improve", "size": "large", "minutes": {"p30": 160, "p50": 240, "p80": 370}, "calls": {"p30": 250, "p50": 380, "p80": 570}, "output_tokens": {"p30": 200000, "p50": 320000, "p80": 490000}, "basis": "발견 31건·PR 3개, 손 판단 결정 약 8(전송별 인가 전달, graphql 하위 좌표, test profile 기동 거부, broadcaster 목적지, metrics registry 맞추기 등), desktop 검증 약 8회(leaf·pr 단계); 원값 300/450/700분·400/600/900호출·350k/550k/850k에 보정 0.53·0.63·0.58을 곱함", "recorded_at": "2026-11-13T06:52+09:00"} diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index 71cfd8cf..4d5db056 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -10,7 +10,8 @@ 요청 ─▶ 인증 필터(JWT 또는 세션) ─▶ AuthenticatedPrincipal(roles, tenant) ─▶ 컨트롤러 ─▶ [프록시] RequiresPermissionAuthorizationManager │ role → permission (app.authz.role-permissions) - │ 없으면 403, 인증 없으면 401 + │ 없으면 403(AUTHZ_INSUFFICIENT_PERMISSION). 인증 없는 요청은 + │ 보통 인증 필터가 먼저 401로 끊고, 공개 경로라 여기 오면 403 ─▶ 유스케이스 본문 ─▶ 객체 로드 ─▶ 소유자·tenant 판정 ─▶ 남의 것이면 404(존재 숨김) ``` diff --git a/docs/runbooks/auth-claim-mapping-failed.md b/docs/runbooks/auth-claim-mapping-failed.md index 338e8430..dc93ae56 100644 --- a/docs/runbooks/auth-claim-mapping-failed.md +++ b/docs/runbooks/auth-claim-mapping-failed.md @@ -4,7 +4,7 @@ category: AUTH error_codes: [AUTH_CLAIM_MAPPING_FAILED] severity: P2 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-13 status: 초안 --- @@ -12,22 +12,32 @@ status: 초안 ## 증상 -- HTTP 401, `error.code=AUTH_CLAIM_MAPPING_FAILED`. -- 토큰 검증은 통과했지만 필요한 클레임(sub, roles, tenant)이 없거나 타입이 다르다. +- HTTP 401, `error.code=AUTH_CLAIM_MAPPING_FAILED`, `WWW-Authenticate: Bearer error="invalid_token"`. +- WARN 로그 줄 `security failure: code=AUTH_CLAIM_MAPPING_FAILED category=AUTH method=… path=…`(logger + `AuthErrorResponseWriter`). +- 서명·issuer·audience·만료 검증은 통과했지만 principal을 만들 수 없다: `sub` claim이 없거나 비었다, 또는 + `tenant_id` claim이 있는데 tenant 문법(`TenantId.GRAMMAR`)에 맞지 않는다(`JwtToAuthenticatedPrincipalConverter`). +- 역할 claim이 없는 것은 이 코드가 아니다. 역할 없는 사용자는 인증되고, 권한이 필요한 쓰기에서 403 + `AUTHZ_INSUFFICIENT_PERMISSION`이 된다. ## 진단 -- 로그에서 토큰 payload의 클레임을 본다. -- 클레임 추출 설정을 확인한다. +- 토큰·`Authorization` 헤더·JWT payload는 로그에 남지 않고 남겨서도 안 된다. 클라이언트 쪽에서 token을 받아 `sub`와 + `tenant_id`를 본다. +- claim 이름은 코드에 고정돼 있다: `sub`, `tenant_id`, 역할은 `realm_access.roles`와 자기 client(`app.security.audience`)의 + `resource_access..roles`. 따로 고칠 claim 대응 설정은 없다. ## 조치 -- IdP 토큰 템플릿에 필요한 클레임이 들어 있는지 확인한다. -- IdP 스키마가 바뀌었으면 클레임 매핑 설정을 고친다. +- IdP token 템플릿이 `sub`를 넣는지, `tenant_id`를 넣는다면 문법에 맞는 값인지 고친다. +- IdP가 tenant를 다른 claim에 둔다면 IdP 쪽 mapper로 `tenant_id`에 옮긴다. ## 에스컬레이션 -- IdP가 클레임 스키마를 바꿨으면 인증 플랫폼 팀에 넘긴다. +- IdP가 claim 스키마를 바꿨으면 인증 플랫폼 팀에 넘긴다. + +> 이력: 2026-11-12 리뷰 전에는 `sub` 없는 token이 통과해 뒤에서 500이 됐고, 틀린 tenant claim은 +> `AUTH_TOKEN_MALFORMED`였다. --- diff --git a/docs/upgrade/2026-11-round9-authz.md b/docs/upgrade/2026-11-round9-authz.md new file mode 100644 index 00000000..8e6ad65c --- /dev/null +++ b/docs/upgrade/2026-11-round9-authz.md @@ -0,0 +1,31 @@ +# 업그레이드 안내 — 2026-11 인증·인가와 GraphQL·WebSocket 계약 + +- 범위: 2026-11-12 전체 리뷰의 인증·인가 묶음을 고친 변경. JWT 역할·claim 대응, JWKS 재조회 실패의 분류, 배포 + 산출물의 profile 검사, 알림 callback, GraphQL 인가·tenant, 전송별 권한 판정이 바뀌었다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 RR9-02-02·16·17·18·20·23·25·28·29 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 JWT로 인증하는 서비스, gRPC·STOMP·GraphQL에서 +`@RequiresPermission` 유스케이스를 부르는 서비스, web-advanced patch나 GraphQL tenant 정책을 쓰는 서비스다. + +## 2. 할 일 + +| # | 바뀐 것 | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | --- | +| 1 | JWT 최상위 `roles` claim을 역할로 읽지 않는다. `realm_access.roles`와 자기 client(`app.security.audience`)의 `resource_access..roles`만 읽는다 | IdP가 최상위 `roles`에만 역할을 넣고 있으면 realm role이나 자기 client role로 옮긴다 | 그 역할이 준 권한이 사라져 쓰기가 403이 된다 | JWT 인증 | +| 2 | `sub` 없는 token, 형식이 틀린 `tenant_id` claim은 401 `AUTH_CLAIM_MAPPING_FAILED`다(전에는 `sub` 없음이 뒤에서 500, 틀린 tenant는 `AUTH_TOKEN_MALFORMED`) | 경보·대시보드가 틀린 tenant를 `AUTH_TOKEN_MALFORMED`로 셌으면 새 코드도 센다 | claim 문제가 「token 깨짐」으로 보인다 | JWT 인증 | +| 3 | decoder를 만든 뒤 JWKS를 다시 받다(모르는 kid, 키 캐시 만료) IdP가 답하지 않으면 503 `AUTH_JWKS_UNAVAILABLE`(`Retry-After: 30`)이다(전에는 401 `AUTH_TOKEN_MALFORMED`) | 경보·대시보드가 이 상황을 `AUTH_TOKEN_MALFORMED`로 셌으면 `AUTH_JWKS_UNAVAILABLE`도 센다 | IdP 장애가 「token 깨짐」으로 보이고 client가 다시 시도하지 않는다 | JWT 인증 | +| 4 | 배포 산출물(`CaSkeletonApplication`)은 `SPRING_PROFILES_ACTIVE`에 `test`가 있으면 기동하지 않는다 | 배포·스테이징 env에서 `test`를 지우고 `local`·`dev`·`prod` 하나를 쓴다. 시험이 이 main class를 `test`로 띄우면 `local`이나 `dev`로 바꾼다 | 기동이 `STARTUP_VALIDATION_FAILED`로 멈춘다 | `test` profile로 띄우던 서비스 | +| 5 | 권한 거부는 Spring `AccessDeniedException`이 아니라 `AuthorizationDeniedException`(`AUTHZ_INSUFFICIENT_PERMISSION` carrier)으로 나간다. web은 전과 같은 403이다. gRPC는 `PERMISSION_DENIED`(전에는 `INTERNAL`), GraphQL은 `AUTHZ_INSUFFICIENT_PERMISSION`·`FORBIDDEN`(전에는 `INTERNAL_ERROR`)이다. STOMP `@MessageMapping` 안의 거부는 frame을 보내지 않고 로그도 남기지 않는다(4xx carrier, 전에는 ERROR 로그) | method security 거부를 `AccessDeniedException`으로 잡던 코드는 `AuthorizationDeniedException`(또는 `ApiErrorCarrier`)으로 잡는다 | 그 catch가 거부를 놓친다 | 거부를 직접 잡던 서비스 | +| 6 | gRPC 인증 정책이 돌려준 호출자, STOMP handshake 사용자가 handler가 도는 동안 `SecurityContext`에 들어간다. `Authentication`이면 그대로, 아니면 권한 없는 인증 token이다. 역할은 principal이 web의 `AuthenticatedPrincipal`일 때만 읽힌다 | gRPC 정책이 JWT를 검증한다면 web의 decoder와 `JwtToAuthenticatedPrincipalConverter`가 만든 token을 돌려준다 | gRPC handler가 부른 `@RequiresPermission` 유스케이스가 역할 없이 거부된다 | gRPC·STOMP | +| 7 | GraphQL 인가 규칙이 root 아래 좌표(`User.salary`)도 실행 전에 판정한다. 아래 좌표는 규칙이 있는 것만 판정한다 | 하위 좌표 규칙을 둔 정책이 있으면 그 규칙이 이제 실제로 거부함을 확인한다 | 전에 통과하던 query가 `COORDINATE_NOT_AUTHORIZED`로 거부된다 | GraphQL 정책에 하위 좌표 규칙을 둔 서비스 | +| 8 | GraphQL 익명 요청의 tenant 출처가 `SYSTEM`이 아니라 `ANONYMOUS`다(값은 그대로 `public`). `GraphQlTenantIsolationPolicy.require(context)`의 출처 검사는 늘 통과하던 죽은 코드라 지웠다 | `TenantSource.SYSTEM`을 「익명」으로 읽던 코드가 있으면 `ANONYMOUS`로 바꾼다. 증명된 tenant가 필요한 곳은 출처를 본다 | 익명 요청을 플랫폼 작업으로 잘못 본다 | GraphQL tenant 출처를 읽는 서비스 | +| 9 | tenant를 제안하는 입력 이름을 web-advanced와 GraphQL이 같은 어휘로 거부한다(`tenant`, `tenant_id`, `tenantId`, `X-Tenant-Id`, 대소문자·`-`·`_` 무관) | 그런 이름의 header·parameter·argument를 쓰던 client를 고친다 | 403 `TENANT_INPUT_UNTRUSTED`나 GraphQL tenant 거부가 난다 | tenant 입력 검사를 쓰는 서비스 | +| 10 | `PATCH_PATH_FORBIDDEN`의 `details.refusedPaths`는 16개까지, `[A-Za-z0-9_.~/-]` 128자 이하 이름만 그대로 싣고 나머지는 ``다 | 그 칸을 화면에 그대로 보이던 client는 대체 문자열을 처리한다 | — | web-advanced patch | +| 11 | 알림 callback: 설정하지 않은 profile로 온 callback은 400이다(전에는 500과 ERROR 로그). `ProviderCallbackAdapterRegistry.require`가 `find`(`Optional`)로 바뀌었다 | registry를 직접 구현한 서비스는 `find`를 구현한다 | 컴파일이 실패한다 | 알림 platform | + +## 3. 바뀌지 않은 것 + +- web의 403 응답(`AUTHZ_INSUFFICIENT_PERMISSION`), 401 응답 모양, `WWW-Authenticate`는 그대로다. +- `@RequiresPermission`·역할 매핑 설정 키는 그대로다. diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index ddef0583..5688b224 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -168,6 +168,17 @@ composition root 는 이 leaf 를 채택할 때 인증/인가 및 CORS 정책을 `spring.graphql.graphiql.enabled=false`, `spring.graphql.schema.introspection.enabled=false` 를 운영 설정으로 명시해야 한다. +`GraphQlAuthorizationPolicy` 규칙은 root 좌표(`Query.report`)와 그 아래 좌표(`User.salary`)를 모두 받는다. +인가 단계(`GraphQlDocumentAuthorizationHandler`)는 resolver 전에 문서 전체를 걷는다. 걸으면서 지금 selection이 실제로 +돌 수 있는 object 타입 집합을 들고 다닌다(field의 선언 타입에서 시작하고, fragment의 type condition이 그 집합을 좁힌다). +- 그 집합에 root 타입이 있으면 그 root 좌표로 판정한다(규칙 없으면 `denyByDefault`). `query { ... on Node { secret } }`는 + `Query.secret`이고, mutation payload의 `query` field나 Node를 돌려주는 field 아래의 `... on Query`도 같다. +- 나머지는 아래 좌표이고 규칙이 있는 것만 판정한다. 같은 resolver가 답하는 좌표의 규칙을 모두 본다: selection이 쓰인 + 타입, 집합의 object 타입들, 그 object들이 구현한 모든 interface. 그래서 `User.salary` 규칙은 `... on Person { salary }`로, + `Payable.salary` 규칙은 `someone { salary }`(`someone: Person`, User가 Person·Payable을 모두 구현)로 읽어도 걸린다. + 구현 object 하나의 규칙이 거부하면 interface로 고른 그 field는 거부된다. +- 집합에 없는 object로 좁힌 branch(root selection 안의 `... on User`)는 그 root 타입의 좌표를 만들지 않는다. + --- # GraphQL API 실행 플랫폼 — 설계 결정의 근거 diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java index e18b89e8..e84b0098 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java @@ -36,9 +36,10 @@ public class GraphQlPlatformAutoConfiguration { /** * Tenant applied to a caller with no verified credential. * - *

Declared as {@link TenantContext#system} rather than as a credential-derived tenant, because - * that is what it is: no credential was verified, so no tenant was proven. An adopter serving - * more than one tenant supplies a principal resolver, and the anonymous path then never runs. + *

Declared as {@link TenantContext#anonymous} rather than as a credential-derived tenant, + * because that is what it is: no credential was verified, so no tenant was proven. An adopter + * serving more than one tenant supplies a principal resolver, and the anonymous path then never + * runs. */ public static final String DEFAULT_ANONYMOUS_TENANT = "public"; diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestContextConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestContextConfiguration.java index 784ef3b2..0737ca98 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestContextConfiguration.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestContextConfiguration.java @@ -125,7 +125,7 @@ class GraphQlRequestContextConfiguration { structurePolicy, extensionsPolicy, new GraphQlClientProfile(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_PROFILE), - TenantContext.system(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT), + TenantContext.anonymous(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT), properties.production(), graphQlPlatformClock, errors); diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/TenantContext.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/TenantContext.java index 3c003e3b..055f629c 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/TenantContext.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/TenantContext.java @@ -23,7 +23,14 @@ public record TenantContext(String value, TenantSource source) { /** A server-side session established by a prior authentication. */ TRUSTED_SESSION, /** An internal, non-request-scoped platform task. */ - SYSTEM + SYSTEM, + /** + * A request with no verified credential: the shared partition the platform names for anonymous + * callers. No tenant was proven; code that needs one checks for this source. It used to be + * labelled {@link #SYSTEM}, which made an anonymous client request indistinguishable from a + * platform task (review 2026-11-12). + */ + ANONYMOUS } public TenantContext { @@ -51,6 +58,11 @@ public record TenantContext(String value, TenantSource source) { return new TenantContext(value, TenantSource.TRUSTED_SESSION); } + /** The shared partition of a request that carries no verified credential. */ + public static TenantContext anonymous(String value) { + return new TenantContext(value, TenantSource.ANONYMOUS); + } + /** Tenant for an internal platform task that runs outside a client request. */ public static TenantContext system(String value) { return new TenantContext(value, TenantSource.SYSTEM); diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java index 34c9c2b2..8132d0d2 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java @@ -13,8 +13,15 @@ import graphql.language.InlineFragment; import graphql.language.OperationDefinition; import graphql.language.Selection; import graphql.language.SelectionSet; +import graphql.language.TypeName; +import graphql.schema.GraphQLCompositeType; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLFieldsContainer; +import graphql.schema.GraphQLInterfaceType; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; +import graphql.schema.GraphQLTypeUtil; +import graphql.schema.GraphQLUnionType; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -23,7 +30,12 @@ import java.util.Objects; import java.util.Set; /** - * Authorizes the operation and its root coordinates, before any resolver runs. + * Authorizes the operation's coordinates, before any resolver runs. + * + *

Every root coordinate is decided. A coordinate below the root (for example {@code + * User.salary}) is decided when a rule names it: {@link + * GraphQlAuthorizationInterceptor#authorizeNested}. Deciding only the root let a rule written for a + * nested field be accepted by the policy and then never consulted (review 2026-11-12). * *

Running before execution is the whole point: a mutation denied halfway through has already * performed the side effect it was denied for. So the decision is made on the document, and a @@ -65,10 +77,13 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti analyzer.verifyIntrospection( context.requireDocument(), operation, policy.introspectionAllowed()); - String rootTypeName = rootTypeName(context.schema(), operation); - for (String fieldName : rootFieldNames(context, operation, analyzer.maximumVisitedNodes())) { - authorization.authorize( - context.requestContext(), new GraphQlSchemaCoordinate(rootTypeName, fieldName)); + GraphQLObjectType root = rootType(context.schema(), operation); + CoordinateWalk walk = coordinates(context, root, analyzer.maximumVisitedNodes()); + for (GraphQlSchemaCoordinate rootCoordinate : walk.roots) { + authorization.authorize(context.requestContext(), rootCoordinate); + } + for (GraphQlSchemaCoordinate nestedCoordinate : walk.nested) { + authorization.authorizeNested(context.requestContext(), nestedCoordinate); } return context; } @@ -84,7 +99,7 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti * @throws IllegalStateException when there is no schema or it declares no such root; both fail * the request closed rather than authorize against a guessed name */ - private static String rootTypeName(GraphQLSchema schema, OperationDefinition operation) { + private static GraphQLObjectType rootType(GraphQLSchema schema, OperationDefinition operation) { OperationDefinition.Operation kind = operation.getOperation() == null ? OperationDefinition.Operation.QUERY @@ -101,24 +116,39 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti if (root == null) { throw new IllegalStateException("the schema declares no root type for " + kind); } - return root.getName(); + return root; } /** - * Root field names the operation actually reaches, fragments included. + * The coordinates the operation actually reaches, fragments included. * - *

Fragments are expanded rather than skipped: a root field reached only through a named - * fragment is executed exactly like one written inline, so authorizing only the inline ones would - * make {@code query { ...Hidden }} a bypass. + *

Fragments are expanded rather than skipped: a field reached only through a named fragment is + * executed exactly like one written inline, so authorizing only the inline ones would make {@code + * query { ...Hidden }} a bypass. * - *

Each fragment is expanded once per walk. The result is a set, and a fragment contributes the - * same root names wherever it is spread, so a second expansion adds nothing — while re-walking - * every spread lets a 1.6 KB document of nested double spreads cost 2^40 visits before the cost - * stage ever sees it. The same set cuts fragment cycles. The analyzer's traversal budget stays as - * a backstop and rejects exactly as the cost stage does. + *

The walk carries the object types the current selections can run on, not only the type they + * are written against. That set decides the coordinates. A selection that can run on a root type + * is a root coordinate of that type, deny-by-default included, wherever it sits: {@code query { + * ... on Node { secret } }} is {@code Query.secret}, and so is {@code node(id:) { ... on Query { + * secret } }} when the field can return the root object. Everything else is decided only when a + * rule names it, and a rule on any coordinate that answers the same field is consulted: the type + * written against, every object type the selection can run on, and every interface those objects + * implement ({@code ... on Person { salary }} against a {@code User.salary} rule, {@code someone + * { salary }} on {@code Person} against a {@code Payable.salary} rule). Narrowing intersects the + * set, so a fragment branch no possible object takes ({@code ... on User} inside a root + * selection) decides nothing on the root type. Deciding by the written type alone let a rule on + * one coordinate be read through another, and let a root field through an interface skip + * deny-by-default. + * + *

Each fragment is expanded once per set of possible object types. Its type condition fixes + * the rest, so a fragment spread again under the same set contributes the same coordinates and a + * second expansion adds nothing — while re-walking every spread lets a 1.6 KB document of nested + * double spreads cost 2^40 visits before the cost stage ever sees it. The same set cuts fragment + * cycles. The analyzer's traversal budget stays as a backstop and rejects exactly as the cost + * stage does. */ - private static Set rootFieldNames( - GraphQlExecutionContext context, OperationDefinition operation, int maximumVisitedNodes) { + private static CoordinateWalk coordinates( + GraphQlExecutionContext context, GraphQLObjectType root, int maximumVisitedNodes) { Map fragments = new LinkedHashMap<>(); context @@ -131,48 +161,179 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti } }); - RootFieldWalk walk = new RootFieldWalk(fragments, maximumVisitedNodes); - walk.collect(operation.getSelectionSet()); - return walk.names; + CoordinateWalk walk = + new CoordinateWalk(context.schema(), root, fragments, maximumVisitedNodes); + walk.collect(context.requireOperation().getSelectionSet(), root, Set.of(root)); + return walk; } - private static final class RootFieldWalk { + private static final class CoordinateWalk { + private final GraphQLSchema schema; private final Map fragments; private final int maximumVisitedNodes; private final Set expanded = new HashSet<>(); - private final Set names = new LinkedHashSet<>(); + private final Set decided = new HashSet<>(); + private final Set rootTypes = new HashSet<>(); + private final Set roots = new LinkedHashSet<>(); + private final Set nested = new LinkedHashSet<>(); private int visited; - RootFieldWalk(Map fragments, int maximumVisitedNodes) { + CoordinateWalk( + GraphQLSchema schema, + GraphQLObjectType root, + Map fragments, + int maximumVisitedNodes) { + this.schema = schema; this.fragments = fragments; this.maximumVisitedNodes = maximumVisitedNodes; + rootTypes.add(root); + // A root type reached below the operation root (a Relay payload's `query` field) is still a + // root: its fields are decided like root fields, deny-by-default included. + for (GraphQLObjectType declared : + new GraphQLObjectType[] { + schema.getQueryType(), schema.getMutationType(), schema.getSubscriptionType() + }) { + if (declared != null) { + rootTypes.add(declared); + } + } } - void collect(SelectionSet selectionSet) { + /** + * Collects a selection set written against {@code parent}. + * + * @param possible the object types these selections can run on + */ + void collect( + SelectionSet selectionSet, GraphQLCompositeType parent, Set possible) { if (selectionSet == null) { return; } + String possibleSignature = signature(possible); for (Selection selection : selectionSet.getSelections()) { if (++visited > maximumVisitedNodes) { throw GraphQlStructuralLimitException.of( "DOCUMENT_TRAVERSAL", visited, maximumVisitedNodes); } if (selection instanceof Field field) { - if (!field - .getName() - .startsWith(GraphQlDocumentShapeAnalyzer.INTROSPECTION_FIELD_PREFIX)) { - names.add(field.getName()); - } + field(field, parent, possible, possibleSignature); } else if (selection instanceof InlineFragment inlineFragment) { - collect(inlineFragment.getSelectionSet()); + GraphQLCompositeType narrowed = narrowed(inlineFragment.getTypeCondition(), parent); + collect(inlineFragment.getSelectionSet(), narrowed, intersect(possible, narrowed)); } else if (selection instanceof FragmentSpread spread) { FragmentDefinition fragment = fragments.get(spread.getName()); - if (fragment != null && expanded.add(spread.getName())) { - collect(fragment.getSelectionSet()); + if (fragment == null) { + continue; + } + GraphQLCompositeType narrowed = narrowed(fragment.getTypeCondition(), parent); + Set within = intersect(possible, narrowed); + if (expanded.add(spread.getName() + "@" + signature(within))) { + collect(fragment.getSelectionSet(), narrowed, within); } } } } + + private void field( + Field field, + GraphQLCompositeType parent, + Set possible, + String possibleSignature) { + String name = field.getName(); + if (name.startsWith(GraphQlDocumentShapeAnalyzer.INTROSPECTION_FIELD_PREFIX)) { + return; + } + // The coordinates of a field depend only on where it is written and what can run it; a + // field repeated under the same set (aliases, a wide schema) is decided once. + if (decided.add(parent.getName() + "." + name + "@" + possibleSignature)) { + decide(parent, name, possible); + } + if (field.getSelectionSet() != null && parent instanceof GraphQLFieldsContainer container) { + GraphQLFieldDefinition definition = container.getFieldDefinition(name); + if (definition != null + && GraphQLTypeUtil.unwrapAll(definition.getType()) + instanceof GraphQLCompositeType child) { + collect(field.getSelectionSet(), child, objectsOf(child)); + } + } + } + + private void decide(GraphQLCompositeType parent, String name, Set possible) { + if (!(parent instanceof GraphQLObjectType object && rootTypes.contains(object))) { + consult(parent.getName(), name); + } + if (parent instanceof GraphQLInterfaceType iface) { + iface.getInterfaces().forEach(extended -> consult(extended.getName(), name)); + } + for (GraphQLObjectType object : possible) { + if (rootTypes.contains(object)) { + // A root coordinate that cannot be written fails the request closed (the constructor + // refuses the name) rather than run unauthorized. + roots.add(new GraphQlSchemaCoordinate(object.getName(), name)); + } else { + consult(object.getName(), name); + } + object.getInterfaces().forEach(iface -> consult(iface.getName(), name)); + } + } + + /** + * Records a nested coordinate to consult. A type or field name a {@link + * GraphQlSchemaCoordinate} cannot express ({@code _Service}, {@code Order_Line}) cannot be + * named by any rule either, so it is left out rather than failing a legal request: no rule + * means it stays readable, exactly what deciding it would have said. + */ + private void consult(String typeName, String fieldName) { + try { + nested.add(new GraphQlSchemaCoordinate(typeName, fieldName)); + } catch (IllegalArgumentException inexpressible) { + // No rule can name it; see above. + } + } + + /** The object types a value of {@code type} can be. */ + private Set objectsOf(GraphQLCompositeType type) { + Set objects = new LinkedHashSet<>(); + if (type instanceof GraphQLObjectType object) { + objects.add(object); + } else if (type instanceof GraphQLInterfaceType iface) { + objects.addAll(schema.getImplementations(iface)); + } else if (type instanceof GraphQLUnionType union) { + union.getTypes().stream() + .filter(GraphQLObjectType.class::isInstance) + .map(GraphQLObjectType.class::cast) + .forEach(objects::add); + } + return objects; + } + + private Set intersect( + Set possible, GraphQLCompositeType narrowed) { + Set within = new LinkedHashSet<>(possible); + within.retainAll(objectsOf(narrowed)); + return within; + } + + private static String signature(Set possible) { + return possible.stream().map(GraphQLObjectType::getName).sorted().toList().toString(); + } + + /** + * The type a fragment's fields belong to. + * + *

The parse stage validated the document, so a named condition is a composite type of this + * schema; anything else fails the request closed rather than authorize under a guessed type. + */ + private GraphQLCompositeType narrowed(TypeName condition, GraphQLCompositeType parent) { + if (condition == null) { + return parent; + } + if (schema.getType(condition.getName()) instanceof GraphQLCompositeType type) { + return type; + } + throw new IllegalStateException( + "a fragment names a type condition the schema does not declare as composite"); + } } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationInterceptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationInterceptor.java index 6c7db4f3..d3504d01 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationInterceptor.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationInterceptor.java @@ -40,6 +40,19 @@ public final class GraphQlAuthorizationInterceptor { } } + /** + * Authorizes a coordinate below the operation root; one no rule names is allowed. + * + * @throws GraphQlAuthorizationDeniedException when a rule names the coordinate and the caller is + * not in it + */ + public void authorizeNested(GraphQlRequestContext context, GraphQlSchemaCoordinate coordinate) { + GraphQlAuthorizationDecision decision = policy.authorizeNested(context, coordinate); + if (!decision.allowed()) { + throw new GraphQlAuthorizationDeniedException(decision); + } + } + /** Maps a denial onto the wire, without disclosing what the caller could not see. */ public static GraphQlWireError toWireError( GraphQlAuthorizationDecision decision, GraphQlErrorContext context) { diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationPolicy.java index f2fda06e..c3af2de1 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationPolicy.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationPolicy.java @@ -64,6 +64,21 @@ public final class GraphQlAuthorizationPolicy { return GraphQlAuthorizationDecision.allow(); } + /** + * Decides a coordinate below the operation root, such as {@code User.salary}. + * + *

Only a coordinate a rule names is decided here; any other nested field is allowed whatever + * {@code denyByDefault} says. Deny-by-default stays a rule about root coordinates — what an + * operation may do — because applying it to every field of every type would make a policy list + * the whole schema. A nested rule narrows the one field it names. + */ + public GraphQlAuthorizationDecision authorizeNested( + GraphQlRequestContext context, GraphQlSchemaCoordinate coordinate) { + return allowedProfilesByCoordinate.containsKey(coordinate.value()) + ? authorize(context, coordinate) + : GraphQlAuthorizationDecision.allow(); + } + /** Whether a coordinate is hidden from introspection, which is not an authorization decision. */ public boolean hiddenFromIntrospection(GraphQlSchemaCoordinate coordinate) { return hiddenCoordinates.contains(coordinate.value()); @@ -78,7 +93,12 @@ public final class GraphQlAuthorizationPolicy { private Builder() {} - /** Allows a coordinate for the given client profiles. */ + /** + * Allows a coordinate for the given client profiles. + * + *

A root coordinate ({@code Query.report}) decides the operation; a nested one ({@code + * User.salary}) narrows that field wherever a document selects it. + */ public Builder allow(GraphQlSchemaCoordinate coordinate, GraphQlClientProfile... profiles) { allowedProfiles.put( coordinate.value(), diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlContextPropagator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlContextPropagator.java index c2c8d13a..46e7e4e3 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlContextPropagator.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlContextPropagator.java @@ -11,8 +11,14 @@ import java.util.function.Supplier; * *

GraphQL execution hops threads constantly — an async data fetcher, a DataLoader dispatch, a * scheduler bridge — and a context held only in a thread local silently disappears at the first - * hop. That is not a lost tag: it is a batch load running with no tenant. Every hop goes through - * here, and every one restores the previous state afterwards so nothing leaks into a pooled thread. + * hop. That is not a lost tag: it is a batch load running with no tenant. Each wrapper here + * restores the previous state afterwards so nothing leaks into a pooled thread. + * + *

A library helper for adopter code that moves work to its own executor. The platform does not + * call it: the request context travels in the {@code GraphQLContext} under {@link + * GraphQlRequestContext#CONTEXT_KEY}, which Spring for GraphQL carries across its own hops, and a + * data fetcher reads it from there. This Javadoc used to say every hop went through here; none did + * (review 2026-11-12). */ public final class GraphQlContextPropagator { diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicy.java index 7d302af6..ac394262 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicy.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicy.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.graphql.security; import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; import dev.caskeleton.adapter.inbound.graphql.context.TenantContext; +import dev.caskeleton.application.tenant.TenantId; import java.util.Map; /** @@ -29,26 +30,34 @@ public final class GraphQlTenantIsolationPolicy { } /** - * Requires the request context to carry a tenant derived from trusted authentication. + * Requires the request context to carry a tenant. * - * @throws GraphQlTenantIsolationException when it is absent or came from an untrusted source + *

The tenant is the verified one, or for a request without a credential the anonymous + * partition the platform assigns ({@link TenantContext.TenantSource#ANONYMOUS}); a public query + * batches its loads inside that partition. Code that needs a proven tenant checks the source. A + * check that the source was not {@code null} used to stand here; {@link TenantContext} cannot be + * built without one, so it never ran (review 2026-11-12). + * + * @throws GraphQlTenantIsolationException when it is absent */ public static TenantContext require(GraphQlRequestContext context) { if (context == null) { throw new GraphQlTenantIsolationException("tenant context required"); } - TenantContext tenant = require(context.tenant()); - if (tenant.source() == null) { - throw new GraphQlTenantIsolationException("tenant source is unknown"); - } - return tenant; + return require(context.tenant()); } /** * Rejects an attempt to take the tenant from client-supplied input. * + *

An argument is refused when {@link TenantId#namesATenant} says it names a tenant — the + * vocabulary the web transport refuses too, compared without case or separators — or when its + * name, compared the same way, is one of the caller's own {@code tenantArgumentNames}. Matching + * used to be the caller's list alone, case-sensitively, so {@code tenantId} and {@code TenantId} + * were two answers (review 2026-11-12). + * * @param arguments the GraphQL arguments or variables for the field - * @param tenantArgumentNames argument names that would denote a tenant + * @param tenantArgumentNames further argument names that denote a tenant in this schema * @throws GraphQlTenantIsolationException when any of them is present */ public static void rejectTenantArgument( @@ -56,7 +65,9 @@ public final class GraphQlTenantIsolationPolicy { if (arguments == null || arguments.isEmpty()) { return; } - boolean present = arguments.keySet().stream().anyMatch(tenantArgumentNames::contains); + boolean present = + arguments.keySet().stream() + .anyMatch(name -> TenantId.namesATenant(name, tenantArgumentNames)); if (present) { throw new GraphQlTenantIsolationException( "tenant must come from authentication, not from a GraphQL argument"); diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformExecutionPathTest.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformExecutionPathTest.java index 88a94ffd..683afb1e 100644 --- a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformExecutionPathTest.java +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformExecutionPathTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; import dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformAutoConfiguration; import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; +import dev.caskeleton.adapter.inbound.graphql.context.TenantContext; import dev.caskeleton.adapter.inbound.graphql.execution.BoundedPreparsedDocumentProvider; import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy; @@ -115,8 +116,10 @@ class GraphQlPlatformExecutionPathTest { GraphQlRequestContext context = OBSERVED_CONTEXT.get(); assertThat(context).as("the resolver must see the platform context").isNotNull(); - assertThat(context.tenant().value()) - .isEqualTo(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT); + assertThat(context.tenant()) + .as("an anonymous request is the anonymous partition, not a platform task") + .isEqualTo( + TenantContext.anonymous(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT)); assertThat(context.clientProfile().value()) .isEqualTo(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_PROFILE); assertThat(context.operationId().value()) diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlRequestContextTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlRequestContextTest.java index 14ee448a..2016f811 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlRequestContextTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlRequestContextTest.java @@ -49,7 +49,8 @@ class GraphQlRequestContextTest { .containsExactly( TenantContext.TenantSource.AUTHENTICATED_CREDENTIAL, TenantContext.TenantSource.TRUSTED_SESSION, - TenantContext.TenantSource.SYSTEM); + TenantContext.TenantSource.SYSTEM, + TenantContext.TenantSource.ANONYMOUS); } static Stream tenantsTheWebTransportRefuses() { diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java index bf3a6673..7b6ea449 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java @@ -12,8 +12,10 @@ import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledE import dev.caskeleton.application.idempotency.IdempotencyInFlightException; import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; +import dev.caskeleton.application.security.AuthorizationDeniedException; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; +import dev.caskeleton.shared.security.Permission; import java.sql.SQLException; import java.time.Duration; import java.util.List; @@ -27,18 +29,22 @@ import org.springframework.validation.BindException; class GraphQlWireErrorMapperTest { - static Stream dataLoaderFailures() { + static Stream failuresWithTheirOwnCode() { return Stream.of( Arguments.of( new GraphQlBatchTimeoutException("customer-by-id"), "REQUEST_TIMEOUT", "TIMEOUT"), Arguments.of(new GraphQlRequestCancelledException(), "REQUEST_TIMEOUT", "TIMEOUT"), - Arguments.of(new GraphQlMissingKeyException(), "GRAPHQL_BATCH_KEY_MISSING", "BUSINESS")); + Arguments.of(new GraphQlMissingKeyException(), "GRAPHQL_BATCH_KEY_MISSING", "BUSINESS"), + Arguments.of( + new AuthorizationDeniedException("sub-1", Permission.parse("order:read")), + "AUTHZ_INSUFFICIENT_PERMISSION", + "AUTHORIZATION")); } @ParameterizedTest - @MethodSource("dataLoaderFailures") - @DisplayName("요청·DataLoader 의 timeout·missing key 는 INTERNAL_ERROR 로 가려지지 않고 플랫폼 code 로 나간다") - void dataLoaderFailuresKeepAPlatformCode( + @MethodSource("failuresWithTheirOwnCode") + @DisplayName("요청·DataLoader 의 timeout·missing key, 권한 거부는 INTERNAL_ERROR 로 가려지지 않고 자기 code 로 나간다") + void aFailureWithItsOwnCodeIsNotMaskedAsInternalError( RuntimeException failure, String expectedCode, String expectedCategory) { // given GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking(); diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandlerTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandlerTest.java index 70895f64..adb8e865 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandlerTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandlerTest.java @@ -22,6 +22,7 @@ import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; /** @@ -122,6 +123,338 @@ class GraphQlDocumentAuthorizationHandlerTest { .hasMessage("GraphQL authorization denied: COORDINATE_NOT_AUTHORIZED"); } + /** A rule below the root narrows one field; the rest of that type stays readable. */ + private static final GraphQLSchema NESTED_SCHEMA = + schema( + "type Query { me: User someone: Person adminReport: String }" + + " type Mutation { promote: Payload }" + + " type Payload { query: Query }" + + " interface Person { name: String salary: Int }" + + " type User implements Person { name: String salary: Int manager: User }" + + " type Contractor implements Person { name: String salary: Int }"); + + private static final GraphQlAuthorizationPolicy SALARY_FOR_ADMINS_ONLY = + GraphQlAuthorizationPolicy.builder() + .denyByDefault(false) + .allow(GraphQlSchemaCoordinate.parse("User.salary"), new GraphQlClientProfile("admin")) + .build(); + + @ParameterizedTest + @ValueSource( + strings = { + "query Q { me { salary } }", + "query Q { me { manager { manager { salary } } } }", + "query Q { me { ... on User { salary } } }", + "query Q { me { ...P } } fragment P on User { name salary }", + "query Q { ...R } fragment R on Query { me { ...P } } fragment P on User { salary }", + "query Q { me { ... on Person { salary } } }", + "query Q { someone { salary } }", + "query Q { someone { ...C } } fragment C on Person { name salary }" + }) + @DisplayName("root 아래 field 의 규칙(User.salary)도 실행 전에 판정한다 — inline·fragment·중첩·interface 경유 포함") + void aRuleOnANestedFieldIsEnforcedWhereverTheDocumentSelectsIt(String document) { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor(SALARY_FOR_ADMINS_ONLY), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = selected(document, NESTED_SCHEMA); + + // when + Throwable thrown = catchThrowable(() -> handler.handle(selected)); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlAuthorizationDeniedException.class) + .hasMessage("GraphQL authorization denied: COORDINATE_NOT_AUTHORIZED"); + } + + private static final GraphQLSchema INTERFACE_SCHEMA = + schema( + "type Query { me: User someone: Person thing: Entity }" + + " interface Entity { salary: Int }" + + " interface Person implements Entity { salary: Int }" + + " interface Payable { salary: Int }" + + " type User implements Person & Entity & Payable { salary: Int }"); + + @ParameterizedTest(name = "{0} 규칙, {1}") + @CsvSource( + delimiter = '|', + value = { + "Person.salary | query Q { me { salary } }", + "Payable.salary | query Q { someone { salary } }", + "Entity.salary | query Q { someone { salary } }", + "Person.salary | query Q { thing { ... on Entity { salary } } }" + }) + @DisplayName("interface 좌표의 규칙은 같은 field 를 다른 interface·구현 object 로 골라도 판정한다") + void aRuleOnAnInterfaceFieldIsEnforcedThroughEveryTypeThatSharesTheField( + String coordinate, String document) { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor( + GraphQlAuthorizationPolicy.builder() + .denyByDefault(false) + .allow( + GraphQlSchemaCoordinate.parse(coordinate), + new GraphQlClientProfile("admin")) + .build()), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = selected(document, INTERFACE_SCHEMA); + + // when + Throwable thrown = catchThrowable(() -> handler.handle(selected)); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlAuthorizationDeniedException.class) + .hasMessage("GraphQL authorization denied: COORDINATE_NOT_AUTHORIZED"); + } + + private static final GraphQLSchema ROOT_IMPLEMENTS_SCHEMA = + schema( + "interface Node { secret: String }" + + " union Thing = Query | User" + + " type Query implements Node {" + + " secret: String me: User node: Node thing: Thing adminReport: String _service: _Service }" + + " type User implements Node { secret: String name: String }" + + " type _Service { sdl: String }"); + + private static final GraphQlAuthorizationPolicy ONLY_ME_FOR_FIRST_PARTY = + GraphQlAuthorizationPolicy.builder() + .allow(GraphQlSchemaCoordinate.parse("Query.me"), new GraphQlClientProfile("first-party")) + .build(); + + @Test + @DisplayName("root 타입이 구현한 interface 로 고른 root field 도 root 로 판정한다(규칙 없으면 deny-by-default)") + void aRootFieldSelectedThroughAnInterfaceTheRootImplementsIsDecidedAsRoot() { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor(ONLY_ME_FOR_FIRST_PARTY), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = + selected("query Q { ... on Node { secret } }", ROOT_IMPLEMENTS_SCHEMA); + + // when + Throwable thrown = catchThrowable(() -> handler.handle(selected)); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlAuthorizationDeniedException.class) + .hasMessage("GraphQL authorization denied: COORDINATE_NOT_AUTHORIZED"); + } + + @ParameterizedTest + @ValueSource( + strings = { + // Node can be the root object, so `... on Query` below it is a root coordinate. + "query Q { me { name } node { ... on Query { adminReport } } }", + // The same fragment spread below the root first and at the root second. + "query Q { me { ...N } ...N } fragment N on Node { secret }", + // A union member can be the root object too. + "query Q { thing { ... on Node { secret } } }" + }) + @DisplayName("root 객체일 수 있는 선택은 어디서 닿아도 root 좌표다 — 같은 fragment 를 아래에서 먼저 펼쳐도") + void aSelectionThatCanRunOnTheRootObjectIsARootCoordinateWhereverItSits(String document) { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor( + GraphQlAuthorizationPolicy.builder() + .allow( + GraphQlSchemaCoordinate.parse("Query.me"), + new GraphQlClientProfile("first-party")) + .allow( + GraphQlSchemaCoordinate.parse("Query.node"), + new GraphQlClientProfile("first-party")) + .allow( + GraphQlSchemaCoordinate.parse("Query.thing"), + new GraphQlClientProfile("first-party")) + .build()), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = selected(document, ROOT_IMPLEMENTS_SCHEMA); + + // when + Throwable thrown = catchThrowable(() -> handler.handle(selected)); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlAuthorizationDeniedException.class) + .hasMessage("GraphQL authorization denied: COORDINATE_NOT_AUTHORIZED"); + } + + @Test + @DisplayName("root 선택 안에서 root 객체가 될 수 없는 type 으로 좁힌 branch 는 root 좌표를 만들지 않는다") + void aBranchNoPossibleObjectTakesNamesNoRootCoordinate() { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor( + GraphQlAuthorizationPolicy.builder() + .allow( + GraphQlSchemaCoordinate.parse("Query.me"), + new GraphQlClientProfile("first-party")) + .allow( + GraphQlSchemaCoordinate.parse("Query.secret"), + new GraphQlClientProfile("first-party")) + .build()), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = + selected( + "query Q { ...F me { ...F } } fragment F on Node { secret ... on User { name } }", + ROOT_IMPLEMENTS_SCHEMA); + + // when + GraphQlExecutionContext authorized = handler.handle(selected); + + // then + assertThat(authorized).isSameAs(selected); + } + + @Test + @DisplayName("root 아래에서 interface 로 고른 field 는 root 규칙(Query.secret)으로 판정하지 않는다") + void aFieldBelowTheRootIsNotDecidedByTheRootTypesRule() { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor( + GraphQlAuthorizationPolicy.builder() + .allow( + GraphQlSchemaCoordinate.parse("Query.me"), + new GraphQlClientProfile("first-party")) + .allow( + GraphQlSchemaCoordinate.parse("Query.secret"), + new GraphQlClientProfile("admin")) + .build()), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = + selected("query Q { me { ... on Node { secret } } }", ROOT_IMPLEMENTS_SCHEMA); + + // when + GraphQlExecutionContext authorized = handler.handle(selected); + + // then + assertThat(authorized).isSameAs(selected); + } + + @Test + @DisplayName("규칙이 이름 붙일 수 없는 하위 타입(_Service)의 field 는 요청을 실패시키지 않고 읽힌다") + void aNestedTypeNoRuleCanNameStaysReadable() { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor( + GraphQlAuthorizationPolicy.builder() + .allow( + GraphQlSchemaCoordinate.parse("Query._service"), + new GraphQlClientProfile("first-party")) + .build()), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = + selected("query Q { _service { sdl } }", ROOT_IMPLEMENTS_SCHEMA); + + // when + GraphQlExecutionContext authorized = handler.handle(selected); + + // then + assertThat(authorized).isSameAs(selected); + } + + @Test + @DisplayName("하위 좌표 규칙이 그 호출자를 허용하면 통과한다") + void aNestedRuleThatAllowsTheCallerLetsTheFieldThrough() { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor( + GraphQlAuthorizationPolicy.builder() + .denyByDefault(false) + .allow( + GraphQlSchemaCoordinate.parse("User.salary"), + new GraphQlClientProfile("first-party")) + .build()), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = selected("query Q { me { salary } }", NESTED_SCHEMA); + + // when + GraphQlExecutionContext authorized = handler.handle(selected); + + // then + assertThat(authorized).isSameAs(selected); + } + + @Test + @DisplayName("같은 interface 를 root 아래에서 고르면 하위 좌표라 규칙이 없으면 읽힌다") + void theSameInterfaceBelowTheRootStaysANestedCoordinate() { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor(ONLY_ME_FOR_FIRST_PARTY), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = + selected("query Q { me { ...N } } fragment N on Node { secret }", ROOT_IMPLEMENTS_SCHEMA); + + // when + GraphQlExecutionContext authorized = handler.handle(selected); + + // then + assertThat(authorized).isSameAs(selected); + } + + @Test + @DisplayName("mutation payload 안의 Query field 도 root field 로 판정한다(규칙 없는 root 는 deny-by-default)") + void aRootTypeReachedBelowTheOperationRootIsStillDecidedAsRoot() { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor( + GraphQlAuthorizationPolicy.builder() + .allow( + GraphQlSchemaCoordinate.parse("Mutation.promote"), + new GraphQlClientProfile("first-party")) + .build()), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = + selected("mutation Q { promote { query { adminReport } } }", NESTED_SCHEMA); + + // when + Throwable thrown = catchThrowable(() -> handler.handle(selected)); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlAuthorizationDeniedException.class) + .hasMessage("GraphQL authorization denied: COORDINATE_NOT_AUTHORIZED"); + } + + @Test + void nestedFieldsNoRuleNamesStayReadable() { + // given + GraphQlDocumentAuthorizationHandler handler = + new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor(SALARY_FOR_ADMINS_ONLY), + new GraphQlDocumentShapeAnalyzer(), + GraphQlClientPolicy.defaults(100, 10_000, false)); + GraphQlExecutionContext selected = + selected("query Q { me { name manager { name } } }", NESTED_SCHEMA); + + // when + GraphQlExecutionContext authorized = handler.handle(selected); + + // then + assertThat(authorized).isSameAs(selected); + } + @Test void aContextWithoutASchemaIsRefusedInsteadOfGuessingRootNames() { // given diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationPolicyTest.java index 9f0a87a7..f3e06831 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthorizationPolicyTest.java @@ -46,6 +46,40 @@ class GraphQlAuthorizationPolicyTest { .isFalse(); } + @Test + void aNestedCoordinateNoRuleNamesIsAllowedEvenWhenRootsAreDeniedByDefault() { + // given + GraphQlAuthorizationPolicy policy = GraphQlAuthorizationPolicy.builder().build(); + GraphQlRequestContext firstParty = GraphQlRequestContexts.testContext("tenant-a"); + + // when + GraphQlAuthorizationDecision decision = + policy.authorizeNested(firstParty, GraphQlSchemaCoordinate.parse("User.name")); + + // then + assertThat(decision.allowed()).isTrue(); + } + + @Test + void aNestedCoordinateARuleNamesIsDecidedByThatRule() { + // given + GraphQlAuthorizationPolicy policy = + GraphQlAuthorizationPolicy.builder() + .denyByDefault(false) + .allow(GraphQlSchemaCoordinate.parse("User.salary"), new GraphQlClientProfile("admin")) + .build(); + GraphQlRequestContext firstParty = GraphQlRequestContexts.testContext("tenant-a"); + + // when + GraphQlAuthorizationDecision decision = + policy.authorizeNested(firstParty, GraphQlSchemaCoordinate.parse("User.salary")); + + // then + assertThat(decision) + .extracting(GraphQlAuthorizationDecision::allowed, GraphQlAuthorizationDecision::code) + .containsExactly(false, "COORDINATE_NOT_AUTHORIZED"); + } + @Test void deniedDecisionsUseStableCodes() { assertThat(GraphQlAuthorizationDecision.deny("ORDER_READ_DENIED").code()) diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicyTest.java index 160c8169..2326d26f 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicyTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.graphql.security; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; import dev.caskeleton.adapter.inbound.graphql.context.TenantContext; @@ -12,7 +13,10 @@ import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** Tenant isolation and context propagation (Stable plan Task 29). */ class GraphQlTenantIsolationPolicyTest { @@ -37,6 +41,38 @@ class GraphQlTenantIsolationPolicyTest { .doesNotThrowAnyException(); } + @ParameterizedTest + @ValueSource(strings = {"tenant_id", "TenantId", "X-Tenant-Id", "tenant"}) + @DisplayName("web 이 거부하는 tenant 입력 이름은 schema 가 이름을 대지 않아도, 대소문자·구분자가 달라도 거부한다") + void theSharedTenantVocabularyIsRefusedWhateverItsSpelling(String argument) { + // when + Throwable thrown = + catchThrowable( + () -> + GraphQlTenantIsolationPolicy.rejectTenantArgument( + Map.of(argument, "tenant-b"), Set.of())); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlTenantIsolationException.class) + .hasMessageContaining("tenant must come from authentication"); + } + + @Test + void aSchemasOwnTenantArgumentIsComparedWithoutCase() { + // when + Throwable thrown = + catchThrowable( + () -> + GraphQlTenantIsolationPolicy.rejectTenantArgument( + Map.of("Organization_ID", "org-b"), Set.of("organizationId"))); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlTenantIsolationException.class) + .hasMessageContaining("tenant must come from authentication"); + } + @Test void crossingATenantBoundaryIsRejected() { assertThatThrownBy( diff --git a/src/adapter/inbound/grpc/AGENTS.md b/src/adapter/inbound/grpc/AGENTS.md index b5e6b947..22e0f893 100644 --- a/src/adapter/inbound/grpc/AGENTS.md +++ b/src/adapter/inbound/grpc/AGENTS.md @@ -27,6 +27,10 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. - `:application-core`, `:domain-core`, `:shared-contract`. - `io.grpc:*` (grpc-netty-shaded / grpc-protobuf / grpc-stub / grpc-services), `spring-boot-starter`, `spring-boot-starter-validation`. +- `spring-security-core` — security context와 인증 token 타입만(`SecurityContextHolder`·`SecurityContextHolderStrategy`·`SecurityContext`·`Authentication`· + `UsernamePasswordAuthenticationToken`). 인증 정책이 돌려준 호출자를 handler가 도는 동안 `SecurityContext`에 둔다 + (`@RequiresPermission`이 읽는 곳). `Authentication`이면 그대로, 그 밖의 `Principal`은 권한 없는 인증 token으로 둔다. 근거는 + README 「기능은 어떻게 기여하는가」. ## 금지 diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index 80733703..1fc4b102 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -132,6 +132,18 @@ Spring Security에 결합되지 않는다. 인증된 호출자(`OptionalThe caller is put on the {@link SecurityContext} while the handler runs, and taken off + * afterwards: the call's start and every listener callback, on whichever executor thread gRPC runs + * them. That is the context {@code @RequiresPermission} reads, so a use case a gRPC handler calls + * judges the same caller a web request would bring. A caller that is a Spring Security {@link + * Authentication} goes on as it is (a policy that verified a bearer token with the web adapter's + * decoder and converter returns one whose principal carries the roles). Any other principal goes on + * as an authenticated token with no authorities: authenticated by the policy, holding no role, so a + * guarded use case refuses it with {@code PERMISSION_DENIED}. An empty context would have made + * Spring refuse before the permission check ran, as an unclassified {@code INTERNAL}. A gRPC call + * used to run with an empty context, and every guarded use case was denied that way (review + * 2026-11-12). */ final class GrpcAuthenticationInterceptor implements ServerInterceptor { @@ -36,7 +56,11 @@ final class GrpcAuthenticationInterceptor implements ServerInterceptor { authenticate(headers, call.getMethodDescriptor().getFullMethodName()); if (caller.isPresent()) { Context context = Context.current().withValue(GrpcAuthenticatedCaller.KEY, caller.get()); - return Contexts.interceptCall(context, call, headers, next); + SecurityContextScope scope = new SecurityContextScope(asAuthentication(caller.get())); + // A streaming handler runs in startCall itself, so the start is inside the scope too. + ServerCall.Listener listener = + scope.call(() -> Contexts.interceptCall(context, call, headers, next)); + return new SecurityContextListener<>(listener, scope); } call.close( @@ -45,6 +69,12 @@ final class GrpcAuthenticationInterceptor implements ServerInterceptor { return new ServerCall.Listener<>() {}; } + private static Authentication asAuthentication(Principal caller) { + return caller instanceof Authentication authentication + ? authentication + : UsernamePasswordAuthenticationToken.authenticated(caller, null, List.of()); + } + private Optional authenticate(Metadata headers, String method) { try { Optional caller = authenticationPolicy.authenticate(headers); @@ -59,4 +89,79 @@ final class GrpcAuthenticationInterceptor implements ServerInterceptor { return Optional.empty(); } } + + /** Puts one caller on the {@link SecurityContext} for the length of a callback. */ + private static final class SecurityContextScope { + + private final SecurityContextHolderStrategy strategy = + SecurityContextHolder.getContextHolderStrategy(); + private final Authentication authentication; + + SecurityContextScope(Authentication authentication) { + this.authentication = authentication; + } + + T call(Supplier action) { + SecurityContext previous = strategy.getContext(); + SecurityContext context = strategy.createEmptyContext(); + context.setAuthentication(authentication); + strategy.setContext(context); + try { + return action.get(); + } finally { + // Put back what the thread had. A gRPC executor thread has nothing, so it is left empty; + // an in-process call with a direct executor runs on the caller's thread, whose own context + // must survive the call. + if (previous.getAuthentication() == null) { + strategy.clearContext(); + } else { + strategy.setContext(previous); + } + } + } + + void run(Runnable action) { + call( + () -> { + action.run(); + return null; + }); + } + } + + private static final class SecurityContextListener + extends SimpleForwardingServerCallListener { + + private final SecurityContextScope scope; + + SecurityContextListener(ServerCall.Listener delegate, SecurityContextScope scope) { + super(delegate); + this.scope = scope; + } + + @Override + public void onMessage(REQT message) { + scope.run(() -> super.onMessage(message)); + } + + @Override + public void onHalfClose() { + scope.run(super::onHalfClose); + } + + @Override + public void onCancel() { + scope.run(super::onCancel); + } + + @Override + public void onComplete() { + scope.run(super::onComplete); + } + + @Override + public void onReady() { + scope.run(super::onReady); + } + } } diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcAuthenticationInterceptorTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcAuthenticationInterceptorTest.java index 265348e9..2334ba2e 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcAuthenticationInterceptorTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcAuthenticationInterceptorTest.java @@ -7,12 +7,26 @@ import io.grpc.MethodDescriptor; import io.grpc.ServerCall; import io.grpc.Status; import java.io.InputStream; +import java.util.Arrays; +import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; @ExtendWith(OutputCaptureExtension.class) class GrpcAuthenticationInterceptorTest { @@ -62,6 +76,175 @@ class GrpcAuthenticationInterceptorTest { assertThat(call.closedWith).isEqualTo(Status.Code.UNAUTHENTICATED); } + @Test + @DisplayName( + "정책이 Spring Authentication 을 돌려주면 handler 를 시작하는 동안 SecurityContext 에 그 호출자가 있고 끝나면 지워진다") + void anAuthenticationCallerIsOnTheSecurityContextWhileTheCallStarts() { + // given + Authentication caller = new TestingAuthenticationToken("caller-1", "n/a", "ROLE_USER"); + GrpcAuthenticationInterceptor interceptor = + new GrpcAuthenticationInterceptor(metadata -> Optional.of(caller), new GrpcStatusMapper()); + AtomicReference atStart = new AtomicReference<>(); + + // when + interceptor.interceptCall( + new MethodCall(), + new Metadata(), + (call, headers) -> { + atStart.set(SecurityContextHolder.getContext().getAuthentication()); + return new ServerCall.Listener<>() {}; + }); + + // then + assertThat(Arrays.asList(atStart.get(), SecurityContextHolder.getContext().getAuthentication())) + .containsExactly(caller, null); + } + + @Test + @DisplayName("half-close callback 도 그 호출자의 context 안에서 돌고 끝나면 지워진다") + void anAuthenticationCallerIsOnTheSecurityContextWhileHalfCloseRuns() { + // given + Authentication caller = new TestingAuthenticationToken("caller-1", "n/a", "ROLE_USER"); + AtomicReference inside = new AtomicReference<>(); + ServerCall.Listener listener = recordingListener(caller, inside); + + // when + listener.onHalfClose(); + + // then + assertThat(Arrays.asList(inside.get(), SecurityContextHolder.getContext().getAuthentication())) + .containsExactly(caller, null); + } + + @Test + @DisplayName("Authentication 이 아닌 호출자는 권한 없는 인증 token 으로 context 에 선다 — 빈 context 가 아니다") + void aPlainPrincipalIsOnTheContextAsAnAuthenticatedCallerWithoutAuthorities() { + // given + GrpcAuthenticationInterceptor interceptor = + new GrpcAuthenticationInterceptor( + metadata -> Optional.of(() -> "plain-caller"), new GrpcStatusMapper()); + AtomicReference atHalfClose = new AtomicReference<>(); + ServerCall.Listener listener = + interceptor.interceptCall( + new MethodCall(), + new Metadata(), + (call, headers) -> + new ServerCall.Listener<>() { + @Override + public void onHalfClose() { + atHalfClose.set(SecurityContextHolder.getContext().getAuthentication()); + } + }); + + // when + listener.onHalfClose(); + + // then + assertThat(atHalfClose.get()) + .extracting( + Authentication::getName, + Authentication::isAuthenticated, + authentication -> authentication.getAuthorities().isEmpty()) + .containsExactly("plain-caller", true, true); + } + + static Stream listenerCallbacks() { + return Stream.of( + Arguments.of(Named.of("onMessage", callback(listener -> listener.onMessage("m")))), + Arguments.of(Named.of("onReady", callback(ServerCall.Listener::onReady))), + Arguments.of(Named.of("onCancel", callback(ServerCall.Listener::onCancel))), + Arguments.of(Named.of("onComplete", callback(ServerCall.Listener::onComplete)))); + } + + private static Consumer> callback( + Consumer> callback) { + return callback; + } + + @ParameterizedTest + @MethodSource("listenerCallbacks") + @DisplayName("message·ready·cancel·complete callback 도 그 호출자의 context 안에서 돌고 끝나면 지운다") + void everyListenerCallbackRunsInsideTheCallersContext( + Consumer> callback) { + // given + Authentication caller = new TestingAuthenticationToken("caller-1", "n/a", "ROLE_USER"); + AtomicReference inside = new AtomicReference<>(); + ServerCall.Listener listener = recordingListener(caller, inside); + + // when + callback.accept(listener); + + // then + assertThat(Arrays.asList(inside.get(), SecurityContextHolder.getContext().getAuthentication())) + .containsExactly(caller, null); + } + + @Test + @DisplayName("callback 이 끝나면 그 스레드에 먼저 있던 context 로 되돌린다 — 호출자 스레드의 context 를 지우지 않는다") + void aContextAlreadyOnTheThreadIsRestoredAfterTheCallback() { + // given + Authentication outer = new TestingAuthenticationToken("outer", "n/a"); + SecurityContext outerContext = SecurityContextHolder.createEmptyContext(); + outerContext.setAuthentication(outer); + SecurityContextHolder.setContext(outerContext); + Authentication caller = new TestingAuthenticationToken("caller-1", "n/a", "ROLE_USER"); + AtomicReference inside = new AtomicReference<>(); + ServerCall.Listener listener = recordingListener(caller, inside); + + // when + listener.onHalfClose(); + + // then + assertThat(Arrays.asList(inside.get(), SecurityContextHolder.getContext().getAuthentication())) + .containsExactly(caller, outer); + } + + @AfterEach + void clearTheThreadsContext() { + SecurityContextHolder.clearContext(); + } + + /** A listener that records the context's caller in whichever callback runs. */ + private static ServerCall.Listener recordingListener( + Authentication caller, AtomicReference inside) { + GrpcAuthenticationInterceptor interceptor = + new GrpcAuthenticationInterceptor(metadata -> Optional.of(caller), new GrpcStatusMapper()); + return interceptor.interceptCall( + new MethodCall(), + new Metadata(), + (call, headers) -> + new ServerCall.Listener<>() { + @Override + public void onMessage(String message) { + record(); + } + + @Override + public void onHalfClose() { + record(); + } + + @Override + public void onReady() { + record(); + } + + @Override + public void onCancel() { + record(); + } + + @Override + public void onComplete() { + record(); + } + + private void record() { + inside.set(SecurityContextHolder.getContext().getAuthentication()); + } + }); + } + /** A server call that only knows its method; the interceptor closes it as unauthenticated. */ private static final class MethodCall extends ServerCall { diff --git a/src/adapter/inbound/web-advanced/README.md b/src/adapter/inbound/web-advanced/README.md index 9ae11896..cbf8ffea 100644 --- a/src/adapter/inbound/web-advanced/README.md +++ b/src/adapter/inbound/web-advanced/README.md @@ -70,6 +70,9 @@ virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관 - `Retry-After` 는 `WebAdvancedError` 가 web 의 `RetryAfterHint` 로 직접 말한다. web 의 `RetryAfterAdvisor` 표에 이 leaf 코드 이름을 넣지 않는다. - `details` 는 `ClientSafeErrorDetails` 로 고른 값만 나간다. 예외 메시지는 나가지 않는다. +- `details.refusedPaths` 는 요청이 쓴 이름이다(허용 목록에 없는 이름이라 거부됐다). 그래서 16개까지, + `[A-Za-z0-9_.~/-]` 128자 이하인 이름만 그대로 돌려주고 나머지는 `` 로 바꾼다. 예외 메시지에는 + 개수와 같은 목록만 있다. - 이 코드들은 `docs/registries/error-codes.yaml`(`OperationalError` SSOT) 밖이다. 5xx 는 `handleCarrier` 가 ERROR 로그를 남긴다(admission 거절 포함 — 경보 임계는 운영에서 정한다). - 응답 status 가 이미 commit 된 스트림 안에서는 HTTP status 가 바뀌지 않는다. 위 표는 commit 전에 던져진 diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java index 93c1439c..355e46d4 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java @@ -7,30 +7,63 @@ import dev.caskeleton.shared.error.ApiErrorCode; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.regex.Pattern; /** * A patch tried to touch something the caller may not. * - *

Names the fields, because the caller needs to know which of them was refused and the names are - * from the server's allowlist rather than from the request — so they are safe to echo. + *

Names the refused fields, because the caller needs to know which of them was refused. The + * names are the request's own: a refused name is by definition not on the server's allowlist. So + * only a bounded, plain echo goes back — at most {@link #MAX_ECHOED} names, each one a JSON Pointer + * or field name of the safe characters below and at most {@link #MAX_ECHOED_LENGTH} long; any other + * is replaced by {@link #UNPRINTABLE}. The message carries the count and the same bounded echo, + * never a raw name (review 2026-11-12: the Javadoc used to say the names came from the allowlist, + * and both message and details echoed them unbounded). */ public final class PatchAuthorizationException extends RuntimeException implements ApiErrorCarrier, ClientSafeErrorDetails { private static final long serialVersionUID = 1L; + /** How many refused names the details echo. */ + static final int MAX_ECHOED = 16; + + /** The longest refused name echoed as written. */ + static final int MAX_ECHOED_LENGTH = 128; + + /** What a refused name outside the echoable form is replaced by. */ + static final String UNPRINTABLE = ""; + + private static final Pattern ECHOABLE = Pattern.compile("[A-Za-z0-9_.~/-]+"); + private final transient List refusedPaths; public PatchAuthorizationException(List refusedPaths) { - super("the patch touches fields this caller may not modify: " + refusedPaths); - this.refusedPaths = List.copyOf(Objects.requireNonNull(refusedPaths, "refusedPaths")); + this(echoed(Objects.requireNonNull(refusedPaths, "refusedPaths")), refusedPaths.size()); } - /** Which paths were refused. */ + private PatchAuthorizationException(List echoed, int refusedCount) { + super("the patch touches " + refusedCount + " field(s) this caller may not modify: " + echoed); + this.refusedPaths = List.copyOf(echoed); + } + + private static List echoed(List refused) { + return refused.stream().limit(MAX_ECHOED).map(PatchAuthorizationException::echoable).toList(); + } + + /** Which paths were refused, as echoed to the client: bounded and plain. */ public List refusedPaths() { return refusedPaths; } + private static String echoable(String refused) { + return refused != null + && refused.length() <= MAX_ECHOED_LENGTH + && ECHOABLE.matcher(refused).matches() + ? refused + : UNPRINTABLE; + } + /** {@link WebAdvancedError#PATCH_PATH_FORBIDDEN}; see the leaf README for the client contract. */ @Override public ApiErrorCode errorCode() { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolver.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolver.java index 14a83b1b..73dab5e6 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolver.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolver.java @@ -1,7 +1,7 @@ package dev.caskeleton.adapter.inbound.web.advanced.security; import dev.caskeleton.adapter.inbound.web.core.TenantContext; -import java.util.Locale; +import dev.caskeleton.application.tenant.TenantId; import java.util.Map; import java.util.Objects; @@ -15,10 +15,6 @@ import java.util.Objects; */ public final class WebTenantContextResolver { - /** Header and parameter names that would be a tenant if anybody believed them. */ - private static final java.util.Set TENANT_INPUT_NAMES = - java.util.Set.of("x-tenant-id", "tenant-id", "tenantid", "tenant"); - /** * The tenant scope for an authentication. * @@ -32,6 +28,9 @@ public final class WebTenantContextResolver { /** * Refuses request input that proposes a tenant. * + *

The names are {@link TenantId#namesATenant}'s, the vocabulary GraphQL refuses too. This list + * used to miss {@code tenant_id} (review 2026-11-12). + * * @param requestInput headers or parameters, keyed by name * @throws UntrustedTenantInputException when any of them names a tenant */ @@ -39,11 +38,7 @@ public final class WebTenantContextResolver { if (requestInput == null || requestInput.isEmpty()) { return; } - boolean proposed = - requestInput.keySet().stream() - .filter(Objects::nonNull) - .map(name -> name.toLowerCase(Locale.ROOT)) - .anyMatch(TENANT_INPUT_NAMES::contains); + boolean proposed = requestInput.keySet().stream().anyMatch(TenantId::namesATenant); if (proposed) { throw new UntrustedTenantInputException(); } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationExceptionTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationExceptionTest.java new file mode 100644 index 00000000..5860022c --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationExceptionTest.java @@ -0,0 +1,50 @@ +package dev.caskeleton.adapter.inbound.web.advanced.patch; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** The refused names are the request's own, so what goes back is bounded and plain. */ +class PatchAuthorizationExceptionTest { + + @Test + @DisplayName("허용 목록에 없는 이름은 요청 값이다 — 안전한 모양만 그대로 돌려주고 나머지는 가린다") + void onlyPlainRefusedNamesAreEchoed() { + // given + List refused = List.of("/role", "", "x".repeat(129)); + + // when + PatchAuthorizationException failure = new PatchAuthorizationException(refused); + + // then + assertThat(failure.clientDetails()) + .isEqualTo( + Map.of( + "refusedPaths", + List.of( + "/role", + PatchAuthorizationException.UNPRINTABLE, + PatchAuthorizationException.UNPRINTABLE))); + } + + @Test + @DisplayName("돌려주는 이름은 16개까지이고 메시지에는 전체 개수와 그 16개만 있다") + void theEchoIsBoundedAndTheMessageCarriesTheCountAndOnlyTheEchoedNames() { + // given + List refused = IntStream.range(0, 40).mapToObj(i -> "/f" + i).toList(); + + // when + PatchAuthorizationException failure = new PatchAuthorizationException(refused); + + // then + assertThat(List.of(failure.refusedPaths().size(), failure.getMessage())) + .containsExactly( + PatchAuthorizationException.MAX_ECHOED, + "the patch touches 40 field(s) this caller may not modify: " + + refused.subList(0, PatchAuthorizationException.MAX_ECHOED)); + } +} diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolverTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolverTest.java new file mode 100644 index 00000000..36e70d33 --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolverTest.java @@ -0,0 +1,27 @@ +package dev.caskeleton.adapter.inbound.web.advanced.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class WebTenantContextResolverTest { + + private final WebTenantContextResolver resolver = new WebTenantContextResolver(); + + @ParameterizedTest + @ValueSource(strings = {"tenant_id", "X-Tenant-Id", "tenantId", "tenant"}) + @DisplayName("tenant 를 제안하는 header·parameter 는 GraphQL 과 같은 어휘로 거부한다(tenant_id 포함)") + void aProposedTenantIsRefusedWhateverItsSpelling(String name) { + // when + Throwable thrown = catchThrowable(() -> resolver.rejectTenantInput(Map.of(name, "tenant-b"))); + + // then + assertThat(thrown) + .isInstanceOf(UntrustedTenantInputException.class) + .hasMessageStartingWith("a tenant was supplied by request input"); + } +} diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 6792c246..5435fc79 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -92,6 +92,11 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - **메커니즘 & 트레이드오프**: Spring Security 는 JWT 실패에 단일 typed reason 을 노출하지 않으므로, classifier 가 예외 그래프와 validator/Nimbus 메시지 텍스트를 검사한다. 매핑: - missing token → `InsufficientAuthenticationException` → `AUTH_TOKEN_MISSING` + - claim 대응 실패(`JwtToAuthenticatedPrincipalConverter`의 `jwt_claim_mapping_failed`: `sub` 없음, 틀린 tenant + claim) → `AUTH_CLAIM_MAPPING_FAILED` + - 원인 사슬에 HTTP·I/O 실패(`RestClientException`·`IOException`)가 있으면 문구 규칙보다 먼저 → + `AUTH_JWKS_UNAVAILABLE`. decoder를 만든 뒤 JWKS를 다시 받다가(모르는 kid, 키 캐시 만료) IdP가 답하지 않은 경우다. + 라이브러리 문구가 "…decode the Jwt: "라 문구 규칙만 보면 `AUTH_TOKEN_MALFORMED`가 됐다 - claim validators(`JwtValidationException`) → description 에 따라 `AUTH_TOKEN_EXPIRED` / `AUTH_ISSUER_MISMATCH` / `AUTH_AUDIENCE_MISMATCH` - decode/signature/unknown-kid(`BadJwtException`/`JwtException` cause) → @@ -160,17 +165,18 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - 가로챈 메서드(또는 선언 타입)에서 애너테이션을 읽고, 현재 `Authentication` 을 프레임워크 독립적 `AuthorizationPrincipal` 로 매핑해 결정을 application `AuthorizationPort` 에 위임한다. 따라서 application/domain 은 어떤 Spring Security 타입도 갖지 않으며, **이 어댑터가 두 세계가 만나는 유일한 지점**이다. -- 포트가 거부 시 application `AuthorizationDeniedException` 을 던지고, 이 매니저가 그것을 거부된 - `AuthorizationDecision` 으로 변환한다. method-security 인터셉터가 이를 `AccessDeniedException` → - `AUTHZ_INSUFFICIENT_PERMISSION` 403 으로 만든다(§4). `null` 반환은 기권(abstain)이라 애너테이션 없는 - 메서드는 영향받지 않는다. +- 포트가 거부 시 application `AuthorizationDeniedException` 을 던지고, 이 매니저는 그것을 거부된 + `AuthorizationDecision` 으로 바꾸지 않고 그대로 내보낸다. 그 예외가 `ApiErrorCarrier`(`AUTHZ_INSUFFICIENT_PERMISSION`)라 + web 은 `GlobalExceptionHandler` 가 403 으로, gRPC·GraphQL 은 자기 오류 대응이 같은 코드로 답한다. 거부를 잡는 코드는 + Spring `AccessDeniedException` 이 아니라 이 예외(또는 `ApiErrorCarrier`)를 잡는다. `null` 반환은 기권(abstain)이라 + 애너테이션 없는 메서드는 영향받지 않는다. - 매핑은 **fail-closed**: 미인증 요청이거나 우리 `AuthenticatedPrincipal` 이 아닌 principal 은 0개 role 로 - 해석되어 거부된다. + 해석되어 거부된다. 역할은 principal 에서만 읽고 `GrantedAuthority` 는 보지 않는다. ### AuthorizationAdapter - application `AuthorizationPort` 의 web-adapter 구현체. - 결정은 **fail-closed**: principal 의 유효 권한 집합에 요구 권한이 없으면 `AuthorizationDeniedException` 으로 - 거부 → `RequiresPermissionAuthorizationManager` 가 변환 → 최종 `AUTHZ_INSUFFICIENT_PERMISSION` 403. + 거부 → `RequiresPermissionAuthorizationManager` 가 그대로 내보냄 → 최종 `AUTHZ_INSUFFICIENT_PERMISSION` 403. ### RolePermissionRegistry - 호출자의 raw role 들을 유효 `Permission` 집합으로 해석한다. @@ -248,7 +254,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML | `InvalidIdempotencyKeyException` | `IDEMPOTENCY_KEY_INVALID` | 400 | `IdempotencyKeyHeader.parse` 가 헤더 누락·문법 밖을 거부. `details.reason` = `MISSING`/`MALFORMED`, 키 원문 미노출(리뷰 02-12) | | `InvalidBearerTokenException` | `INVALID_TOKEN` | 코드 상태 | | | `AuthenticationException` | `UNAUTHENTICATED` | 코드 상태 | | -| `AccessDeniedException` | `SecurityErrorClassifier` 결정(예: `AUTHZ_INSUFFICIENT_PERMISSION`) | 분류기 결정 | 메서드-시큐리티 거부가 컨트롤러를 빠져나오면 여기 도달. 필터 계층 `EnvelopeAccessDeniedHandler` 와 **동일한 세분화 코드**를 내도록 무상태 classifier 에 위임 | +| `AccessDeniedException` | `SecurityErrorClassifier` 결정(예: `AUTHZ_INSUFFICIENT_PERMISSION`) | 분류기 결정 | 컨트롤러를 빠져나온 Spring 거부(서비스가 직접 던진 것 등). 필터 계층 `EnvelopeAccessDeniedHandler` 와 **동일한 세분화 코드**를 내도록 무상태 classifier 에 위임. `@RequiresPermission` 거부는 여기 오지 않는다 — `AuthorizationDeniedException` carrier 라 carrier 분기가 `AUTHZ_INSUFFICIENT_PERMISSION` 403 으로 답한다 | | `PreconditionFailedException` | `PRECONDITION_FAILED` | 412 | D15: `If-Match` 불일치 쓰기 = 낙관적 동시성 충돌 → 412 (raw 409/500 금지) | | `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 | | `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | action 전에 거부 — 조정 저장소가 응답하지 않았거나, claim의 processing lease가 시작 전에 끝나 저장소가 시작을 거절했다(실행 안 됨, 저장소는 정상일 수 있다). 같은 키로 나중에 재전송하면 다음 요청이 그 claim을 넘겨받아 실행한다(`docs/web/http-contract.md` §2, 라운드6 RR6-02-04). carrier 분기 | diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java index 32c3f7d1..bcbc7122 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java @@ -59,7 +59,12 @@ public class JwtDecoderConfig { }; } - private static boolean causedByExternalKeyService(Throwable failure) { + /** + * Whether a failure was the key service (discovery or JWKS) not answering: an HTTP client or I/O + * failure anywhere in its cause chain. Also used by {@link SecurityErrorClassifier} for a JWKS + * refresh that fails after the decoder was built. + */ + static boolean causedByExternalKeyService(Throwable failure) { Throwable current = failure; for (int depth = 0; current != null && depth < 32; depth++) { if (current instanceof RestClientException || current instanceof IOException) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java index 2ac7296e..7cf680e5 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java @@ -5,7 +5,6 @@ import dev.caskeleton.application.tenant.TenantId; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; -import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -15,8 +14,9 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.jwt.Jwt; -import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.stereotype.Component; @@ -28,7 +28,14 @@ import org.springframework.stereotype.Component; * *

Only the clients named by {@code app.security.audience} contribute {@code resource_access} * roles. Another client of the same issuer may define a role with the same name (for example {@code - * operation-submit}); reading every client would hand that role to this service. + * operation-submit}); reading every client would hand that role to this service. A top-level {@code + * roles} claim is not read either: it has no client, so any client of the issuer could put a role + * in it (review 2026-11-12, the fallback that read it was removed). + * + *

A token the claims cannot be mapped from — no {@code sub}, or a malformed tenant — is refused + * here as {@code AUTH_CLAIM_MAPPING_FAILED} (401), by a structured error code rather than message + * text. A principal without a subject used to reach callers that require one and fail there as a + * 500. */ @Component public class JwtToAuthenticatedPrincipalConverter @@ -37,11 +44,18 @@ public class JwtToAuthenticatedPrincipalConverter /** * The claim a token names its tenant in. * - *

Snake case like the rest of this platform's field names ({@code tenant_id} is also the MDC - * and baggage key). An IdP that puts the tenant elsewhere maps it to this claim. + *

Snake case like the rest of this platform's field names. No code puts the tenant on MDC, so + * no log line carries it (this line used to say it was an MDC key, review 2026-11-12). An IdP + * that puts the tenant elsewhere maps it to this claim. */ public static final String TENANT_CLAIM = "tenant_id"; + /** + * The {@link OAuth2Error} code of a token whose claims cannot be mapped to a principal; {@link + * SecurityErrorClassifier} answers it as {@code AUTH_CLAIM_MAPPING_FAILED}. + */ + static final String ERROR_CLAIM_MAPPING_FAILED = "jwt_claim_mapping_failed"; + /** The clients whose {@code resource_access} roles this service honours: its own audiences. */ private final Set roleClients; @@ -51,10 +65,14 @@ public class JwtToAuthenticatedPrincipalConverter @Override public AbstractAuthenticationToken convert(Jwt jwt) { + String subject = jwt.getSubject(); + if (subject == null || subject.isBlank()) { + throw claimMappingFailed("the token names no subject"); + } Set roles = extractRoles(jwt); String email = jwt.getClaimAsString("email"); AuthenticatedPrincipal principal = - new AuthenticatedPrincipal(jwt.getSubject(), email, roles, tenant(jwt)); + new AuthenticatedPrincipal(subject, email, roles, tenant(jwt)); Collection authorities = roles.stream() .map(r -> new SimpleGrantedAuthority("ROLE_" + r.toUpperCase(Locale.ROOT))) @@ -73,12 +91,16 @@ public class JwtToAuthenticatedPrincipalConverter try { return TenantId.optional(jwt.getClaimAsString(TENANT_CLAIM)); } catch (IllegalArgumentException malformed) { - // No cause: Spring's (description, cause) constructor replaces the description with the - // cause's message, and a 401 description names the claim, not our grammar. - throw new InvalidBearerTokenException("the token's tenant claim is malformed"); + // No cause: the description names the claim, not our grammar or the value. + throw claimMappingFailed("the token's tenant claim is malformed"); } } + private static OAuth2AuthenticationException claimMappingFailed(String description) { + return new OAuth2AuthenticationException( + new OAuth2Error(ERROR_CLAIM_MAPPING_FAILED, description, null), description); + } + private Set extractRoles(Jwt jwt) { Set roles = new HashSet<>(); @@ -98,11 +120,6 @@ public class JwtToAuthenticatedPrincipalConverter } } } - // Generic OIDC "roles" claim as a fallback - List flat = jwt.getClaimAsStringList("roles"); - if (flat != null) { - roles.addAll(flat); - } return roles; } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityErrorClassifier.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityErrorClassifier.java index e0389013..ddcccbb1 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityErrorClassifier.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityErrorClassifier.java @@ -11,9 +11,10 @@ import org.springframework.security.oauth2.jwt.JwtValidationException; /** * Classifies a resource-server security failure into a fine-grained {@link OperationalError} by - * inspecting structured validator error codes first and Nimbus message text only as a decoder - * fallback. Unmapped failures fall back to the generic, safe {@code AUTH_TOKEN_MALFORMED} (401) - * rather than a 500. See README for the design rationale. + * inspecting structured error codes first, then the cause's type (the decoder's own failures, and + * an HTTP or I/O failure of the key service anywhere in the chain), and Nimbus message text only as + * a decoder fallback. Unmapped failures fall back to the generic, safe {@code AUTH_TOKEN_MALFORMED} + * (401) rather than a 500. See README for the design rationale. */ public class SecurityErrorClassifier { @@ -49,6 +50,13 @@ public class SecurityErrorClassifier { if (cause instanceof JwtDecoderConfig.AuthenticationDecoderMisconfigurationException) { return OperationalError.INTERNAL_AUTH_MISCONFIGURATION; } + // A JWKS refresh after the decoder was built (an unknown kid, an expired key cache) that the + // key + // service did not answer. The library's message is "...attempting to decode the Jwt: ", which the text rules below would read as a malformed token. + if (JwtDecoderConfig.causedByExternalKeyService(cause)) { + return OperationalError.AUTH_JWKS_UNAVAILABLE; + } if (cause instanceof JwtValidationException validation) { // A JWKS retrieval failure can surface wrapped in validation errors too. OperationalError classified = null; @@ -70,6 +78,8 @@ public class SecurityErrorClassifier { case JwtDecoderConfig.ERROR_TIMESTAMP_INVALID -> OperationalError.AUTH_TOKEN_EXPIRED; case JwtDecoderConfig.ERROR_ISSUER_MISMATCH -> OperationalError.AUTH_ISSUER_MISMATCH; case JwtDecoderConfig.ERROR_AUDIENCE_MISMATCH -> OperationalError.AUTH_AUDIENCE_MISMATCH; + case JwtToAuthenticatedPrincipalConverter.ERROR_CLAIM_MAPPING_FAILED -> + OperationalError.AUTH_CLAIM_MAPPING_FAILED; default -> null; }; return structured != null ? structured : classifyByText(describe(error)); diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/authz/RequiresPermissionAuthorizationManager.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/authz/RequiresPermissionAuthorizationManager.java index acea282c..3f53b911 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/authz/RequiresPermissionAuthorizationManager.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/authz/RequiresPermissionAuthorizationManager.java @@ -23,12 +23,21 @@ import org.springframework.security.core.Authentication; *

Reads the {@link RequiresPermission} annotation off the intercepted method (or its declaring * type), maps the current {@link Authentication} to the framework-free {@link * AuthorizationPrincipal}, and delegates the decision to the application {@link AuthorizationPort}. - * A denial from the port becomes a denied {@link AuthorizationDecision}; an absent annotation - * returns {@code null} to abstain. See README for the design rationale. + * An absent annotation returns {@code null} to abstain. See README for the design rationale. + * + *

A denial is thrown as the application's {@link AuthorizationDeniedException}, which carries + * {@code AUTHZ_INSUFFICIENT_PERMISSION}, instead of being returned as a denied decision. Spring + * turns a denied decision into its own {@code AccessDeniedException}, which only the web adapter + * maps; a use case called from gRPC, GraphQL or STOMP answered it as {@code INTERNAL_ERROR} with an + * ERROR line (review 2026-11-12). Those transports put their authenticated caller on the {@code + * SecurityContext} for the call, so the same check sees the same principal there. */ public final class RequiresPermissionAuthorizationManager implements AuthorizationManager { + /** The subject a denial names when no authenticated caller is on the context. */ + static final String UNAUTHENTICATED_SUBJECT = "unauthenticated"; + private final Supplier authorizationPort; /** @@ -54,14 +63,10 @@ public final class RequiresPermissionAuthorizationManager Authentication auth = authentication.get(); if (auth == null || !auth.isAuthenticated()) { - return new AuthorizationDecision(false); - } - try { - authorizationPort.get().requirePermission(toPrincipal(auth), required); - return new AuthorizationDecision(true); - } catch (AuthorizationDeniedException denied) { - return new AuthorizationDecision(false); + throw new AuthorizationDeniedException(UNAUTHENTICATED_SUBJECT, required); } + authorizationPort.get().requirePermission(toPrincipal(auth), required); + return new AuthorizationDecision(true); } private RequiresPermission findAnnotation(MethodInvocation invocation) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index 617b1500..ea56e6ee 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -135,8 +135,10 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { } /** - * Handles a method-security {@link AccessDeniedException} that escaped the controller, delegating - * to {@link SecurityErrorClassifier} for the fine-grained authorization code. See README for the + * Handles a Spring {@link AccessDeniedException} that escaped the controller, delegating to + * {@link SecurityErrorClassifier} for the fine-grained authorization code. A + * {@code @RequiresPermission} denial does not come here: it is an {@code + * AuthorizationDeniedException}, a carrier, answered by the carrier branch. See README for the * design rationale. */ @ExceptionHandler(AccessDeniedException.class) diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtJwksSecurityFilterIntegrationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtJwksSecurityFilterIntegrationTest.java index ce5ff188..a8247324 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtJwksSecurityFilterIntegrationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtJwksSecurityFilterIntegrationTest.java @@ -38,6 +38,7 @@ import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -181,6 +182,39 @@ class JwtJwksSecurityFilterIntegrationTest { } } + @Test + @DisplayName( + "한 번 성공한 뒤 모르는 kid 로 JWKS 를 다시 받다 IdP 가 503 이면 401 이 아니라 503 AUTH_JWKS_UNAVAILABLE 이다") + void aJwksRefreshTheIdpDoesNotAnswerAfterTheFirstSuccessIsARetryable503() throws Exception { + try (OidcServer issuer = OidcServer.available()) { + String known = + token( + PRIMARY_KEY, PRIMARY_KID, issuer.issuer(), AUDIENCE, Instant.now().plusSeconds(300)); + String rotated = + token( + PRIMARY_KEY, + "rotated-key", + issuer.issuer(), + AUDIENCE, + Instant.now().plusSeconds(300)); + + withContext( + issuer, + mvc -> { + // given + mvc.perform(get("/protected").header(HttpHeaders.AUTHORIZATION, "Bearer " + known)) + .andExpect(status().isOk()); + issuer.makeJwksUnavailable(); + + // when + MvcResult refreshFailed = assertJwksUnavailable(mvc, rotated); + + // then + assertSafe(refreshFailed, rotated, issuer.issuer(), "rotated-key"); + }); + } + } + @Test void mismatchedDiscoveryMetadataUsesSafeInternalMisconfigurationEnvelope() throws Exception { try (OidcServer issuer = OidcServer.misconfiguredDiscovery()) { @@ -304,7 +338,7 @@ class JwtJwksSecurityFilterIntegrationTest { .issueTime(Date.from(now.minusSeconds(300))) .expirationTime(Date.from(expiresAt)) .claim("email", "user-1@example.test") - .claim("roles", List.of("operator")) + .claim("realm_access", Map.of("roles", List.of("operator"))) .build(); SignedJWT jwt = new SignedJWT( @@ -389,6 +423,10 @@ class JwtJwksSecurityFilterIntegrationTest { unavailable = false; } + void makeJwksUnavailable() { + unavailable = true; + } + private void discovery(HttpExchange exchange) throws IOException { discoveryRequests.incrementAndGet(); String body = diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java index 8d62ceac..11c40954 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java @@ -5,14 +5,15 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; import dev.caskeleton.application.tenant.TenantId; +import dev.caskeleton.shared.error.OperationalError; import java.util.List; import java.util.Locale; import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; -import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; class JwtToAuthenticatedPrincipalConverterTest { @@ -27,7 +28,7 @@ class JwtToAuthenticatedPrincipalConverterTest { Jwt.withTokenValue("token") .header("alg", "none") .subject("user-1") - .claim("roles", List.of("admin")) + .claim("realm_access", Map.of("roles", List.of("admin"))) .build(); var authentication = converter().convert(jwt); @@ -63,7 +64,7 @@ class JwtToAuthenticatedPrincipalConverterTest { } @Test - @DisplayName("형식이 틀린 tenant claim은 '없음'이 아니라 잘못된 token으로 거부한다(401)") + @DisplayName("형식이 틀린 tenant claim은 '없음'이 아니라 claim 대응 실패로 거부한다(AUTH_CLAIM_MAPPING_FAILED, 401)") void aTokenWithAMalformedTenantClaimIsRefused() { // given Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "ac me").build(); @@ -72,9 +73,38 @@ class JwtToAuthenticatedPrincipalConverterTest { Throwable thrown = catchThrowable(() -> converter().convert(jwt)); // then - assertThat(thrown) - .isInstanceOf(InvalidBearerTokenException.class) - .hasMessage("the token's tenant claim is malformed"); + assertThat( + new SecurityErrorClassifier().classifyAuthentication((AuthenticationException) thrown)) + .isEqualTo(OperationalError.AUTH_CLAIM_MAPPING_FAILED); + } + + @Test + @DisplayName("sub 없는 token은 principal 없이 넘어가지 않고 AUTH_CLAIM_MAPPING_FAILED(401)로 거부한다") + void aTokenWithoutASubjectIsRefusedAsAClaimMappingFailure() { + // given + Jwt jwt = + Jwt.withTokenValue("token").header("alg", "none").claim("email", "x@example.test").build(); + + // when + Throwable thrown = catchThrowable(() -> converter().convert(jwt)); + + // then + assertThat( + new SecurityErrorClassifier().classifyAuthentication((AuthenticationException) thrown)) + .isEqualTo(OperationalError.AUTH_CLAIM_MAPPING_FAILED); + } + + @Test + @DisplayName("client 가 없는 최상위 roles claim 은 권한이 되지 않는다") + void aTopLevelRolesClaimGrantsNoAuthority() { + // given + Jwt jwt = token().claim("roles", List.of("operation-submit")).build(); + + // when + var authentication = converter().convert(jwt); + + // then + assertThat(authentication.getAuthorities()).isEmpty(); } @Test diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityErrorClassifierTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityErrorClassifierTest.java index 8507529a..1a137a07 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityErrorClassifierTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityErrorClassifierTest.java @@ -3,7 +3,9 @@ package dev.caskeleton.adapter.inbound.web.auth; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.shared.error.OperationalError; +import java.net.ConnectException; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationServiceException; @@ -15,6 +17,7 @@ import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.jwt.JwtValidationException; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; +import org.springframework.web.client.ResourceAccessException; /** * feature-security-operational-baseline §구현가이드 3 — the resource-server exception → fine-grained @@ -148,6 +151,25 @@ class SecurityErrorClassifierTest { .isEqualTo(OperationalError.AUTH_KID_UNKNOWN); } + @Test + @DisplayName("decoder 를 만든 뒤 JWKS 를 다시 받다 실패하면 decode 문구가 있어도 AUTH_JWKS_UNAVAILABLE 이다") + void aJwksRefreshTheKeyServiceDidNotAnswerIsJwksUnavailable() { + // given + JwtException cause = + new JwtException( + "An error occurred while attempting to decode the Jwt: I/O error on GET request for" + + " \"http://idp.invalid/certs\": Connection refused", + new ResourceAccessException( + "I/O error on GET request for \"http://idp.invalid/certs\": Connection refused", + new ConnectException("Connection refused"))); + + // when + OperationalError classified = classify(new InvalidBearerTokenException("invalid", cause)); + + // then + assertThat(classified).isEqualTo(OperationalError.AUTH_JWKS_UNAVAILABLE); + } + @Test void jwksEndpointOutageIsJwksUnavailable() { JwtException cause = diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/authz/RequiresPermissionAuthorizationManagerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/authz/RequiresPermissionAuthorizationManagerTest.java index 3e8f3d26..8c02a2b4 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/authz/RequiresPermissionAuthorizationManagerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/authz/RequiresPermissionAuthorizationManagerTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.web.authz; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -10,6 +11,8 @@ import dev.caskeleton.application.security.AuthorizationDeniedException; import dev.caskeleton.application.security.AuthorizationPort; import dev.caskeleton.application.security.AuthorizationPrincipal; import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.security.Permission; import java.lang.reflect.Method; import java.util.List; @@ -17,6 +20,7 @@ import java.util.Map; import java.util.Set; import java.util.function.Supplier; import org.aopalliance.intercept.MethodInvocation; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken; @@ -79,12 +83,22 @@ class RequiresPermissionAuthorizationManagerTest { } @Test + @DisplayName( + "권한이 없으면 Spring 거부 결정이 아니라 AUTHZ_INSUFFICIENT_PERMISSION carrier 를 던진다 — 모든 전송이 같은 코드로 답한다") void deniesWhenPrincipalLacksRequiredPermission() throws Exception { - AuthorizationResult decision = - manager.authorize(principalWithRoles("user"), invocationOf("close")); + // given + MethodInvocation close = invocationOf("close"); - assertThat(decision).isNotNull(); - assertThat(decision.isGranted()).isFalse(); + // when + Throwable thrown = catchThrowable(() -> manager.authorize(principalWithRoles("user"), close)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + ApiErrorCarrier.class, + carrier -> + assertThat(carrier.errorCode()) + .isEqualTo(OperationalError.AUTHZ_INSUFFICIENT_PERMISSION)); } @Test @@ -97,6 +111,7 @@ class RequiresPermissionAuthorizationManagerTest { @Test void deniesUnauthenticatedRequestFailClosed() throws Exception { + // given Supplier anonymous = () -> { AnonymousAuthenticationToken token = @@ -106,14 +121,23 @@ class RequiresPermissionAuthorizationManagerTest { return token; }; - AuthorizationResult decision = manager.authorize(anonymous, invocationOf("close")); + MethodInvocation close = invocationOf("close"); - assertThat(decision).isNotNull(); - assertThat(decision.isGranted()).isFalse(); + // when + Throwable thrown = catchThrowable(() -> manager.authorize(anonymous, close)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + AuthorizationDeniedException.class, + denied -> + assertThat(denied.subject()) + .isEqualTo(RequiresPermissionAuthorizationManager.UNAUTHENTICATED_SUBJECT)); } @Test void deniesWhenPrincipalIsNotOurAuthenticatedUser() throws Exception { + // given Supplier foreignPrincipal = () -> { TestingAuthenticationToken auth = @@ -122,9 +146,15 @@ class RequiresPermissionAuthorizationManagerTest { return auth; }; - AuthorizationResult decision = manager.authorize(foreignPrincipal, invocationOf("close")); + MethodInvocation close = invocationOf("close"); - assertThat(decision.isGranted()).isFalse(); + // when + Throwable thrown = catchThrowable(() -> manager.authorize(foreignPrincipal, close)); + + // then + assertThat(thrown) + .isInstanceOf(AuthorizationDeniedException.class) + .hasMessageContaining("worklog:close"); } @Test diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java index faf2ac72..7b3300d4 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java @@ -11,6 +11,7 @@ import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedExceptio import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; +import dev.caskeleton.application.security.AuthorizationDeniedException; import dev.caskeleton.shared.error.AdapterDisabledException; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; @@ -19,6 +20,7 @@ import dev.caskeleton.shared.error.MappingException; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; import dev.caskeleton.shared.response.Envelope; +import dev.caskeleton.shared.security.Permission; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import jakarta.validation.ConstraintViolation; import jakarta.validation.ConstraintViolationException; @@ -31,6 +33,7 @@ import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -375,10 +378,10 @@ class GlobalExceptionHandlerTest { assertThat(response.getBody().error().message()).isEqualTo(ClientErrorMessages.OPAQUE); } - // feature-authentication-authorization-contract D5/§4: an authorization denial that - // escapes the controller (a @RequiresPermission the caller could not satisfy) reaches this - // controller-advice path as an AccessDeniedException. It must emit the same fine-grained - // AUTHZ_INSUFFICIENT_PERMISSION code as the filter-layer handler, not a coarse FORBIDDEN. + // feature-authentication-authorization-contract D5/§4: a Spring AccessDeniedException that + // escapes the controller (one a service throws itself) reaches this controller-advice path. It + // must emit the same fine-grained AUTHZ_INSUFFICIENT_PERMISSION code as the filter-layer handler, + // not a coarse FORBIDDEN. A @RequiresPermission denial is a carrier and is tested below. @Test void accessDeniedMapsToFineGrainedInsufficientPermission() { ResponseEntity> response = @@ -393,6 +396,20 @@ class GlobalExceptionHandlerTest { assertThat(body.error().retryable()).isFalse(); } + @Test + @DisplayName("method security 가 던진 권한 거부 carrier 도 같은 403 AUTHZ_INSUFFICIENT_PERMISSION 이다") + void anApplicationAuthorizationDenialAnswersInsufficientPermission() { + // when + ResponseEntity> response = + handler.handleUnknown( + new AuthorizationDeniedException("sub-1", Permission.parse("worklog:close")), + new ServletWebRequest(new MockHttpServletRequest("POST", "/x"))); + + // then + assertThat(List.of(response.getStatusCode(), response.getBody().error().code())) + .containsExactly(HttpStatus.FORBIDDEN, "AUTHZ_INSUFFICIENT_PERMISSION"); + } + // feature-persistence-failure-baseline D1 + business-rule-validation C7/D9: a classified // persistence carrier sets the envelope from its DB_* code, but the client message is a fixed // category-derived safe string — the raw diagnostic (SQLState / constraint name) the translator diff --git a/src/adapter/inbound/websocket/AGENTS.md b/src/adapter/inbound/websocket/AGENTS.md index b8ea9bfb..8aa31af2 100644 --- a/src/adapter/inbound/websocket/AGENTS.md +++ b/src/adapter/inbound/websocket/AGENTS.md @@ -33,6 +33,9 @@ command는 그 유스케이스 안에서 애플리케이션 `IdempotencyExecutor - `@DomainEvent` 표지를 위한 `:domain-core` 등록 의존. - 저장소 BOM이 관리하는 Spring Boot WebSocket·validation starter. +- `spring-security-core` — security context와 인증 token 타입만(`SecurityContextHolder`·`SecurityContextHolderStrategy`·`SecurityContext`·`Authentication`· + `UsernamePasswordAuthenticationToken`). handshake가 인증한 사용자를 frame 처리 동안 `SecurityContext`에 둔다(`@RequiresPermission`이 + 읽는 곳, `WebSocketSecurityContextInterceptor`). `Authentication`이면 그대로, 그 밖의 `Principal`은 권한 없는 인증 token으로 둔다. - 시험에서만: 내장 Tomcat·Jetty·SockJS·STOMP 클라이언트와 Testcontainers(Nginx lane). ## 금지 @@ -94,6 +97,9 @@ WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에 ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은 `ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), `IllegalArgumentException`이면 `BAD_PARAMETER`, 그 밖에는 `WEBSOCKET_REQUEST_REJECTED`다. +- 플랫폼 거부는 거부마다 정한 사유·command만 담은 WARN 한 줄을 남긴다. client가 쓴 값(destination·header·SockJS + session id)은 남기지 않는다. SUBSCRIBE가 아닌 거부에 Spring `StompSubProtocolHandler`가 더 남기는 ERROR 줄은 session + id를 싣는다(README 「STOMP 채널」). ## 이벤트 projection 계약 diff --git a/src/adapter/inbound/websocket/README.md b/src/adapter/inbound/websocket/README.md index 4c9ef53f..750e956f 100644 --- a/src/adapter/inbound/websocket/README.md +++ b/src/adapter/inbound/websocket/README.md @@ -19,6 +19,21 @@ - `/ws`(설정 가능) SockJS endpoint, `/topic` simple broker, `/app` application prefix. - HTTP 계층이 이미 인증한 `Principal`이 있어야 handshake가 통과한다. 이 leaf는 자격 증명을 직접 해석하지 않는다. +- frame을 처리하는 동안(inbound 채널 executor thread) handshake의 사용자를 `SecurityContext`에 두고 끝나면 + 지운다(`WebSocketSecurityContextInterceptor`). web chain이 upgrade 요청을 인증했으면 그 사용자는 Spring Security + `Authentication`이라 그대로 두고, `@MessageMapping` 메서드가 부른 `@RequiresPermission` 유스케이스가 web 요청과 같은 + 호출자로 판정한다. 그 밖의 `Principal`은 권한 없는 인증 token으로 둔다(빈 context면 Spring이 판정 전에 거부해 분류되지 + 않은 실패가 된다). 권한이 없으면 `AUTHZ_INSUFFICIENT_PERMISSION` carrier가 되어 `StompHandlerFailureLog`가 4xx + carrier로 처리한다(frame도 로그도 없다). +- 플랫폼 거부(인증 없음, 허용하지 않은 destination, 두 번째 구독)는 거부마다 WARN 한 줄 + `STOMP frame refused: reason=<사유> command=`을 남긴다. 사유는 + `UNAUTHENTICATED`·`SUBSCRIBE_DESTINATION_NOT_ALLOWED`·`SUBSCRIPTION_ALREADY_HELD`·`SEND_DESTINATION_NOT_ALLOWED`다. + client가 쓴 값(destination, header, SockJS가 client URL에서 받은 session id)은 남기지 않는다. 거부는 frame을 받은 + thread의 `preSend`에서 일어나 request id도 아직 없다. SUBSCRIBE가 아닌 거부된 frame(SEND 등)에는 Spring + `StompSubProtocolHandler`가 ERROR 한 줄 `Failed to send message to MessageChannel in session :…`을 더 + 남긴다. 그 줄은 SockJS가 client URL에서 받은 session id를 싣는다(끝의 메시지는 고정 코드다). 같은 줄이 채널 포화 + 같은 서버 실패도 남기므로 그 logger를 끄지 않는다. session id를 남기지 않으려면 서비스가 로그 수집 단계에서 그 + logger의 줄을 가린다. - SUBSCRIBE는 설정된 broadcast destination 하나만, SEND는 `/app/**`만 허용한다. 클라이언트가 `/topic/**`으로 직접 보내는 것은 거부한다. - 세션 하나에 구독은 하나다. 같은 세션의 두 번째 SUBSCRIBE는 id가 달라도 ERROR 프레임으로 diff --git a/src/adapter/inbound/websocket/build.gradle b/src/adapter/inbound/websocket/build.gradle index ef455230..c9b01f72 100644 --- a/src/adapter/inbound/websocket/build.gradle +++ b/src/adapter/inbound/websocket/build.gradle @@ -26,6 +26,10 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-websocket' implementation 'org.springframework.boot:spring-boot-starter-validation' + // Security context and authentication token types only: the session's user is put on the + // context @RequiresPermission reads while a @MessageMapping method runs (an Authentication as it + // is, any other Principal as an authenticated token with no authorities). + implementation 'org.springframework.security:spring-security-core' } testing { diff --git a/src/adapter/inbound/websocket/gradle.lockfile b/src/adapter/inbound/websocket/gradle.lockfile index 6de8867d..a51e3a6a 100644 --- a/src/adapter/inbound/websocket/gradle.lockfile +++ b/src/adapter/inbound/websocket/gradle.lockfile @@ -185,6 +185,8 @@ org.springframework.boot:spring-boot-web-server:4.0.9=compileClasspath,jettyWebS org.springframework.boot:spring-boot-webmvc:4.0.9=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-websocket:4.0.9=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot:4.0.9=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.8=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.8=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-aop:7.0.10=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-beans:7.0.10=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-context:7.0.10=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java index 15abcbd5..01ae0b91 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java @@ -53,6 +53,8 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { new SafeStompSubProtocolErrorHandler(); private final WebSocketInboundAuthorizationInterceptor inboundAuthorization; private final WebSocketCorrelationInterceptor correlation = new WebSocketCorrelationInterceptor(); + private final WebSocketSecurityContextInterceptor securityContext = + new WebSocketSecurityContextInterceptor(); private final StompConnectionLimit connectionLimit; public WebSocketConfig(WebSocketSettings properties) { @@ -90,8 +92,11 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureClientInboundChannel(ChannelRegistration registration) { - // Correlation first, so an authorization refusal is logged with the frame's request id. - bounded(registration).interceptors(correlation, inboundAuthorization); + // The authorization refusal runs in preSend, on the thread that received the frame, before + // any correlation is on MDC. Correlation and the security context are put on in beforeHandle, + // on the executor thread that runs the handler, and taken off after it: correlation first, so + // a line the handler writes carries the frame's request id. + bounded(registration).interceptors(correlation, inboundAuthorization, securityContext); } @Override diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java index 7293605a..5c70d1ef 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java @@ -4,6 +4,8 @@ import java.security.Principal; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.simp.stomp.StompCommand; @@ -25,6 +27,9 @@ import org.springframework.messaging.support.MessageHeaderAccessor; */ final class WebSocketInboundAuthorizationInterceptor implements ChannelInterceptor { + private static final Logger log = + LoggerFactory.getLogger(WebSocketInboundAuthorizationInterceptor.class); + private static final String APPLICATION_PREFIX = "/app/"; private final WebSocketSettings properties; @@ -46,14 +51,14 @@ final class WebSocketInboundAuthorizationInterceptor implements ChannelIntercept StompCommand command = accessor.getCommand(); if (requiresAuthentication(command) && !hasAuthenticatedPrincipal(accessor.getUser())) { - throw new WebSocketPolicyViolationException(); + throw refused("UNAUTHENTICATED", command); } if (command == StompCommand.SUBSCRIBE && !properties.getBroadcastDestination().equals(accessor.getDestination())) { - throw new WebSocketPolicyViolationException(); + throw refused("SUBSCRIBE_DESTINATION_NOT_ALLOWED", command); } if (command == StompCommand.SUBSCRIBE && !holdSubscription(accessor)) { - throw new WebSocketPolicyViolationException(); + throw refused("SUBSCRIPTION_ALREADY_HELD", command); } String sessionId = accessor.getSessionId(); if (command == StompCommand.UNSUBSCRIBE && sessionId != null) { @@ -65,11 +70,24 @@ final class WebSocketInboundAuthorizationInterceptor implements ChannelIntercept String destination = accessor.getDestination(); if (command == StompCommand.SEND && (destination == null || !destination.startsWith(APPLICATION_PREFIX))) { - throw new WebSocketPolicyViolationException(); + throw refused("SEND_DESTINATION_NOT_ALLOWED", command); } return message; } + /** + * Logs a refusal and returns the signal the error handler turns into the fixed ERROR frame. + * + *

One WARN line per refusal, with a fixed reason and the command — nothing the client wrote: + * not the destination, not a header, and not the session id, which SockJS takes from the URL the + * client chose. A refusal used to leave no line of its own: Spring logs a refused SEND at ERROR + * from its protocol handler and a refused SUBSCRIBE not at all (review 2026-11-12). + */ + private static WebSocketPolicyViolationException refused(String reason, StompCommand command) { + log.warn("STOMP frame refused: reason={} command={}", reason, command); + return new WebSocketPolicyViolationException(); + } + /** * Gives the slot back when a SUBSCRIBE this interceptor admitted never reached the broker — a * full channel queue rejects it after {@code preSend} — so the client can subscribe again. diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSecurityContextInterceptor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSecurityContextInterceptor.java new file mode 100644 index 00000000..6412a1d8 --- /dev/null +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSecurityContextInterceptor.java @@ -0,0 +1,58 @@ +package dev.caskeleton.adapter.inbound.websocket.stomp; + +import java.security.Principal; +import java.util.List; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.MessageHandler; +import org.springframework.messaging.simp.SimpMessageHeaderAccessor; +import org.springframework.messaging.support.ExecutorChannelInterceptor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.context.SecurityContextHolderStrategy; + +/** + * Puts the session's authenticated user on the {@link SecurityContext} while a client frame is + * handled, on the inbound channel's executor thread, and takes it off afterwards. + * + *

That is the context {@code @RequiresPermission} reads, so a use case a {@code @MessageMapping} + * method calls judges the user the handshake authenticated. Frames used to be handled with an empty + * context, and every guarded use case was denied (review 2026-11-12). The user is the handshake's + * principal: a Spring Security {@link Authentication} when the web chain authenticated the upgrade + * request, put on as it is. Any other principal goes on as an authenticated token with no + * authorities, so a guarded use case refuses it with {@code AUTHZ_INSUFFICIENT_PERMISSION} rather + * than Spring refusing an empty context before the check runs. + */ +final class WebSocketSecurityContextInterceptor implements ExecutorChannelInterceptor { + + private final SecurityContextHolderStrategy strategy = + SecurityContextHolder.getContextHolderStrategy(); + + @Override + public Message beforeHandle( + Message message, MessageChannel channel, MessageHandler handler) { + Principal user = SimpMessageHeaderAccessor.getUser(message.getHeaders()); + if (user != null) { + SecurityContext context = strategy.createEmptyContext(); + context.setAuthentication(asAuthentication(user)); + strategy.setContext(context); + } + return message; + } + + private static Authentication asAuthentication(Principal user) { + return user instanceof Authentication authentication + ? authentication + : UsernamePasswordAuthenticationToken.authenticated(user, null, List.of()); + } + + @Override + public void afterMessageHandled( + Message message, MessageChannel channel, MessageHandler handler, Exception failure) { + // The executor's threads carry no context of their own; clearing leaves the next frame on this + // thread nothing to inherit. + strategy.clearContext(); + } +} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java index a4243e1a..b5899a56 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java @@ -1,12 +1,21 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import java.security.Principal; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.simp.stomp.StompCommand; @@ -58,6 +67,40 @@ class WebSocketInboundAuthorizationInterceptorTest { .hasMessageNotContaining("SECRET_SENTINEL"); } + @Test + @DisplayName("거부마다 정한 사유·command 만 담은 WARN 한 줄을 남기고 client 가 쓴 destination·session id 는 남기지 않는다") + void aRefusalLeavesOneWarnLineWithoutTheClientsDestination() { + // given + Message message = + message(StompCommand.SUBSCRIBE, "/topic/SECRET_SENTINEL", AUTHENTICATED); + + // when + List lines = refusalLines(message); + + // then + assertThat(lines) + .extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) + .containsExactly( + tuple( + Level.WARN, + "STOMP frame refused: reason=SUBSCRIBE_DESTINATION_NOT_ALLOWED command=SUBSCRIBE")); + } + + private List refusalLines(Message message) { + Logger logger = + (Logger) LoggerFactory.getLogger(WebSocketInboundAuthorizationInterceptor.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + assertThat(catchThrowable(() -> interceptor.preSend(message, channel))) + .isInstanceOf(WebSocketPolicyViolationException.class); + } finally { + logger.detachAppender(appender); + } + return appender.list; + } + @Test @DisplayName("같은 세션의 두 번째 SUBSCRIBE는 id가 달라도 거부된다") void aSecondSubscribeFromTheSameSessionIsRejected() { diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSecurityContextInterceptorTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSecurityContextInterceptorTest.java new file mode 100644 index 00000000..5e2ccc0e --- /dev/null +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSecurityContextInterceptorTest.java @@ -0,0 +1,92 @@ +package dev.caskeleton.adapter.inbound.websocket.stomp; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.security.Principal; +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.MessageHandler; +import org.springframework.messaging.simp.stomp.StompCommand; +import org.springframework.messaging.simp.stomp.StompHeaderAccessor; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +class WebSocketSecurityContextInterceptorTest { + + private final WebSocketSecurityContextInterceptor interceptor = + new WebSocketSecurityContextInterceptor(); + private final MessageChannel channel = mock(MessageChannel.class); + + @AfterEach + void clearContext() { + SecurityContextHolder.clearContext(); + } + + @Test + @DisplayName("handshake 가 인증한 사용자는 handler 가 도는 동안 SecurityContext 에 있고 끝나면 지워진다") + void theSessionsAuthenticationIsOnTheContextOnlyWhileTheFrameIsHandled() { + // given + Authentication user = new TestingAuthenticationToken("user-1", "n/a", "ROLE_USER"); + AtomicReference seen = new AtomicReference<>(); + MessageHandler handler = + message -> seen.set(SecurityContextHolder.getContext().getAuthentication()); + Message frame = send(user); + + // when + handleOnTheExecutor(frame, handler); + + // then + assertThat(Arrays.asList(seen.get(), SecurityContextHolder.getContext().getAuthentication())) + .containsExactly(user, null); + } + + @Test + @DisplayName("Authentication 이 아닌 사용자는 권한 없는 인증 token 으로 context 에 선다 — 빈 context 가 아니다") + void aPlainPrincipalIsOnTheContextAsAnAuthenticatedUserWithoutAuthorities() { + // given + AtomicReference seen = new AtomicReference<>(); + MessageHandler handler = + message -> seen.set(SecurityContextHolder.getContext().getAuthentication()); + Message frame = send(() -> "plain-principal"); + + // when + handleOnTheExecutor(frame, handler); + + // then + assertThat(seen.get()) + .extracting( + Authentication::getName, + Authentication::isAuthenticated, + authentication -> authentication.getAuthorities().isEmpty()) + .containsExactly("plain-principal", true, true); + } + + /** + * What the inbound channel's executor does with one frame: the interceptor around the handler. + */ + private void handleOnTheExecutor(Message frame, MessageHandler handler) { + Message intercepted = interceptor.beforeHandle(frame, channel, handler); + try { + handler.handleMessage(intercepted); + } finally { + interceptor.afterMessageHandled(frame, channel, handler, null); + } + } + + private static Message send(Principal user) { + StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); + accessor.setDestination("/app/commands"); + accessor.setSessionId("session-0"); + accessor.setUser(user); + accessor.setLeaveMutable(true); + return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()); + } +} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/MapProviderCallbackAdapterRegistry.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/MapProviderCallbackAdapterRegistry.java index bd180636..3fd5a4bc 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/MapProviderCallbackAdapterRegistry.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/MapProviderCallbackAdapterRegistry.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.callback; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import java.util.Map; import java.util.Objects; +import java.util.Optional; /** * Profile-to-adapter lookup over a map fixed at assembly time. @@ -15,12 +16,13 @@ import java.util.Objects; * composition root still decides the map's contents; what it no longer holds is the lookup, the * refusal and the limits. * - *

The other, which the move surfaced: {@link #require} runs per callback request, not - * at startup. While it lived in bootstrap it was briefly migrated to the startup-failure factory - * along with that leaf's genuine startup guards, which would have classified an unknown profile in - * an inbound request as a configuration error carrying a JVM exit code. Here the contract is the - * one the interface documents and every sibling {@code require(...)} registry in this repository - * uses. + *

The other, which the move surfaced: {@link #find} runs per callback request, not at + * startup. While it lived in bootstrap it was briefly migrated to the startup-failure factory along + * with that leaf's genuine startup guards, which would have classified an unknown profile in an + * inbound request as a configuration error carrying a JVM exit code. An unknown profile is not a + * server failure either: it used to be an {@code IllegalStateException}, which the web error + * handler answered as a 500 with an ERROR line and stack for any unauthenticated POST (review + * 2026-11-12). The lookup answers empty and the caller rejects the callback. * *

Refusing an unknown profile is a security property rather than a convenience: an endpoint that * accepted any profile name would let a caller choose which signature check runs. @@ -43,13 +45,9 @@ public final class MapProviderCallbackAdapterRegistry implements ProviderCallbac } @Override - public ProviderCallbackAdapter require(ProviderProfileId profileId) { + public Optional find(ProviderProfileId profileId) { Objects.requireNonNull(profileId, "profileId"); - ProviderCallbackAdapter adapter = byProfile.get(profileId); - if (adapter == null) { - throw new IllegalStateException("no callback adapter registered for the profile"); - } - return adapter; + return Optional.ofNullable(byProfile.get(profileId)); } @Override diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/ProviderCallbackAdapterRegistry.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/ProviderCallbackAdapterRegistry.java index 355ea31a..d46c887f 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/ProviderCallbackAdapterRegistry.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/ProviderCallbackAdapterRegistry.java @@ -1,13 +1,20 @@ package dev.caskeleton.adapter.outbound.notification.platform.callback; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import java.util.Optional; /** * Profile-to-provider callback verifier registry assembled by the outbound notification adapter. */ public interface ProviderCallbackAdapterRegistry { - ProviderCallbackAdapter require(ProviderProfileId profileId); + /** + * The adapter of a profile this deployment configured, or empty for any other profile. + * + *

The profile comes from an unauthenticated request path, so an unknown one is an ordinary + * rejection for the caller to answer, not a server failure. + */ + Optional find(ProviderProfileId profileId); CallbackLimits limitsFor(ProviderProfileId profileId); } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java index f1118c54..78091d13 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java @@ -313,7 +313,7 @@ class NotificationProviderAssemblyTest { new NotificationPlatformRegistriesConfig() .providerCallbackAdapterRegistry(platform, settings); - assertThat(registry.require(new ProviderProfileId("ses-events")).providerId()) + assertThat(registry.find(new ProviderProfileId("ses-events")).orElseThrow().providerId()) .isEqualTo(new ProviderId("ses")); } diff --git a/src/application/core/README.md b/src/application/core/README.md index 83132c58..d6001379 100644 --- a/src/application/core/README.md +++ b/src/application/core/README.md @@ -238,9 +238,10 @@ application/domain 을 프레임워크-free 로 유지하는 핵심 장치. - 인증된 호출자가 필요한 `Permission` 을 못 가졌을 때 `AuthorizationPort` 가 던진다. - **프레임워크-free, application 소유**: application 계층은 Spring Security 에 의존할 수 없어 - Spring `AccessDeniedException` 을 던질 수 없다. web adapter 의 method-security enforcement - point 가 경계에서 이 예외를 잡아 Spring authorization 실패로 번역하고, error pipeline 이 - `AUTHZ_INSUFFICIENT_PERMISSION` 403 으로 매핑한다(코드 SSOT 는 베이스라인 소유). + Spring `AccessDeniedException` 을 던질 수 없다. 대신 이 예외가 `ApiErrorCarrier`로 + `AUTHZ_INSUFFICIENT_PERMISSION`을 싣는다. web adapter 의 method-security enforcement point 는 이 예외를 + Spring 실패로 바꾸지 않고 그대로 내보낸다. 그래서 web(403)·gRPC(`PERMISSION_DENIED`)·GraphQL(`FORBIDDEN`)이 같은 + 코드로 답한다. STOMP `@MessageMapping` 안의 거부는 frame을 보내지 않고, 4xx carrier라 로그도 남기지 않는다. - **fail-closed**: denial 은 필요한 권한과 호출자 subject 만 담고, 호출자의 *유효 권한 집합* 은 절대 담지 않는다(인가 표면을 클라이언트에 노출하지 않기 위함). @@ -685,7 +686,7 @@ leaf의 코드 Javadoc과 `docs/notification/`이 정본이다. R1 오케스트 | `messaging.event.ValidatedIntegrationEvent` | 안정된 semantic identity와 바뀌지 않는 정확한 인코딩 바이트·hash. 뒤의 durable append 경계로 넘길 준비가 된 값이다. | | `messaging.event.IntegrationEventEncoderPort` | 프레임워크 없는 로컬 경계(초안 → 검증된 이벤트). outbound 어댑터가 구현한다(템플릿은 `adapter:outbound:support`의 `JsonIntegrationEventEncoder`). | | `outbox.OutboxAppendPort` | 유일한 outbox append: `ValidatedIntegrationEvent` 하나를 호출자의 쓰기 트랜잭션 안에서 넣는다. | -| `tenant.TenantId` | 테넌트 식별자와 그 유일한 문법(`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`). web과 GraphQL 전송 문맥이 모두 이 값을 싣는다. 전송 계층이 검증된 인증 데이터로만 만든다. | +| `tenant.TenantId` | 테넌트 식별자와 그 유일한 문법(`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`). web과 GraphQL 전송 문맥이 모두 이 값을 싣는다. 전송 계층이 검증된 인증 데이터로만 만든다. 전송 계층이 거절하는 tenant 입력 이름(`namesATenant`)도 여기 하나로 둔다. | ### 패키지 소유 (Package ownership) diff --git a/src/application/core/src/main/java/dev/caskeleton/application/security/AuthorizationDeniedException.java b/src/application/core/src/main/java/dev/caskeleton/application/security/AuthorizationDeniedException.java index 2652683c..dfb349f0 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/security/AuthorizationDeniedException.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/security/AuthorizationDeniedException.java @@ -1,15 +1,24 @@ package dev.caskeleton.application.security; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.security.Permission; /** * Raised by {@link AuthorizationPort} when an authenticated caller lacks a required {@link * Permission}. Framework-free and application-owned (the layer cannot throw Spring's {@code - * AccessDeniedException}); the web adapter translates it to a {@code AUTHZ_INSUFFICIENT_PERMISSION} - * 403. Fail-closed: it carries the required permission and subject for diagnostics, never the - * caller's effective permission set. See README. + * AccessDeniedException}). Fail-closed: it carries the required permission and subject for + * diagnostics, never the caller's effective permission set. See README. + * + *

It carries {@code AUTHZ_INSUFFICIENT_PERMISSION} itself, so a denial answers with that code: + * 403 on web, {@code PERMISSION_DENIED} on gRPC, {@code FORBIDDEN} on GraphQL. A STOMP {@code + * MessageMapping} method sends no frame either way; the denial is a client-side carrier, so it + * leaves no line. The method-security check lets it through instead of turning it into Spring's + * {@code AccessDeniedException}, which only the web adapter maps; the others answered that as an + * unclassified failure with an ERROR line (review 2026-11-12). */ -public class AuthorizationDeniedException extends RuntimeException { +public class AuthorizationDeniedException extends RuntimeException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -27,6 +36,11 @@ public class AuthorizationDeniedException extends RuntimeException { this.requiredPermission = requiredPermission; } + @Override + public ApiErrorCode errorCode() { + return OperationalError.AUTHZ_INSUFFICIENT_PERMISSION; + } + public Permission requiredPermission() { return requiredPermission; } diff --git a/src/application/core/src/main/java/dev/caskeleton/application/tenant/TenantId.java b/src/application/core/src/main/java/dev/caskeleton/application/tenant/TenantId.java index e4fdf772..29bbc2a0 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/tenant/TenantId.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/tenant/TenantId.java @@ -1,6 +1,10 @@ package dev.caskeleton.application.tenant; +import java.util.Collection; +import java.util.Locale; +import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.regex.Pattern; /** @@ -29,6 +33,9 @@ public record TenantId(String value) { private static final Pattern PATTERN = Pattern.compile(GRAMMAR); + /** {@link #namesATenant} names, folded: lower case, no {@code -} or {@code _}. */ + private static final Set TENANT_INPUT_NAMES = Set.of("tenant", "tenantid", "xtenantid"); + public TenantId { if (value == null || !PATTERN.matcher(value).matches()) { throw new IllegalArgumentException("tenant identifier must match " + GRAMMAR); @@ -45,6 +52,44 @@ public record TenantId(String value) { return value == null || value.isBlank() ? Optional.empty() : Optional.of(new TenantId(value)); } + /** + * Whether a request input name — a header, a query or form parameter, a GraphQL argument or + * variable — would carry a tenant if anybody believed it. + * + *

The one vocabulary every transport refuses: {@code tenant}, {@code tenant_id}, {@code + * tenantId}, {@code X-Tenant-Id} and their spellings, compared without case and without {@code -} + * and {@code _}. Web and GraphQL each kept a list — web lower-case names without {@code + * tenant_id}, GraphQL the caller's own names compared case-sensitively — so the same input was + * refused by one transport and passed by the other (review 2026-11-12). + * + * @param name the input's name; {@code null} names nothing + */ + public static boolean namesATenant(String name) { + return namesATenant(name, Set.of()); + } + + /** + * {@link #namesATenant(String)}, or one of a schema's own tenant names, compared the same way. + * + * @param name the input's name; {@code null} names nothing + * @param extraNames further names that denote a tenant where the caller works + */ + public static boolean namesATenant(String name, Collection extraNames) { + if (name == null) { + return false; + } + String folded = folded(name); + return TENANT_INPUT_NAMES.contains(folded) + || extraNames.stream() + .filter(Objects::nonNull) + .map(TenantId::folded) + .anyMatch(folded::equals); + } + + private static String folded(String name) { + return name.replace("-", "").replace("_", "").toLowerCase(Locale.ROOT); + } + @Override public String toString() { return value; diff --git a/src/application/core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java b/src/application/core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java index 2012adcf..fa2bcf4c 100644 --- a/src/application/core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java +++ b/src/application/core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java @@ -74,4 +74,26 @@ class TenantIdTest { .isInstanceOf(IllegalArgumentException.class) .hasMessage("tenant identifier must match " + TenantId.GRAMMAR); } + + @ParameterizedTest + @ValueSource( + strings = { + "tenant", + "tenant_id", + "tenant-id", + "tenantId", + "TenantId", + "X-Tenant-Id", + "x_tenant_id" + }) + @DisplayName("tenant 를 실을 입력 이름은 대소문자·'-'·'_' 와 상관없이 하나의 어휘로 알아본다") + void everySpellingOfATenantInputNameIsRecognised(String name) { + assertThat(TenantId.namesATenant(name)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"id", "tenancy", "owner", "x-request-id"}) + void otherInputNamesAreNotTenants(String name) { + assertThat(TenantId.namesATenant(name)).isFalse(); + } } diff --git a/src/bootstrap/app/gradle.lockfile b/src/bootstrap/app/gradle.lockfile index bf5a8111..2112b530 100644 --- a/src/bootstrap/app/gradle.lockfile +++ b/src/bootstrap/app/gradle.lockfile @@ -352,8 +352,8 @@ org.springframework.graphql:spring-graphql:2.0.6=architectureTestRuntimeClasspat org.springframework.integration:spring-integration-core:7.0.7=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath org.springframework.integration:spring-integration-jdbc:7.0.7=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath org.springframework.security:spring-security-config:7.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.security:spring-security-core:7.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.security:spring-security-crypto:7.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.security:spring-security-oauth2-client:7.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath org.springframework.security:spring-security-oauth2-core:7.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath org.springframework.security:spring-security-oauth2-jose:7.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath diff --git a/src/bootstrap/app/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java b/src/bootstrap/app/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java index bb78f9e3..8fea7483 100644 --- a/src/bootstrap/app/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java +++ b/src/bootstrap/app/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java @@ -26,8 +26,14 @@ import org.springframework.core.env.ConfigurableEnvironment; *

Scoped to the deployable artifact, which means contexts whose main class is {@link * dev.caskeleton.bootstrap.CaSkeletonApplication}. Slice tests boot minimal applications with no * environment profile and are not deployments; applying a deployment rule to them would have made - * this validator a tax on every test that does not care where it is running. The {@code test} - * profile is exempt for the same reason from the other direction. + * this validator a tax on every test that does not care where it is running. + * + *

The {@code test} profile is refused here. It used to be exempt, so {@code + * SPRING_PROFILES_ACTIVE=test} on the shipped jar started with every production check off: secret + * sentinels accepted, fileserver authorization unenforced, local persistence conveniences on + * (review 2026-11-12). No test boots this main class under {@code test} — Spring's test loader + * makes the test class the main class, and the shipped-composition system tests start it under + * {@code local} or {@code dev} — so the exemption only ever opened production. */ public class RuntimeEnvironmentProfileValidator implements EnvironmentPostProcessor, Ordered { @@ -48,7 +54,13 @@ public class RuntimeEnvironmentProfileValidator implements EnvironmentPostProces List active = profiles.activeProfiles(); if (profiles.isTestContext()) { - return; + throw StartupFailures.envValidation( + "SPRING_PROFILES_ACTIVE names the " + + RuntimeEnvironment.testProfileName() + + " profile, which is reserved for test-source contexts and never starts the shipped " + + "application: under it every production safety check is off. Set exactly one of " + + RuntimeEnvironment.deployableProfileNames() + + "."); } if (active.isEmpty()) { throw StartupFailures.envValidation( diff --git a/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidatorTest.java b/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidatorTest.java index a0da123c..80941829 100644 --- a/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidatorTest.java +++ b/src/bootstrap/app/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidatorTest.java @@ -2,9 +2,13 @@ package dev.caskeleton.bootstrap.runtime; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.SpringApplication; import org.springframework.mock.env.MockEnvironment; @@ -51,10 +55,18 @@ class RuntimeEnvironmentProfileValidatorTest { } } - @Test - @DisplayName("a test-source context may run under test") - void aTestContextIsExempt() { - validate("test"); + @ParameterizedTest + @ValueSource(strings = {"test", "prod,test", "TEST"}) + @DisplayName("배포 산출물은 test profile 로 뜨지 않는다 — 운영 검사가 모두 꺼지기 때문이다") + void theShippedApplicationRefusesTheTestProfile(String profiles) { + // when + Throwable failure = catchThrowable(() -> validate(profiles.split(","))); + + // then + assertThat(failure) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("reserved for test-source contexts") + .hasMessageContaining("[dev, local, prod]"); } @Test diff --git a/src/bootstrap/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java b/src/bootstrap/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java index 4aaf68a2..7f594912 100644 --- a/src/bootstrap/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java +++ b/src/bootstrap/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java @@ -48,6 +48,14 @@ final class ProviderCallbackIngressBridge implements ProviderCallbackIngress { public CallbackIngestionResult ingest(ProviderCallbackHttpRequest request) { Objects.requireNonNull(request, "request"); + // The profile comes from the unauthenticated path, so it is checked first: an unknown one is + // refused before any limit check could write the caller's string to the security audit log. + // No line either — any POST could otherwise fill the log at will (review 2026-11-12). + ProviderCallbackAdapter adapter = + adapters + .find(request.providerProfileId()) + .orElseThrow(() -> rejected(NotificationFailureCode.CALLBACK_PAYLOAD_REJECTED)); + CallbackLimits limits = adapters.limitsFor(request.providerProfileId()); if (request.bodyLength() > limits.maxBodyBytes()) { securityAudit.callbackRejectedByLimit(request.providerProfileId(), "BODY_TOO_LARGE"); @@ -58,7 +66,6 @@ final class ProviderCallbackIngressBridge implements ProviderCallbackIngress { throw rejected(NotificationFailureCode.CALLBACK_PAYLOAD_REJECTED); } - ProviderCallbackAdapter adapter = adapters.require(request.providerProfileId()); if (!adapter.providerId().equals(request.providerId())) { securityAudit.callbackRejectedByLimit( request.providerProfileId(), "PROVIDER_PROFILE_MISMATCH"); diff --git a/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java b/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java index fd6160b3..097581c6 100644 --- a/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java +++ b/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java @@ -24,6 +24,7 @@ import dev.caskeleton.application.notification.platform.api.NormalizedProviderEv import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.api.error.CallbackValidationException; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import dev.caskeleton.application.notification.platform.observation.NotificationSecurityAuditPort; import dev.caskeleton.application.notification.platform.port.in.IngestProviderCallbackCommand; import dev.caskeleton.application.notification.platform.port.in.IngestProviderCallbackUseCase; @@ -193,6 +194,36 @@ class ProviderCallbackIngressBridgeTest { .containsExactly(CallbackIngressUnavailableException.class, List.of(), List.of()); } + @Test + @DisplayName( + "설정하지 않은 profile 의 콜백은 크기·형식 검사 전에 CALLBACK_PAYLOAD_REJECTED 로 거절되고 감사 로그에 그 문자열을 남기지 않는다") + void aCallbackForAnUnconfiguredProfileIsRejectedFirstWithoutAuditingTheCallersString() { + // given + ProviderCallbackAdapterRegistry registry = + new MapProviderCallbackAdapterRegistry( + Map.of(), new CallbackLimits(4, Set.of("application/json"))); + RecordingAudit audit = new RecordingAudit(); + RecordingIngestion ingestion = new RecordingIngestion(); + ProviderCallbackIngressBridge bridge = + new ProviderCallbackIngressBridge(registry, ingestion, audit); + + // when + Throwable failure = + catchThrowable(() -> bridge.ingest(request("text/plain", "longer than four bytes"))); + + // then + assertThat( + List.of( + failure instanceof CallbackValidationException rejected + ? rejected.descriptor().code() + : String.valueOf(failure), + audit.limitReasons, + audit.signatureReasons, + ingestion.callbacks)) + .containsExactly( + NotificationFailureCode.CALLBACK_PAYLOAD_REJECTED, List.of(), List.of(), List.of()); + } + @Test void rawHttpLimitsAreEnforcedBeforeTheProviderAdapterRuns() { RecordingAdapter adapter = new RecordingAdapter(TWILIO, true); @@ -215,8 +246,8 @@ class ProviderCallbackIngressBridgeTest { ProviderCallbackAdapterRegistry registry = new ProviderCallbackAdapterRegistry() { @Override - public ProviderCallbackAdapter require(ProviderProfileId profileId) { - return adapter; + public Optional find(ProviderProfileId profileId) { + return Optional.of(adapter); } @Override -- 2.54.0 From 01caee3c015db1dc07c9183629ee16634843ec8e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 12:24:15 +0900 Subject: [PATCH 2/2] =?UTF-8?q?fix(graphql)!:=20cursor=C2=B7connection=20?= =?UTF-8?q?=EA=B1=B0=EB=B6=80=EC=99=80=20STOMP=20=EC=98=A4=EB=A5=98=20fram?= =?UTF-8?q?e=EC=9D=84=20=EB=93=B1=EB=A1=9D=EB=90=9C=20=EC=BD=94=EB=93=9C?= =?UTF-8?q?=EB=A1=9C=20=EB=8B=B5=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GraphQL cursor·connection 예외는 Javadoc이 「안정 요청 오류 코드」라면서 플랫폼 거부가 아니라 INTERNAL_ERROR와 ERROR 로그가 된다. STOMP ERROR frame은 code만 싣고, 원인 사슬 어디에 IllegalArgumentException이 있든 BAD_PARAMETER로 본다(다른 전송은 실패 자신만 본다). STOMP broadcast는 모든 인증 세션에 가는데 projector가 무엇을 실어도 되는지 규칙이 없다. maxInputListElements Javadoc은 실제보다 넓은 상한을 약속한다. - 두 예외를 GraphQlPlatformRejection으로 만들고 GRAPHQL_CURSOR_REJECTED· GRAPHQL_CONNECTION_REJECTED를 catalog에 더한다. - STOMP 오류 처리기는 MessagingException 포장을 벗긴 실패 자신만 IAE로 보고, 등록된 코드면 error-category·error-retryable header를 더한다(gRPC trailer와 같은 이름·값). - broadcast 규칙(모든 tenant의 인증 사용자가 읽어도 되는 것만)을 projector Javadoc·README·AGENTS에 적는다. 버린 안: destination을 tenant별로 나누기(projector가 tenant를 모르고, simple broker는 R1 증거라 범위 밖). - maxInputListElements Javadoc을 실제 검사 범위로 좁힌다. 위험: client가 보는 GraphQL 코드와 STOMP header가 바뀐다. docs/upgrade/2026-11-round9-authz.md 12~13행. 검증: desktop :adapter:inbound:graphql:check·systemTest, :adapter:inbound:websocket:check·systemTest rc=0(묶음 전체 실행). Refs: RR9-02-19, RR9-02-31, RR9-03-14, RR9-03-29 BREAKING CHANGE: GraphQL cursor·connection 거부 코드와 STOMP ERROR frame의 error-code(묻힌 IAE)·새 header. docs/upgrade/2026-11-round9-authz.md 12~13행. --- docs/upgrade/2026-11-round9-authz.md | 11 +++- src/adapter/inbound/graphql/AGENTS.md | 3 +- .../graphql/error/GraphQlErrorCode.java | 8 ++- .../GraphQlConnectionException.java | 23 +++++++- .../pagination/GraphQlCursorException.java | 22 ++++++- .../graphql/policy/GraphQlClientPolicy.java | 6 +- .../error/GraphQlErrorCodeCatalogTest.java | 11 +++- .../error/GraphQlWireErrorMapperTest.java | 11 +++- src/adapter/inbound/websocket/AGENTS.md | 8 ++- src/adapter/inbound/websocket/README.md | 12 +++- .../websocket/stomp/LiveEventProjector.java | 7 +++ .../stomp/LiveEventStompBroadcaster.java | 4 ++ .../SafeStompSubProtocolErrorHandler.java | 55 ++++++++++++------ .../SafeStompSubProtocolErrorHandlerTest.java | 57 +++++++++++++++++++ 14 files changed, 205 insertions(+), 33 deletions(-) diff --git a/docs/upgrade/2026-11-round9-authz.md b/docs/upgrade/2026-11-round9-authz.md index 8e6ad65c..7a7e6427 100644 --- a/docs/upgrade/2026-11-round9-authz.md +++ b/docs/upgrade/2026-11-round9-authz.md @@ -1,8 +1,9 @@ # 업그레이드 안내 — 2026-11 인증·인가와 GraphQL·WebSocket 계약 -- 범위: 2026-11-12 전체 리뷰의 인증·인가 묶음을 고친 변경. JWT 역할·claim 대응, JWKS 재조회 실패의 분류, 배포 - 산출물의 profile 검사, 알림 callback, GraphQL 인가·tenant, 전송별 권한 판정이 바뀌었다. -- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 RR9-02-02·16·17·18·20·23·25·28·29 +- 범위: 2026-11-12 전체 리뷰의 인증·인가 묶음과 GraphQL·WebSocket 계약 묶음을 고친 변경. JWT 역할·claim 대응, JWKS 재조회 실패의 분류, 배포 + 산출물의 profile 검사, 알림 callback, GraphQL 인가·tenant·오류 코드, 전송별 권한 판정, STOMP 오류 frame이 바뀌었다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 RR9-02-02·16·17·18·19·20·23·25·28·29·31, + RR9-03-14·29 ## 1. 누가 읽나 @@ -24,8 +25,12 @@ | 9 | tenant를 제안하는 입력 이름을 web-advanced와 GraphQL이 같은 어휘로 거부한다(`tenant`, `tenant_id`, `tenantId`, `X-Tenant-Id`, 대소문자·`-`·`_` 무관) | 그런 이름의 header·parameter·argument를 쓰던 client를 고친다 | 403 `TENANT_INPUT_UNTRUSTED`나 GraphQL tenant 거부가 난다 | tenant 입력 검사를 쓰는 서비스 | | 10 | `PATCH_PATH_FORBIDDEN`의 `details.refusedPaths`는 16개까지, `[A-Za-z0-9_.~/-]` 128자 이하 이름만 그대로 싣고 나머지는 ``다 | 그 칸을 화면에 그대로 보이던 client는 대체 문자열을 처리한다 | — | web-advanced patch | | 11 | 알림 callback: 설정하지 않은 profile로 온 callback은 400이다(전에는 500과 ERROR 로그). `ProviderCallbackAdapterRegistry.require`가 `find`(`Optional`)로 바뀌었다 | registry를 직접 구현한 서비스는 `find`를 구현한다 | 컴파일이 실패한다 | 알림 platform | +| 12 | GraphQL cursor·connection 거부가 `GRAPHQL_CURSOR_REJECTED`·`GRAPHQL_CONNECTION_REJECTED` 요청 오류다(전에는 `INTERNAL_ERROR`와 ERROR 로그) | client가 그 코드로 분기하게 한다 | — | GraphQL pagination API를 쓰는 서비스 | +| 13 | STOMP ERROR frame: 다른 실패의 원인으로 묻힌 `IllegalArgumentException`은 `BAD_PARAMETER`가 아니라 `WEBSOCKET_REQUEST_REJECTED`다. 모든 ERROR frame에 `error-retryable` header가 붙고, 등록된 코드면 `error-category`도 붙는다 | client가 새 header를 읽게 한다 | — | STOMP client | ## 3. 바뀌지 않은 것 - web의 403 응답(`AUTHZ_INSUFFICIENT_PERMISSION`), 401 응답 모양, `WWW-Authenticate`는 그대로다. - `@RequiresPermission`·역할 매핑 설정 키는 그대로다. +- STOMP broadcast는 여전히 destination 하나로 모든 인증된 세션에 간다. 그래서 `LiveEventProjector`는 모든 tenant의 인증된 + 사용자가 읽어도 되는 것만 싣는다(`src/adapter/inbound/websocket/README.md` 「한계」). 이 규칙을 이번에 문서로 적었다. diff --git a/src/adapter/inbound/graphql/AGENTS.md b/src/adapter/inbound/graphql/AGENTS.md index 3e101844..b4982bdb 100644 --- a/src/adapter/inbound/graphql/AGENTS.md +++ b/src/adapter/inbound/graphql/AGENTS.md @@ -70,7 +70,8 @@ required-class 검사가 이 테스트가 조용히 사라지는 것을 막는 - GraphQL이 가진 새 플랫폼 코드는 `GRAPHQL_` 접두어를 쓴다. 접두어 없는 기존 플랫폼 값은 얼려 둔 옛 wire 계약이고 `legacyUnprefixedPlatformCodes()`가 하나씩 적는다. - 모델만 있는 capability 코드는 그 capability가 출하하는 요청 경로에 닿기 전까지 `platformCodes()`에 - 더하지 않는다. + 더하지 않는다. 서비스 resolver가 부르는 라이브러리(`pagination/`의 cursor·connection)의 거부 코드는 더한다. resolver + 안에서 던져지면 그 요청의 오류로 wire에 닿기 때문이다. `GraphQlErrorCodeCatalogTest`가 출하하는 catalog 전체, 접두어 규칙, application·플랫폼 namespace 분리를 고정한다. diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCode.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCode.java index 49c8fa89..0a1d0441 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCode.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCode.java @@ -47,6 +47,10 @@ public record GraphQlErrorCode(String value) { /** A DataLoader key declared always resolvable had no row. */ public static final String GRAPHQL_BATCH_KEY_MISSING = "GRAPHQL_BATCH_KEY_MISSING"; + public static final String GRAPHQL_CURSOR_REJECTED = "GRAPHQL_CURSOR_REJECTED"; + + public static final String GRAPHQL_CONNECTION_REJECTED = "GRAPHQL_CONNECTION_REJECTED"; + private static final Set LEGACY_UNPREFIXED_PLATFORM_CODES = Set.of( INTERNAL_ERROR, @@ -69,7 +73,9 @@ public record GraphQlErrorCode(String value) { GRAPHQL_DOCUMENT_SHAPE_REJECTED, GRAPHQL_COMPLEXITY_EXCEEDED, GRAPHQL_OPERATION_NAME_REQUIRED, - GRAPHQL_BATCH_KEY_MISSING); + GRAPHQL_BATCH_KEY_MISSING, + GRAPHQL_CURSOR_REJECTED, + GRAPHQL_CONNECTION_REJECTED); private static final Pattern PATTERN = Pattern.compile("[A-Z][A-Z0-9_]{2,63}"); diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionException.java index 853486c8..db4c37f2 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionException.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionException.java @@ -1,11 +1,16 @@ package dev.caskeleton.adapter.inbound.graphql.pagination; +import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode; +import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection; +import dev.caskeleton.shared.error.Category; + /** * Raised when connection arguments are invalid or contradictory. * *

Carries the rule that was broken, never the cursor. */ -public class GraphQlConnectionException extends RuntimeException { +public class GraphQlConnectionException extends RuntimeException + implements GraphQlPlatformRejection { private static final long serialVersionUID = 1L; @@ -25,4 +30,20 @@ public class GraphQlConnectionException extends RuntimeException { public String code() { return CODE; } + + /** + * {@code GRAPHQL_CONNECTION_REJECTED} on the wire, as a request error: connection arguments the + * client sent is wrong, and retrying it unchanged fails the same way. A resolver that used the + * pagination API used to let it through as a masked {@code INTERNAL_ERROR} with an ERROR line, + * although this class named the code a stable request-error code (review 2026-11-12). + */ + @Override + public GraphQlErrorCode wireCode() { + return GraphQlErrorCode.platform(CODE); + } + + @Override + public Category failureCategory() { + return Category.VALIDATION; + } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlCursorException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlCursorException.java index 4614bed6..9d307675 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlCursorException.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlCursorException.java @@ -1,5 +1,9 @@ package dev.caskeleton.adapter.inbound.graphql.pagination; +import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode; +import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection; +import dev.caskeleton.shared.error.Category; + /** * Raised when a cursor is unusable: unknown version, unknown key, bad signature, or a different * query profile or filter than it was issued for. @@ -7,7 +11,7 @@ package dev.caskeleton.adapter.inbound.graphql.pagination; *

Every rejection carries the same shape of message and no cursor content, so a caller cannot * probe which part of a forged cursor was wrong. */ -public class GraphQlCursorException extends RuntimeException { +public class GraphQlCursorException extends RuntimeException implements GraphQlPlatformRejection { private static final long serialVersionUID = 1L; @@ -27,4 +31,20 @@ public class GraphQlCursorException extends RuntimeException { public String code() { return CODE; } + + /** + * {@code GRAPHQL_CURSOR_REJECTED} on the wire, as a request error: a cursor the client sent is + * wrong, and retrying it unchanged fails the same way. A resolver that used the pagination API + * used to let it through as a masked {@code INTERNAL_ERROR} with an ERROR line, although this + * class named the code a stable request-error code (review 2026-11-12). + */ + @Override + public GraphQlErrorCode wireCode() { + return GraphQlErrorCode.platform(CODE); + } + + @Override + public Category failureCategory() { + return Category.VALIDATION; + } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java index d00ea632..dd408363 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java @@ -21,7 +21,11 @@ import java.time.Duration; * @param maxAliases most accepted aliases, counted separately so an alias bomb cannot hide behind a * small depth * @param maxFragments most accepted fragment definitions - * @param maxInputListElements most accepted elements in one input list + * @param maxInputListElements most accepted elements in one JSON array, and keys in one JSON + * object, of the request's {@code variables} and {@code extensions} ({@code + * GraphQlJsonStructurePolicy}). A list written inline in the document is not counted against + * it; the document's size bounds it ({@code maxDocumentBytes}). This used to read "one input + * list", which an inline list is too (review 2026-11-12) * @param defaultPageSize page size used for cost when a connection omits {@code first}/{@code last} * @param maxPageSize largest accepted page size. This record only holds the two numbers; the page a * resolver serves is decided by {@code GraphQlConnectionPolicy.effectivePageSize} and the page diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCodeCatalogTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCodeCatalogTest.java index a9d3c1d4..ed5bae73 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCodeCatalogTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCodeCatalogTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitExcepti import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlAnonymousOperationException; +import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnectionException; import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException; import java.util.Set; import org.junit.jupiter.api.Test; @@ -28,7 +29,9 @@ class GraphQlErrorCodeCatalogTest { GraphQlErrorCode.GRAPHQL_DOCUMENT_SHAPE_REJECTED, GraphQlErrorCode.GRAPHQL_COMPLEXITY_EXCEEDED, GraphQlErrorCode.GRAPHQL_OPERATION_NAME_REQUIRED, - GraphQlErrorCode.GRAPHQL_BATCH_KEY_MISSING); + GraphQlErrorCode.GRAPHQL_BATCH_KEY_MISSING, + GraphQlErrorCode.GRAPHQL_CURSOR_REJECTED, + GraphQlErrorCode.GRAPHQL_CONNECTION_REJECTED); assertThat(GraphQlMissingKeyException.CODE) .isEqualTo(GraphQlErrorCode.GRAPHQL_BATCH_KEY_MISSING); @@ -38,6 +41,9 @@ class GraphQlErrorCodeCatalogTest { .isEqualTo(GraphQlErrorCode.GRAPHQL_COMPLEXITY_EXCEEDED); assertThat(GraphQlAnonymousOperationException.CODE) .isEqualTo(GraphQlErrorCode.GRAPHQL_OPERATION_NAME_REQUIRED); + assertThat(GraphQlCursorException.CODE).isEqualTo(GraphQlErrorCode.GRAPHQL_CURSOR_REJECTED); + assertThat(GraphQlConnectionException.CODE) + .isEqualTo(GraphQlErrorCode.GRAPHQL_CONNECTION_REJECTED); } @Test @@ -56,8 +62,7 @@ class GraphQlErrorCodeCatalogTest { // loader-level cause for logs, not a separate thing a client should branch on. @Test void modelledOnlyCapabilityCodesDoNotPretendToBeShippedWireCodes() { - assertThat(GraphQlErrorCode.platformCodes()) - .doesNotContain(GraphQlBatchTimeoutException.CODE, GraphQlCursorException.CODE); + assertThat(GraphQlErrorCode.platformCodes()).doesNotContain(GraphQlBatchTimeoutException.CODE); } @Test diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java index 7b6ea449..7426b248 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java @@ -9,6 +9,8 @@ import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException; +import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnectionException; +import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException; import dev.caskeleton.application.idempotency.IdempotencyInFlightException; import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; @@ -35,6 +37,12 @@ class GraphQlWireErrorMapperTest { new GraphQlBatchTimeoutException("customer-by-id"), "REQUEST_TIMEOUT", "TIMEOUT"), Arguments.of(new GraphQlRequestCancelledException(), "REQUEST_TIMEOUT", "TIMEOUT"), Arguments.of(new GraphQlMissingKeyException(), "GRAPHQL_BATCH_KEY_MISSING", "BUSINESS"), + Arguments.of( + new GraphQlCursorException("bad signature"), "GRAPHQL_CURSOR_REJECTED", "REQUEST"), + Arguments.of( + new GraphQlConnectionException("first and last together"), + "GRAPHQL_CONNECTION_REJECTED", + "REQUEST"), Arguments.of( new AuthorizationDeniedException("sub-1", Permission.parse("order:read")), "AUTHZ_INSUFFICIENT_PERMISSION", @@ -43,7 +51,8 @@ class GraphQlWireErrorMapperTest { @ParameterizedTest @MethodSource("failuresWithTheirOwnCode") - @DisplayName("요청·DataLoader 의 timeout·missing key, 권한 거부는 INTERNAL_ERROR 로 가려지지 않고 자기 code 로 나간다") + @DisplayName( + "요청·DataLoader 의 timeout·missing key, cursor·connection 거부, 권한 거부는 INTERNAL_ERROR 로 가려지지 않고 자기 code 로 나간다") void aFailureWithItsOwnCodeIsNotMaskedAsInternalError( RuntimeException failure, String expectedCode, String expectedCategory) { // given diff --git a/src/adapter/inbound/websocket/AGENTS.md b/src/adapter/inbound/websocket/AGENTS.md index 8aa31af2..e3ee0e06 100644 --- a/src/adapter/inbound/websocket/AGENTS.md +++ b/src/adapter/inbound/websocket/AGENTS.md @@ -95,8 +95,9 @@ WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에 - 클라이언트가 `/topic/**`나 다른 destination으로 보내는 `SEND`는 거절한다. - 클라이언트에게 보이는 처리 실패는 모두 빈 payload와 정해진 `message` `WEBSOCKET_REQUEST_REJECTED`를 가진 ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은 - `ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), `IllegalArgumentException`이면 `BAD_PARAMETER`, 그 - 밖에는 `WEBSOCKET_REQUEST_REJECTED`다. + `ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), 실패 자신(Spring `MessagingException` 포장 안)이 + `IllegalArgumentException`이면 `BAD_PARAMETER`, 그 밖에는 `WEBSOCKET_REQUEST_REJECTED`다. 등록된 코드는 + `error-category`·`error-retryable`도 싣는다. - 플랫폼 거부는 거부마다 정한 사유·command만 담은 WARN 한 줄을 남긴다. client가 쓴 값(destination·header·SockJS session id)은 남기지 않는다. SUBSCRIBE가 아닌 거부에 Spring `StompSubProtocolHandler`가 더 남기는 ERROR 줄은 session id를 싣는다(README 「STOMP 채널」). @@ -106,7 +107,8 @@ WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에 나중의 기능이 정확히 하나의 `@DomainEvent` 클래스에 대해 `LiveEventProjector` bean을 기여할 수 있다. broadcaster는 projector가 정확히 하나 맞을 때만 보낸다. projector가 없거나 둘 이상이거나, projection이 실패하거나, 이벤트 타입이 잘못됐거나, 필드가 null이거나, map이 한계를 넘으면 버린다. wire envelope에는 -`type`, 한계 있는 문자열 `fields`, `occurredAt`만 있다. broker 채널은 자기 한계 있는 executor를 가지므로, +`type`, 한계 있는 문자열 `fields`, `occurredAt`만 있다. 이벤트는 구독한 인증된 세션 모두에게 tenant·소유자 +구분 없이 간다. 그래서 projector는 모든 tenant의 인증된 사용자 누구나 읽어도 되는 것만 싣는다(근거 README 「한계」). broker 채널은 자기 한계 있는 executor를 가지므로, simple broker가 구독자에게 퍼뜨리는 일은 도메인 이벤트를 발행한 스레드에서 돌지 않는다. broker queue가 차면 이벤트를 버린다(best-effort, R1). diff --git a/src/adapter/inbound/websocket/README.md b/src/adapter/inbound/websocket/README.md index 750e956f..40ad72d7 100644 --- a/src/adapter/inbound/websocket/README.md +++ b/src/adapter/inbound/websocket/README.md @@ -47,8 +47,11 @@ 클라이언트가 물러났다가(가능하면 다른 노드로) 다시 붙게 한다. - handler 메서드가 돌기 전의 처리 실패(inbound interceptor의 거부 등)는 빈 본문의 ERROR 프레임이 되고 `message` 헤더는 고정값 `WEBSOCKET_REQUEST_REJECTED`다. `error-code` 헤더는 원인 사슬에 - `ApiErrorCarrier`가 있으면 첫 carrier의 코드(`IllegalArgumentException` 뒤에 있어도), - `IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는 `WEBSOCKET_REQUEST_REJECTED`다. + `ApiErrorCarrier`가 있으면 첫 carrier의 코드(`IllegalArgumentException` 뒤에 있어도), 실패 자신(Spring + `MessagingException` 포장을 벗긴 것)이 `IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는 + `WEBSOCKET_REQUEST_REJECTED`다. 다른 실패의 원인으로 묻힌 `IllegalArgumentException`은 web·GraphQL·gRPC처럼 + `BAD_PARAMETER`로 보지 않는다. 등록된 코드면 `error-category`·`error-retryable` 헤더도 싣는다(gRPC trailer와 + 같은 이름·값). `WEBSOCKET_REQUEST_REJECTED`는 등록된 코드가 아니라 `error-retryable: false`만 싣는다. - `@MessageMapping` 메서드의 실패는 inbound 채널 executor에서 끝나서 프레임이 나가지 않는다. 서버 로그는 `StompHandlerFailureLog`가 web·GraphQL·gRPC와 같은 줄로 남긴다(`ServerFailureLog`): persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. 다른 예외로 감싼 carrier도 원인 사슬의 @@ -116,6 +119,11 @@ simple broker는 한 프로세스 안의 best-effort 전달이다. 영속·트 - **principal별 연결 상한 없음.** 상한은 노드 단위다. 인증된 사용자 한 명(또는 탈취된 토큰)이 한 노드의 자리를 모두 차지할 수 있다. principal별 상한은 모든 노드가 공유하는 카운터(Redis 등)가 필요해 이 leaf 범위를 넘는다. 필요하면 서비스가 프록시나 공유 카운터로 막는다. +- **broadcast 대상을 좁히지 않는다.** 모든 이벤트가 broadcast destination 하나로 가고, 그 destination을 + 구독한 인증된 세션 모두가 받는다. tenant·소유자 판정은 없다. 그래서 `LiveEventProjector`는 모든 tenant의 + 인증된 사용자 누구나 읽어도 되는 것만 싣는다 — 「무엇이 바뀌었다」는 표지(`type`과 공개 id)를 보내고, 내용은 + 클라이언트가 권한 검사를 거치는 조회로 다시 읽는다. tenant·소유자 범위의 데이터는 이 채널에 싣지 않는다. + 사용자·tenant별 destination이 필요하면 구독 인가와 함께 따로 설계한다. - **연결 수명 동안 토큰을 다시 확인하지 않는다.** 인증은 handshake 한 번이다. 토큰이 만료되거나 폐기돼도 열린 연결은 유지된다. 연결 수명은 프록시 read timeout이나 서비스의 세션 정책으로 끊는다. diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventProjector.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventProjector.java index 258b6c15..116b5ebc 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventProjector.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventProjector.java @@ -4,6 +4,13 @@ import java.util.Map; /** * Explicitly allowlists one domain-event type and maps it to a client-safe primitive projection. + * + *

The projection goes to one shared destination that every authenticated session may subscribe + * to, whatever its tenant or owner: the broadcaster has no audience, and nothing narrows who + * receives an event. So a projector emits only what every authenticated user of every tenant may + * read — a change marker such as {@code {"type": "order.changed"}} that makes the client re-read + * through an authorized query, not the order's contents. Tenant- or owner-scoped data does not + * belong on this channel (review 2026-11-12: the rule was not written anywhere). */ public interface LiveEventProjector { diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java index 96a0da28..34beda05 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java @@ -27,6 +27,10 @@ import org.springframework.messaging.simp.SimpMessagingTemplate; * *

The adapter never serializes a domain object. Feature modules must contribute exactly one * explicit {@link LiveEventProjector} for an event type; otherwise the event is dropped. + * + *

Every event goes to the one broadcast destination, to every authenticated session subscribed + * to it — no tenant or owner check happens here. What a projector may emit is therefore limited to + * what any authenticated user may read ({@link LiveEventProjector}). */ public final class LiveEventStompBroadcaster { diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandler.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandler.java index 017bb745..a58b3dcc 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandler.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandler.java @@ -1,9 +1,11 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; import java.util.Optional; import org.springframework.messaging.Message; +import org.springframework.messaging.MessagingException; import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.support.MessageBuilder; @@ -17,8 +19,15 @@ import org.springframework.web.socket.messaging.StompSubProtocolErrorHandler; * failure: an {@link ApiErrorCarrier} anywhere in the cause chain (Spring wraps a failure raised * while the frame is processed in a {@code MessagingException}) reports its own code — the first * one, found as every transport finds it ({@link ApiErrorCarrier#firstIn}), even behind an {@link - * IllegalArgumentException} — then an {@link IllegalArgumentException} reports {@code - * BAD_PARAMETER}, and everything else stays {@link #SAFE_ERROR_CODE}. + * IllegalArgumentException} — then the failure itself being an {@link IllegalArgumentException} + * reports {@code BAD_PARAMETER}, and everything else stays {@link #SAFE_ERROR_CODE}. "Itself" is + * the first cause that is not Spring's {@code MessagingException} wrapper: an argument refusal + * deeper in the chain is a cause of some other failure, and web, GraphQL and gRPC do not answer + * that as {@code BAD_PARAMETER} either (review 2026-11-12). + * + *

A registered code also carries {@code error-category} and {@code error-retryable}, the same + * values as the gRPC trailers of those names and the web Envelope. {@link #SAFE_ERROR_CODE} is not + * a registered code and carries only {@code error-retryable: false}. * *

What reaches it is what fails before a handler method runs — an inbound interceptor's refusal, * on the thread that received the frame. A {@code @MessageMapping} method runs on the inbound @@ -32,6 +41,10 @@ final class SafeStompSubProtocolErrorHandler extends StompSubProtocolErrorHandle /** Bounds the cause walk: a cause chain can loop. */ private static final int MAX_CAUSE_DEPTH = 16; + static final String CODE_HEADER = "error-code"; + static final String CATEGORY_HEADER = "error-category"; + static final String RETRYABLE_HEADER = "error-retryable"; + @Override public Message handleClientMessageProcessingError( Message clientMessage, Throwable ex) { @@ -40,29 +53,39 @@ final class SafeStompSubProtocolErrorHandler extends StompSubProtocolErrorHandle @Override public Message handleErrorMessageToClient(Message errorMessage) { - return safeError(SAFE_ERROR_CODE); + return safeError(Optional.empty()); } - private static String errorCodeOf(Throwable failure) { + private static Optional errorCodeOf(Throwable failure) { Optional carrier = ApiErrorCarrier.firstIn(failure); if (carrier.isPresent()) { - return ((ApiErrorCarrier) carrier.get()).errorCode().code(); + return Optional.of(((ApiErrorCarrier) carrier.get()).errorCode()); } - int depth = 0; - for (Throwable cause = failure; - cause != null && depth++ < MAX_CAUSE_DEPTH; - cause = cause.getCause()) { - if (cause instanceof IllegalArgumentException) { - return OperationalError.BAD_PARAMETER.code(); - } - } - return SAFE_ERROR_CODE; + return unwrapped(failure) instanceof IllegalArgumentException + ? Optional.of(OperationalError.BAD_PARAMETER) + : Optional.empty(); } - private static Message safeError(String errorCode) { + /** The failure behind Spring's {@code MessagingException} wrappers. */ + private static Throwable unwrapped(Throwable failure) { + Throwable current = failure; + int depth = 0; + while (current instanceof MessagingException + && current.getCause() != null + && depth++ < MAX_CAUSE_DEPTH) { + current = current.getCause(); + } + return current; + } + + private static Message safeError(Optional code) { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR); accessor.setMessage(SAFE_ERROR_CODE); - accessor.setNativeHeader("error-code", errorCode); + accessor.setNativeHeader(CODE_HEADER, code.map(ApiErrorCode::code).orElse(SAFE_ERROR_CODE)); + code.ifPresent( + registered -> accessor.setNativeHeader(CATEGORY_HEADER, registered.category().name())); + accessor.setNativeHeader( + RETRYABLE_HEADER, Boolean.toString(code.map(ApiErrorCode::retryable).orElse(false))); accessor.setLeaveMutable(true); return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()); } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandlerTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandlerTest.java index 2c180d1c..d5a5e48a 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandlerTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandlerTest.java @@ -4,7 +4,9 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.shared.error.MappingException; +import dev.caskeleton.shared.error.OperationalError; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; @@ -74,4 +76,59 @@ class SafeStompSubProtocolErrorHandlerTest { assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code")) .isEqualTo("BAD_PARAMETER"); } + + @Test + @DisplayName("다른 실패의 원인으로 묻힌 IllegalArgumentException 은 BAD_PARAMETER 가 아니다(다른 전송과 같다)") + void anIllegalArgumentBuriedUnderAnotherFailureIsNotBadParameter() { + // given + Throwable failure = + new MessagingException( + "SECRET_SENTINEL", + new IllegalStateException("SECRET_SENTINEL", new IllegalArgumentException("x"))); + + // when + Message result = handler.handleClientMessageProcessingError(null, failure); + + // then + assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code")) + .isEqualTo(SafeStompSubProtocolErrorHandler.SAFE_ERROR_CODE); + } + + @Test + @DisplayName("등록된 코드는 gRPC trailer·web Envelope 와 같은 category·retryable 을 함께 싣는다") + void aRegisteredCodeCarriesItsCategoryAndRetryable() { + // given + Throwable failure = + new MessagingException("SECRET_SENTINEL", new MappingException("SECRET_SENTINEL")); + + // when + Message result = handler.handleClientMessageProcessingError(null, failure); + + // then + StompHeaderAccessor accessor = StompHeaderAccessor.wrap(result); + assertThat( + List.of( + accessor.getFirstNativeHeader("error-code"), + accessor.getFirstNativeHeader("error-category"), + accessor.getFirstNativeHeader("error-retryable"))) + .containsExactly( + "MAPPING_FAILED", + OperationalError.MAPPING_FAILED.category().name(), + Boolean.toString(OperationalError.MAPPING_FAILED.retryable())); + } + + @Test + @DisplayName("Spring 이 감싼 IllegalArgumentException(interceptor 의 인자 거부)은 BAD_PARAMETER 다") + void anIllegalArgumentWrappedByTheChannelIsBadParameter() { + // given + Throwable failure = + new MessagingException("SECRET_SENTINEL", new IllegalArgumentException("SECRET_SENTINEL")); + + // when + Message result = handler.handleClientMessageProcessingError(null, failure); + + // then + assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code")) + .isEqualTo("BAD_PARAMETER"); + } } -- 2.54.0