From 02e35d2b386c3978fdae1146262106fab78a3221 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 02:05:53 +0900 Subject: [PATCH] =?UTF-8?q?fix(http):=20=EC=A7=9D=20=EB=B0=B1=EC=97=94?= =?UTF-8?q?=EB=93=9C=EC=9D=98=20400=20VALIDATION=5FFAILED=EB=A5=BC=20?= =?UTF-8?q?=ED=8F=BC=20=ED=95=84=EB=93=9C=20=EC=98=A4=EB=A5=98=EB=A1=9C=20?= =?UTF-8?q?=EC=9D=BD=EB=8A=94=EB=8B=A4=20(=EB=B0=B1=EC=97=94=EB=93=9C=2011?= =?UTF-8?q?01/02-01)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 짝 백엔드는 필드 검증 실패를 400 VALIDATION_FAILED로 보낸다. details는 위반 하나마다 {field, code, message}인 배열이다(백엔드 docs/web/http- contract.md 4절, ClientSafeValidationDetails). field는 점으로 이은 속성 이름이고 인덱스는 뺀다. 클래스 수준 오류는 "request"다. 프론트 V2 클라이언트(client.ts)는 422만 필드 검증으로 읽는다. 400은 UNKNOWN_CLIENT_FAILURE이고 validationIssues가 없어서, 폼(use-app-form.ts)이 필드 오류 대신 "unavailable" 상태를 보인다. safeValidationIssues도 {issues}·{fieldErrors} 객체만 읽어서 배열 details를 버린다. 고른 방법 - V2: 400 + code VALIDATION_FAILED + details가 배열이면 422와 같은 것으로 본다. kind VALIDATION_REJECTED와 validationIssues를 422 경로와 같은 식으로 만든다. 폼은 기존 mapValidationFailureToFields와 allowedServerFields를 그대로 쓴다. 새 폼 경로는 없다. - safeValidationIssues: details가 배열이면 각 항목의 field를 path로 읽는다. message는 버린다. 후보 수는 기존 상한(MAX_VALIDATION_ISSUE_CANDIDATES)으로 자른 뒤 projectValidationIssues에 넘긴다. - 그 밖의 400은 그대로 둔다: details가 {cause}인 VALIDATION_FAILED(본문 파싱 실패), details 없는 VALIDATION_FAILED, BAD_PARAMETER, IDEMPOTENCY_KEY_INVALID(NOT_APPLIED 판정 유지). 버린 대안 - 400 VALIDATION_FAILED 전체를 VALIDATION_REJECTED로: 파싱 실패 같은 클라이언트 버그가 "입력값을 다시 확인해 주세요."로 보인다. 필드 목록이 있을 때만 바꾼다. - 공용 projectValidationIssues가 field를 path 별칭으로 받게: zod 이슈와 V3 경로까지 같은 규칙을 갖게 된다. 백엔드 wire 모양은 V2 전용 safeValidationIssues에서만 읽는다. - V3 참조 기능 mapProblem도 바꾸기: 참조 fixture는 problem+json (type·title·status·issues)이라 짝 백엔드 Envelope가 problem 검증을 통과하지 않는다. 짝 백엔드 wire를 읽는 곳은 V2다. 위험·한계 - 백엔드 code(NOT_BLANK, SIZE 등)는 폼 문구 표(VALIDATION_COPY)에 없어서 필드 문구가 "입력값을 확인해 주세요."(form.validation.unknown)다. 필드 위치는 맞게 표시된다. 코드별 문구는 이 변경 밖이다. - 페이지·정렬 파라미터 검증(PageValidationException)은 details가 배열이 아닌 단일 {field, code}라 지금처럼 UNKNOWN_CLIENT_FAILURE로 남는다. 폼 입력이 아니라 목록 조회 파라미터다. - V2 필드 검증 실패에는 effect가 없다(422와 같다). mutation 코디네이터는 이것을 MAYBE_APPLIED로 보고 admission을 붙든다. 422에도 있던 기존 동작이다. 검증 - RED: tests/component/form-foundation.test.tsx 새 행이 실패. V2 클라이언트가 400 VALIDATION_FAILED를 받으면 폼 결과가 "unavailable"이고 Name 필드에 aria-invalid가 없다. tests/integration/http-client.test.ts "reads the field details as validation issues" 실패(kind UNKNOWN_CLIENT_FAILURE, issues 없음). 다른 400 3행은 처음부터 통과(유지 동작 고정). - GREEN: 위 행 모두 통과. tests/unit·contract·runtime-schema·integration· component·features·platform 283 files 중 282 통과, 3394 tests 통과. 실패 1개(tests/unit/second-api-feature-registries.test.ts "passes check-registries…")는 기준 3b7d73a에서도 같은 메시지로 실패한다. tsc app·test·node 통과, 바꾼 파일 eslint 통과, check:registries PASS. Refs: clean-architecture-backend-template docs/web/http-contract.md 4절 --- src/adapters/http/client.ts | 26 ++++++--- src/contracts/errors.ts | 24 +++++++- tests/component/form-foundation.test.tsx | 62 ++++++++++++++++++++ tests/integration/http-client.test.ts | 72 ++++++++++++++++++++++++ 4 files changed, 174 insertions(+), 10 deletions(-) diff --git a/src/adapters/http/client.ts b/src/adapters/http/client.ts index 209f9c7b..e8721266 100644 --- a/src/adapters/http/client.ts +++ b/src/adapters/http/client.ts @@ -1002,14 +1002,27 @@ async function parseResponse( }; } - // R3-1. V2 treats a 408/425 error envelope as the same server failure as a - // gateway body; the shared status map in contracts is not changed. - const kind = gatewayFailureOr(response.status, statusKind(response.status)); const backendError = envelopeRecord.error && typeof envelopeRecord.error === "object" ? (envelopeRecord.error as Record) : {}; const code = safeBackendCode(envelope); + // 백엔드 1101/02-01 후속. The paired backend answers a field validation + // failure with 400 VALIDATION_FAILED whose details is the field list + // (clean-architecture-backend-template docs/web/http-contract.md §4). It is + // the same failure as a 422, so it gets the same kind and issues and a form + // maps it with the same allowed fields. A 400 VALIDATION_FAILED whose body + // did not parse carries `{cause}`, not a list, and keeps its reading. + const fieldValidation = + response.status === 422 || + (response.status === 400 && + code === "VALIDATION_FAILED" && + Array.isArray(backendError.details)); + // R3-1. V2 treats a 408/425 error envelope as the same server failure as a + // gateway body; the shared status map in contracts is not changed. + const kind = fieldValidation + ? "VALIDATION_REJECTED" + : gatewayFailureOr(response.status, statusKind(response.status)); return { ok: false, error: failure(kind, operation.operationId, attempt, { @@ -1021,10 +1034,9 @@ async function parseResponse( requestId: safeMeta(envelopeRecord.meta).requestId, traceId: safeMeta(envelopeRecord.meta).traceId, retryAfterMs, - validationIssues: - response.status === 422 - ? safeValidationIssues(backendError.details) - : undefined, + validationIssues: fieldValidation + ? safeValidationIssues(backendError.details) + : undefined, }), }; } diff --git a/src/contracts/errors.ts b/src/contracts/errors.ts index 04ad9758..b559cc81 100644 --- a/src/contracts/errors.ts +++ b/src/contracts/errors.ts @@ -1,4 +1,5 @@ import { + MAX_VALIDATION_ISSUE_CANDIDATES, projectValidationIssues, type ValidationIssue, } from "./validation-issues.ts"; @@ -225,14 +226,31 @@ export function withFailureEffect( } /** - * Projects an untrusted 422 details payload into the only validation metadata - * allowed to cross the HTTP boundary. Backend copy and additional values are - * deliberately discarded. + * Projects an untrusted validation details payload into the only validation + * metadata allowed to cross the HTTP boundary. Backend copy and additional + * values are deliberately discarded. * + * 백엔드 1101/02-01 후속. The paired backend's details is the list itself, + * one `{field, code, message}` per violation (its docs/web/http-contract.md + * §4); `field` is read as the path. The scan stays bounded. */ export function safeValidationIssues( value: unknown, ): readonly ValidationIssue[] { + if (Array.isArray(value)) { + return projectValidationIssues( + value + .slice(0, MAX_VALIDATION_ISSUE_CANDIDATES) + .map((entry: unknown) => + entry && typeof entry === "object" + ? { + path: (entry as Readonly>).field, + code: (entry as Readonly>).code, + } + : entry, + ), + ); + } if (!value || typeof value !== "object") return Object.freeze([]); const candidate = value as Readonly<{ issues?: unknown; diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index be1d1bb3..9d4c9277 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -7,7 +7,9 @@ import { createMemoryRouter, RouterProvider, useNavigate } from "react-router-do import { z } from "zod"; import { describe, expect, it, vi } from "vitest"; +import { createHttpClient } from "../../src/adapters/http/client.ts"; import { createFailure } from "../../src/contracts/errors.ts"; +import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts"; import { Button } from "../../src/presentation/components/ui/button.ts"; import { DirtyNavigationDialog, @@ -148,6 +150,66 @@ describe("local form facade", () => { expect(document.body).not.toHaveTextContent("raw-secret-message"); }); + // 백엔드 1101/02-01 후속. The paired backend answers a field validation + // failure with 400 VALIDATION_FAILED and details [{field, code, message}] + // (its docs/web/http-contract.md §4). It reaches the form through the V2 + // client and lands on the same allowed fields a 422 does. + it("maps a paired backend 400 VALIDATION_FAILED onto the form fields", async () => { + const user = userEvent.setup(); + const client = createHttpClient({ + ...TEST_HTTP_CONTRACT, + baseUrl: "https://api.test", + fetcher: async () => + Response.json( + { + success: false, + error: { + code: "VALIDATION_FAILED", + category: "VALIDATION", + message: "요청 값이 올바르지 않습니다.", + retryable: false, + details: [ + { field: "name", code: "NOT_BLANK", message: "raw backend copy" }, + { field: "request", code: "INVALID", message: "raw backend copy" }, + ], + }, + meta: { requestId: "request-1", traceId: "trace-1" }, + }, + { status: 400 }, + ), + }); + render( + { + const result = await client.execute("CREATE_ENTITY", { + body: { name: command.name }, + idempotencyKey: "key-1", + }); + if (result.ok) throw new Error("expected a validation failure"); + return result; + }} + />, + ); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid"); + await user.click(screen.getByRole("button", { name: "Submit" })); + + await waitFor(() => + expect(screen.getByTestId("result")).toHaveTextContent("validation-error"), + ); + expect(screen.getByRole("textbox", { name: /Name/ })).toHaveAttribute( + "aria-invalid", + "true", + ); + expect(screen.getByRole("textbox", { name: /Note/ })).not.toHaveAttribute( + "aria-invalid", + ); + // A class-level error names no form field. + expect(screen.getByRole("alert")).toHaveTextContent( + "서버가 확인하지 못한 입력 항목", + ); + expect(document.body).not.toHaveTextContent("raw backend copy"); + }); + it.each([ [ "AUTH_REQUIRED", diff --git a/tests/integration/http-client.test.ts b/tests/integration/http-client.test.ts index d1a993f6..d640a775 100644 --- a/tests/integration/http-client.test.ts +++ b/tests/integration/http-client.test.ts @@ -616,3 +616,75 @@ describe("envelope keys the paired backend omits", () => { }); }); }); + +// 백엔드 1101/02-01 후속. The paired backend answers a field validation +// failure with 400 VALIDATION_FAILED, details [{field, code, message}] +// (its docs/web/http-contract.md §4): read as the 422 field validation it is. +// Every other 400 keeps its reading. +describe("paired backend 400 VALIDATION_FAILED", () => { + const meta = { requestId: "request-1", traceId: "trace-1" }; + + function answer400(code: string, details?: unknown) { + server.use( + http.post("https://api.test/api/entities", () => + HttpResponse.json( + { + success: false, + error: { + code, + category: "VALIDATION", + message: "요청 값이 올바르지 않습니다.", + retryable: false, + ...(details === undefined ? {} : { details }), + }, + meta, + }, + { status: 400 }, + ), + ), + ); + return testClient({ baseUrl: "https://api.test", clock }).execute( + "CREATE_ENTITY", + { body: { name: "n" }, idempotencyKey: "key-1" }, + ); + } + + it("reads the field details as validation issues, without backend copy", async () => { + const result = await answer400("VALIDATION_FAILED", [ + { field: "name", code: "NOT_BLANK", message: "raw backend copy" }, + { field: "items.name", code: "SIZE", message: "raw backend copy" }, + { field: "request", code: "INVALID", message: "raw backend copy" }, + ]); + + expect(result).toMatchObject({ + ok: false, + error: { + kind: "VALIDATION_REJECTED", + code: "VALIDATION_FAILED", + httpStatus: 400, + retryable: false, + validationIssues: [ + { path: "name", code: "NOT_BLANK" }, + { path: "items.name", code: "SIZE" }, + { path: "request", code: "INVALID" }, + ], + }, + }); + expect(JSON.stringify(result)).not.toContain("raw backend copy"); + }); + + it.each([ + // A body that did not parse: details names the cause, not a field. + { code: "VALIDATION_FAILED", details: { cause: "JsonParseException" } }, + { code: "VALIDATION_FAILED", details: undefined }, + { code: "BAD_PARAMETER", details: { parameter: "limit" } }, + ])("keeps a 400 $code with details $details as before", async ({ code, details }) => { + const result = await answer400(code, details); + + expect(result).toMatchObject({ + ok: false, + error: { kind: "UNKNOWN_CLIENT_FAILURE", code, httpStatus: 400 }, + }); + expect(result.ok ? null : result.error.validationIssues).toBeUndefined(); + }); +});