fix(graphql)!: cursor·connection 거부와 STOMP 오류 frame을 등록된 코드로 답한다
pr / done (pull_request) Canceled after 0s

GraphQL cursor·connection 예외는 Javadoc이 「안정 요청 오류 코드」라면서
플랫폼 거부가 아니라 INTERNAL_ERROR와 ERROR 로그가 된다. STOMP ERROR
frame은 code만 싣고, 원인 사슬 어디에 IllegalArgumentException이 있든
BAD_PARAMETER로 본다(다른 전송은 실패 자신만 본다). STOMP broadcast는 모든
인증 세션에 가는데 projector가 무엇을 실어도 되는지 규칙이 없다.
maxInputListElements Javadoc은 실제보다 넓은 상한을 약속한다.

- 두 예외를 GraphQlPlatformRejection으로 만들고 GRAPHQL_CURSOR_REJECTED·
  GRAPHQL_CONNECTION_REJECTED를 catalog에 더한다.
- STOMP 오류 처리기는 MessagingException 포장을 벗긴 실패 자신만 IAE로
  보고, 등록된 코드면 error-category·error-retryable header를 더한다(gRPC
  trailer와 같은 이름·값).
- broadcast 규칙(모든 tenant의 인증 사용자가 읽어도 되는 것만)을
  projector Javadoc·README·AGENTS에 적는다. 버린 안: destination을
  tenant별로 나누기(projector가 tenant를 모르고, simple broker는 R1
  증거라 범위 밖).
- maxInputListElements Javadoc을 실제 검사 범위로 좁힌다.

위험: client가 보는 GraphQL 코드와 STOMP header가 바뀐다.
docs/upgrade/2026-11-round9-authz.md 12~13행.

검증: desktop :adapter:inbound:graphql:check·systemTest,
:adapter:inbound:websocket:check·systemTest rc=0(묶음 전체 실행).

Refs: RR9-02-19, RR9-02-31, RR9-03-14, RR9-03-29
BREAKING CHANGE: GraphQL cursor·connection 거부 코드와 STOMP ERROR frame의
  error-code(묻힌 IAE)·새 header. docs/upgrade/2026-11-round9-authz.md 12~13행.
This commit is contained in:
DongHyeonka
2026-11-13 12:24:54 +09:00
parent 2f0aefadee
commit 01caee3c01
14 changed files with 205 additions and 33 deletions
+8 -3
View File
@@ -1,8 +1,9 @@
# 업그레이드 안내 — 2026-11 인증·인가와 GraphQL·WebSocket 계약 # 업그레이드 안내 — 2026-11 인증·인가와 GraphQL·WebSocket 계약
- 범위: 2026-11-12 전체 리뷰의 인증·인가 묶음을 고친 변경. JWT 역할·claim 대응, JWKS 재조회 실패의 분류, 배포 - 범위: 2026-11-12 전체 리뷰의 인증·인가 묶음과 GraphQL·WebSocket 계약 묶음을 고친 변경. JWT 역할·claim 대응, JWKS 재조회 실패의 분류, 배포
산출물의 profile 검사, 알림 callback, GraphQL 인가·tenant, 전송별 권한 판정이 바뀌었다. 산출물의 profile 검사, 알림 callback, GraphQL 인가·tenant·오류 코드, 전송별 권한 판정, STOMP 오류 frame이 바뀌었다.
- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 RR9-02-02·16·17·18·20·23·25·28·29 - 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 RR9-02-02·16·17·18·19·20·23·25·28·29·31,
RR9-03-14·29
## 1. 누가 읽나 ## 1. 누가 읽나
@@ -24,8 +25,12 @@
| 9 | tenant를 제안하는 입력 이름을 web-advanced와 GraphQL이 같은 어휘로 거부한다(`tenant`, `tenant_id`, `tenantId`, `X-Tenant-Id`, 대소문자·`-`·`_` 무관) | 그런 이름의 header·parameter·argument를 쓰던 client를 고친다 | 403 `TENANT_INPUT_UNTRUSTED`나 GraphQL tenant 거부가 난다 | tenant 입력 검사를 쓰는 서비스 | | 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 | | 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 | | 11 | 알림 callback: 설정하지 않은 profile로 온 callback은 400이다(전에는 500과 ERROR 로그). `ProviderCallbackAdapterRegistry.require`가 `find`(`Optional`)로 바뀌었다 | registry를 직접 구현한 서비스는 `find`를 구현한다 | 컴파일이 실패한다 | 알림 platform |
| 12 | GraphQL cursor·connection 거부가 `GRAPHQL_CURSOR_REJECTED`·`GRAPHQL_CONNECTION_REJECTED` 요청 오류다(전에는 `INTERNAL_ERROR`와 ERROR 로그) | client가 그 코드로 분기하게 한다 | — | GraphQL pagination API를 쓰는 서비스 |
| 13 | STOMP ERROR frame: 다른 실패의 원인으로 묻힌 `IllegalArgumentException`은 `BAD_PARAMETER`가 아니라 `WEBSOCKET_REQUEST_REJECTED`다. 모든 ERROR frame에 `error-retryable` header가 붙고, 등록된 코드면 `error-category`도 붙는다 | client가 새 header를 읽게 한다 | — | STOMP client |
## 3. 바뀌지 않은 것 ## 3. 바뀌지 않은 것
- web의 403 응답(`AUTHZ_INSUFFICIENT_PERMISSION`), 401 응답 모양, `WWW-Authenticate`는 그대로다. - web의 403 응답(`AUTHZ_INSUFFICIENT_PERMISSION`), 401 응답 모양, `WWW-Authenticate`는 그대로다.
- `@RequiresPermission`·역할 매핑 설정 키는 그대로다. - `@RequiresPermission`·역할 매핑 설정 키는 그대로다.
- STOMP broadcast는 여전히 destination 하나로 모든 인증된 세션에 간다. 그래서 `LiveEventProjector`는 모든 tenant의 인증된
사용자가 읽어도 되는 것만 싣는다(`src/adapter/inbound/websocket/README.md` 「한계」). 이 규칙을 이번에 문서로 적었다.
+2 -1
View File
@@ -70,7 +70,8 @@ required-class 검사가 이 테스트가 조용히 사라지는 것을 막는
- GraphQL이 가진 새 플랫폼 코드는 `GRAPHQL_` 접두어를 쓴다. 접두어 없는 기존 플랫폼 값은 얼려 둔 옛 wire - GraphQL이 가진 새 플랫폼 코드는 `GRAPHQL_` 접두어를 쓴다. 접두어 없는 기존 플랫폼 값은 얼려 둔 옛 wire
계약이고 `legacyUnprefixedPlatformCodes()`가 하나씩 적는다. 계약이고 `legacyUnprefixedPlatformCodes()`가 하나씩 적는다.
- 모델만 있는 capability 코드는 그 capability가 출하하는 요청 경로에 닿기 전까지 `platformCodes()`에 - 모델만 있는 capability 코드는 그 capability가 출하하는 요청 경로에 닿기 전까지 `platformCodes()`에
더하지 않는다. 더하지 않는다. 서비스 resolver가 부르는 라이브러리(`pagination/`의 cursor·connection)의 거부 코드는 더한다. resolver
안에서 던져지면 그 요청의 오류로 wire에 닿기 때문이다.
`GraphQlErrorCodeCatalogTest`가 출하하는 catalog 전체, 접두어 규칙, application·플랫폼 namespace 분리를 `GraphQlErrorCodeCatalogTest`가 출하하는 catalog 전체, 접두어 규칙, application·플랫폼 namespace 분리를
고정한다. 고정한다.
@@ -47,6 +47,10 @@ public record GraphQlErrorCode(String value) {
/** A DataLoader key declared always resolvable had no row. */ /** A DataLoader key declared always resolvable had no row. */
public static final String GRAPHQL_BATCH_KEY_MISSING = "GRAPHQL_BATCH_KEY_MISSING"; public static final String GRAPHQL_BATCH_KEY_MISSING = "GRAPHQL_BATCH_KEY_MISSING";
public static final String GRAPHQL_CURSOR_REJECTED = "GRAPHQL_CURSOR_REJECTED";
public static final String GRAPHQL_CONNECTION_REJECTED = "GRAPHQL_CONNECTION_REJECTED";
private static final Set<String> LEGACY_UNPREFIXED_PLATFORM_CODES = private static final Set<String> LEGACY_UNPREFIXED_PLATFORM_CODES =
Set.of( Set.of(
INTERNAL_ERROR, INTERNAL_ERROR,
@@ -69,7 +73,9 @@ public record GraphQlErrorCode(String value) {
GRAPHQL_DOCUMENT_SHAPE_REJECTED, GRAPHQL_DOCUMENT_SHAPE_REJECTED,
GRAPHQL_COMPLEXITY_EXCEEDED, GRAPHQL_COMPLEXITY_EXCEEDED,
GRAPHQL_OPERATION_NAME_REQUIRED, GRAPHQL_OPERATION_NAME_REQUIRED,
GRAPHQL_BATCH_KEY_MISSING); GRAPHQL_BATCH_KEY_MISSING,
GRAPHQL_CURSOR_REJECTED,
GRAPHQL_CONNECTION_REJECTED);
private static final Pattern PATTERN = Pattern.compile("[A-Z][A-Z0-9_]{2,63}"); private static final Pattern PATTERN = Pattern.compile("[A-Z][A-Z0-9_]{2,63}");
@@ -1,11 +1,16 @@
package dev.caskeleton.adapter.inbound.graphql.pagination; package dev.caskeleton.adapter.inbound.graphql.pagination;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/** /**
* Raised when connection arguments are invalid or contradictory. * Raised when connection arguments are invalid or contradictory.
* *
* <p>Carries the rule that was broken, never the cursor. * <p>Carries the rule that was broken, never the cursor.
*/ */
public class GraphQlConnectionException extends RuntimeException { public class GraphQlConnectionException extends RuntimeException
implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@@ -25,4 +30,20 @@ public class GraphQlConnectionException extends RuntimeException {
public String code() { public String code() {
return CODE; return CODE;
} }
/**
* {@code GRAPHQL_CONNECTION_REJECTED} on the wire, as a request error: connection arguments the
* client sent is wrong, and retrying it unchanged fails the same way. A resolver that used the
* pagination API used to let it through as a masked {@code INTERNAL_ERROR} with an ERROR line,
* although this class named the code a stable request-error code (review 2026-11-12).
*/
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(CODE);
}
@Override
public Category failureCategory() {
return Category.VALIDATION;
}
} }
@@ -1,5 +1,9 @@
package dev.caskeleton.adapter.inbound.graphql.pagination; package dev.caskeleton.adapter.inbound.graphql.pagination;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection;
import dev.caskeleton.shared.error.Category;
/** /**
* Raised when a cursor is unusable: unknown version, unknown key, bad signature, or a different * Raised when a cursor is unusable: unknown version, unknown key, bad signature, or a different
* query profile or filter than it was issued for. * query profile or filter than it was issued for.
@@ -7,7 +11,7 @@ package dev.caskeleton.adapter.inbound.graphql.pagination;
* <p>Every rejection carries the same shape of message and no cursor content, so a caller cannot * <p>Every rejection carries the same shape of message and no cursor content, so a caller cannot
* probe which part of a forged cursor was wrong. * probe which part of a forged cursor was wrong.
*/ */
public class GraphQlCursorException extends RuntimeException { public class GraphQlCursorException extends RuntimeException implements GraphQlPlatformRejection {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@@ -27,4 +31,20 @@ public class GraphQlCursorException extends RuntimeException {
public String code() { public String code() {
return CODE; return CODE;
} }
/**
* {@code GRAPHQL_CURSOR_REJECTED} on the wire, as a request error: a cursor the client sent is
* wrong, and retrying it unchanged fails the same way. A resolver that used the pagination API
* used to let it through as a masked {@code INTERNAL_ERROR} with an ERROR line, although this
* class named the code a stable request-error code (review 2026-11-12).
*/
@Override
public GraphQlErrorCode wireCode() {
return GraphQlErrorCode.platform(CODE);
}
@Override
public Category failureCategory() {
return Category.VALIDATION;
}
} }
@@ -21,7 +21,11 @@ import java.time.Duration;
* @param maxAliases most accepted aliases, counted separately so an alias bomb cannot hide behind a * @param maxAliases most accepted aliases, counted separately so an alias bomb cannot hide behind a
* small depth * small depth
* @param maxFragments most accepted fragment definitions * @param maxFragments most accepted fragment definitions
* @param maxInputListElements most accepted elements in one input list * @param maxInputListElements most accepted elements in one JSON array, and keys in one JSON
* object, of the request's {@code variables} and {@code extensions} ({@code
* GraphQlJsonStructurePolicy}). A list written inline in the document is not counted against
* it; the document's size bounds it ({@code maxDocumentBytes}). This used to read "one input
* list", which an inline list is too (review 2026-11-12)
* @param defaultPageSize page size used for cost when a connection omits {@code first}/{@code last} * @param defaultPageSize page size used for cost when a connection omits {@code first}/{@code last}
* @param maxPageSize largest accepted page size. This record only holds the two numbers; the page a * @param maxPageSize largest accepted page size. This record only holds the two numbers; the page a
* resolver serves is decided by {@code GraphQlConnectionPolicy.effectivePageSize} and the page * resolver serves is decided by {@code GraphQlConnectionPolicy.effectivePageSize} and the page
@@ -8,6 +8,7 @@ import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitExcepti
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlAnonymousOperationException; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlAnonymousOperationException;
import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnectionException;
import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException; import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException;
import java.util.Set; import java.util.Set;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -28,7 +29,9 @@ class GraphQlErrorCodeCatalogTest {
GraphQlErrorCode.GRAPHQL_DOCUMENT_SHAPE_REJECTED, GraphQlErrorCode.GRAPHQL_DOCUMENT_SHAPE_REJECTED,
GraphQlErrorCode.GRAPHQL_COMPLEXITY_EXCEEDED, GraphQlErrorCode.GRAPHQL_COMPLEXITY_EXCEEDED,
GraphQlErrorCode.GRAPHQL_OPERATION_NAME_REQUIRED, GraphQlErrorCode.GRAPHQL_OPERATION_NAME_REQUIRED,
GraphQlErrorCode.GRAPHQL_BATCH_KEY_MISSING); GraphQlErrorCode.GRAPHQL_BATCH_KEY_MISSING,
GraphQlErrorCode.GRAPHQL_CURSOR_REJECTED,
GraphQlErrorCode.GRAPHQL_CONNECTION_REJECTED);
assertThat(GraphQlMissingKeyException.CODE) assertThat(GraphQlMissingKeyException.CODE)
.isEqualTo(GraphQlErrorCode.GRAPHQL_BATCH_KEY_MISSING); .isEqualTo(GraphQlErrorCode.GRAPHQL_BATCH_KEY_MISSING);
@@ -38,6 +41,9 @@ class GraphQlErrorCodeCatalogTest {
.isEqualTo(GraphQlErrorCode.GRAPHQL_COMPLEXITY_EXCEEDED); .isEqualTo(GraphQlErrorCode.GRAPHQL_COMPLEXITY_EXCEEDED);
assertThat(GraphQlAnonymousOperationException.CODE) assertThat(GraphQlAnonymousOperationException.CODE)
.isEqualTo(GraphQlErrorCode.GRAPHQL_OPERATION_NAME_REQUIRED); .isEqualTo(GraphQlErrorCode.GRAPHQL_OPERATION_NAME_REQUIRED);
assertThat(GraphQlCursorException.CODE).isEqualTo(GraphQlErrorCode.GRAPHQL_CURSOR_REJECTED);
assertThat(GraphQlConnectionException.CODE)
.isEqualTo(GraphQlErrorCode.GRAPHQL_CONNECTION_REJECTED);
} }
@Test @Test
@@ -56,8 +62,7 @@ class GraphQlErrorCodeCatalogTest {
// loader-level cause for logs, not a separate thing a client should branch on. // loader-level cause for logs, not a separate thing a client should branch on.
@Test @Test
void modelledOnlyCapabilityCodesDoNotPretendToBeShippedWireCodes() { void modelledOnlyCapabilityCodesDoNotPretendToBeShippedWireCodes() {
assertThat(GraphQlErrorCode.platformCodes()) assertThat(GraphQlErrorCode.platformCodes()).doesNotContain(GraphQlBatchTimeoutException.CODE);
.doesNotContain(GraphQlBatchTimeoutException.CODE, GraphQlCursorException.CODE);
} }
@Test @Test
@@ -9,6 +9,8 @@ import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnectionException;
import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException;
import dev.caskeleton.application.idempotency.IdempotencyInFlightException; import dev.caskeleton.application.idempotency.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;
@@ -35,6 +37,12 @@ class GraphQlWireErrorMapperTest {
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 GraphQlCursorException("bad signature"), "GRAPHQL_CURSOR_REJECTED", "REQUEST"),
Arguments.of(
new GraphQlConnectionException("first and last together"),
"GRAPHQL_CONNECTION_REJECTED",
"REQUEST"),
Arguments.of( Arguments.of(
new AuthorizationDeniedException("sub-1", Permission.parse("order:read")), new AuthorizationDeniedException("sub-1", Permission.parse("order:read")),
"AUTHZ_INSUFFICIENT_PERMISSION", "AUTHZ_INSUFFICIENT_PERMISSION",
@@ -43,7 +51,8 @@ class GraphQlWireErrorMapperTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("failuresWithTheirOwnCode") @MethodSource("failuresWithTheirOwnCode")
@DisplayName("요청·DataLoader 의 timeout·missing key, 권한 거부는 INTERNAL_ERROR 로 가려지지 않고 자기 code 로 나간다") @DisplayName(
"요청·DataLoader 의 timeout·missing key, cursor·connection 거부, 권한 거부는 INTERNAL_ERROR 로 가려지지 않고 자기 code 로 나간다")
void aFailureWithItsOwnCodeIsNotMaskedAsInternalError( void aFailureWithItsOwnCodeIsNotMaskedAsInternalError(
RuntimeException failure, String expectedCode, String expectedCategory) { RuntimeException failure, String expectedCode, String expectedCategory) {
// given // given
+5 -3
View File
@@ -95,8 +95,9 @@ WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에
- 클라이언트가 `/topic/**`나 다른 destination으로 보내는 `SEND`는 거절한다. - 클라이언트가 `/topic/**`나 다른 destination으로 보내는 `SEND`는 거절한다.
- 클라이언트에게 보이는 처리 실패는 모두 빈 payload와 정해진 `message` `WEBSOCKET_REQUEST_REJECTED`를 가진 - 클라이언트에게 보이는 처리 실패는 모두 빈 payload와 정해진 `message` `WEBSOCKET_REQUEST_REJECTED`를 가진
ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은 ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은
`ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), `IllegalArgumentException`이면 `BAD_PARAMETER`, 그 `ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), 실패 자신(Spring `MessagingException` 포장 안)이
밖에는 `WEBSOCKET_REQUEST_REJECTED`다. `IllegalArgumentException`이면 `BAD_PARAMETER`, 그 밖에는 `WEBSOCKET_REQUEST_REJECTED`다. 등록된 코드는
`error-category`·`error-retryable`도 싣는다.
- 플랫폼 거부는 거부마다 정한 사유·command만 담은 WARN 한 줄을 남긴다. client가 쓴 값(destination·header·SockJS - 플랫폼 거부는 거부마다 정한 사유·command만 담은 WARN 한 줄을 남긴다. client가 쓴 값(destination·header·SockJS
session id)은 남기지 않는다. SUBSCRIBE가 아닌 거부에 Spring `StompSubProtocolHandler`가 더 남기는 ERROR 줄은 session session id)은 남기지 않는다. SUBSCRIBE가 아닌 거부에 Spring `StompSubProtocolHandler`가 더 남기는 ERROR 줄은 session
id를 싣는다(README 「STOMP 채널」). id를 싣는다(README 「STOMP 채널」).
@@ -106,7 +107,8 @@ WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에
나중의 기능이 정확히 하나의 `@DomainEvent` 클래스에 대해 `LiveEventProjector<T>` bean을 기여할 수 있다. 나중의 기능이 정확히 하나의 `@DomainEvent` 클래스에 대해 `LiveEventProjector<T>` bean을 기여할 수 있다.
broadcaster는 projector가 정확히 하나 맞을 때만 보낸다. projector가 없거나 둘 이상이거나, projection이 broadcaster는 projector가 정확히 하나 맞을 때만 보낸다. projector가 없거나 둘 이상이거나, projection이
실패하거나, 이벤트 타입이 잘못됐거나, 필드가 null이거나, map이 한계를 넘으면 버린다. wire envelope에는 실패하거나, 이벤트 타입이 잘못됐거나, 필드가 null이거나, map이 한계를 넘으면 버린다. wire envelope에는
`type`, 한계 있는 문자열 `fields`, `occurredAt`만 있다. broker 채널은 자기 한계 있는 executor를 가지므로, `type`, 한계 있는 문자열 `fields`, `occurredAt`만 있다. 이벤트는 구독한 인증된 세션 모두에게 tenant·소유자
구분 없이 간다. 그래서 projector는 모든 tenant의 인증된 사용자 누구나 읽어도 되는 것만 싣는다(근거 README 「한계」). broker 채널은 자기 한계 있는 executor를 가지므로,
simple broker가 구독자에게 퍼뜨리는 일은 도메인 이벤트를 발행한 스레드에서 돌지 않는다. broker queue가 차면 simple broker가 구독자에게 퍼뜨리는 일은 도메인 이벤트를 발행한 스레드에서 돌지 않는다. broker queue가 차면
이벤트를 버린다(best-effort, R1). 이벤트를 버린다(best-effort, R1).
+10 -2
View File
@@ -47,8 +47,11 @@
클라이언트가 물러났다가(가능하면 다른 노드로) 다시 붙게 한다. 클라이언트가 물러났다가(가능하면 다른 노드로) 다시 붙게 한다.
- handler 메서드가 돌기 전의 처리 실패(inbound interceptor의 거부 등)는 빈 본문의 ERROR 프레임이 되고 - handler 메서드가 돌기 전의 처리 실패(inbound interceptor의 거부 등)는 빈 본문의 ERROR 프레임이 되고
`message` 헤더는 고정값 `WEBSOCKET_REQUEST_REJECTED`다. `error-code` 헤더는 원인 사슬에 `message` 헤더는 고정값 `WEBSOCKET_REQUEST_REJECTED`다. `error-code` 헤더는 원인 사슬에
`ApiErrorCarrier`가 있으면 첫 carrier의 코드(`IllegalArgumentException` 뒤에 있어도), `ApiErrorCarrier`가 있으면 첫 carrier의 코드(`IllegalArgumentException` 뒤에 있어도), 실패 자신(Spring
`IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는 `WEBSOCKET_REQUEST_REJECTED`다. `MessagingException` 포장을 벗긴 것)이 `IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는
`WEBSOCKET_REQUEST_REJECTED`다. 다른 실패의 원인으로 묻힌 `IllegalArgumentException`은 web·GraphQL·gRPC처럼
`BAD_PARAMETER`로 보지 않는다. 등록된 코드면 `error-category`·`error-retryable` 헤더도 싣는다(gRPC trailer와
같은 이름·값). `WEBSOCKET_REQUEST_REJECTED`는 등록된 코드가 아니라 `error-retryable: false`만 싣는다.
- `@MessageMapping` 메서드의 실패는 inbound 채널 executor에서 끝나서 프레임이 나가지 않는다. 서버 로그는 - `@MessageMapping` 메서드의 실패는 inbound 채널 executor에서 끝나서 프레임이 나가지 않는다. 서버 로그는
`StompHandlerFailureLog`가 web·GraphQL·gRPC와 같은 줄로 남긴다(`ServerFailureLog`): persistence 실패는 `StompHandlerFailureLog`가 web·GraphQL·gRPC와 같은 줄로 남긴다(`ServerFailureLog`): persistence 실패는
분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. 다른 예외로 감싼 carrier도 원인 사슬의 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. 다른 예외로 감싼 carrier도 원인 사슬의
@@ -116,6 +119,11 @@ simple broker는 한 프로세스 안의 best-effort 전달이다. 영속·트
- **principal별 연결 상한 없음.** 상한은 노드 단위다. 인증된 사용자 한 명(또는 탈취된 토큰)이 한 - **principal별 연결 상한 없음.** 상한은 노드 단위다. 인증된 사용자 한 명(또는 탈취된 토큰)이 한
노드의 자리를 모두 차지할 수 있다. principal별 상한은 모든 노드가 공유하는 카운터(Redis 등)가 노드의 자리를 모두 차지할 수 있다. principal별 상한은 모든 노드가 공유하는 카운터(Redis 등)가
필요해 이 leaf 범위를 넘는다. 필요하면 서비스가 프록시나 공유 카운터로 막는다. 필요해 이 leaf 범위를 넘는다. 필요하면 서비스가 프록시나 공유 카운터로 막는다.
- **broadcast 대상을 좁히지 않는다.** 모든 이벤트가 broadcast destination 하나로 가고, 그 destination을
구독한 인증된 세션 모두가 받는다. tenant·소유자 판정은 없다. 그래서 `LiveEventProjector`는 모든 tenant의
인증된 사용자 누구나 읽어도 되는 것만 싣는다 — 「무엇이 바뀌었다」는 표지(`type`과 공개 id)를 보내고, 내용은
클라이언트가 권한 검사를 거치는 조회로 다시 읽는다. tenant·소유자 범위의 데이터는 이 채널에 싣지 않는다.
사용자·tenant별 destination이 필요하면 구독 인가와 함께 따로 설계한다.
- **연결 수명 동안 토큰을 다시 확인하지 않는다.** 인증은 handshake 한 번이다. 토큰이 만료되거나 - **연결 수명 동안 토큰을 다시 확인하지 않는다.** 인증은 handshake 한 번이다. 토큰이 만료되거나
폐기돼도 열린 연결은 유지된다. 연결 수명은 프록시 read timeout이나 서비스의 세션 정책으로 끊는다. 폐기돼도 열린 연결은 유지된다. 연결 수명은 프록시 read timeout이나 서비스의 세션 정책으로 끊는다.
@@ -4,6 +4,13 @@ import java.util.Map;
/** /**
* Explicitly allowlists one domain-event type and maps it to a client-safe primitive projection. * Explicitly allowlists one domain-event type and maps it to a client-safe primitive projection.
*
* <p>The projection goes to one shared destination that every authenticated session may subscribe
* to, whatever its tenant or owner: the broadcaster has no audience, and nothing narrows who
* receives an event. So a projector emits only what every authenticated user of every tenant may
* read — a change marker such as {@code {"type": "order.changed"}} that makes the client re-read
* through an authorized query, not the order's contents. Tenant- or owner-scoped data does not
* belong on this channel (review 2026-11-12: the rule was not written anywhere).
*/ */
public interface LiveEventProjector<T> { public interface LiveEventProjector<T> {
@@ -27,6 +27,10 @@ import org.springframework.messaging.simp.SimpMessagingTemplate;
* *
* <p>The adapter never serializes a domain object. Feature modules must contribute exactly one * <p>The adapter never serializes a domain object. Feature modules must contribute exactly one
* explicit {@link LiveEventProjector} for an event type; otherwise the event is dropped. * explicit {@link LiveEventProjector} for an event type; otherwise the event is dropped.
*
* <p>Every event goes to the one broadcast destination, to every authenticated session subscribed
* to it — no tenant or owner check happens here. What a projector may emit is therefore limited to
* what any authenticated user may read ({@link LiveEventProjector}).
*/ */
public final class LiveEventStompBroadcaster { public final class LiveEventStompBroadcaster {
@@ -1,9 +1,11 @@
package dev.caskeleton.adapter.inbound.websocket.stomp; package dev.caskeleton.adapter.inbound.websocket.stomp;
import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.OperationalError;
import java.util.Optional; import java.util.Optional;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageBuilder;
@@ -17,8 +19,15 @@ import org.springframework.web.socket.messaging.StompSubProtocolErrorHandler;
* failure: an {@link ApiErrorCarrier} anywhere in the cause chain (Spring wraps a failure raised * failure: an {@link ApiErrorCarrier} anywhere in the cause chain (Spring wraps a failure raised
* while the frame is processed in a {@code MessagingException}) reports its own code — the first * while the frame is processed in a {@code MessagingException}) reports its own code — the first
* one, found as every transport finds it ({@link ApiErrorCarrier#firstIn}), even behind an {@link * one, found as every transport finds it ({@link ApiErrorCarrier#firstIn}), even behind an {@link
* IllegalArgumentException} — then an {@link IllegalArgumentException} reports {@code * IllegalArgumentException} — then the failure itself being an {@link IllegalArgumentException}
* BAD_PARAMETER}, and everything else stays {@link #SAFE_ERROR_CODE}. * reports {@code BAD_PARAMETER}, and everything else stays {@link #SAFE_ERROR_CODE}. "Itself" is
* the first cause that is not Spring's {@code MessagingException} wrapper: an argument refusal
* deeper in the chain is a cause of some other failure, and web, GraphQL and gRPC do not answer
* that as {@code BAD_PARAMETER} either (review 2026-11-12).
*
* <p>A registered code also carries {@code error-category} and {@code error-retryable}, the same
* values as the gRPC trailers of those names and the web Envelope. {@link #SAFE_ERROR_CODE} is not
* a registered code and carries only {@code error-retryable: false}.
* *
* <p>What reaches it is what fails before a handler method runs — an inbound interceptor's refusal, * <p>What reaches it is what fails before a handler method runs — an inbound interceptor's refusal,
* on the thread that received the frame. A {@code @MessageMapping} method runs on the inbound * on the thread that received the frame. A {@code @MessageMapping} method runs on the inbound
@@ -32,6 +41,10 @@ final class SafeStompSubProtocolErrorHandler extends StompSubProtocolErrorHandle
/** Bounds the cause walk: a cause chain can loop. */ /** Bounds the cause walk: a cause chain can loop. */
private static final int MAX_CAUSE_DEPTH = 16; private static final int MAX_CAUSE_DEPTH = 16;
static final String CODE_HEADER = "error-code";
static final String CATEGORY_HEADER = "error-category";
static final String RETRYABLE_HEADER = "error-retryable";
@Override @Override
public Message<byte[]> handleClientMessageProcessingError( public Message<byte[]> handleClientMessageProcessingError(
Message<byte[]> clientMessage, Throwable ex) { Message<byte[]> clientMessage, Throwable ex) {
@@ -40,29 +53,39 @@ final class SafeStompSubProtocolErrorHandler extends StompSubProtocolErrorHandle
@Override @Override
public Message<byte[]> handleErrorMessageToClient(Message<byte[]> errorMessage) { public Message<byte[]> handleErrorMessageToClient(Message<byte[]> errorMessage) {
return safeError(SAFE_ERROR_CODE); return safeError(Optional.empty());
} }
private static String errorCodeOf(Throwable failure) { private static Optional<ApiErrorCode> errorCodeOf(Throwable failure) {
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure); Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
if (carrier.isPresent()) { if (carrier.isPresent()) {
return ((ApiErrorCarrier) carrier.get()).errorCode().code(); return Optional.of(((ApiErrorCarrier) carrier.get()).errorCode());
} }
int depth = 0; return unwrapped(failure) instanceof IllegalArgumentException
for (Throwable cause = failure; ? Optional.of(OperationalError.BAD_PARAMETER)
cause != null && depth++ < MAX_CAUSE_DEPTH; : Optional.empty();
cause = cause.getCause()) {
if (cause instanceof IllegalArgumentException) {
return OperationalError.BAD_PARAMETER.code();
}
}
return SAFE_ERROR_CODE;
} }
private static Message<byte[]> safeError(String errorCode) { /** The failure behind Spring's {@code MessagingException} wrappers. */
private static Throwable unwrapped(Throwable failure) {
Throwable current = failure;
int depth = 0;
while (current instanceof MessagingException
&& current.getCause() != null
&& depth++ < MAX_CAUSE_DEPTH) {
current = current.getCause();
}
return current;
}
private static Message<byte[]> safeError(Optional<ApiErrorCode> code) {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
accessor.setMessage(SAFE_ERROR_CODE); accessor.setMessage(SAFE_ERROR_CODE);
accessor.setNativeHeader("error-code", errorCode); accessor.setNativeHeader(CODE_HEADER, code.map(ApiErrorCode::code).orElse(SAFE_ERROR_CODE));
code.ifPresent(
registered -> accessor.setNativeHeader(CATEGORY_HEADER, registered.category().name()));
accessor.setNativeHeader(
RETRYABLE_HEADER, Boolean.toString(code.map(ApiErrorCode::retryable).orElse(false)));
accessor.setLeaveMutable(true); accessor.setLeaveMutable(true);
return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()); return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());
} }
@@ -4,7 +4,9 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.error.MappingException; import dev.caskeleton.shared.error.MappingException;
import dev.caskeleton.shared.error.OperationalError;
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.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException; import org.springframework.messaging.MessagingException;
@@ -74,4 +76,59 @@ class SafeStompSubProtocolErrorHandlerTest {
assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code")) assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code"))
.isEqualTo("BAD_PARAMETER"); .isEqualTo("BAD_PARAMETER");
} }
@Test
@DisplayName("다른 실패의 원인으로 묻힌 IllegalArgumentException 은 BAD_PARAMETER 가 아니다(다른 전송과 같다)")
void anIllegalArgumentBuriedUnderAnotherFailureIsNotBadParameter() {
// given
Throwable failure =
new MessagingException(
"SECRET_SENTINEL",
new IllegalStateException("SECRET_SENTINEL", new IllegalArgumentException("x")));
// when
Message<byte[]> result = handler.handleClientMessageProcessingError(null, failure);
// then
assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code"))
.isEqualTo(SafeStompSubProtocolErrorHandler.SAFE_ERROR_CODE);
}
@Test
@DisplayName("등록된 코드는 gRPC trailer·web Envelope 와 같은 category·retryable 을 함께 싣는다")
void aRegisteredCodeCarriesItsCategoryAndRetryable() {
// given
Throwable failure =
new MessagingException("SECRET_SENTINEL", new MappingException("SECRET_SENTINEL"));
// when
Message<byte[]> result = handler.handleClientMessageProcessingError(null, failure);
// then
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(result);
assertThat(
List.of(
accessor.getFirstNativeHeader("error-code"),
accessor.getFirstNativeHeader("error-category"),
accessor.getFirstNativeHeader("error-retryable")))
.containsExactly(
"MAPPING_FAILED",
OperationalError.MAPPING_FAILED.category().name(),
Boolean.toString(OperationalError.MAPPING_FAILED.retryable()));
}
@Test
@DisplayName("Spring 이 감싼 IllegalArgumentException(interceptor 의 인자 거부)은 BAD_PARAMETER 다")
void anIllegalArgumentWrappedByTheChannelIsBadParameter() {
// given
Throwable failure =
new MessagingException("SECRET_SENTINEL", new IllegalArgumentException("SECRET_SENTINEL"));
// when
Message<byte[]> result = handler.handleClientMessageProcessingError(null, failure);
// then
assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code"))
.isEqualTo("BAD_PARAMETER");
}
} }