fix!: 재리뷰가 찾은 결함과 색인에서 빠졌던 발견 5건을 고친다

문제: 성숙도 리뷰 수정을 다시 읽은 재리뷰(Critical 0, 회귀 0)가
Important 27건·Minor 41건을 찾았다. 수정이 새로 만든 결함이 많았다.
@SystemInvoked가 권한 규칙의 탈출구가 됐고, 데모 계정 거부가 정확히
prod일 때만 걸렸고, outbox 순서 번호가 업그레이드 때 뒤로 갔고,
GraphQL union 아래 복잡도가 0이었고, 서블릿 오류 응답이 success:true로
나갔고, 호출자 deadline이 breaker를 열었다. 원래 리뷰 색인이 06 영역
발견 5건(06-10~14)을 빠뜨려 그동안 처리되지 않았다.

방법: 영역별 7묶음이 test-driven-development 절차로 실패 테스트를
먼저 쓰고 고쳤다. 결정은 재리뷰 README 4절에 적었다: 순서 번호는 V21이
기록한 전역 floor부터, 데모 계정은 local·test·demo 허용 목록,
@SystemInvoked bean은 기동 실패, complete 단계 실패는
IDEMPOTENCY_COMPLETION_UNKNOWN(결과 불명), 캐시 조건부 쓰기는 별도
SCRIPT lane, strict lane 정책은 build cache 입력, 끝나지 않는 재시도
행은 원인 코드·지표·PARKED 절차. 레지스트리가 선언만 하고 아무 코드도
내보내지 않던 redis.capability.* 지표 6개는 빼고 runbook을 실제
지표(redis.lane.*) 기준으로 고쳤다.

위험·한계: V21을 V22 없이 직접 고쳤다(어느 배포에도 아직 없음). 이
브랜치의 V21을 적용한 개발 DB는 다시 만들어야 한다. 서블릿 오류
디스패치를 보안 체인이 허용한다. 발행·저장소 포트 시그니처가 바뀌어
파생 서비스 코드가 깨진다. prod에서 fixture-로 시작하는 설정값은
기동을 막는다. httpclient failure-injection lane의 main 단계 중복
실행은 이전 결정대로 남겼다. 실제 CI runner 실행은 확인하지 못했다.

검증: ci, mainCheck, :integrationCheck, -p optional-platforms ci
integrationCheck performanceCheck, :performanceCheck, :releaseCheck
(-PgitRevision), verify-compose-profile-contracts(18 lane) 통과.
첫 실행의 실패 2건(FindSecBugs 1, sample 동시 생성 테스트의 v4 event
id)은 고친 뒤 ci·integrationCheck·mainCheck를 다시 돌려 통과했다.

Refs: docs/reviews/2026-11-03-rereview/README.md 3·4·6·7절
BREAKING CHANGE: outbox 발행 포트와 저장소 포트 시그니처, 순서 번호
첫 값(V21 floor 다음), 샘플 데모 계정 프로필 허용 목록, 새 오류 코드
IDEMPOTENCY_COMPLETION_UNKNOWN, prod의 fixture- 값 거부, 기동 rule은
static·의존 없음이어야 한다.
This commit is contained in:
DongHyeonka
2026-11-03 23:29:35 +09:00
parent 7ef8d0b4cb
commit bbe944bd3c
406 changed files with 13493 additions and 1656 deletions
+6 -1
View File
@@ -77,7 +77,12 @@ instrumentation, data fetcher resolver 세 곳이 같은 bean 을 받는다).
- **client 문구**: shared-contract `ClientErrorMessages`(Category 별 한국어 문구 표 하나, 소유자
결정 11). 예외 메시지는 절대 나가지 않는다.
- **retryable**: 코드의 `retryable()` 이다(category 에서 계산하지 않는다). 플랫폼 자체 코드만 wire
category 기본값을 쓴다.
category 기본값을 쓴다. 그래서 공유 코드의 값을 바꾸면 이 wire 도 바뀐다: 처리 중 중복
`IDEMPOTENT_IN_FLIGHT` 는 2026-11-01 리뷰(02-01)부터 `retryable: true` 다 — 같은 키로 다시 보내면 서버가
판정한다(`docs/web/http-contract.md` §2). `GraphQlWireErrorMapperTest` 가 고정한다(재리뷰 RR-02-06).
- **`REQUEST_TIMEOUT` 은 web 과 이름만 같다.** 여기의 `category` 는 GraphQL wire 전용 6값 어휘(`TIMEOUT`)이고,
web 의 같은 이름 코드는 HTTP 503·operational category `TRANSIENT_DEPENDENCY` 다
(`docs/web/http-contract.md` §4). 둘 다 `retryable: true` 다.
- **body 크기 초과**: `PAYLOAD_TOO_LARGE`(web 과 같은 코드). 문서 모양 거부(`GRAPHQL_DOCUMENT_SHAPE_REJECTED`)는
별도 코드.
@@ -14,6 +14,9 @@ import java.time.Instant;
* <li>{@code GraphQlPlatformWebInterceptor} ends the request with {@code REQUEST_TIMEOUT} when it
* passes, and Spring cancels the execution so no further field is dispatched. A resolver
* already running is not interrupted.
* <li>{@code GraphQlDeadlineInstrumentation} refuses to start a non-trivial resolver once it has
* passed, failing that field with {@code REQUEST_TIMEOUT}; this is what still holds when the
* whole execution runs on the request thread and the interceptor's timer starts too late.
* <li>{@code GraphQlCostBudgetHandler} refuses to start an execution whose deadline has passed.
* <li>{@code GraphQlBatchExecutor} clamps each platform-registered DataLoader batch to what is
* left, and stops between chunks once it is spent.
@@ -121,11 +121,6 @@ public final class GraphQlComplexityCalculator {
}
}
/** The effective page size for a connection request. */
public int effectivePageSize(Integer first, Integer last) {
return first != null ? first : last != null ? last : defaultPageSize;
}
private void requireAllowedPage(Integer requested) {
if (requested == null) {
return;
@@ -15,6 +15,7 @@ import graphql.language.Value;
import graphql.language.VariableDefinition;
import graphql.language.VariableReference;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLCompositeType;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLFieldsContainer;
import graphql.schema.GraphQLList;
@@ -59,6 +60,13 @@ import java.util.Objects;
* <p>Pricing an omitted argument as one row was the bypass: {@code items(first: 20)} scored 410
* while {@code items} scored 40, and four nested lists added up instead of multiplying.
*
* <p>A selection set is walked whatever kind of composite type it selects from. A union has no
* fields of its own — only {@code __typename} — so its selections are inline fragments and fragment
* spreads, each priced against its type condition. Treating "not a fields container" as "nothing
* below" was the second bypass (re-review 2026-11-03, RR-02-01): {@code search { ... on Post {
* comments(first: 100000) } }} scored 20, and neither the budget nor the page maximum applied under
* any union-typed field.
*
* <p>Traversal is bounded, and fragment cycles are cut by tracking the expansion path. This runs on
* documents that have passed validation, but the bound stays because the scorer is also used from
* the pre-execution path where a hostile document is exactly what it is meant to price.
@@ -143,7 +151,7 @@ public final class GraphQlDocumentComplexityScorer {
private long selectionSetCost(
GraphQLSchema schema,
GraphQLFieldsContainer parent,
GraphQLCompositeType parent,
SelectionSet selectionSet,
Map<String, FragmentDefinition> fragments,
PageVariables variables,
@@ -173,10 +181,10 @@ public final class GraphQlDocumentComplexityScorer {
expansionPath,
listsAreThePage));
} else if (selection instanceof InlineFragment inlineFragment) {
GraphQLFieldsContainer target =
GraphQLCompositeType target =
inlineFragment.getTypeCondition() == null
? parent
: fieldsContainer(schema, inlineFragment.getTypeCondition().getName());
: compositeType(schema, inlineFragment.getTypeCondition().getName());
total =
GraphQlComplexityCalculator.saturatedAdd(
total,
@@ -196,10 +204,10 @@ public final class GraphQlDocumentComplexityScorer {
if (fragment == null || expansionPath.contains(spread.getName())) {
continue;
}
GraphQLFieldsContainer target =
GraphQLCompositeType target =
fragment.getTypeCondition() == null
? parent
: fieldsContainer(schema, fragment.getTypeCondition().getName());
: compositeType(schema, fragment.getTypeCondition().getName());
expansionPath.push(spread.getName());
total =
GraphQlComplexityCalculator.saturatedAdd(
@@ -221,7 +229,7 @@ public final class GraphQlDocumentComplexityScorer {
private long fieldCost(
GraphQLSchema schema,
GraphQLFieldsContainer parent,
GraphQLCompositeType parent,
Field field,
Map<String, FragmentDefinition> fragments,
PageVariables variables,
@@ -235,8 +243,12 @@ public final class GraphQlDocumentComplexityScorer {
return 0;
}
GraphQLFieldDefinition definition = parent.getFieldDefinition(field.getName());
String coordinate = parent.getName() + "." + field.getName();
// A union declares no fields; validation rejects anything but __typename directly under one.
GraphQLFieldDefinition definition =
parent instanceof GraphQLFieldsContainer container
? container.getFieldDefinition(field.getName())
: null;
if (definition == null) {
// Validation rejects an unknown field; price what is there rather than invent a type.
return calculator.fieldCost(coordinate, 0).total();
@@ -250,7 +262,7 @@ public final class GraphQlDocumentComplexityScorer {
long childCost =
selectionSetCost(
schema,
fieldsContainer(definition.getType()),
compositeType(definition.getType()),
field.getSelectionSet(),
fragments,
variables,
@@ -353,14 +365,14 @@ public final class GraphQlDocumentComplexityScorer {
};
}
private static GraphQLFieldsContainer fieldsContainer(GraphQLSchema schema, String typeName) {
GraphQLType type = schema.getType(typeName);
return fieldsContainer(type);
private static GraphQLCompositeType compositeType(GraphQLSchema schema, String typeName) {
return compositeType(schema.getType(typeName));
}
private static GraphQLFieldsContainer fieldsContainer(GraphQLType type) {
/** The object, interface or union a selection set selects from; null for a leaf type. */
private static GraphQLCompositeType compositeType(GraphQLType type) {
GraphQLType unwrapped = unwrap(type);
return unwrapped instanceof GraphQLFieldsContainer container ? container : null;
return unwrapped instanceof GraphQLCompositeType composite ? composite : null;
}
private static GraphQLType unwrap(GraphQLType type) {
@@ -34,11 +34,19 @@ class GraphQlDocumentComplexityScorerTest {
pagedWithDefault(first: Int = 50): [Item!]!
itemConnection(first: Int): ItemConnection
node: Item
allItems: [Item!]!
search: [SearchResult!]!
nodes: [Named!]!
}
type Item {
union SearchResult = Item
interface Named {
name: String!
}
type Item implements Named {
name: String!
children: [Item!]!
grid: [[Item!]!]!
paged(first: Int): [Item!]!
}
type ItemConnection {
edges: [ItemEdge!]!
@@ -48,10 +56,15 @@ class GraphQlDocumentComplexityScorerTest {
}
""";
// Pricing never resolves a runtime type; the resolvers only satisfy the schema generator.
private static final GraphQLSchema SCHEMA =
new SchemaGenerator()
.makeExecutableSchema(
new SchemaParser().parse(SDL), RuntimeWiring.newRuntimeWiring().build());
new SchemaParser().parse(SDL),
RuntimeWiring.newRuntimeWiring()
.type("SearchResult", type -> type.typeResolver(environment -> null))
.type("Named", type -> type.typeResolver(environment -> null))
.build());
private static final long BUDGET = 10_000;
@@ -246,6 +259,87 @@ class GraphQlDocumentComplexityScorerTest {
assertThat(score).isEqualTo(20L + 20L);
}
@Test
@DisplayName("union 필드 아래 inline fragment 의 중첩 list 도 일반 list 와 같이 곱한다")
void nestedListsUnderAUnionFieldMultiplyLikeAPlainList() {
// given
String plain = "query Q { allItems { children { children { children { name } } } } }";
// when
long score =
score(
"query Q { search { ... on Item { children { children { children { name } } } } } }",
Map.of());
// then
assertThat(score).isEqualTo(score(plain, Map.of()));
assertThatThrownBy(() -> calculator.verify(new GraphQlComplexityResult(score), BUDGET))
.isInstanceOf(GraphQlComplexityRejectedException.class);
}
@Test
@DisplayName("union 필드 아래 fragment spread 도 그 타입으로 내려가 곱한다")
void aFragmentSpreadUnderAUnionFieldIsPricedAgainstItsTypeCondition() {
// given
String plain = "query Q { allItems { children { children { children { name } } } } }";
// when
long score =
score(
"query Q { search { ...F } } "
+ "fragment F on Item { children { children { children { name } } } }",
Map.of());
// then
assertThat(score).isEqualTo(score(plain, Map.of()));
}
@Test
@DisplayName("union 필드 아래 page 인자도 상한을 넘으면 page size exceeds maximum 으로 거부된다")
void aPageSizeUnderAUnionFieldIsCheckedAgainstTheMaximum() {
// given
String document = "query Q { search { ... on Item { paged(first: 100000) { name } } } }";
// when
Throwable thrown = catchThrowable(() -> score(document, Map.of()));
// then
assertThat(thrown)
.isInstanceOf(GraphQlComplexityRejectedException.class)
.hasMessageContaining("page size exceeds maximum");
}
@Test
@DisplayName("interface 필드 아래 inline fragment 의 중첩 list 도 일반 list 와 같이 곱한다")
void nestedListsUnderAnInterfaceFieldMultiplyLikeAPlainList() {
// given
String plain = "query Q { allItems { children { children { children { name } } } } }";
// when
long score =
score(
"query Q { nodes { ... on Item { children { children { children { name } } } } } }",
Map.of());
// then
assertThat(score).isEqualTo(score(plain, Map.of()));
}
@Test
@DisplayName("interface 필드 아래 page 인자도 상한을 넘으면 page size exceeds maximum 으로 거부된다")
void aPageSizeUnderAnInterfaceFieldIsCheckedAgainstTheMaximum() {
// given
String document = "query Q { nodes { ... on Item { paged(first: 100000) { name } } } }";
// when
Throwable thrown = catchThrowable(() -> score(document, Map.of()));
// then
assertThat(thrown)
.isInstanceOf(GraphQlComplexityRejectedException.class)
.hasMessageContaining("page size exceeds maximum");
}
private long score(String source, Map<String, Object> variables) {
return score(calculator, source, variables);
}
@@ -55,6 +55,29 @@ class GraphQlWireErrorMapperTest {
.containsExactly("DB_QUERY_CANCELED", false);
}
/**
* The in-flight duplicate's {@code retryable} became {@code true} in the 2026-11-01 review
* (02-01): a resend with the same key is judged by the server, so it is safe. GraphQL carries the
* code's own value, so the change reached this wire too; this pins it (re-review RR-02-06).
*/
@org.junit.jupiter.api.Test
@DisplayName("처리 중 중복(IDEMPOTENT_IN_FLIGHT)은 GraphQL extension 에서도 retryable=true 로 나간다")
void anInFlightDuplicateIsRetryableOnTheGraphQlWire() {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
RuntimeException failure =
dev.caskeleton.application.idempotency.IdempotencyInFlightException.forScopeDigest(
"digest");
// when
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("retryable"))
.containsExactly("IDEMPOTENT_IN_FLIGHT", true);
}
@org.junit.jupiter.api.Test
void anIllegalArgumentIsABadParameterRequestError() {
// given
+2 -1
View File
@@ -140,7 +140,8 @@ handler throw, listener callback throw, `responseObserver.onError(...)`, raw
- **와이어 status(coarse)** 는 `GrpcStatusMapper.toStatus(Category)` 가 결정한다(HTTP status 가
coarse 인 것과 동형). 정확한 `code`/`category`/`retryable` 은 `Status` trailer `Metadata`
(`error-code` / `error-category` / `error-retryable`)에 실어 클라이언트가 switch 하게 한다.
`retryable` 은 코드의 값이다. status description 은 shared-contract `ClientErrorMessages` 의
`retryable` 은 코드의 값이다(처리 중 중복 `IDEMPOTENT_IN_FLIGHT` 는 2026-11-01 리뷰 02-01부터 `ABORTED` +
`error-retryable: true` — 같은 키로 다시 보내면 서버가 판정한다. `GrpcStatusMapperTest` 가 고정, 재리뷰 RR-02-06). status description 은 shared-contract `ClientErrorMessages` 의
Category 별 한국어 문구(web·GraphQL 과 같은 표)다.
- **`IllegalArgumentException`** 은 `BAD_PARAMETER`(`INVALID_ARGUMENT`) — 모든 전송이 같다.
- **`ApiErrorCode` 추출**: feature 예외는 `ApiErrorCarrier`(이 모듈이 제공하는 전송-중립 hook)를
@@ -7,6 +7,7 @@ import dev.caskeleton.shared.error.OperationalError;
import io.grpc.Metadata;
import io.grpc.Status;
import java.util.EnumSet;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -64,4 +65,22 @@ class GrpcStatusMapperTest {
// then
assertThat(retryable).isEqualTo("false");
}
/**
* The in-flight duplicate's {@code retryable} became {@code true} in the 2026-11-01 review
* (02-01). The trailer carries the code's own value, so the change reached the gRPC wire as well:
* status {@code ABORTED} (category {@code CONFLICT}) with {@code error-retryable: true}
* (re-review RR-02-06).
*/
@Test
@DisplayName("처리 중 중복(IDEMPOTENT_IN_FLIGHT)은 ABORTED 이고 trailer 의 retryable 은 true 다")
void anInFlightDuplicateIsAbortedAndRetryableOnTheGrpcWire() {
// when
Metadata trailers = mapper.trailersFor(OperationalError.IDEMPOTENT_IN_FLIGHT);
// then
assertThat(mapper.statusFor(OperationalError.IDEMPOTENT_IN_FLIGHT).getCode())
.isEqualTo(Status.Code.ABORTED);
assertThat(trailers.get(GrpcStatusMapper.RETRYABLE_KEY)).isEqualTo("true");
}
}
+18
View File
@@ -241,6 +241,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
| `PreconditionFailedException` | `PRECONDITION_FAILED` | 412 | D15: `If-Match` 불일치 쓰기 = 낙관적 동시성 충돌 → 412 (raw 409/500 금지) |
| `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 |
| `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | 조정 저장소가 응답하지 않아 action 전에 거부. carrier 분기 |
| `IdempotencyCompletionUnknownException` | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 503 (retryable=true) | action 이 돈 뒤 결과 기록(complete) 중 저장소가 응답하지 않음. 결과 불명 — 같은 키로 재전송, 새 키 금지(`docs/web/http-contract.md` §2, 재리뷰 RR-02-03). carrier 분기 |
| `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 |
| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=true, `Retry-After: 2`) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 클라이언트 행동: 결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). 진단정보(scope digest)는 클라이언트 미도달 |
| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 (retryable=false) | D8: `Idempotency-Key` 를 다른 본문으로 재사용. 다시 보내지 않는다(`docs/web/http-contract.md` §2). fingerprint/scope 노출 금지 |
@@ -284,9 +285,26 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
advice 가 같은 mapper 로 Envelope 를 문자열로 직렬화해 넘긴다. 텍스트를 요청한 클라이언트는 그대로
문자열을 받는다. ArchUnit 으로 `String` 반환을 금지하는 안은 버렸다: `text/plain` 엔드포인트의 정당한
용도를 막고, 규칙을 돌리지 않는 서비스에는 함정이 그대로 남는다.
- **4xx·5xx 본문은 감싸지 않는다.** `success` 는 클라이언트가 가르는 판별자라, 오류 status 본문을
`success:true` 로 감싸면 성공으로 읽힌다. Boot `/error` 의 map 이 그렇게 나갔다(재리뷰 RR-02-02).
- 위치: sample 모듈이 아니라 adapter-web. 실행 앱은 adapter-web 에 의존하지만 sample-portfolio 에는 의존하지
않으므로, 응답 래핑이 실제로 동작하려면 여기 있어야 한다.
### EnvelopeErrorController
- 컨트롤러에 닿기 전에 생긴 오류(보안 방화벽의 `RequestRejectedException`, 필터의 `sendError`, 필터가
던진 예외)는 `GlobalExceptionHandler` 를 지나지 않고 컨테이너의 `/error` 디스패치로 간다. Boot 기본
`BasicErrorController` 는 거기서 `{timestamp, status, error, path}` 를 썼고, advice 가 그것을
`success:true` 로 감쌌으며 `path` 는 요청 경로 원문이었다(재리뷰 RR-02-02). 이 컨트롤러가 그 자리를
대신해 status 를 `GlobalExceptionHandler` 와 같은 표(`HttpStatusErrorCodes`)로 코드에 매핑하고 실패
Envelope 를 `EnvelopeResponseWriter` 로 쓴다. 요청에서 가져온 값은 싣지 않는다.
- `WebMvcPlatformAutoConfiguration` 이 `ErrorMvcAutoConfiguration` 보다 먼저 `ErrorController` 가 없을 때만
등록한다. 어댑터가 자기 `ErrorController` 를 두면 물러난다.
- `SecurityConfig` 는 오류 **디스패치**만 허용한다(`DispatcherType.ERROR`). 예전에는 `/error` 가 공개 경로가
아니라서 익명 요청의 400 이 401 로 바뀌었다. `/error` 를 직접 부른 요청은 여전히 인증이 필요하다.
단언은 실제 Tomcat 의 `TomcatWebContractIT`(공유 `WebContractAssertions`)와 `JwtChainErrorDispatchIT`.
- 앱이 보안 체인을 직접 정의하면(예: sample 의 데모 체인) 같은 한 줄
(`dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`)을 그 체인에도 둬야 원래 status 가 나간다.
### CacheControlFilter
- 스켈레톤 기본 HTTP 캐시 정책.
- `Cache-Control: no-store` 는 인증된 API 의 안전한 기본값. `Vary: Accept, Accept-Encoding, Authorization` 로
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.web.auth;
import dev.caskeleton.adapter.inbound.web.settings.CorsSettings;
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
import jakarta.servlet.DispatcherType;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -83,6 +84,11 @@ public class SecurityConfig {
.requestCache(cache -> cache.disable())
.authorizeHttpRequests(
auth -> {
// The container's error dispatch for a request that already failed. Authorising it
// again turned an anonymous 400 into a 401 that blamed authentication. Only the
// dispatch type is opened: a request that names /error itself is still a request.
// The error controller writes nothing from the request (re-review RR-02-02).
auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll();
if (publicPaths.length > 0) {
auth.requestMatchers(publicPaths).permitAll();
}
@@ -12,6 +12,7 @@ import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import tools.jackson.databind.ObjectMapper;
@@ -34,6 +35,13 @@ import tools.jackson.databind.json.JsonMapper;
* still sees {@code 200 text/plain}. So when the String converter is about to write JSON, the
* envelope is serialised here, with the same mapper and wire rules, and the converter writes that
* text (review 2026-11-01 02-06). A text client still gets the plain string.
*
* <p>A body sent with a 4xx or 5xx status is never wrapped. {@code success} is the discriminator a
* client branches on, so a {@code success:true} envelope around an error-status body tells it the
* request worked. Boot's {@code /error} map reached clients exactly that way until the error
* dispatch got its own envelope writer ({@code EnvelopeErrorController}, re-review 2026-11-03
* RR-02-02). Failure envelopes come from the error handlers; a handler that returns some other body
* with an error status gets that body on the wire as it wrote it, not a false success.
*/
@RestControllerAdvice
public final class EnvelopeBodyAdvice implements ResponseBodyAdvice<Object> {
@@ -74,10 +82,18 @@ public final class EnvelopeBodyAdvice implements ResponseBodyAdvice<Object> {
if (selectedContentType != null && !MediaType.APPLICATION_JSON.includes(selectedContentType)) {
return body;
}
if (isErrorStatus(response)) {
return body;
}
Envelope<Object> envelope = Envelope.ok(body, ResponseMetaFactory.fromMdc());
if (StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) {
return objectMapper.writeValueAsString(envelope);
}
return envelope;
}
private static boolean isErrorStatus(ServerHttpResponse response) {
return response instanceof ServletServerHttpResponse servlet
&& servlet.getServletResponse().getStatus() >= 400;
}
}
@@ -29,7 +29,7 @@ public class EnvelopeWireFormatConfig {
}
/** The module itself, for a writer that has no Boot mapper to take it from. */
static SimpleModule module() {
public static SimpleModule module() {
SimpleModule module = new SimpleModule("EnvelopeWireFormatModule");
module.setMixInAnnotation(Envelope.class, OmitNullFields.class);
module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class);
@@ -0,0 +1,72 @@
package dev.caskeleton.adapter.inbound.web.error;
import dev.caskeleton.adapter.inbound.web.core.OwnsAbsoluteWebRoute;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import org.springframework.boot.webmvc.error.ErrorController;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import tools.jackson.databind.ObjectMapper;
/**
* Answers the container's error dispatch with the failure {@code Envelope}.
*
* <p>A failure raised outside the MVC handler — the security firewall's {@code
* RequestRejectedException}, a filter's {@code sendError}, an exception thrown by a filter — never
* reaches {@link GlobalExceptionHandler}. The container forwards it to {@code /error} instead,
* where Boot's {@code BasicErrorController} wrote {@code {timestamp, status, error, path}}; the
* success advice then wrapped that map as {@code success:true}, and {@code path} echoed the raw
* request URI back (re-review 2026-11-03, RR-02-02). This replaces that controller: the error
* status is classified by the same table the exception handler uses, and the body is the failure
* envelope, with nothing from the request in it.
*
* <p>Written straight to the response by {@link EnvelopeResponseWriter}, like the other refusals
* made outside a converter. An error dispatch has no handler of its own to negotiate for, and a
* browser's {@code Accept: text/html} would otherwise turn the error into a 406 about the error.
*
* <p>A request that names {@code /error} itself carries no error status; it is answered as an
* unknown route. The security chain permits only the error dispatch, so such a request still needs
* a token under the JWT chain.
*
* <p>An absolute route ({@link OwnsAbsoluteWebRoute}): the container forwards to {@code /error},
* not to {@code /error} under the presentation prefix.
*/
@Controller
@OwnsAbsoluteWebRoute
@RequestMapping("${server.error.path:${error.path:/error}}")
public final class EnvelopeErrorController implements ErrorController {
private final ObjectMapper objectMapper;
/**
* Creates the controller.
*
* @param objectMapper Boot's mapper, which carries the envelope wire rules
*/
public EnvelopeErrorController(ObjectMapper objectMapper) {
this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper");
}
/** Writes the failure envelope for the status the error dispatch carries. */
@RequestMapping
public void error(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (response.isCommitted()) {
return;
}
ApiErrorCode code =
request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE) instanceof Integer status
? HttpStatusErrorCodes.forStatus(HttpStatusCode.valueOf(status))
: OperationalError.ROUTE_NOT_FOUND;
RetryAfterAdvisor.retryAfterSeconds(code)
.ifPresent(seconds -> response.setHeader(ApiHeaders.RETRY_AFTER, String.valueOf(seconds)));
EnvelopeResponseWriter.write(response, code, objectMapper);
}
}
@@ -407,7 +407,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
return null;
}
}
ApiErrorCode code = errorCodeFor(statusCode);
ApiErrorCode code = HttpStatusErrorCodes.forStatus(statusCode);
if (code.httpStatus() >= 500) {
log.error("spring mvc failure classified as {}", code.code(), ex);
spanErrorRecorder.recordException(ex, code.code());
@@ -415,25 +415,4 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
return new ResponseEntity<>(
ErrorResponseFactory.body(code, null), headers, HttpStatusCode.valueOf(code.httpStatus()));
}
private static ApiErrorCode errorCodeFor(HttpStatusCode status) {
return switch (status.value()) {
case 401 -> OperationalError.UNAUTHENTICATED;
case 403 -> OperationalError.FORBIDDEN;
case 404 -> OperationalError.ROUTE_NOT_FOUND;
case 405 -> OperationalError.METHOD_NOT_ALLOWED;
case 406 -> OperationalError.NOT_ACCEPTABLE;
case 412 -> OperationalError.PRECONDITION_FAILED;
case 413 -> OperationalError.PAYLOAD_TOO_LARGE;
case 414 -> OperationalError.URI_TOO_LONG;
case 415 -> OperationalError.UNSUPPORTED_MEDIA_TYPE;
case 429 -> OperationalError.RATE_LIMIT_EXCEEDED;
// Spring answers its async request timeout with 503: transient, not an internal fault.
case 503 -> WebTransportError.REQUEST_TIMEOUT;
default ->
status.is4xxClientError()
? OperationalError.BAD_PARAMETER
: OperationalError.INTERNAL_ERROR;
};
}
}
@@ -0,0 +1,38 @@
package dev.caskeleton.adapter.inbound.web.error;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
import org.springframework.http.HttpStatusCode;
/**
* The operational code a bare HTTP status stands for, when a status is all that is known.
*
* <p>Two places only have a status to classify: a Spring MVC exception this adapter has no
* dedicated handler for, and the container's error dispatch for a failure raised outside the
* handler. They share this one table, so the same status never reaches a client as two codes.
*/
final class HttpStatusErrorCodes {
private HttpStatusErrorCodes() {}
static ApiErrorCode forStatus(HttpStatusCode status) {
return switch (status.value()) {
case 401 -> OperationalError.UNAUTHENTICATED;
case 403 -> OperationalError.FORBIDDEN;
case 404 -> OperationalError.ROUTE_NOT_FOUND;
case 405 -> OperationalError.METHOD_NOT_ALLOWED;
case 406 -> OperationalError.NOT_ACCEPTABLE;
case 412 -> OperationalError.PRECONDITION_FAILED;
case 413 -> OperationalError.PAYLOAD_TOO_LARGE;
case 414 -> OperationalError.URI_TOO_LONG;
case 415 -> OperationalError.UNSUPPORTED_MEDIA_TYPE;
case 429 -> OperationalError.RATE_LIMIT_EXCEEDED;
// Spring answers its async request timeout with 503: transient, not an internal fault.
case 503 -> WebTransportError.REQUEST_TIMEOUT;
default ->
status.is4xxClientError()
? OperationalError.BAD_PARAMETER
: OperationalError.INTERNAL_ERROR;
};
}
}
@@ -1,5 +1,7 @@
package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig;
import dev.caskeleton.adapter.inbound.web.error.EnvelopeErrorController;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter;
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
@@ -12,8 +14,12 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
import org.springframework.boot.webmvc.autoconfigure.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.webmvc.error.ErrorController;
import org.springframework.context.annotation.Bean;
import tools.jackson.core.StreamReadFeature;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/**
* Wires the web platform into a servlet application.
@@ -30,8 +36,12 @@ import tools.jackson.core.StreamReadFeature;
*
* <p>Every bean is {@link ConditionalOnMissingBean}: the platform supplies the one that would
* otherwise be missing rather than the one that must be used.
*
* <p>Before {@link ErrorMvcAutoConfiguration}, so the envelope error controller is the {@link
* ErrorController} that configuration finds and Boot's {@code BasicErrorController} backs off. Its
* error-page registration with the container stays: that is what forwards to {@code /error}.
*/
@AutoConfiguration
@AutoConfiguration(before = ErrorMvcAutoConfiguration.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnProperty(
prefix = "app.web.mvc",
@@ -54,6 +64,22 @@ public class WebMvcPlatformAutoConfiguration {
return new GlobalExceptionHandler(spanErrorRecorderProvider);
}
/**
* Answers the container's error dispatch — failures raised outside the MVC handler — with the
* failure envelope instead of Boot's {@code {timestamp, status, error, path}} map.
*
* <p>Boot's mapper when there is one, which already carries the envelope wire rules; otherwise a
* mapper with only those rules, as {@code EnvelopeBodyAdvice} does without Boot.
*/
@Bean
@ConditionalOnMissingBean(ErrorController.class)
public EnvelopeErrorController envelopeErrorController(
ObjectProvider<ObjectMapper> objectMapper) {
return new EnvelopeErrorController(
objectMapper.getIfAvailable(
() -> JsonMapper.builder().addModule(EnvelopeWireFormatConfig.module()).build()));
}
/**
* Assigns the correlation identifiers, validating anything a caller proposed. With a tracer in
* the composition the trace id is the tracer's: the filter runs inside Boot's server observation
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.web.observability;
import dev.caskeleton.application.idempotency.IdempotencyExecutor;
import dev.caskeleton.shared.error.ApiErrorCode;
import java.util.Map;
import java.util.OptionalInt;
@@ -13,17 +14,26 @@ public final class RetryAfterAdvisor {
/** Per-code {@code Retry-After} values (seconds). */
private static final Map<String, Integer> RETRY_AFTER_SECONDS =
Map.of(
"RATE_LIMIT_EXCEEDED", 1,
// Below the default processing lease (30s): the resend arrives while the first attempt
// can still finish, and an early resend costs one more 409. docs/web/http-contract.md.
"IDEMPOTENT_IN_FLIGHT", 2,
"AUTH_KID_UNKNOWN", 5,
"AUTH_JWKS_UNAVAILABLE", 30,
"DEPENDENCY_TIMEOUT", 2,
"DEPENDENCY_CONNECT_FAILED", 2,
"DEPENDENCY_DNS_FAILED", 5,
"DEPENDENCY_5XX_SERVER", 2,
"DEPENDENCY_CIRCUIT_OPEN", 10);
"RATE_LIMIT_EXCEEDED",
1,
// The application's value, which the processing-lease check also reads: the resend
// arrives while the first attempt can still finish. docs/web/http-contract.md §2.
"IDEMPOTENT_IN_FLIGHT",
Math.toIntExact(IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER.toSeconds()),
"AUTH_KID_UNKNOWN",
5,
"AUTH_JWKS_UNAVAILABLE",
30,
"DEPENDENCY_TIMEOUT",
2,
"DEPENDENCY_CONNECT_FAILED",
2,
"DEPENDENCY_DNS_FAILED",
5,
"DEPENDENCY_5XX_SERVER",
2,
"DEPENDENCY_CIRCUIT_OPEN",
10);
private RetryAfterAdvisor() {}
@@ -0,0 +1,91 @@
package dev.caskeleton.adapter.inbound.web.testkit.mvc;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* The error dispatch under the production JWT security chain, over a real Tomcat.
*
* <p>The chain authorises every dispatch, the container's error dispatch to {@code /error}
* included. {@code /error} is not a public path, so an anonymous request whose original failure was
* a 400 used to come back as 401 — the client was told to authenticate when its request was
* malformed (re-review 2026-11-03, RR-02-02). The error dispatch is now permitted; a request that
* names {@code /error} directly is still a request and still needs a token.
*
* <p>The chain is {@code WebSecurityAutoConfiguration} itself. The JWT decoder is lazy, so the
* unreachable issuer below is never contacted: no request here carries a token.
*/
@SpringBootTest(
classes = JwtChainErrorDispatchIT.JwtChainApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {
"spring.main.banner-mode=off",
"spring.mvc.problemdetails.enabled=false",
"app.web.mvc.enabled=true",
"app.security.auth-mode=jwt",
"app.security.issuer-uri=https://issuer.invalid/realms/ca",
"app.security.audience=ca-skeleton-api",
"app.security.public-paths=/api/v1/fixtures/**",
"app.cors.enabled=false"
})
class JwtChainErrorDispatchIT {
private final HttpClient client =
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
@LocalServerPort private int port;
@Test
@DisplayName("JWT 체인에서 익명 요청이 핸들러 밖에서 400 으로 거부되면 401 이 아니라 400 실패 Envelope 로 나간다")
void anAnonymousRequestRejectedOutsideTheHandlerKeepsItsOwnStatus() throws Exception {
// when
HttpResponse<String> rejected = get(WebContractAssertions.FIREWALL_REJECTED_PATH);
// then
assertThat(rejected.statusCode()).isEqualTo(400);
WebContractAssertions.assertFailureEnvelope(rejected, "BAD_PARAMETER");
}
@Test
@DisplayName("오류 디스패치만 허용한다 — /error 를 직접 부른 익명 요청은 여전히 401 이다")
void aDirectRequestForTheErrorPathStillNeedsAToken() throws Exception {
// when
HttpResponse<String> direct = get("/error");
// then
assertThat(direct.statusCode()).isEqualTo(401);
}
private HttpResponse<String> get(String path) throws Exception {
return client.send(
HttpRequest.newBuilder(URI.create("http://localhost:" + port + path))
.header("Accept", "application/json")
.GET()
.build(),
HttpResponse.BodyHandlers.ofString());
}
/**
* The production web stack minus {@link WebAdapterAutoConfiguration}, whose request-logging
* filter needs the composition root's pseudonymizer, plus that root's envelope wire format; the
* security chain is the shipped one.
*/
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration(exclude = WebAdapterAutoConfiguration.class)
@Import({ContractFixtureController.class, EnvelopeWireFormatConfig.class})
static class JwtChainApplication {}
}
@@ -23,6 +23,7 @@ import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.json.JsonCompareMode;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
@@ -64,6 +65,12 @@ class EnvelopeBodyAdviceTest {
return "{\"openapi\":\"3.1.0\"}".getBytes(StandardCharsets.UTF_8);
}
/** A failure status with a body that is not an envelope. */
@GetMapping("/probe/conflict")
public ResponseEntity<Map<String, String>> conflict() {
return ResponseEntity.status(409).body(Map.of("k", "v"));
}
@GetMapping("/probe/bulk")
public BulkEnvelope<Map<String, String>> bulk() {
return BulkEnvelope.allOk(List.of(Map.of("k", "v")), new ResponseMeta("r", "t", "c"));
@@ -149,6 +156,25 @@ class EnvelopeBodyAdviceTest {
.andExpect(content().json("{\"openapi\":\"3.1.0\"}", JsonCompareMode.STRICT));
}
/**
* A 4xx/5xx body is never a success envelope. {@code success} is the discriminator clients branch
* on (docs/web/http-contract.md §1), so wrapping an error-status body as {@code success:true}
* tells a contract-following client the request worked — Boot's {@code /error} map arrived that
* way (re-review 2026-11-03, RR-02-02). The body is left as the handler wrote it.
*/
@Test
@DisplayName("4xx·5xx 응답 본문은 success:true Envelope 로 감싸지 않는다")
void anErrorStatusBodyIsNotWrappedAsASuccess() throws Exception {
// when
var result = mvc.perform(get("/probe/conflict").accept(MediaType.APPLICATION_JSON));
// then
result
.andExpect(status().isConflict())
.andExpect(jsonPath("$.success").doesNotExist())
.andExpect(content().json("{\"k\":\"v\"}", JsonCompareMode.STRICT));
}
@SpringBootConfiguration
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
static class TestBootstrap {}
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.error;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.application.idempotency.IdempotencyCompletionUnknownException;
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException;
import dev.caskeleton.shared.error.Category;
@@ -74,4 +75,24 @@ class IdempotencyExceptionMappingTest {
false,
ClientErrorMessages.of(Category.VALIDATION));
}
@Test
@DisplayName("complete 단계 결과 불명은 실행 전 거부(IDEMPOTENCY_UNAVAILABLE)와 다른 code 의 retryable 503 이다")
void completionUnknownMapsToItsOwnRetryable503SoTheClientDoesNotReadItAsNotApplied() {
// given
IdempotencyCompletionUnknownException unknown = new IdempotencyCompletionUnknownException();
// when
ResponseEntity<Envelope<Void>> response = handler.handleCarrier(unknown);
// then
assertThat(response)
.extracting(
r -> r.getStatusCode().value(),
r -> r.getHeaders().getFirst(ApiHeaders.RETRY_AFTER),
r -> r.getBody().error().code(),
r -> r.getBody().error().category(),
r -> r.getBody().error().retryable())
.containsExactly(503, null, "IDEMPOTENCY_COMPLETION_UNKNOWN", "TRANSIENT_DEPENDENCY", true);
}
}
@@ -8,6 +8,8 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* The status contract as socket-level assertions, written once and run against every container.
@@ -22,6 +24,11 @@ import java.time.Duration;
*/
public final class WebContractAssertions {
/** A path the servlet firewall refuses before any handler runs ({@code ;} in the URI). */
public static final String FIREWALL_REJECTED_PATH = "/api/v1/fixtures/f1;x=1";
private static final JsonMapper JSON = JsonMapper.builder().build();
private final HttpClient client =
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
@@ -122,6 +129,46 @@ public final class WebContractAssertions {
assertThat(post("/api/v1/fixtures", "{\"name\":").statusCode()).isEqualTo(400);
}
/**
* An error raised outside the MVC handler is still a failure envelope.
*
* <p>The firewall rejects the request before any controller runs, and the container answers it
* with an error dispatch to {@code /error}. Boot's default error controller wrote a map there,
* which the success advice then wrapped as {@code success:true} with the raw request path inside
* (re-review 2026-11-03, RR-02-02). MockMvc performs no error dispatch, so only a container can
* show this.
*/
public void aRequestRejectedOutsideTheHandlerIsAFailureEnvelope()
throws IOException, InterruptedException {
HttpResponse<String> rejected = get(FIREWALL_REJECTED_PATH);
assertThat(rejected.statusCode()).isEqualTo(400);
assertFailureEnvelope(rejected, "BAD_PARAMETER");
}
/**
* Asserts the failure envelope of {@code docs/web/http-contract.md} §1 on an error response.
*
* @param response a response the container wrote through its error dispatch
* @param expectedCode the {@code error.code} the status maps to
*/
public static void assertFailureEnvelope(HttpResponse<String> response, String expectedCode) {
JsonNode body = JSON.readTree(response.body());
assertThat(body.path("success").isBoolean() && !body.path("success").booleanValue())
.as(
"a 4xx/5xx body that says success:true is read as a success by a client that follows"
+ " the contract: %s",
response.body())
.isTrue();
assertThat(body.path("error").path("code").asString()).isEqualTo(expectedCode);
assertThat(body.has("data")).as("a failure envelope has no data key").isFalse();
assertThat(response.body())
.as("the error body must not echo the request path back")
.doesNotContain(";x=1")
.doesNotContain("\"path\"")
.doesNotContain("timestamp");
}
/** Runs every assertion, so a lane cannot silently cover a subset. */
public void assertWholeContract() throws IOException, InterruptedException {
createdCarriesALocationHeader();
@@ -131,6 +178,7 @@ public final class WebContractAssertions {
anUnknownMethodOnAKnownRouteIsRefused();
anUnsupportedMediaTypeIsRefused();
malformedJsonIsRefused();
aRequestRejectedOutsideTheHandlerIsAFailureEnvelope();
}
private HttpResponse<String> post(String path, String body)
@@ -143,6 +191,12 @@ public final class WebContractAssertions {
HttpResponse.BodyHandlers.ofString());
}
private HttpResponse<String> get(String path) throws IOException, InterruptedException {
return client.send(
HttpRequest.newBuilder(uri(path)).header("Accept", "application/json").GET().build(),
HttpResponse.BodyHandlers.ofString());
}
private URI uri(String path) {
return URI.create("http://localhost:" + port + path);
}
@@ -1,5 +1,6 @@
package dev.caskeleton.webtestkit;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.testkit.fault.FaultFixtureController;
@@ -31,6 +32,10 @@ import org.springframework.security.web.SecurityFilterChain;
* are the "sum of the leaf" the paragraph above keeps out. Excluded by class, so a rename breaks
* compilation rather than the gate. The third root, {@code WebMethodSecurityAutoConfiguration}, is
* left in: no fixture route runs a permissioned use case, so it decides nothing here.
*
* <p>{@link EnvelopeWireFormatConfig} is imported by name from the excluded web root: it is the
* wire shape of every envelope this gate reads (a failure body has no {@code data} key), not a
* capability, and without it the gate would certify {@code "data": null} that no deployment sends.
*/
// Outside `dev.caskeleton.adapter.inbound.web`, which the composition root component-scans.
// A fixture application under that root is loaded into the real deployment: its permit-all
@@ -40,7 +45,11 @@ import org.springframework.security.web.SecurityFilterChain;
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration(
exclude = {WebAdapterAutoConfiguration.class, WebSecurityAutoConfiguration.class})
@Import({ContractFixtureController.class, FaultFixtureController.class})
@Import({
ContractFixtureController.class,
FaultFixtureController.class,
EnvelopeWireFormatConfig.class
})
public class ContractFixtureApplication {
/**