From 365d8c3c029a63d1e7ce699cb15bdcfda2937217 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 22:22:35 +0900 Subject: [PATCH] =?UTF-8?q?fix(contracts):=20=EC=BF=A0=ED=82=A4=20?= =?UTF-8?q?=EC=9D=B8=EC=A6=9D=20=EC=93=B0=EA=B8=B0=EB=8A=94=20CSRF=20?= =?UTF-8?q?=ED=97=A4=EB=8D=94=EB=A5=BC=20=EC=9A=94=EA=B5=AC=ED=95=98?= =?UTF-8?q?=EB=8A=94=20=ED=94=84=EB=A1=9C=ED=95=84=EB=A7=8C=20=EC=A1=B0?= =?UTF-8?q?=EB=A6=BD=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 브라우저는 쿠키를 어느 사이트의 요청에든 붙이므로, 쿠키로 인증하는 쓰기 요청은 페이지만 넣을 수 있는 헤더(CSRF 토큰)가 있어야 서버가 진짜 요청을 가른다. V2 클라이언트는 resolveRestSecurityProfiles로 "쿠키 프로필 + GET·HEAD 밖 method면 HEADER CSRF 프로필"을 강제했다. 048f490·12f3bb7이 V2를 지운 뒤 V3에는 이 검사가 없다. V3 프로필 설치 규칙은 SAME_ORIGIN_COOKIE에 쿠키 전송과 bearer 금지만 요구한다. 그래서 제품이 CSRF 헤더 없는 쿠키 프로필을 POST에 붙여도 조립이 통과한다. 고른 방법 assertHttpContract가 operation의 auth profile을 설치된 레지스트리에서 찾아, 쓰기(GET·HEAD 밖)인데 SAME_ORIGIN_COOKIE이고 requiredCredentialHeaders에 x-csrf-token·x-xsrf-token이 없으면 operation·method·프로필 이름을 담아 거절한다. 읽기 쿠키 프로필은 CSRF 없이 그대로 된다(tech-log·memento 예시와 같다). 버린 대안 - 프로필 설치 때 모든 쿠키 프로필에 CSRF 요구: 읽기 전용 쿠키 프로필 (MEMENTO_BFF_READ 등)까지 막는다. method는 operation에만 있다. - 요청 때(attachCredentials) 검사: 조립 때 잡을 수 있는 설정 실수를 사용자 요청 시점까지 미룬다. 위험·한계 - 이미 CSRF 없는 쿠키 쓰기 프로필을 쓰는 제품은 조립이 실패한다. 의도한 실패다(CHANGELOG [보안]). - 헤더 값이 올바른 CSRF 토큰인지는 서버만 안다. 프론트는 헤더가 반드시 실리는지만 보장한다(requiredCredentialHeaders가 없으면 fetch 0회). 검증 - RED: tests/unit/rest-profile-contract.test.ts "refuses a write whose cookie profile requires no CSRF header" 실패(조립이 통과). - GREEN: 같은 파일 7건 통과. CSRF를 요구하는 쓰기와 CSRF 없는 쿠키 읽기는 조립된다. - check:types, lint, check:architecture, check:registries, test:unit 2,568, test:integration 117, test:component 245 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.7 --- docs/manual/reference/errors.md | 1 + src/contracts/external-contract-runtime.ts | 14 ++++++ tests/unit/rest-profile-contract.test.ts | 51 ++++++++++++++++++++++ 3 files changed, 66 insertions(+) diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index c22a5b87..4cf83d62 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -72,6 +72,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | 메시지 | 원인 | 고칠 곳 | |---|---|---| | `/: unknown authProfileId ` (계약 조립 오류의 `reason`) | 없는 인증 프로필 | `contracts/-contract-contribution.ts`의 `frontend.authProfileId`. 제품 프로필이면 `src/contracts/product-contracts.ts` | +| `/: with cookie profile must require x-csrf-token or x-xsrf-token` (계약 조립 오류의 `reason`) | 쿠키 인증 프로필로 쓰기 요청을 보내는데 프로필이 CSRF 헤더를 요구하지 않는다 | `src/contracts/product-contracts.ts`의 그 프로필 `requiredCredentialHeaders`. 짝 백엔드는 `x-xsrf-token` | | `Product REST auth profile reuses a template profile id.` | 제품 프로필 ID가 템플릿 것과 같다 | `src/contracts/product-contracts.ts` | ### 계약·스키마·mapper diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 5976fbbe..4ac7ffec 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -540,6 +540,20 @@ function assertHttpContract( } } assertExecutionPolicy(installed.frontend, label, authProfiles); + // A browser attaches an ambient cookie to any site's request, so a + // cookie-authenticated write needs a header only the page can set. + const profile = authProfiles.get(installed.frontend.authProfileId); + if ( + !isRead && + profile?.transport === "SAME_ORIGIN_COOKIE" && + !profile.requiredCredentialHeaders.some( + (header) => header === "x-csrf-token" || header === "x-xsrf-token", + ) + ) { + fail( + `${label}: ${contract.method} with cookie profile ${profile.authProfileId} must require x-csrf-token or x-xsrf-token`, + ); + } if ( installed.frontend.retryBudget > 0 && contract.retrySemantics === "NEVER" diff --git a/tests/unit/rest-profile-contract.test.ts b/tests/unit/rest-profile-contract.test.ts index 09be86f6..8451c7a3 100644 --- a/tests/unit/rest-profile-contract.test.ts +++ b/tests/unit/rest-profile-contract.test.ts @@ -56,6 +56,57 @@ describe("one installed REST auth profile registry", () => { }); }); +/** + * A cookie-authenticated write must carry a CSRF proof header: the browser + * attaches the cookie to any site's request, so the header is what tells the + * server the page itself sent it. The V2 client refused such a binding; the + * installed HTTP contract has to refuse it too. + */ +describe("cookie profiles on writes", () => { + const cookie = (authProfileId: string, csrf: readonly ("x-csrf-token" | "x-xsrf-token")[]) => ({ + authProfileId, + transport: "SAME_ORIGIN_COOKIE" as const, + credentials: "include" as const, + allowedCredentialHeaders: [...csrf], + requiredCredentialHeaders: [...csrf], + }); + const registry = installRestAuthProfileRegistry({ + ...REST_AUTH_PROFILES, + COOKIE_READ: cookie("COOKIE_READ", []), + COOKIE_WRITE: cookie("COOKIE_WRITE", ["x-xsrf-token"]), + }); + const withProfile = (index: number, authProfileId: string) => { + const row = TEST_CONTRACT_CONTRIBUTION.http[index]!; + return { + ...TEST_CONTRACT_CONTRIBUTION, + http: [{ ...row, frontend: { ...row.frontend, authProfileId } }], + }; + }; + // TEST_CONTRACT_CONTRIBUTION.http: [list (GET), detail (GET), create (POST)] + + it("refuses a write whose cookie profile requires no CSRF header", () => { + expect(() => + composeContractContributions([withProfile(2, "COOKIE_READ")], registry), + ).toThrow( + expect.objectContaining({ + reason: + "test-feature/TEST_CREATE_ENTITY: POST with cookie profile COOKIE_READ must require x-csrf-token or x-xsrf-token", + }), + ); + }); + + it("accepts a write that requires a CSRF header, and a cookie read without one", () => { + expect( + composeContractContributions([withProfile(2, "COOKIE_WRITE")], registry) + .httpByOperationId.size, + ).toBe(1); + expect( + composeContractContributions([withProfile(0, "COOKIE_READ")], registry) + .httpByOperationId.size, + ).toBe(1); + }); +}); + /** * 1101/16-03. The only bearer profile is the platform's, not the sample's: * `EXTERNAL_BEARER`. The old name stays for one release as a deprecated alias