fix(security)!: 모든 전송이 같은 호출자로 권한을 판정하고 JWT·tenant 빈틈을 막는다
@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: <HTTP 오류>") 때문에 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행.
This commit is contained in:
@@ -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", "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": "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": "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"}
|
||||||
|
|||||||
@@ -10,7 +10,8 @@
|
|||||||
요청 ─▶ 인증 필터(JWT 또는 세션) ─▶ AuthenticatedPrincipal(roles, tenant)
|
요청 ─▶ 인증 필터(JWT 또는 세션) ─▶ AuthenticatedPrincipal(roles, tenant)
|
||||||
─▶ 컨트롤러 ─▶ [프록시] RequiresPermissionAuthorizationManager
|
─▶ 컨트롤러 ─▶ [프록시] RequiresPermissionAuthorizationManager
|
||||||
│ role → permission (app.authz.role-permissions)
|
│ role → permission (app.authz.role-permissions)
|
||||||
│ 없으면 403, 인증 없으면 401
|
│ 없으면 403(AUTHZ_INSUFFICIENT_PERMISSION). 인증 없는 요청은
|
||||||
|
│ 보통 인증 필터가 먼저 401로 끊고, 공개 경로라 여기 오면 403
|
||||||
─▶ 유스케이스 본문 ─▶ 객체 로드 ─▶ 소유자·tenant 판정 ─▶ 남의 것이면 404(존재 숨김)
|
─▶ 유스케이스 본문 ─▶ 객체 로드 ─▶ 소유자·tenant 판정 ─▶ 남의 것이면 404(존재 숨김)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ category: AUTH
|
|||||||
error_codes: [AUTH_CLAIM_MAPPING_FAILED]
|
error_codes: [AUTH_CLAIM_MAPPING_FAILED]
|
||||||
severity: P2
|
severity: P2
|
||||||
owner: oncall
|
owner: oncall
|
||||||
last_updated: 2026-06-15
|
last_updated: 2026-11-13
|
||||||
status: 초안
|
status: 초안
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -12,22 +12,32 @@ status: 초안
|
|||||||
|
|
||||||
## 증상
|
## 증상
|
||||||
|
|
||||||
- HTTP 401, `error.code=AUTH_CLAIM_MAPPING_FAILED`.
|
- HTTP 401, `error.code=AUTH_CLAIM_MAPPING_FAILED`, `WWW-Authenticate: Bearer error="invalid_token"`.
|
||||||
- 토큰 검증은 통과했지만 필요한 클레임(sub, roles, tenant)이 없거나 타입이 다르다.
|
- 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.<client>.roles`. 따로 고칠 claim 대응 설정은 없다.
|
||||||
|
|
||||||
## 조치
|
## 조치
|
||||||
|
|
||||||
- IdP 토큰 템플릿에 필요한 클레임이 들어 있는지 확인한다.
|
- IdP token 템플릿이 `sub`를 넣는지, `tenant_id`를 넣는다면 문법에 맞는 값인지 고친다.
|
||||||
- IdP 스키마가 바뀌었으면 클레임 매핑 설정을 고친다.
|
- IdP가 tenant를 다른 claim에 둔다면 IdP 쪽 mapper로 `tenant_id`에 옮긴다.
|
||||||
|
|
||||||
## 에스컬레이션
|
## 에스컬레이션
|
||||||
|
|
||||||
- IdP가 클레임 스키마를 바꿨으면 인증 플랫폼 팀에 넘긴다.
|
- IdP가 claim 스키마를 바꿨으면 인증 플랫폼 팀에 넘긴다.
|
||||||
|
|
||||||
|
> 이력: 2026-11-12 리뷰 전에는 `sub` 없는 token이 통과해 뒤에서 500이 됐고, 틀린 tenant claim은
|
||||||
|
> `AUTH_TOKEN_MALFORMED`였다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -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.<client>.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자 이하 이름만 그대로 싣고 나머지는 `<not echoed>`다 | 그 칸을 화면에 그대로 보이던 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`·역할 매핑 설정 키는 그대로다.
|
||||||
@@ -168,6 +168,17 @@ composition root 는 이 leaf 를 채택할 때 인증/인가 및 CORS 정책을
|
|||||||
`spring.graphql.graphiql.enabled=false`,
|
`spring.graphql.graphiql.enabled=false`,
|
||||||
`spring.graphql.schema.introspection.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 실행 플랫폼 — 설계 결정의 근거
|
# GraphQL API 실행 플랫폼 — 설계 결정의 근거
|
||||||
|
|||||||
+4
-3
@@ -36,9 +36,10 @@ public class GraphQlPlatformAutoConfiguration {
|
|||||||
/**
|
/**
|
||||||
* Tenant applied to a caller with no verified credential.
|
* Tenant applied to a caller with no verified credential.
|
||||||
*
|
*
|
||||||
* <p>Declared as {@link TenantContext#system} rather than as a credential-derived tenant, because
|
* <p>Declared as {@link TenantContext#anonymous} rather than as a credential-derived tenant,
|
||||||
* that is what it is: no credential was verified, so no tenant was proven. An adopter serving
|
* because that is what it is: no credential was verified, so no tenant was proven. An adopter
|
||||||
* more than one tenant supplies a principal resolver, and the anonymous path then never runs.
|
* serving more than one tenant supplies a principal resolver, and the anonymous path then never
|
||||||
|
* runs.
|
||||||
*/
|
*/
|
||||||
public static final String DEFAULT_ANONYMOUS_TENANT = "public";
|
public static final String DEFAULT_ANONYMOUS_TENANT = "public";
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -125,7 +125,7 @@ class GraphQlRequestContextConfiguration {
|
|||||||
structurePolicy,
|
structurePolicy,
|
||||||
extensionsPolicy,
|
extensionsPolicy,
|
||||||
new GraphQlClientProfile(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_PROFILE),
|
new GraphQlClientProfile(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_PROFILE),
|
||||||
TenantContext.system(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT),
|
TenantContext.anonymous(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT),
|
||||||
properties.production(),
|
properties.production(),
|
||||||
graphQlPlatformClock,
|
graphQlPlatformClock,
|
||||||
errors);
|
errors);
|
||||||
|
|||||||
+13
-1
@@ -23,7 +23,14 @@ public record TenantContext(String value, TenantSource source) {
|
|||||||
/** A server-side session established by a prior authentication. */
|
/** A server-side session established by a prior authentication. */
|
||||||
TRUSTED_SESSION,
|
TRUSTED_SESSION,
|
||||||
/** An internal, non-request-scoped platform task. */
|
/** 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 {
|
public TenantContext {
|
||||||
@@ -51,6 +58,11 @@ public record TenantContext(String value, TenantSource source) {
|
|||||||
return new TenantContext(value, TenantSource.TRUSTED_SESSION);
|
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. */
|
/** Tenant for an internal platform task that runs outside a client request. */
|
||||||
public static TenantContext system(String value) {
|
public static TenantContext system(String value) {
|
||||||
return new TenantContext(value, TenantSource.SYSTEM);
|
return new TenantContext(value, TenantSource.SYSTEM);
|
||||||
|
|||||||
+194
-33
@@ -13,8 +13,15 @@ import graphql.language.InlineFragment;
|
|||||||
import graphql.language.OperationDefinition;
|
import graphql.language.OperationDefinition;
|
||||||
import graphql.language.Selection;
|
import graphql.language.Selection;
|
||||||
import graphql.language.SelectionSet;
|
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.GraphQLObjectType;
|
||||||
import graphql.schema.GraphQLSchema;
|
import graphql.schema.GraphQLSchema;
|
||||||
|
import graphql.schema.GraphQLTypeUtil;
|
||||||
|
import graphql.schema.GraphQLUnionType;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.LinkedHashSet;
|
import java.util.LinkedHashSet;
|
||||||
@@ -23,7 +30,12 @@ import java.util.Objects;
|
|||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Authorizes the operation and its root coordinates, before any resolver runs.
|
* Authorizes the operation's coordinates, before any resolver runs.
|
||||||
|
*
|
||||||
|
* <p>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).
|
||||||
*
|
*
|
||||||
* <p>Running before execution is the whole point: a mutation denied halfway through has already
|
* <p>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
|
* 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(
|
analyzer.verifyIntrospection(
|
||||||
context.requireDocument(), operation, policy.introspectionAllowed());
|
context.requireDocument(), operation, policy.introspectionAllowed());
|
||||||
|
|
||||||
String rootTypeName = rootTypeName(context.schema(), operation);
|
GraphQLObjectType root = rootType(context.schema(), operation);
|
||||||
for (String fieldName : rootFieldNames(context, operation, analyzer.maximumVisitedNodes())) {
|
CoordinateWalk walk = coordinates(context, root, analyzer.maximumVisitedNodes());
|
||||||
authorization.authorize(
|
for (GraphQlSchemaCoordinate rootCoordinate : walk.roots) {
|
||||||
context.requestContext(), new GraphQlSchemaCoordinate(rootTypeName, fieldName));
|
authorization.authorize(context.requestContext(), rootCoordinate);
|
||||||
|
}
|
||||||
|
for (GraphQlSchemaCoordinate nestedCoordinate : walk.nested) {
|
||||||
|
authorization.authorizeNested(context.requestContext(), nestedCoordinate);
|
||||||
}
|
}
|
||||||
return context;
|
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
|
* @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
|
* 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 =
|
OperationDefinition.Operation kind =
|
||||||
operation.getOperation() == null
|
operation.getOperation() == null
|
||||||
? OperationDefinition.Operation.QUERY
|
? OperationDefinition.Operation.QUERY
|
||||||
@@ -101,24 +116,39 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti
|
|||||||
if (root == null) {
|
if (root == null) {
|
||||||
throw new IllegalStateException("the schema declares no root type for " + kind);
|
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.
|
||||||
*
|
*
|
||||||
* <p>Fragments are expanded rather than skipped: a root field reached only through a named
|
* <p>Fragments are expanded rather than skipped: a field reached only through a named fragment is
|
||||||
* fragment is executed exactly like one written inline, so authorizing only the inline ones would
|
* executed exactly like one written inline, so authorizing only the inline ones would make {@code
|
||||||
* make {@code query { ...Hidden }} a bypass.
|
* query { ...Hidden }} a bypass.
|
||||||
*
|
*
|
||||||
* <p>Each fragment is expanded once per walk. The result is a set, and a fragment contributes the
|
* <p>The walk carries the object types the current selections can run on, not only the type they
|
||||||
* same root names wherever it is spread, so a second expansion adds nothing — while re-walking
|
* are written against. That set decides the coordinates. A selection that can run on a root type
|
||||||
* every spread lets a 1.6 KB document of nested double spreads cost 2^40 visits before the cost
|
* is a root coordinate of that type, deny-by-default included, wherever it sits: {@code query {
|
||||||
* stage ever sees it. The same set cuts fragment cycles. The analyzer's traversal budget stays as
|
* ... on Node { secret } }} is {@code Query.secret}, and so is {@code node(id:) { ... on Query {
|
||||||
* a backstop and rejects exactly as the cost stage does.
|
* 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.
|
||||||
|
*
|
||||||
|
* <p>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<String> rootFieldNames(
|
private static CoordinateWalk coordinates(
|
||||||
GraphQlExecutionContext context, OperationDefinition operation, int maximumVisitedNodes) {
|
GraphQlExecutionContext context, GraphQLObjectType root, int maximumVisitedNodes) {
|
||||||
|
|
||||||
Map<String, FragmentDefinition> fragments = new LinkedHashMap<>();
|
Map<String, FragmentDefinition> fragments = new LinkedHashMap<>();
|
||||||
context
|
context
|
||||||
@@ -131,48 +161,179 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
RootFieldWalk walk = new RootFieldWalk(fragments, maximumVisitedNodes);
|
CoordinateWalk walk =
|
||||||
walk.collect(operation.getSelectionSet());
|
new CoordinateWalk(context.schema(), root, fragments, maximumVisitedNodes);
|
||||||
return walk.names;
|
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<String, FragmentDefinition> fragments;
|
private final Map<String, FragmentDefinition> fragments;
|
||||||
private final int maximumVisitedNodes;
|
private final int maximumVisitedNodes;
|
||||||
private final Set<String> expanded = new HashSet<>();
|
private final Set<String> expanded = new HashSet<>();
|
||||||
private final Set<String> names = new LinkedHashSet<>();
|
private final Set<String> decided = new HashSet<>();
|
||||||
|
private final Set<GraphQLObjectType> rootTypes = new HashSet<>();
|
||||||
|
private final Set<GraphQlSchemaCoordinate> roots = new LinkedHashSet<>();
|
||||||
|
private final Set<GraphQlSchemaCoordinate> nested = new LinkedHashSet<>();
|
||||||
private int visited;
|
private int visited;
|
||||||
|
|
||||||
RootFieldWalk(Map<String, FragmentDefinition> fragments, int maximumVisitedNodes) {
|
CoordinateWalk(
|
||||||
|
GraphQLSchema schema,
|
||||||
|
GraphQLObjectType root,
|
||||||
|
Map<String, FragmentDefinition> fragments,
|
||||||
|
int maximumVisitedNodes) {
|
||||||
|
this.schema = schema;
|
||||||
this.fragments = fragments;
|
this.fragments = fragments;
|
||||||
this.maximumVisitedNodes = maximumVisitedNodes;
|
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<GraphQLObjectType> possible) {
|
||||||
if (selectionSet == null) {
|
if (selectionSet == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
String possibleSignature = signature(possible);
|
||||||
for (Selection<?> selection : selectionSet.getSelections()) {
|
for (Selection<?> selection : selectionSet.getSelections()) {
|
||||||
if (++visited > maximumVisitedNodes) {
|
if (++visited > maximumVisitedNodes) {
|
||||||
throw GraphQlStructuralLimitException.of(
|
throw GraphQlStructuralLimitException.of(
|
||||||
"DOCUMENT_TRAVERSAL", visited, maximumVisitedNodes);
|
"DOCUMENT_TRAVERSAL", visited, maximumVisitedNodes);
|
||||||
}
|
}
|
||||||
if (selection instanceof Field field) {
|
if (selection instanceof Field field) {
|
||||||
if (!field
|
field(field, parent, possible, possibleSignature);
|
||||||
.getName()
|
|
||||||
.startsWith(GraphQlDocumentShapeAnalyzer.INTROSPECTION_FIELD_PREFIX)) {
|
|
||||||
names.add(field.getName());
|
|
||||||
}
|
|
||||||
} else if (selection instanceof InlineFragment inlineFragment) {
|
} 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) {
|
} else if (selection instanceof FragmentSpread spread) {
|
||||||
FragmentDefinition fragment = fragments.get(spread.getName());
|
FragmentDefinition fragment = fragments.get(spread.getName());
|
||||||
if (fragment != null && expanded.add(spread.getName())) {
|
if (fragment == null) {
|
||||||
collect(fragment.getSelectionSet());
|
continue;
|
||||||
|
}
|
||||||
|
GraphQLCompositeType narrowed = narrowed(fragment.getTypeCondition(), parent);
|
||||||
|
Set<GraphQLObjectType> within = intersect(possible, narrowed);
|
||||||
|
if (expanded.add(spread.getName() + "@" + signature(within))) {
|
||||||
|
collect(fragment.getSelectionSet(), narrowed, within);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void field(
|
||||||
|
Field field,
|
||||||
|
GraphQLCompositeType parent,
|
||||||
|
Set<GraphQLObjectType> 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<GraphQLObjectType> 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<GraphQLObjectType> objectsOf(GraphQLCompositeType type) {
|
||||||
|
Set<GraphQLObjectType> 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<GraphQLObjectType> intersect(
|
||||||
|
Set<GraphQLObjectType> possible, GraphQLCompositeType narrowed) {
|
||||||
|
Set<GraphQLObjectType> within = new LinkedHashSet<>(possible);
|
||||||
|
within.retainAll(objectsOf(narrowed));
|
||||||
|
return within;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String signature(Set<GraphQLObjectType> possible) {
|
||||||
|
return possible.stream().map(GraphQLObjectType::getName).sorted().toList().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The type a fragment's fields belong to.
|
||||||
|
*
|
||||||
|
* <p>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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+13
@@ -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. */
|
/** Maps a denial onto the wire, without disclosing what the caller could not see. */
|
||||||
public static GraphQlWireError toWireError(
|
public static GraphQlWireError toWireError(
|
||||||
GraphQlAuthorizationDecision decision, GraphQlErrorContext context) {
|
GraphQlAuthorizationDecision decision, GraphQlErrorContext context) {
|
||||||
|
|||||||
+21
-1
@@ -64,6 +64,21 @@ public final class GraphQlAuthorizationPolicy {
|
|||||||
return GraphQlAuthorizationDecision.allow();
|
return GraphQlAuthorizationDecision.allow();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decides a coordinate below the operation root, such as {@code User.salary}.
|
||||||
|
*
|
||||||
|
* <p>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. */
|
/** Whether a coordinate is hidden from introspection, which is not an authorization decision. */
|
||||||
public boolean hiddenFromIntrospection(GraphQlSchemaCoordinate coordinate) {
|
public boolean hiddenFromIntrospection(GraphQlSchemaCoordinate coordinate) {
|
||||||
return hiddenCoordinates.contains(coordinate.value());
|
return hiddenCoordinates.contains(coordinate.value());
|
||||||
@@ -78,7 +93,12 @@ public final class GraphQlAuthorizationPolicy {
|
|||||||
|
|
||||||
private Builder() {}
|
private Builder() {}
|
||||||
|
|
||||||
/** Allows a coordinate for the given client profiles. */
|
/**
|
||||||
|
* Allows a coordinate for the given client profiles.
|
||||||
|
*
|
||||||
|
* <p>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) {
|
public Builder allow(GraphQlSchemaCoordinate coordinate, GraphQlClientProfile... profiles) {
|
||||||
allowedProfiles.put(
|
allowedProfiles.put(
|
||||||
coordinate.value(),
|
coordinate.value(),
|
||||||
|
|||||||
+8
-2
@@ -11,8 +11,14 @@ import java.util.function.Supplier;
|
|||||||
*
|
*
|
||||||
* <p>GraphQL execution hops threads constantly — an async data fetcher, a DataLoader dispatch, a
|
* <p>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
|
* 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
|
* hop. That is not a lost tag: it is a batch load running with no tenant. Each wrapper here
|
||||||
* here, and every one restores the previous state afterwards so nothing leaks into a pooled thread.
|
* restores the previous state afterwards so nothing leaks into a pooled thread.
|
||||||
|
*
|
||||||
|
* <p>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 {
|
public final class GraphQlContextPropagator {
|
||||||
|
|
||||||
|
|||||||
+20
-9
@@ -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.GraphQlRequestContext;
|
||||||
import dev.caskeleton.adapter.inbound.graphql.context.TenantContext;
|
import dev.caskeleton.adapter.inbound.graphql.context.TenantContext;
|
||||||
|
import dev.caskeleton.application.tenant.TenantId;
|
||||||
import java.util.Map;
|
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
|
* <p>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) {
|
public static TenantContext require(GraphQlRequestContext context) {
|
||||||
if (context == null) {
|
if (context == null) {
|
||||||
throw new GraphQlTenantIsolationException("tenant context required");
|
throw new GraphQlTenantIsolationException("tenant context required");
|
||||||
}
|
}
|
||||||
TenantContext tenant = require(context.tenant());
|
return require(context.tenant());
|
||||||
if (tenant.source() == null) {
|
|
||||||
throw new GraphQlTenantIsolationException("tenant source is unknown");
|
|
||||||
}
|
|
||||||
return tenant;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rejects an attempt to take the tenant from client-supplied input.
|
* Rejects an attempt to take the tenant from client-supplied input.
|
||||||
*
|
*
|
||||||
|
* <p>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 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
|
* @throws GraphQlTenantIsolationException when any of them is present
|
||||||
*/
|
*/
|
||||||
public static void rejectTenantArgument(
|
public static void rejectTenantArgument(
|
||||||
@@ -56,7 +65,9 @@ public final class GraphQlTenantIsolationPolicy {
|
|||||||
if (arguments == null || arguments.isEmpty()) {
|
if (arguments == null || arguments.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
boolean present = arguments.keySet().stream().anyMatch(tenantArgumentNames::contains);
|
boolean present =
|
||||||
|
arguments.keySet().stream()
|
||||||
|
.anyMatch(name -> TenantId.namesATenant(name, tenantArgumentNames));
|
||||||
if (present) {
|
if (present) {
|
||||||
throw new GraphQlTenantIsolationException(
|
throw new GraphQlTenantIsolationException(
|
||||||
"tenant must come from authentication, not from a GraphQL argument");
|
"tenant must come from authentication, not from a GraphQL argument");
|
||||||
|
|||||||
+5
-2
@@ -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.api.GraphQlSchemaCoordinate;
|
||||||
import dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformAutoConfiguration;
|
import dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformAutoConfiguration;
|
||||||
import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext;
|
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.execution.BoundedPreparsedDocumentProvider;
|
||||||
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
|
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
|
||||||
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy;
|
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy;
|
||||||
@@ -115,8 +116,10 @@ class GraphQlPlatformExecutionPathTest {
|
|||||||
|
|
||||||
GraphQlRequestContext context = OBSERVED_CONTEXT.get();
|
GraphQlRequestContext context = OBSERVED_CONTEXT.get();
|
||||||
assertThat(context).as("the resolver must see the platform context").isNotNull();
|
assertThat(context).as("the resolver must see the platform context").isNotNull();
|
||||||
assertThat(context.tenant().value())
|
assertThat(context.tenant())
|
||||||
.isEqualTo(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT);
|
.as("an anonymous request is the anonymous partition, not a platform task")
|
||||||
|
.isEqualTo(
|
||||||
|
TenantContext.anonymous(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT));
|
||||||
assertThat(context.clientProfile().value())
|
assertThat(context.clientProfile().value())
|
||||||
.isEqualTo(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_PROFILE);
|
.isEqualTo(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_PROFILE);
|
||||||
assertThat(context.operationId().value())
|
assertThat(context.operationId().value())
|
||||||
|
|||||||
+2
-1
@@ -49,7 +49,8 @@ class GraphQlRequestContextTest {
|
|||||||
.containsExactly(
|
.containsExactly(
|
||||||
TenantContext.TenantSource.AUTHENTICATED_CREDENTIAL,
|
TenantContext.TenantSource.AUTHENTICATED_CREDENTIAL,
|
||||||
TenantContext.TenantSource.TRUSTED_SESSION,
|
TenantContext.TenantSource.TRUSTED_SESSION,
|
||||||
TenantContext.TenantSource.SYSTEM);
|
TenantContext.TenantSource.SYSTEM,
|
||||||
|
TenantContext.TenantSource.ANONYMOUS);
|
||||||
}
|
}
|
||||||
|
|
||||||
static Stream<String> tenantsTheWebTransportRefuses() {
|
static Stream<String> tenantsTheWebTransportRefuses() {
|
||||||
|
|||||||
+11
-5
@@ -12,8 +12,10 @@ import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledE
|
|||||||
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
|
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
|
||||||
import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException;
|
import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException;
|
||||||
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
||||||
|
import dev.caskeleton.application.security.AuthorizationDeniedException;
|
||||||
import dev.caskeleton.shared.error.OperationalError;
|
import dev.caskeleton.shared.error.OperationalError;
|
||||||
import dev.caskeleton.shared.error.PersistenceFailureException;
|
import dev.caskeleton.shared.error.PersistenceFailureException;
|
||||||
|
import dev.caskeleton.shared.security.Permission;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -27,18 +29,22 @@ import org.springframework.validation.BindException;
|
|||||||
|
|
||||||
class GraphQlWireErrorMapperTest {
|
class GraphQlWireErrorMapperTest {
|
||||||
|
|
||||||
static Stream<Arguments> dataLoaderFailures() {
|
static Stream<Arguments> failuresWithTheirOwnCode() {
|
||||||
return Stream.of(
|
return Stream.of(
|
||||||
Arguments.of(
|
Arguments.of(
|
||||||
new GraphQlBatchTimeoutException("customer-by-id"), "REQUEST_TIMEOUT", "TIMEOUT"),
|
new GraphQlBatchTimeoutException("customer-by-id"), "REQUEST_TIMEOUT", "TIMEOUT"),
|
||||||
Arguments.of(new GraphQlRequestCancelledException(), "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
|
@ParameterizedTest
|
||||||
@MethodSource("dataLoaderFailures")
|
@MethodSource("failuresWithTheirOwnCode")
|
||||||
@DisplayName("요청·DataLoader 의 timeout·missing key 는 INTERNAL_ERROR 로 가려지지 않고 플랫폼 code 로 나간다")
|
@DisplayName("요청·DataLoader 의 timeout·missing key, 권한 거부는 INTERNAL_ERROR 로 가려지지 않고 자기 code 로 나간다")
|
||||||
void dataLoaderFailuresKeepAPlatformCode(
|
void aFailureWithItsOwnCodeIsNotMaskedAsInternalError(
|
||||||
RuntimeException failure, String expectedCode, String expectedCategory) {
|
RuntimeException failure, String expectedCode, String expectedCategory) {
|
||||||
// given
|
// given
|
||||||
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
|
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
|
||||||
|
|||||||
+333
@@ -22,6 +22,7 @@ import java.util.Map;
|
|||||||
import org.junit.jupiter.api.DisplayName;
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.params.ParameterizedTest;
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
import org.junit.jupiter.params.provider.ValueSource;
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -122,6 +123,338 @@ class GraphQlDocumentAuthorizationHandlerTest {
|
|||||||
.hasMessage("GraphQL authorization denied: COORDINATE_NOT_AUTHORIZED");
|
.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
|
@Test
|
||||||
void aContextWithoutASchemaIsRefusedInsteadOfGuessingRootNames() {
|
void aContextWithoutASchemaIsRefusedInsteadOfGuessingRootNames() {
|
||||||
// given
|
// given
|
||||||
|
|||||||
+34
@@ -46,6 +46,40 @@ class GraphQlAuthorizationPolicyTest {
|
|||||||
.isFalse();
|
.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
|
@Test
|
||||||
void deniedDecisionsUseStableCodes() {
|
void deniedDecisionsUseStableCodes() {
|
||||||
assertThat(GraphQlAuthorizationDecision.deny("ORDER_READ_DENIED").code())
|
assertThat(GraphQlAuthorizationDecision.deny("ORDER_READ_DENIED").code())
|
||||||
|
|||||||
+36
@@ -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.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
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.GraphQlRequestContext;
|
||||||
import dev.caskeleton.adapter.inbound.graphql.context.TenantContext;
|
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.Callable;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
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). */
|
/** Tenant isolation and context propagation (Stable plan Task 29). */
|
||||||
class GraphQlTenantIsolationPolicyTest {
|
class GraphQlTenantIsolationPolicyTest {
|
||||||
@@ -37,6 +41,38 @@ class GraphQlTenantIsolationPolicyTest {
|
|||||||
.doesNotThrowAnyException();
|
.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
|
@Test
|
||||||
void crossingATenantBoundaryIsRejected() {
|
void crossingATenantBoundaryIsRejected() {
|
||||||
assertThatThrownBy(
|
assertThatThrownBy(
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`.
|
|||||||
- `:application-core`, `:domain-core`, `:shared-contract`.
|
- `:application-core`, `:domain-core`, `:shared-contract`.
|
||||||
- `io.grpc:*` (grpc-netty-shaded / grpc-protobuf / grpc-stub / grpc-services),
|
- `io.grpc:*` (grpc-netty-shaded / grpc-protobuf / grpc-stub / grpc-services),
|
||||||
`spring-boot-starter`, `spring-boot-starter-validation`.
|
`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 「기능은 어떻게 기여하는가」.
|
||||||
|
|
||||||
## 금지
|
## 금지
|
||||||
|
|
||||||
|
|||||||
@@ -132,6 +132,18 @@ Spring Security에 결합되지 않는다. 인증된 호출자(`Optional<Princip
|
|||||||
handler가 metadata를 다시 해석하지 않는다. 빈 값·`null` 반환과 policy 예외는 동일한 안정적
|
handler가 metadata를 다시 해석하지 않는다. 빈 값·`null` 반환과 policy 예외는 동일한 안정적
|
||||||
`UNAUTHENTICATED` 계약으로 끝난다.
|
`UNAUTHENTICATED` 계약으로 끝난다.
|
||||||
|
|
||||||
|
인터셉터는 handler가 도는 동안 정책이 돌려준 호출자를 `SecurityContext`에 둔다. 호출 시작과 listener callback마다,
|
||||||
|
gRPC가 어느 executor thread에서 돌리든 넣고, 끝나면 그 thread에 먼저 있던 context로 되돌린다(없었으면 지운다). `@RequiresPermission`이 읽는 곳이 거기라서, gRPC
|
||||||
|
handler가 부른 유스케이스도 web 요청과 같은 방식으로 권한을 판정한다. 권한이 없으면
|
||||||
|
`AuthorizationDeniedException`(`AUTHZ_INSUFFICIENT_PERMISSION`)이 아래 표대로 `PERMISSION_DENIED`가 된다.
|
||||||
|
|
||||||
|
- 호출자가 Spring Security `Authentication`이면 그대로 둔다. 역할은 그 principal이 web의 `AuthenticatedPrincipal`일
|
||||||
|
때만 읽힌다. 정책이 web의 JWT decoder로 token을 검증하고 `JwtToAuthenticatedPrincipalConverter`로 바꾸면 그렇다.
|
||||||
|
`GrantedAuthority`는 보지 않는다(web과 같다).
|
||||||
|
- 그 밖의 `Principal`은 권한 없는 인증 token으로 둔다. 정책이 인증했지만 역할이 없으니 권한이 필요한 유스케이스는
|
||||||
|
`PERMISSION_DENIED`로 거부한다. context를 비워 두면 Spring이 권한 판정 전에 거부해 분류되지 않은 `INTERNAL`이 된다.
|
||||||
|
- 이 일에만 `spring-security-core`의 security context 타입과 `UsernamePasswordAuthenticationToken`을 쓴다.
|
||||||
|
|
||||||
## 에러 매핑 — web `GlobalExceptionHandler` 의 gRPC 형제
|
## 에러 매핑 — web `GlobalExceptionHandler` 의 gRPC 형제
|
||||||
|
|
||||||
`GrpcExceptionHandlingInterceptor`는 forwarding `ServerCall`의 `close`까지 감싼다. 동기
|
`GrpcExceptionHandlingInterceptor`는 forwarding `ServerCall`의 `close`까지 감싼다. 동기
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ dependencies {
|
|||||||
|
|
||||||
implementation 'org.springframework.boot:spring-boot-starter'
|
implementation 'org.springframework.boot:spring-boot-starter'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||||
|
// Security context and authentication token types only: the caller the authentication policy
|
||||||
|
// returns is put on the context @RequiresPermission reads while the handler runs (an
|
||||||
|
// Authentication as it is, any other Principal as an authenticated token with no authorities).
|
||||||
|
implementation 'org.springframework.security:spring-security-core'
|
||||||
|
|
||||||
// Keep the direct versions in the outgoing project metadata as well as importing the BOM.
|
// Keep the direct versions in the outgoing project metadata as well as importing the BOM.
|
||||||
// Spring dependency-management constraints are local to this leaf and are not propagated to
|
// Spring dependency-management constraints are local to this leaf and are not propagated to
|
||||||
|
|||||||
@@ -133,6 +133,8 @@ org.springframework.boot:spring-boot-test-autoconfigure:4.0.9=testCompileClasspa
|
|||||||
org.springframework.boot:spring-boot-test:4.0.9=testCompileClasspath,testRuntimeClasspath
|
org.springframework.boot:spring-boot-test:4.0.9=testCompileClasspath,testRuntimeClasspath
|
||||||
org.springframework.boot:spring-boot-validation:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
org.springframework.boot:spring-boot-validation:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||||
org.springframework.boot:spring-boot:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
org.springframework.boot:spring-boot:4.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||||
|
org.springframework.security:spring-security-core:7.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||||
|
org.springframework.security:spring-security-crypto:7.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||||
org.springframework:spring-aop:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
org.springframework:spring-aop:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||||
org.springframework:spring-beans:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
org.springframework:spring-beans:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||||
org.springframework:spring-context:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
org.springframework:spring-context:7.0.10=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
|
||||||
|
|||||||
+106
-1
@@ -3,18 +3,38 @@ package dev.caskeleton.adapter.inbound.grpc;
|
|||||||
import dev.caskeleton.shared.error.OperationalError;
|
import dev.caskeleton.shared.error.OperationalError;
|
||||||
import io.grpc.Context;
|
import io.grpc.Context;
|
||||||
import io.grpc.Contexts;
|
import io.grpc.Contexts;
|
||||||
|
import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener;
|
||||||
import io.grpc.Metadata;
|
import io.grpc.Metadata;
|
||||||
import io.grpc.ServerCall;
|
import io.grpc.ServerCall;
|
||||||
import io.grpc.ServerCallHandler;
|
import io.grpc.ServerCallHandler;
|
||||||
import io.grpc.ServerInterceptor;
|
import io.grpc.ServerInterceptor;
|
||||||
import java.security.Principal;
|
import java.security.Principal;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.function.Supplier;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Applies the caller-supplied authentication policy before a feature RPC can reach its handler, and
|
* Applies the caller-supplied authentication policy before a feature RPC can reach its handler, and
|
||||||
* hands the authenticated caller to the handler through the gRPC {@link Context}.
|
* hands the authenticated caller to the handler through the gRPC {@link Context}.
|
||||||
|
*
|
||||||
|
* <p>The 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 {
|
final class GrpcAuthenticationInterceptor implements ServerInterceptor {
|
||||||
|
|
||||||
@@ -36,7 +56,11 @@ final class GrpcAuthenticationInterceptor implements ServerInterceptor {
|
|||||||
authenticate(headers, call.getMethodDescriptor().getFullMethodName());
|
authenticate(headers, call.getMethodDescriptor().getFullMethodName());
|
||||||
if (caller.isPresent()) {
|
if (caller.isPresent()) {
|
||||||
Context context = Context.current().withValue(GrpcAuthenticatedCaller.KEY, caller.get());
|
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<REQT> listener =
|
||||||
|
scope.call(() -> Contexts.interceptCall(context, call, headers, next));
|
||||||
|
return new SecurityContextListener<>(listener, scope);
|
||||||
}
|
}
|
||||||
|
|
||||||
call.close(
|
call.close(
|
||||||
@@ -45,6 +69,12 @@ final class GrpcAuthenticationInterceptor implements ServerInterceptor {
|
|||||||
return new ServerCall.Listener<>() {};
|
return new ServerCall.Listener<>() {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Authentication asAuthentication(Principal caller) {
|
||||||
|
return caller instanceof Authentication authentication
|
||||||
|
? authentication
|
||||||
|
: UsernamePasswordAuthenticationToken.authenticated(caller, null, List.of());
|
||||||
|
}
|
||||||
|
|
||||||
private Optional<Principal> authenticate(Metadata headers, String method) {
|
private Optional<Principal> authenticate(Metadata headers, String method) {
|
||||||
try {
|
try {
|
||||||
Optional<Principal> caller = authenticationPolicy.authenticate(headers);
|
Optional<Principal> caller = authenticationPolicy.authenticate(headers);
|
||||||
@@ -59,4 +89,79 @@ final class GrpcAuthenticationInterceptor implements ServerInterceptor {
|
|||||||
return Optional.empty();
|
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> T call(Supplier<T> 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<REQT>
|
||||||
|
extends SimpleForwardingServerCallListener<REQT> {
|
||||||
|
|
||||||
|
private final SecurityContextScope scope;
|
||||||
|
|
||||||
|
SecurityContextListener(ServerCall.Listener<REQT> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+183
@@ -7,12 +7,26 @@ import io.grpc.MethodDescriptor;
|
|||||||
import io.grpc.ServerCall;
|
import io.grpc.ServerCall;
|
||||||
import io.grpc.Status;
|
import io.grpc.Status;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
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.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Named;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
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.CapturedOutput;
|
||||||
import org.springframework.boot.test.system.OutputCaptureExtension;
|
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)
|
@ExtendWith(OutputCaptureExtension.class)
|
||||||
class GrpcAuthenticationInterceptorTest {
|
class GrpcAuthenticationInterceptorTest {
|
||||||
@@ -62,6 +76,175 @@ class GrpcAuthenticationInterceptorTest {
|
|||||||
assertThat(call.closedWith).isEqualTo(Status.Code.UNAUTHENTICATED);
|
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<Authentication> 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<Authentication> inside = new AtomicReference<>();
|
||||||
|
ServerCall.Listener<String> 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<Authentication> atHalfClose = new AtomicReference<>();
|
||||||
|
ServerCall.Listener<String> 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<Arguments> 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<ServerCall.Listener<String>> callback(
|
||||||
|
Consumer<ServerCall.Listener<String>> callback) {
|
||||||
|
return callback;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("listenerCallbacks")
|
||||||
|
@DisplayName("message·ready·cancel·complete callback 도 그 호출자의 context 안에서 돌고 끝나면 지운다")
|
||||||
|
void everyListenerCallbackRunsInsideTheCallersContext(
|
||||||
|
Consumer<ServerCall.Listener<String>> callback) {
|
||||||
|
// given
|
||||||
|
Authentication caller = new TestingAuthenticationToken("caller-1", "n/a", "ROLE_USER");
|
||||||
|
AtomicReference<Authentication> inside = new AtomicReference<>();
|
||||||
|
ServerCall.Listener<String> 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<Authentication> inside = new AtomicReference<>();
|
||||||
|
ServerCall.Listener<String> 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<String> recordingListener(
|
||||||
|
Authentication caller, AtomicReference<Authentication> 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. */
|
/** A server call that only knows its method; the interceptor closes it as unauthenticated. */
|
||||||
private static final class MethodCall extends ServerCall<String, String> {
|
private static final class MethodCall extends ServerCall<String, String> {
|
||||||
|
|
||||||
|
|||||||
@@ -70,6 +70,9 @@ virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관
|
|||||||
- `Retry-After` 는 `WebAdvancedError` 가 web 의 `RetryAfterHint` 로 직접 말한다. web 의 `RetryAfterAdvisor`
|
- `Retry-After` 는 `WebAdvancedError` 가 web 의 `RetryAfterHint` 로 직접 말한다. web 의 `RetryAfterAdvisor`
|
||||||
표에 이 leaf 코드 이름을 넣지 않는다.
|
표에 이 leaf 코드 이름을 넣지 않는다.
|
||||||
- `details` 는 `ClientSafeErrorDetails` 로 고른 값만 나간다. 예외 메시지는 나가지 않는다.
|
- `details` 는 `ClientSafeErrorDetails` 로 고른 값만 나간다. 예외 메시지는 나가지 않는다.
|
||||||
|
- `details.refusedPaths` 는 요청이 쓴 이름이다(허용 목록에 없는 이름이라 거부됐다). 그래서 16개까지,
|
||||||
|
`[A-Za-z0-9_.~/-]` 128자 이하인 이름만 그대로 돌려주고 나머지는 `<not echoed>` 로 바꾼다. 예외 메시지에는
|
||||||
|
개수와 같은 목록만 있다.
|
||||||
- 이 코드들은 `docs/registries/error-codes.yaml`(`OperationalError` SSOT) 밖이다. 5xx 는
|
- 이 코드들은 `docs/registries/error-codes.yaml`(`OperationalError` SSOT) 밖이다. 5xx 는
|
||||||
`handleCarrier` 가 ERROR 로그를 남긴다(admission 거절 포함 — 경보 임계는 운영에서 정한다).
|
`handleCarrier` 가 ERROR 로그를 남긴다(admission 거절 포함 — 경보 임계는 운영에서 정한다).
|
||||||
- 응답 status 가 이미 commit 된 스트림 안에서는 HTTP status 가 바뀌지 않는다. 위 표는 commit 전에 던져진
|
- 응답 status 가 이미 commit 된 스트림 안에서는 HTTP status 가 바뀌지 않는다. 위 표는 commit 전에 던져진
|
||||||
|
|||||||
+38
-5
@@ -7,30 +7,63 @@ import dev.caskeleton.shared.error.ApiErrorCode;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A patch tried to touch something the caller may not.
|
* A patch tried to touch something the caller may not.
|
||||||
*
|
*
|
||||||
* <p>Names the fields, because the caller needs to know which of them was refused and the names are
|
* <p>Names the refused fields, because the caller needs to know which of them was refused. The
|
||||||
* from the server's allowlist rather than from the request — so they are safe to echo.
|
* 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
|
public final class PatchAuthorizationException extends RuntimeException
|
||||||
implements ApiErrorCarrier, ClientSafeErrorDetails {
|
implements ApiErrorCarrier, ClientSafeErrorDetails {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
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 = "<not echoed>";
|
||||||
|
|
||||||
|
private static final Pattern ECHOABLE = Pattern.compile("[A-Za-z0-9_.~/-]+");
|
||||||
|
|
||||||
private final transient List<String> refusedPaths;
|
private final transient List<String> refusedPaths;
|
||||||
|
|
||||||
public PatchAuthorizationException(List<String> refusedPaths) {
|
public PatchAuthorizationException(List<String> refusedPaths) {
|
||||||
super("the patch touches fields this caller may not modify: " + refusedPaths);
|
this(echoed(Objects.requireNonNull(refusedPaths, "refusedPaths")), refusedPaths.size());
|
||||||
this.refusedPaths = List.copyOf(Objects.requireNonNull(refusedPaths, "refusedPaths"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Which paths were refused. */
|
private PatchAuthorizationException(List<String> echoed, int refusedCount) {
|
||||||
|
super("the patch touches " + refusedCount + " field(s) this caller may not modify: " + echoed);
|
||||||
|
this.refusedPaths = List.copyOf(echoed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> echoed(List<String> 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<String> refusedPaths() {
|
public List<String> refusedPaths() {
|
||||||
return 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. */
|
/** {@link WebAdvancedError#PATCH_PATH_FORBIDDEN}; see the leaf README for the client contract. */
|
||||||
@Override
|
@Override
|
||||||
public ApiErrorCode errorCode() {
|
public ApiErrorCode errorCode() {
|
||||||
|
|||||||
+5
-10
@@ -1,7 +1,7 @@
|
|||||||
package dev.caskeleton.adapter.inbound.web.advanced.security;
|
package dev.caskeleton.adapter.inbound.web.advanced.security;
|
||||||
|
|
||||||
import dev.caskeleton.adapter.inbound.web.core.TenantContext;
|
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.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
@@ -15,10 +15,6 @@ import java.util.Objects;
|
|||||||
*/
|
*/
|
||||||
public final class WebTenantContextResolver {
|
public final class WebTenantContextResolver {
|
||||||
|
|
||||||
/** Header and parameter names that would be a tenant if anybody believed them. */
|
|
||||||
private static final java.util.Set<String> TENANT_INPUT_NAMES =
|
|
||||||
java.util.Set.of("x-tenant-id", "tenant-id", "tenantid", "tenant");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The tenant scope for an authentication.
|
* The tenant scope for an authentication.
|
||||||
*
|
*
|
||||||
@@ -32,6 +28,9 @@ public final class WebTenantContextResolver {
|
|||||||
/**
|
/**
|
||||||
* Refuses request input that proposes a tenant.
|
* Refuses request input that proposes a tenant.
|
||||||
*
|
*
|
||||||
|
* <p>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
|
* @param requestInput headers or parameters, keyed by name
|
||||||
* @throws UntrustedTenantInputException when any of them names a tenant
|
* @throws UntrustedTenantInputException when any of them names a tenant
|
||||||
*/
|
*/
|
||||||
@@ -39,11 +38,7 @@ public final class WebTenantContextResolver {
|
|||||||
if (requestInput == null || requestInput.isEmpty()) {
|
if (requestInput == null || requestInput.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
boolean proposed =
|
boolean proposed = requestInput.keySet().stream().anyMatch(TenantId::namesATenant);
|
||||||
requestInput.keySet().stream()
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.map(name -> name.toLowerCase(Locale.ROOT))
|
|
||||||
.anyMatch(TENANT_INPUT_NAMES::contains);
|
|
||||||
if (proposed) {
|
if (proposed) {
|
||||||
throw new UntrustedTenantInputException();
|
throw new UntrustedTenantInputException();
|
||||||
}
|
}
|
||||||
|
|||||||
+50
@@ -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<String> refused = List.of("/role", "<script>alert(1)</script>", "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<String> 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -92,6 +92,11 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
|||||||
- **메커니즘 & 트레이드오프**: Spring Security 는 JWT 실패에 단일 typed reason 을 노출하지 않으므로,
|
- **메커니즘 & 트레이드오프**: Spring Security 는 JWT 실패에 단일 typed reason 을 노출하지 않으므로,
|
||||||
classifier 가 예외 그래프와 validator/Nimbus 메시지 텍스트를 검사한다. 매핑:
|
classifier 가 예외 그래프와 validator/Nimbus 메시지 텍스트를 검사한다. 매핑:
|
||||||
- missing token → `InsufficientAuthenticationException` → `AUTH_TOKEN_MISSING`
|
- 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: <HTTP 오류>"라 문구 규칙만 보면 `AUTH_TOKEN_MALFORMED`가 됐다
|
||||||
- claim validators(`JwtValidationException`) → description 에 따라 `AUTH_TOKEN_EXPIRED` /
|
- claim validators(`JwtValidationException`) → description 에 따라 `AUTH_TOKEN_EXPIRED` /
|
||||||
`AUTH_ISSUER_MISMATCH` / `AUTH_AUDIENCE_MISMATCH`
|
`AUTH_ISSUER_MISMATCH` / `AUTH_AUDIENCE_MISMATCH`
|
||||||
- decode/signature/unknown-kid(`BadJwtException`/`JwtException` cause) →
|
- decode/signature/unknown-kid(`BadJwtException`/`JwtException` cause) →
|
||||||
@@ -160,17 +165,18 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
|||||||
- 가로챈 메서드(또는 선언 타입)에서 애너테이션을 읽고, 현재 `Authentication` 을 프레임워크 독립적
|
- 가로챈 메서드(또는 선언 타입)에서 애너테이션을 읽고, 현재 `Authentication` 을 프레임워크 독립적
|
||||||
`AuthorizationPrincipal` 로 매핑해 결정을 application `AuthorizationPort` 에 위임한다. 따라서
|
`AuthorizationPrincipal` 로 매핑해 결정을 application `AuthorizationPort` 에 위임한다. 따라서
|
||||||
application/domain 은 어떤 Spring Security 타입도 갖지 않으며, **이 어댑터가 두 세계가 만나는 유일한 지점**이다.
|
application/domain 은 어떤 Spring Security 타입도 갖지 않으며, **이 어댑터가 두 세계가 만나는 유일한 지점**이다.
|
||||||
- 포트가 거부 시 application `AuthorizationDeniedException` 을 던지고, 이 매니저가 그것을 거부된
|
- 포트가 거부 시 application `AuthorizationDeniedException` 을 던지고, 이 매니저는 그것을 거부된
|
||||||
`AuthorizationDecision` 으로 변환한다. method-security 인터셉터가 이를 `AccessDeniedException` →
|
`AuthorizationDecision` 으로 바꾸지 않고 그대로 내보낸다. 그 예외가 `ApiErrorCarrier`(`AUTHZ_INSUFFICIENT_PERMISSION`)라
|
||||||
`AUTHZ_INSUFFICIENT_PERMISSION` 403 으로 만든다(§4). `null` 반환은 기권(abstain)이라 애너테이션 없는
|
web 은 `GlobalExceptionHandler` 가 403 으로, gRPC·GraphQL 은 자기 오류 대응이 같은 코드로 답한다. 거부를 잡는 코드는
|
||||||
메서드는 영향받지 않는다.
|
Spring `AccessDeniedException` 이 아니라 이 예외(또는 `ApiErrorCarrier`)를 잡는다. `null` 반환은 기권(abstain)이라
|
||||||
|
애너테이션 없는 메서드는 영향받지 않는다.
|
||||||
- 매핑은 **fail-closed**: 미인증 요청이거나 우리 `AuthenticatedPrincipal` 이 아닌 principal 은 0개 role 로
|
- 매핑은 **fail-closed**: 미인증 요청이거나 우리 `AuthenticatedPrincipal` 이 아닌 principal 은 0개 role 로
|
||||||
해석되어 거부된다.
|
해석되어 거부된다. 역할은 principal 에서만 읽고 `GrantedAuthority` 는 보지 않는다.
|
||||||
|
|
||||||
### AuthorizationAdapter
|
### AuthorizationAdapter
|
||||||
- application `AuthorizationPort` 의 web-adapter 구현체.
|
- application `AuthorizationPort` 의 web-adapter 구현체.
|
||||||
- 결정은 **fail-closed**: principal 의 유효 권한 집합에 요구 권한이 없으면 `AuthorizationDeniedException` 으로
|
- 결정은 **fail-closed**: principal 의 유효 권한 집합에 요구 권한이 없으면 `AuthorizationDeniedException` 으로
|
||||||
거부 → `RequiresPermissionAuthorizationManager` 가 변환 → 최종 `AUTHZ_INSUFFICIENT_PERMISSION` 403.
|
거부 → `RequiresPermissionAuthorizationManager` 가 그대로 내보냄 → 최종 `AUTHZ_INSUFFICIENT_PERMISSION` 403.
|
||||||
|
|
||||||
### RolePermissionRegistry
|
### RolePermissionRegistry
|
||||||
- 호출자의 raw role 들을 유효 `Permission` 집합으로 해석한다.
|
- 호출자의 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) |
|
| `InvalidIdempotencyKeyException` | `IDEMPOTENCY_KEY_INVALID` | 400 | `IdempotencyKeyHeader.parse` 가 헤더 누락·문법 밖을 거부. `details.reason` = `MISSING`/`MALFORMED`, 키 원문 미노출(리뷰 02-12) |
|
||||||
| `InvalidBearerTokenException` | `INVALID_TOKEN` | 코드 상태 | |
|
| `InvalidBearerTokenException` | `INVALID_TOKEN` | 코드 상태 | |
|
||||||
| `AuthenticationException` | `UNAUTHENTICATED` | 코드 상태 | |
|
| `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 금지) |
|
| `PreconditionFailedException` | `PRECONDITION_FAILED` | 412 | D15: `If-Match` 불일치 쓰기 = 낙관적 동시성 충돌 → 412 (raw 409/500 금지) |
|
||||||
| `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 |
|
| `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 분기 |
|
| `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | action 전에 거부 — 조정 저장소가 응답하지 않았거나, claim의 processing lease가 시작 전에 끝나 저장소가 시작을 거절했다(실행 안 됨, 저장소는 정상일 수 있다). 같은 키로 나중에 재전송하면 다음 요청이 그 claim을 넘겨받아 실행한다(`docs/web/http-contract.md` §2, 라운드6 RR6-02-04). carrier 분기 |
|
||||||
|
|||||||
+6
-1
@@ -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;
|
Throwable current = failure;
|
||||||
for (int depth = 0; current != null && depth < 32; depth++) {
|
for (int depth = 0; current != null && depth < 32; depth++) {
|
||||||
if (current instanceof RestClientException || current instanceof IOException) {
|
if (current instanceof RestClientException || current instanceof IOException) {
|
||||||
|
|||||||
+31
-14
@@ -5,7 +5,6 @@ import dev.caskeleton.application.tenant.TenantId;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
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.authentication.AbstractAuthenticationToken;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
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.jwt.Jwt;
|
||||||
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
|
|
||||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@@ -28,7 +28,14 @@ import org.springframework.stereotype.Component;
|
|||||||
*
|
*
|
||||||
* <p>Only the clients named by {@code app.security.audience} contribute {@code resource_access}
|
* <p>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
|
* 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).
|
||||||
|
*
|
||||||
|
* <p>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
|
@Component
|
||||||
public class JwtToAuthenticatedPrincipalConverter
|
public class JwtToAuthenticatedPrincipalConverter
|
||||||
@@ -37,11 +44,18 @@ public class JwtToAuthenticatedPrincipalConverter
|
|||||||
/**
|
/**
|
||||||
* The claim a token names its tenant in.
|
* The claim a token names its tenant in.
|
||||||
*
|
*
|
||||||
* <p>Snake case like the rest of this platform's field names ({@code tenant_id} is also the MDC
|
* <p>Snake case like the rest of this platform's field names. No code puts the tenant on MDC, so
|
||||||
* and baggage key). An IdP that puts the tenant elsewhere maps it to this claim.
|
* 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";
|
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. */
|
/** The clients whose {@code resource_access} roles this service honours: its own audiences. */
|
||||||
private final Set<String> roleClients;
|
private final Set<String> roleClients;
|
||||||
|
|
||||||
@@ -51,10 +65,14 @@ public class JwtToAuthenticatedPrincipalConverter
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public AbstractAuthenticationToken convert(Jwt jwt) {
|
public AbstractAuthenticationToken convert(Jwt jwt) {
|
||||||
|
String subject = jwt.getSubject();
|
||||||
|
if (subject == null || subject.isBlank()) {
|
||||||
|
throw claimMappingFailed("the token names no subject");
|
||||||
|
}
|
||||||
Set<String> roles = extractRoles(jwt);
|
Set<String> roles = extractRoles(jwt);
|
||||||
String email = jwt.getClaimAsString("email");
|
String email = jwt.getClaimAsString("email");
|
||||||
AuthenticatedPrincipal principal =
|
AuthenticatedPrincipal principal =
|
||||||
new AuthenticatedPrincipal(jwt.getSubject(), email, roles, tenant(jwt));
|
new AuthenticatedPrincipal(subject, email, roles, tenant(jwt));
|
||||||
Collection<GrantedAuthority> authorities =
|
Collection<GrantedAuthority> authorities =
|
||||||
roles.stream()
|
roles.stream()
|
||||||
.map(r -> new SimpleGrantedAuthority("ROLE_" + r.toUpperCase(Locale.ROOT)))
|
.map(r -> new SimpleGrantedAuthority("ROLE_" + r.toUpperCase(Locale.ROOT)))
|
||||||
@@ -73,12 +91,16 @@ public class JwtToAuthenticatedPrincipalConverter
|
|||||||
try {
|
try {
|
||||||
return TenantId.optional(jwt.getClaimAsString(TENANT_CLAIM));
|
return TenantId.optional(jwt.getClaimAsString(TENANT_CLAIM));
|
||||||
} catch (IllegalArgumentException malformed) {
|
} catch (IllegalArgumentException malformed) {
|
||||||
// No cause: Spring's (description, cause) constructor replaces the description with the
|
// No cause: the description names the claim, not our grammar or the value.
|
||||||
// cause's message, and a 401 description names the claim, not our grammar.
|
throw claimMappingFailed("the token's tenant claim is malformed");
|
||||||
throw new InvalidBearerTokenException("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<String> extractRoles(Jwt jwt) {
|
private Set<String> extractRoles(Jwt jwt) {
|
||||||
Set<String> roles = new HashSet<>();
|
Set<String> roles = new HashSet<>();
|
||||||
|
|
||||||
@@ -98,11 +120,6 @@ public class JwtToAuthenticatedPrincipalConverter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Generic OIDC "roles" claim as a fallback
|
|
||||||
List<String> flat = jwt.getClaimAsStringList("roles");
|
|
||||||
if (flat != null) {
|
|
||||||
roles.addAll(flat);
|
|
||||||
}
|
|
||||||
return roles;
|
return roles;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+13
-3
@@ -11,9 +11,10 @@ import org.springframework.security.oauth2.jwt.JwtValidationException;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Classifies a resource-server security failure into a fine-grained {@link OperationalError} by
|
* 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
|
* inspecting structured error codes first, then the cause's type (the decoder's own failures, and
|
||||||
* fallback. Unmapped failures fall back to the generic, safe {@code AUTH_TOKEN_MALFORMED} (401)
|
* an HTTP or I/O failure of the key service anywhere in the chain), and Nimbus message text only as
|
||||||
* rather than a 500. See README for the design rationale.
|
* 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 {
|
public class SecurityErrorClassifier {
|
||||||
|
|
||||||
@@ -49,6 +50,13 @@ public class SecurityErrorClassifier {
|
|||||||
if (cause instanceof JwtDecoderConfig.AuthenticationDecoderMisconfigurationException) {
|
if (cause instanceof JwtDecoderConfig.AuthenticationDecoderMisconfigurationException) {
|
||||||
return OperationalError.INTERNAL_AUTH_MISCONFIGURATION;
|
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: <HTTP
|
||||||
|
// client message>", 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) {
|
if (cause instanceof JwtValidationException validation) {
|
||||||
// A JWKS retrieval failure can surface wrapped in validation errors too.
|
// A JWKS retrieval failure can surface wrapped in validation errors too.
|
||||||
OperationalError classified = null;
|
OperationalError classified = null;
|
||||||
@@ -70,6 +78,8 @@ public class SecurityErrorClassifier {
|
|||||||
case JwtDecoderConfig.ERROR_TIMESTAMP_INVALID -> OperationalError.AUTH_TOKEN_EXPIRED;
|
case JwtDecoderConfig.ERROR_TIMESTAMP_INVALID -> OperationalError.AUTH_TOKEN_EXPIRED;
|
||||||
case JwtDecoderConfig.ERROR_ISSUER_MISMATCH -> OperationalError.AUTH_ISSUER_MISMATCH;
|
case JwtDecoderConfig.ERROR_ISSUER_MISMATCH -> OperationalError.AUTH_ISSUER_MISMATCH;
|
||||||
case JwtDecoderConfig.ERROR_AUDIENCE_MISMATCH -> OperationalError.AUTH_AUDIENCE_MISMATCH;
|
case JwtDecoderConfig.ERROR_AUDIENCE_MISMATCH -> OperationalError.AUTH_AUDIENCE_MISMATCH;
|
||||||
|
case JwtToAuthenticatedPrincipalConverter.ERROR_CLAIM_MAPPING_FAILED ->
|
||||||
|
OperationalError.AUTH_CLAIM_MAPPING_FAILED;
|
||||||
default -> null;
|
default -> null;
|
||||||
};
|
};
|
||||||
return structured != null ? structured : classifyByText(describe(error));
|
return structured != null ? structured : classifyByText(describe(error));
|
||||||
|
|||||||
+14
-9
@@ -23,12 +23,21 @@ import org.springframework.security.core.Authentication;
|
|||||||
* <p>Reads the {@link RequiresPermission} annotation off the intercepted method (or its declaring
|
* <p>Reads the {@link RequiresPermission} annotation off the intercepted method (or its declaring
|
||||||
* type), maps the current {@link Authentication} to the framework-free {@link
|
* type), maps the current {@link Authentication} to the framework-free {@link
|
||||||
* AuthorizationPrincipal}, and delegates the decision to the application {@link AuthorizationPort}.
|
* AuthorizationPrincipal}, and delegates the decision to the application {@link AuthorizationPort}.
|
||||||
* A denial from the port becomes a denied {@link AuthorizationDecision}; an absent annotation
|
* An absent annotation returns {@code null} to abstain. See README for the design rationale.
|
||||||
* returns {@code null} to abstain. See README for the design rationale.
|
*
|
||||||
|
* <p>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
|
public final class RequiresPermissionAuthorizationManager
|
||||||
implements AuthorizationManager<MethodInvocation> {
|
implements AuthorizationManager<MethodInvocation> {
|
||||||
|
|
||||||
|
/** The subject a denial names when no authenticated caller is on the context. */
|
||||||
|
static final String UNAUTHENTICATED_SUBJECT = "unauthenticated";
|
||||||
|
|
||||||
private final Supplier<AuthorizationPort> authorizationPort;
|
private final Supplier<AuthorizationPort> authorizationPort;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -54,14 +63,10 @@ public final class RequiresPermissionAuthorizationManager
|
|||||||
|
|
||||||
Authentication auth = authentication.get();
|
Authentication auth = authentication.get();
|
||||||
if (auth == null || !auth.isAuthenticated()) {
|
if (auth == null || !auth.isAuthenticated()) {
|
||||||
return new AuthorizationDecision(false);
|
throw new AuthorizationDeniedException(UNAUTHENTICATED_SUBJECT, required);
|
||||||
}
|
|
||||||
try {
|
|
||||||
authorizationPort.get().requirePermission(toPrincipal(auth), required);
|
|
||||||
return new AuthorizationDecision(true);
|
|
||||||
} catch (AuthorizationDeniedException denied) {
|
|
||||||
return new AuthorizationDecision(false);
|
|
||||||
}
|
}
|
||||||
|
authorizationPort.get().requirePermission(toPrincipal(auth), required);
|
||||||
|
return new AuthorizationDecision(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private RequiresPermission findAnnotation(MethodInvocation invocation) {
|
private RequiresPermission findAnnotation(MethodInvocation invocation) {
|
||||||
|
|||||||
+4
-2
@@ -135,8 +135,10 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles a method-security {@link AccessDeniedException} that escaped the controller, delegating
|
* Handles a Spring {@link AccessDeniedException} that escaped the controller, delegating to
|
||||||
* to {@link SecurityErrorClassifier} for the fine-grained authorization code. See README for the
|
* {@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.
|
* design rationale.
|
||||||
*/
|
*/
|
||||||
@ExceptionHandler(AccessDeniedException.class)
|
@ExceptionHandler(AccessDeniedException.class)
|
||||||
|
|||||||
+39
-1
@@ -38,6 +38,7 @@ import java.util.Map;
|
|||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Tag;
|
import org.junit.jupiter.api.Tag;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
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
|
@Test
|
||||||
void mismatchedDiscoveryMetadataUsesSafeInternalMisconfigurationEnvelope() throws Exception {
|
void mismatchedDiscoveryMetadataUsesSafeInternalMisconfigurationEnvelope() throws Exception {
|
||||||
try (OidcServer issuer = OidcServer.misconfiguredDiscovery()) {
|
try (OidcServer issuer = OidcServer.misconfiguredDiscovery()) {
|
||||||
@@ -304,7 +338,7 @@ class JwtJwksSecurityFilterIntegrationTest {
|
|||||||
.issueTime(Date.from(now.minusSeconds(300)))
|
.issueTime(Date.from(now.minusSeconds(300)))
|
||||||
.expirationTime(Date.from(expiresAt))
|
.expirationTime(Date.from(expiresAt))
|
||||||
.claim("email", "user-1@example.test")
|
.claim("email", "user-1@example.test")
|
||||||
.claim("roles", List.of("operator"))
|
.claim("realm_access", Map.of("roles", List.of("operator")))
|
||||||
.build();
|
.build();
|
||||||
SignedJWT jwt =
|
SignedJWT jwt =
|
||||||
new SignedJWT(
|
new SignedJWT(
|
||||||
@@ -389,6 +423,10 @@ class JwtJwksSecurityFilterIntegrationTest {
|
|||||||
unavailable = false;
|
unavailable = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void makeJwksUnavailable() {
|
||||||
|
unavailable = true;
|
||||||
|
}
|
||||||
|
|
||||||
private void discovery(HttpExchange exchange) throws IOException {
|
private void discovery(HttpExchange exchange) throws IOException {
|
||||||
discoveryRequests.incrementAndGet();
|
discoveryRequests.incrementAndGet();
|
||||||
String body =
|
String body =
|
||||||
|
|||||||
+36
-6
@@ -5,14 +5,15 @@ import static org.assertj.core.api.Assertions.catchThrowable;
|
|||||||
|
|
||||||
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
|
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
|
||||||
import dev.caskeleton.application.tenant.TenantId;
|
import dev.caskeleton.application.tenant.TenantId;
|
||||||
|
import dev.caskeleton.shared.error.OperationalError;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import org.junit.jupiter.api.DisplayName;
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
import org.springframework.security.oauth2.jwt.Jwt;
|
import org.springframework.security.oauth2.jwt.Jwt;
|
||||||
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
|
|
||||||
|
|
||||||
class JwtToAuthenticatedPrincipalConverterTest {
|
class JwtToAuthenticatedPrincipalConverterTest {
|
||||||
|
|
||||||
@@ -27,7 +28,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
|||||||
Jwt.withTokenValue("token")
|
Jwt.withTokenValue("token")
|
||||||
.header("alg", "none")
|
.header("alg", "none")
|
||||||
.subject("user-1")
|
.subject("user-1")
|
||||||
.claim("roles", List.of("admin"))
|
.claim("realm_access", Map.of("roles", List.of("admin")))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
var authentication = converter().convert(jwt);
|
var authentication = converter().convert(jwt);
|
||||||
@@ -63,7 +64,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("형식이 틀린 tenant claim은 '없음'이 아니라 잘못된 token으로 거부한다(401)")
|
@DisplayName("형식이 틀린 tenant claim은 '없음'이 아니라 claim 대응 실패로 거부한다(AUTH_CLAIM_MAPPING_FAILED, 401)")
|
||||||
void aTokenWithAMalformedTenantClaimIsRefused() {
|
void aTokenWithAMalformedTenantClaimIsRefused() {
|
||||||
// given
|
// given
|
||||||
Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "ac me").build();
|
Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "ac me").build();
|
||||||
@@ -72,9 +73,38 @@ class JwtToAuthenticatedPrincipalConverterTest {
|
|||||||
Throwable thrown = catchThrowable(() -> converter().convert(jwt));
|
Throwable thrown = catchThrowable(() -> converter().convert(jwt));
|
||||||
|
|
||||||
// then
|
// then
|
||||||
assertThat(thrown)
|
assertThat(
|
||||||
.isInstanceOf(InvalidBearerTokenException.class)
|
new SecurityErrorClassifier().classifyAuthentication((AuthenticationException) thrown))
|
||||||
.hasMessage("the token's tenant claim is malformed");
|
.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
|
@Test
|
||||||
|
|||||||
+22
@@ -3,7 +3,9 @@ package dev.caskeleton.adapter.inbound.web.auth;
|
|||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
import dev.caskeleton.shared.error.OperationalError;
|
import dev.caskeleton.shared.error.OperationalError;
|
||||||
|
import java.net.ConnectException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.security.access.AccessDeniedException;
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
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.JwtException;
|
||||||
import org.springframework.security.oauth2.jwt.JwtValidationException;
|
import org.springframework.security.oauth2.jwt.JwtValidationException;
|
||||||
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
|
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
|
* feature-security-operational-baseline §구현가이드 3 — the resource-server exception → fine-grained
|
||||||
@@ -148,6 +151,25 @@ class SecurityErrorClassifierTest {
|
|||||||
.isEqualTo(OperationalError.AUTH_KID_UNKNOWN);
|
.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
|
@Test
|
||||||
void jwksEndpointOutageIsJwksUnavailable() {
|
void jwksEndpointOutageIsJwksUnavailable() {
|
||||||
JwtException cause =
|
JwtException cause =
|
||||||
|
|||||||
+39
-9
@@ -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.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
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.mock;
|
||||||
import static org.mockito.Mockito.when;
|
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.AuthorizationPort;
|
||||||
import dev.caskeleton.application.security.AuthorizationPrincipal;
|
import dev.caskeleton.application.security.AuthorizationPrincipal;
|
||||||
import dev.caskeleton.application.security.RequiresPermission;
|
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 dev.caskeleton.shared.security.Permission;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -17,6 +20,7 @@ import java.util.Map;
|
|||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import org.aopalliance.intercept.MethodInvocation;
|
import org.aopalliance.intercept.MethodInvocation;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||||
@@ -79,12 +83,22 @@ class RequiresPermissionAuthorizationManagerTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@DisplayName(
|
||||||
|
"권한이 없으면 Spring 거부 결정이 아니라 AUTHZ_INSUFFICIENT_PERMISSION carrier 를 던진다 — 모든 전송이 같은 코드로 답한다")
|
||||||
void deniesWhenPrincipalLacksRequiredPermission() throws Exception {
|
void deniesWhenPrincipalLacksRequiredPermission() throws Exception {
|
||||||
AuthorizationResult decision =
|
// given
|
||||||
manager.authorize(principalWithRoles("user"), invocationOf("close"));
|
MethodInvocation close = invocationOf("close");
|
||||||
|
|
||||||
assertThat(decision).isNotNull();
|
// when
|
||||||
assertThat(decision.isGranted()).isFalse();
|
Throwable thrown = catchThrowable(() -> manager.authorize(principalWithRoles("user"), close));
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(thrown)
|
||||||
|
.isInstanceOfSatisfying(
|
||||||
|
ApiErrorCarrier.class,
|
||||||
|
carrier ->
|
||||||
|
assertThat(carrier.errorCode())
|
||||||
|
.isEqualTo(OperationalError.AUTHZ_INSUFFICIENT_PERMISSION));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -97,6 +111,7 @@ class RequiresPermissionAuthorizationManagerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void deniesUnauthenticatedRequestFailClosed() throws Exception {
|
void deniesUnauthenticatedRequestFailClosed() throws Exception {
|
||||||
|
// given
|
||||||
Supplier<Authentication> anonymous =
|
Supplier<Authentication> anonymous =
|
||||||
() -> {
|
() -> {
|
||||||
AnonymousAuthenticationToken token =
|
AnonymousAuthenticationToken token =
|
||||||
@@ -106,14 +121,23 @@ class RequiresPermissionAuthorizationManagerTest {
|
|||||||
return token;
|
return token;
|
||||||
};
|
};
|
||||||
|
|
||||||
AuthorizationResult decision = manager.authorize(anonymous, invocationOf("close"));
|
MethodInvocation close = invocationOf("close");
|
||||||
|
|
||||||
assertThat(decision).isNotNull();
|
// when
|
||||||
assertThat(decision.isGranted()).isFalse();
|
Throwable thrown = catchThrowable(() -> manager.authorize(anonymous, close));
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(thrown)
|
||||||
|
.isInstanceOfSatisfying(
|
||||||
|
AuthorizationDeniedException.class,
|
||||||
|
denied ->
|
||||||
|
assertThat(denied.subject())
|
||||||
|
.isEqualTo(RequiresPermissionAuthorizationManager.UNAUTHENTICATED_SUBJECT));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void deniesWhenPrincipalIsNotOurAuthenticatedUser() throws Exception {
|
void deniesWhenPrincipalIsNotOurAuthenticatedUser() throws Exception {
|
||||||
|
// given
|
||||||
Supplier<Authentication> foreignPrincipal =
|
Supplier<Authentication> foreignPrincipal =
|
||||||
() -> {
|
() -> {
|
||||||
TestingAuthenticationToken auth =
|
TestingAuthenticationToken auth =
|
||||||
@@ -122,9 +146,15 @@ class RequiresPermissionAuthorizationManagerTest {
|
|||||||
return auth;
|
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
|
@Test
|
||||||
|
|||||||
+21
-4
@@ -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.http.ApiHeaders;
|
||||||
import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException;
|
import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException;
|
||||||
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
||||||
|
import dev.caskeleton.application.security.AuthorizationDeniedException;
|
||||||
import dev.caskeleton.shared.error.AdapterDisabledException;
|
import dev.caskeleton.shared.error.AdapterDisabledException;
|
||||||
import dev.caskeleton.shared.error.Category;
|
import dev.caskeleton.shared.error.Category;
|
||||||
import dev.caskeleton.shared.error.ClientErrorMessages;
|
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.OperationalError;
|
||||||
import dev.caskeleton.shared.error.PersistenceFailureException;
|
import dev.caskeleton.shared.error.PersistenceFailureException;
|
||||||
import dev.caskeleton.shared.response.Envelope;
|
import dev.caskeleton.shared.response.Envelope;
|
||||||
|
import dev.caskeleton.shared.security.Permission;
|
||||||
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
||||||
import jakarta.validation.ConstraintViolation;
|
import jakarta.validation.ConstraintViolation;
|
||||||
import jakarta.validation.ConstraintViolationException;
|
import jakarta.validation.ConstraintViolationException;
|
||||||
@@ -31,6 +33,7 @@ import java.time.Duration;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.slf4j.MDC;
|
import org.slf4j.MDC;
|
||||||
@@ -375,10 +378,10 @@ class GlobalExceptionHandlerTest {
|
|||||||
assertThat(response.getBody().error().message()).isEqualTo(ClientErrorMessages.OPAQUE);
|
assertThat(response.getBody().error().message()).isEqualTo(ClientErrorMessages.OPAQUE);
|
||||||
}
|
}
|
||||||
|
|
||||||
// feature-authentication-authorization-contract D5/§4: an authorization denial that
|
// feature-authentication-authorization-contract D5/§4: a Spring AccessDeniedException that
|
||||||
// escapes the controller (a @RequiresPermission the caller could not satisfy) reaches this
|
// escapes the controller (one a service throws itself) reaches this controller-advice path. It
|
||||||
// controller-advice path as an AccessDeniedException. It must emit the same fine-grained
|
// must emit the same fine-grained AUTHZ_INSUFFICIENT_PERMISSION code as the filter-layer handler,
|
||||||
// AUTHZ_INSUFFICIENT_PERMISSION code as the filter-layer handler, not a coarse FORBIDDEN.
|
// not a coarse FORBIDDEN. A @RequiresPermission denial is a carrier and is tested below.
|
||||||
@Test
|
@Test
|
||||||
void accessDeniedMapsToFineGrainedInsufficientPermission() {
|
void accessDeniedMapsToFineGrainedInsufficientPermission() {
|
||||||
ResponseEntity<Envelope<Void>> response =
|
ResponseEntity<Envelope<Void>> response =
|
||||||
@@ -393,6 +396,20 @@ class GlobalExceptionHandlerTest {
|
|||||||
assertThat(body.error().retryable()).isFalse();
|
assertThat(body.error().retryable()).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("method security 가 던진 권한 거부 carrier 도 같은 403 AUTHZ_INSUFFICIENT_PERMISSION 이다")
|
||||||
|
void anApplicationAuthorizationDenialAnswersInsufficientPermission() {
|
||||||
|
// when
|
||||||
|
ResponseEntity<Envelope<Void>> response =
|
||||||
|
handler.handleUnknown(
|
||||||
|
new AuthorizationDeniedException("sub-1", Permission.parse("worklog:close")),
|
||||||
|
new ServletWebRequest(new MockHttpServletRequest("POST", "/x")));
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(List.<Object>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
|
// 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
|
// 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
|
// category-derived safe string — the raw diagnostic (SQLState / constraint name) the translator
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ command는 그 유스케이스 안에서 애플리케이션 `IdempotencyExecutor
|
|||||||
|
|
||||||
- `@DomainEvent` 표지를 위한 `:domain-core` 등록 의존.
|
- `@DomainEvent` 표지를 위한 `:domain-core` 등록 의존.
|
||||||
- 저장소 BOM이 관리하는 Spring Boot WebSocket·validation starter.
|
- 저장소 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).
|
- 시험에서만: 내장 Tomcat·Jetty·SockJS·STOMP 클라이언트와 Testcontainers(Nginx lane).
|
||||||
|
|
||||||
## 금지
|
## 금지
|
||||||
@@ -94,6 +97,9 @@ WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에
|
|||||||
ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은
|
ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은
|
||||||
`ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), `IllegalArgumentException`이면 `BAD_PARAMETER`, 그
|
`ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), `IllegalArgumentException`이면 `BAD_PARAMETER`, 그
|
||||||
밖에는 `WEBSOCKET_REQUEST_REJECTED`다.
|
밖에는 `WEBSOCKET_REQUEST_REJECTED`다.
|
||||||
|
- 플랫폼 거부는 거부마다 정한 사유·command만 담은 WARN 한 줄을 남긴다. client가 쓴 값(destination·header·SockJS
|
||||||
|
session id)은 남기지 않는다. SUBSCRIBE가 아닌 거부에 Spring `StompSubProtocolHandler`가 더 남기는 ERROR 줄은 session
|
||||||
|
id를 싣는다(README 「STOMP 채널」).
|
||||||
|
|
||||||
## 이벤트 projection 계약
|
## 이벤트 projection 계약
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,21 @@
|
|||||||
- `/ws`(설정 가능) SockJS endpoint, `/topic` simple broker, `/app` application prefix.
|
- `/ws`(설정 가능) SockJS endpoint, `/topic` simple broker, `/app` application prefix.
|
||||||
- HTTP 계층이 이미 인증한 `Principal`이 있어야 handshake가 통과한다. 이 leaf는 자격 증명을 직접
|
- 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=<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 <session id>:…`을 더
|
||||||
|
남긴다. 그 줄은 SockJS가 client URL에서 받은 session id를 싣는다(끝의 메시지는 고정 코드다). 같은 줄이 채널 포화
|
||||||
|
같은 서버 실패도 남기므로 그 logger를 끄지 않는다. session id를 남기지 않으려면 서비스가 로그 수집 단계에서 그
|
||||||
|
logger의 줄을 가린다.
|
||||||
- SUBSCRIBE는 설정된 broadcast destination 하나만, SEND는 `/app/**`만 허용한다. 클라이언트가
|
- SUBSCRIBE는 설정된 broadcast destination 하나만, SEND는 `/app/**`만 허용한다. 클라이언트가
|
||||||
`/topic/**`으로 직접 보내는 것은 거부한다.
|
`/topic/**`으로 직접 보내는 것은 거부한다.
|
||||||
- 세션 하나에 구독은 하나다. 같은 세션의 두 번째 SUBSCRIBE는 id가 달라도 ERROR 프레임으로
|
- 세션 하나에 구독은 하나다. 같은 세션의 두 번째 SUBSCRIBE는 id가 달라도 ERROR 프레임으로
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ dependencies {
|
|||||||
|
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-websocket'
|
implementation 'org.springframework.boot:spring-boot-starter-websocket'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
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 {
|
testing {
|
||||||
|
|||||||
@@ -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-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-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.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-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-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
|
org.springframework:spring-context:7.0.10=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||||
|
|||||||
+7
-2
@@ -53,6 +53,8 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
|||||||
new SafeStompSubProtocolErrorHandler();
|
new SafeStompSubProtocolErrorHandler();
|
||||||
private final WebSocketInboundAuthorizationInterceptor inboundAuthorization;
|
private final WebSocketInboundAuthorizationInterceptor inboundAuthorization;
|
||||||
private final WebSocketCorrelationInterceptor correlation = new WebSocketCorrelationInterceptor();
|
private final WebSocketCorrelationInterceptor correlation = new WebSocketCorrelationInterceptor();
|
||||||
|
private final WebSocketSecurityContextInterceptor securityContext =
|
||||||
|
new WebSocketSecurityContextInterceptor();
|
||||||
private final StompConnectionLimit connectionLimit;
|
private final StompConnectionLimit connectionLimit;
|
||||||
|
|
||||||
public WebSocketConfig(WebSocketSettings properties) {
|
public WebSocketConfig(WebSocketSettings properties) {
|
||||||
@@ -90,8 +92,11 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void configureClientInboundChannel(ChannelRegistration registration) {
|
public void configureClientInboundChannel(ChannelRegistration registration) {
|
||||||
// Correlation first, so an authorization refusal is logged with the frame's request id.
|
// The authorization refusal runs in preSend, on the thread that received the frame, before
|
||||||
bounded(registration).interceptors(correlation, inboundAuthorization);
|
// 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
|
@Override
|
||||||
|
|||||||
+22
-4
@@ -4,6 +4,8 @@ import java.security.Principal;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.messaging.Message;
|
import org.springframework.messaging.Message;
|
||||||
import org.springframework.messaging.MessageChannel;
|
import org.springframework.messaging.MessageChannel;
|
||||||
import org.springframework.messaging.simp.stomp.StompCommand;
|
import org.springframework.messaging.simp.stomp.StompCommand;
|
||||||
@@ -25,6 +27,9 @@ import org.springframework.messaging.support.MessageHeaderAccessor;
|
|||||||
*/
|
*/
|
||||||
final class WebSocketInboundAuthorizationInterceptor implements ChannelInterceptor {
|
final class WebSocketInboundAuthorizationInterceptor implements ChannelInterceptor {
|
||||||
|
|
||||||
|
private static final Logger log =
|
||||||
|
LoggerFactory.getLogger(WebSocketInboundAuthorizationInterceptor.class);
|
||||||
|
|
||||||
private static final String APPLICATION_PREFIX = "/app/";
|
private static final String APPLICATION_PREFIX = "/app/";
|
||||||
|
|
||||||
private final WebSocketSettings properties;
|
private final WebSocketSettings properties;
|
||||||
@@ -46,14 +51,14 @@ final class WebSocketInboundAuthorizationInterceptor implements ChannelIntercept
|
|||||||
|
|
||||||
StompCommand command = accessor.getCommand();
|
StompCommand command = accessor.getCommand();
|
||||||
if (requiresAuthentication(command) && !hasAuthenticatedPrincipal(accessor.getUser())) {
|
if (requiresAuthentication(command) && !hasAuthenticatedPrincipal(accessor.getUser())) {
|
||||||
throw new WebSocketPolicyViolationException();
|
throw refused("UNAUTHENTICATED", command);
|
||||||
}
|
}
|
||||||
if (command == StompCommand.SUBSCRIBE
|
if (command == StompCommand.SUBSCRIBE
|
||||||
&& !properties.getBroadcastDestination().equals(accessor.getDestination())) {
|
&& !properties.getBroadcastDestination().equals(accessor.getDestination())) {
|
||||||
throw new WebSocketPolicyViolationException();
|
throw refused("SUBSCRIBE_DESTINATION_NOT_ALLOWED", command);
|
||||||
}
|
}
|
||||||
if (command == StompCommand.SUBSCRIBE && !holdSubscription(accessor)) {
|
if (command == StompCommand.SUBSCRIBE && !holdSubscription(accessor)) {
|
||||||
throw new WebSocketPolicyViolationException();
|
throw refused("SUBSCRIPTION_ALREADY_HELD", command);
|
||||||
}
|
}
|
||||||
String sessionId = accessor.getSessionId();
|
String sessionId = accessor.getSessionId();
|
||||||
if (command == StompCommand.UNSUBSCRIBE && sessionId != null) {
|
if (command == StompCommand.UNSUBSCRIBE && sessionId != null) {
|
||||||
@@ -65,11 +70,24 @@ final class WebSocketInboundAuthorizationInterceptor implements ChannelIntercept
|
|||||||
String destination = accessor.getDestination();
|
String destination = accessor.getDestination();
|
||||||
if (command == StompCommand.SEND
|
if (command == StompCommand.SEND
|
||||||
&& (destination == null || !destination.startsWith(APPLICATION_PREFIX))) {
|
&& (destination == null || !destination.startsWith(APPLICATION_PREFIX))) {
|
||||||
throw new WebSocketPolicyViolationException();
|
throw refused("SEND_DESTINATION_NOT_ALLOWED", command);
|
||||||
}
|
}
|
||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs a refusal and returns the signal the error handler turns into the fixed ERROR frame.
|
||||||
|
*
|
||||||
|
* <p>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
|
* 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.
|
* full channel queue rejects it after {@code preSend} — so the client can subscribe again.
|
||||||
|
|||||||
+58
@@ -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.
|
||||||
|
*
|
||||||
|
* <p>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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -1,12 +1,21 @@
|
|||||||
package dev.caskeleton.adapter.inbound.websocket.stomp;
|
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.assertThatCode;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
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 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.security.Principal;
|
||||||
|
import java.util.List;
|
||||||
import org.junit.jupiter.api.DisplayName;
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.messaging.Message;
|
import org.springframework.messaging.Message;
|
||||||
import org.springframework.messaging.MessageChannel;
|
import org.springframework.messaging.MessageChannel;
|
||||||
import org.springframework.messaging.simp.stomp.StompCommand;
|
import org.springframework.messaging.simp.stomp.StompCommand;
|
||||||
@@ -58,6 +67,40 @@ class WebSocketInboundAuthorizationInterceptorTest {
|
|||||||
.hasMessageNotContaining("SECRET_SENTINEL");
|
.hasMessageNotContaining("SECRET_SENTINEL");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("거부마다 정한 사유·command 만 담은 WARN 한 줄을 남기고 client 가 쓴 destination·session id 는 남기지 않는다")
|
||||||
|
void aRefusalLeavesOneWarnLineWithoutTheClientsDestination() {
|
||||||
|
// given
|
||||||
|
Message<byte[]> message =
|
||||||
|
message(StompCommand.SUBSCRIBE, "/topic/SECRET_SENTINEL", AUTHENTICATED);
|
||||||
|
|
||||||
|
// when
|
||||||
|
List<ILoggingEvent> 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<ILoggingEvent> refusalLines(Message<byte[]> message) {
|
||||||
|
Logger logger =
|
||||||
|
(Logger) LoggerFactory.getLogger(WebSocketInboundAuthorizationInterceptor.class);
|
||||||
|
ListAppender<ILoggingEvent> 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
|
@Test
|
||||||
@DisplayName("같은 세션의 두 번째 SUBSCRIBE는 id가 달라도 거부된다")
|
@DisplayName("같은 세션의 두 번째 SUBSCRIBE는 id가 달라도 거부된다")
|
||||||
void aSecondSubscribeFromTheSameSessionIsRejected() {
|
void aSecondSubscribeFromTheSameSessionIsRejected() {
|
||||||
|
|||||||
+92
@@ -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<Authentication> seen = new AtomicReference<>();
|
||||||
|
MessageHandler handler =
|
||||||
|
message -> seen.set(SecurityContextHolder.getContext().getAuthentication());
|
||||||
|
Message<byte[]> 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<Authentication> seen = new AtomicReference<>();
|
||||||
|
MessageHandler handler =
|
||||||
|
message -> seen.set(SecurityContextHolder.getContext().getAuthentication());
|
||||||
|
Message<byte[]> 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<byte[]> frame, MessageHandler handler) {
|
||||||
|
Message<?> intercepted = interceptor.beforeHandle(frame, channel, handler);
|
||||||
|
try {
|
||||||
|
handler.handleMessage(intercepted);
|
||||||
|
} finally {
|
||||||
|
interceptor.afterMessageHandled(frame, channel, handler, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Message<byte[]> 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-12
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.callback;
|
|||||||
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
|
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Profile-to-adapter lookup over a map fixed at assembly time.
|
* 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
|
* composition root still decides the map's contents; what it no longer holds is the lookup, the
|
||||||
* refusal and the limits.
|
* refusal and the limits.
|
||||||
*
|
*
|
||||||
* <p>The other, which the move surfaced: {@link #require} runs <em>per callback request</em>, not
|
* <p>The other, which the move surfaced: {@link #find} runs <em>per callback request</em>, not at
|
||||||
* at startup. While it lived in bootstrap it was briefly migrated to the startup-failure factory
|
* startup. While it lived in bootstrap it was briefly migrated to the startup-failure factory along
|
||||||
* along with that leaf's genuine startup guards, which would have classified an unknown profile in
|
* with that leaf's genuine startup guards, which would have classified an unknown profile in an
|
||||||
* an inbound request as a configuration error carrying a JVM exit code. Here the contract is the
|
* inbound request as a configuration error carrying a JVM exit code. An unknown profile is not a
|
||||||
* one the interface documents and every sibling {@code require(...)} registry in this repository
|
* server failure either: it used to be an {@code IllegalStateException}, which the web error
|
||||||
* uses.
|
* 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.
|
||||||
*
|
*
|
||||||
* <p>Refusing an unknown profile is a security property rather than a convenience: an endpoint that
|
* <p>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.
|
* accepted any profile name would let a caller choose which signature check runs.
|
||||||
@@ -43,13 +45,9 @@ public final class MapProviderCallbackAdapterRegistry implements ProviderCallbac
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ProviderCallbackAdapter require(ProviderProfileId profileId) {
|
public Optional<ProviderCallbackAdapter> find(ProviderProfileId profileId) {
|
||||||
Objects.requireNonNull(profileId, "profileId");
|
Objects.requireNonNull(profileId, "profileId");
|
||||||
ProviderCallbackAdapter adapter = byProfile.get(profileId);
|
return Optional.ofNullable(byProfile.get(profileId));
|
||||||
if (adapter == null) {
|
|
||||||
throw new IllegalStateException("no callback adapter registered for the profile");
|
|
||||||
}
|
|
||||||
return adapter;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+8
-1
@@ -1,13 +1,20 @@
|
|||||||
package dev.caskeleton.adapter.outbound.notification.platform.callback;
|
package dev.caskeleton.adapter.outbound.notification.platform.callback;
|
||||||
|
|
||||||
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
|
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Profile-to-provider callback verifier registry assembled by the outbound notification adapter.
|
* Profile-to-provider callback verifier registry assembled by the outbound notification adapter.
|
||||||
*/
|
*/
|
||||||
public interface ProviderCallbackAdapterRegistry {
|
public interface ProviderCallbackAdapterRegistry {
|
||||||
|
|
||||||
ProviderCallbackAdapter require(ProviderProfileId profileId);
|
/**
|
||||||
|
* The adapter of a profile this deployment configured, or empty for any other profile.
|
||||||
|
*
|
||||||
|
* <p>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<ProviderCallbackAdapter> find(ProviderProfileId profileId);
|
||||||
|
|
||||||
CallbackLimits limitsFor(ProviderProfileId profileId);
|
CallbackLimits limitsFor(ProviderProfileId profileId);
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -313,7 +313,7 @@ class NotificationProviderAssemblyTest {
|
|||||||
new NotificationPlatformRegistriesConfig()
|
new NotificationPlatformRegistriesConfig()
|
||||||
.providerCallbackAdapterRegistry(platform, settings);
|
.providerCallbackAdapterRegistry(platform, settings);
|
||||||
|
|
||||||
assertThat(registry.require(new ProviderProfileId("ses-events")).providerId())
|
assertThat(registry.find(new ProviderProfileId("ses-events")).orElseThrow().providerId())
|
||||||
.isEqualTo(new ProviderId("ses"));
|
.isEqualTo(new ProviderId("ses"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -238,9 +238,10 @@ application/domain 을 프레임워크-free 로 유지하는 핵심 장치.
|
|||||||
|
|
||||||
- 인증된 호출자가 필요한 `Permission` 을 못 가졌을 때 `AuthorizationPort` 가 던진다.
|
- 인증된 호출자가 필요한 `Permission` 을 못 가졌을 때 `AuthorizationPort` 가 던진다.
|
||||||
- **프레임워크-free, application 소유**: application 계층은 Spring Security 에 의존할 수 없어
|
- **프레임워크-free, application 소유**: application 계층은 Spring Security 에 의존할 수 없어
|
||||||
Spring `AccessDeniedException` 을 던질 수 없다. web adapter 의 method-security enforcement
|
Spring `AccessDeniedException` 을 던질 수 없다. 대신 이 예외가 `ApiErrorCarrier`로
|
||||||
point 가 경계에서 이 예외를 잡아 Spring authorization 실패로 번역하고, error pipeline 이
|
`AUTHZ_INSUFFICIENT_PERMISSION`을 싣는다. web adapter 의 method-security enforcement point 는 이 예외를
|
||||||
`AUTHZ_INSUFFICIENT_PERMISSION` 403 으로 매핑한다(코드 SSOT 는 베이스라인 소유).
|
Spring 실패로 바꾸지 않고 그대로 내보낸다. 그래서 web(403)·gRPC(`PERMISSION_DENIED`)·GraphQL(`FORBIDDEN`)이 같은
|
||||||
|
코드로 답한다. STOMP `@MessageMapping` 안의 거부는 frame을 보내지 않고, 4xx carrier라 로그도 남기지 않는다.
|
||||||
- **fail-closed**: denial 은 필요한 권한과 호출자 subject 만 담고, 호출자의 *유효 권한 집합* 은
|
- **fail-closed**: denial 은 필요한 권한과 호출자 subject 만 담고, 호출자의 *유효 권한 집합* 은
|
||||||
절대 담지 않는다(인가 표면을 클라이언트에 노출하지 않기 위함).
|
절대 담지 않는다(인가 표면을 클라이언트에 노출하지 않기 위함).
|
||||||
|
|
||||||
@@ -685,7 +686,7 @@ leaf의 코드 Javadoc과 `docs/notification/`이 정본이다. R1 오케스트
|
|||||||
| `messaging.event.ValidatedIntegrationEvent` | 안정된 semantic identity와 바뀌지 않는 정확한 인코딩 바이트·hash. 뒤의 durable append 경계로 넘길 준비가 된 값이다. |
|
| `messaging.event.ValidatedIntegrationEvent` | 안정된 semantic identity와 바뀌지 않는 정확한 인코딩 바이트·hash. 뒤의 durable append 경계로 넘길 준비가 된 값이다. |
|
||||||
| `messaging.event.IntegrationEventEncoderPort` | 프레임워크 없는 로컬 경계(초안 → 검증된 이벤트). outbound 어댑터가 구현한다(템플릿은 `adapter:outbound:support`의 `JsonIntegrationEventEncoder`). |
|
| `messaging.event.IntegrationEventEncoderPort` | 프레임워크 없는 로컬 경계(초안 → 검증된 이벤트). outbound 어댑터가 구현한다(템플릿은 `adapter:outbound:support`의 `JsonIntegrationEventEncoder`). |
|
||||||
| `outbox.OutboxAppendPort` | 유일한 outbox append: `ValidatedIntegrationEvent` 하나를 호출자의 쓰기 트랜잭션 안에서 넣는다. |
|
| `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)
|
### 패키지 소유 (Package ownership)
|
||||||
|
|
||||||
|
|||||||
+18
-4
@@ -1,15 +1,24 @@
|
|||||||
package dev.caskeleton.application.security;
|
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;
|
import dev.caskeleton.shared.security.Permission;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Raised by {@link AuthorizationPort} when an authenticated caller lacks a required {@link
|
* 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
|
* 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}
|
* AccessDeniedException}). Fail-closed: it carries the required permission and subject for
|
||||||
* 403. Fail-closed: it carries the required permission and subject for diagnostics, never the
|
* diagnostics, never the caller's effective permission set. See README.
|
||||||
* caller's effective permission set. See README.
|
*
|
||||||
|
* <p>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;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@@ -27,6 +36,11 @@ public class AuthorizationDeniedException extends RuntimeException {
|
|||||||
this.requiredPermission = requiredPermission;
|
this.requiredPermission = requiredPermission;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ApiErrorCode errorCode() {
|
||||||
|
return OperationalError.AUTHZ_INSUFFICIENT_PERMISSION;
|
||||||
|
}
|
||||||
|
|
||||||
public Permission requiredPermission() {
|
public Permission requiredPermission() {
|
||||||
return requiredPermission;
|
return requiredPermission;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
package dev.caskeleton.application.tenant;
|
package dev.caskeleton.application.tenant;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,6 +33,9 @@ public record TenantId(String value) {
|
|||||||
|
|
||||||
private static final Pattern PATTERN = Pattern.compile(GRAMMAR);
|
private static final Pattern PATTERN = Pattern.compile(GRAMMAR);
|
||||||
|
|
||||||
|
/** {@link #namesATenant} names, folded: lower case, no {@code -} or {@code _}. */
|
||||||
|
private static final Set<String> TENANT_INPUT_NAMES = Set.of("tenant", "tenantid", "xtenantid");
|
||||||
|
|
||||||
public TenantId {
|
public TenantId {
|
||||||
if (value == null || !PATTERN.matcher(value).matches()) {
|
if (value == null || !PATTERN.matcher(value).matches()) {
|
||||||
throw new IllegalArgumentException("tenant identifier must match " + GRAMMAR);
|
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));
|
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.
|
||||||
|
*
|
||||||
|
* <p>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<String> 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
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return value;
|
return value;
|
||||||
|
|||||||
+22
@@ -74,4 +74,26 @@ class TenantIdTest {
|
|||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessage("tenant identifier must match " + TenantId.GRAMMAR);
|
.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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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-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.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-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-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,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-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-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
|
org.springframework.security:spring-security-oauth2-jose:7.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
|
||||||
|
|||||||
+15
-3
@@ -26,8 +26,14 @@ import org.springframework.core.env.ConfigurableEnvironment;
|
|||||||
* <p>Scoped to the deployable artifact, which means contexts whose main class is {@link
|
* <p>Scoped to the deployable artifact, which means contexts whose main class is {@link
|
||||||
* dev.caskeleton.bootstrap.CaSkeletonApplication}. Slice tests boot minimal applications with no
|
* 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
|
* 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}
|
* this validator a tax on every test that does not care where it is running.
|
||||||
* profile is exempt for the same reason from the other direction.
|
*
|
||||||
|
* <p>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 {
|
public class RuntimeEnvironmentProfileValidator implements EnvironmentPostProcessor, Ordered {
|
||||||
|
|
||||||
@@ -48,7 +54,13 @@ public class RuntimeEnvironmentProfileValidator implements EnvironmentPostProces
|
|||||||
List<String> active = profiles.activeProfiles();
|
List<String> active = profiles.activeProfiles();
|
||||||
|
|
||||||
if (profiles.isTestContext()) {
|
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()) {
|
if (active.isEmpty()) {
|
||||||
throw StartupFailures.envValidation(
|
throw StartupFailures.envValidation(
|
||||||
|
|||||||
+16
-4
@@ -2,9 +2,13 @@ package dev.caskeleton.bootstrap.runtime;
|
|||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
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.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
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.boot.SpringApplication;
|
||||||
import org.springframework.mock.env.MockEnvironment;
|
import org.springframework.mock.env.MockEnvironment;
|
||||||
|
|
||||||
@@ -51,10 +55,18 @@ class RuntimeEnvironmentProfileValidatorTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@ParameterizedTest
|
||||||
@DisplayName("a test-source context may run under test")
|
@ValueSource(strings = {"test", "prod,test", "TEST"})
|
||||||
void aTestContextIsExempt() {
|
@DisplayName("배포 산출물은 test profile 로 뜨지 않는다 — 운영 검사가 모두 꺼지기 때문이다")
|
||||||
validate("test");
|
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
|
@Test
|
||||||
|
|||||||
+8
-1
@@ -48,6 +48,14 @@ final class ProviderCallbackIngressBridge implements ProviderCallbackIngress {
|
|||||||
public CallbackIngestionResult ingest(ProviderCallbackHttpRequest request) {
|
public CallbackIngestionResult ingest(ProviderCallbackHttpRequest request) {
|
||||||
Objects.requireNonNull(request, "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());
|
CallbackLimits limits = adapters.limitsFor(request.providerProfileId());
|
||||||
if (request.bodyLength() > limits.maxBodyBytes()) {
|
if (request.bodyLength() > limits.maxBodyBytes()) {
|
||||||
securityAudit.callbackRejectedByLimit(request.providerProfileId(), "BODY_TOO_LARGE");
|
securityAudit.callbackRejectedByLimit(request.providerProfileId(), "BODY_TOO_LARGE");
|
||||||
@@ -58,7 +66,6 @@ final class ProviderCallbackIngressBridge implements ProviderCallbackIngress {
|
|||||||
throw rejected(NotificationFailureCode.CALLBACK_PAYLOAD_REJECTED);
|
throw rejected(NotificationFailureCode.CALLBACK_PAYLOAD_REJECTED);
|
||||||
}
|
}
|
||||||
|
|
||||||
ProviderCallbackAdapter adapter = adapters.require(request.providerProfileId());
|
|
||||||
if (!adapter.providerId().equals(request.providerId())) {
|
if (!adapter.providerId().equals(request.providerId())) {
|
||||||
securityAudit.callbackRejectedByLimit(
|
securityAudit.callbackRejectedByLimit(
|
||||||
request.providerProfileId(), "PROVIDER_PROFILE_MISMATCH");
|
request.providerProfileId(), "PROVIDER_PROFILE_MISMATCH");
|
||||||
|
|||||||
+33
-2
@@ -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.ProviderId;
|
||||||
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
|
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.CallbackValidationException;
|
||||||
|
import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode;
|
||||||
import dev.caskeleton.application.notification.platform.observation.NotificationSecurityAuditPort;
|
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.IngestProviderCallbackCommand;
|
||||||
import dev.caskeleton.application.notification.platform.port.in.IngestProviderCallbackUseCase;
|
import dev.caskeleton.application.notification.platform.port.in.IngestProviderCallbackUseCase;
|
||||||
@@ -193,6 +194,36 @@ class ProviderCallbackIngressBridgeTest {
|
|||||||
.containsExactly(CallbackIngressUnavailableException.class, List.of(), List.of());
|
.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
|
@Test
|
||||||
void rawHttpLimitsAreEnforcedBeforeTheProviderAdapterRuns() {
|
void rawHttpLimitsAreEnforcedBeforeTheProviderAdapterRuns() {
|
||||||
RecordingAdapter adapter = new RecordingAdapter(TWILIO, true);
|
RecordingAdapter adapter = new RecordingAdapter(TWILIO, true);
|
||||||
@@ -215,8 +246,8 @@ class ProviderCallbackIngressBridgeTest {
|
|||||||
ProviderCallbackAdapterRegistry registry =
|
ProviderCallbackAdapterRegistry registry =
|
||||||
new ProviderCallbackAdapterRegistry() {
|
new ProviderCallbackAdapterRegistry() {
|
||||||
@Override
|
@Override
|
||||||
public ProviderCallbackAdapter require(ProviderProfileId profileId) {
|
public Optional<ProviderCallbackAdapter> find(ProviderProfileId profileId) {
|
||||||
return adapter;
|
return Optional.of(adapter);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
Reference in New Issue
Block a user