From 0aada28b91044cac84d6ef2c9d836e0401aa5278 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:15:26 +0900 Subject: [PATCH] =?UTF-8?q?fix(bootstrap):=20401=EC=9D=84=20=EA=B7=B8=20?= =?UTF-8?q?=EC=9A=94=EC=B2=AD=EC=9D=98=20=EC=9E=90=EA=B2=A9=20=EC=A6=9D?= =?UTF-8?q?=EB=AA=85=EC=9D=84=20=EB=82=B8=20=EC=AA=BD=EC=97=90=EB=A7=8C=20?= =?UTF-8?q?=EC=95=8C=EB=A6=B0=EB=8B=A4=20(1103/09-01)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 조립 루트는 응답이 있는 UNAUTHENTICATED면 프로필을 보지 않고 authSession.onUnauthenticated()를 불렀다. ANONYMOUS 요청은 세션을 묻지 않고 헤더 없이 나가는데도, 그 401이 로그인한 사용자를 로그아웃시키고 scope fence가 서버 상태 캐시를 모두 비웠다. 제품 credentialProviders가 자격 증명을 낸 요청의 401도 템플릿 세션을 로그아웃시켰다. 고른 방법 attachCredentials와 같은 순서로 401의 주인을 가른다(reportServerUnauthenticated). - ANONYMOUS 프로필: 아무에게도 알리지 않는다. - 제품 provider 프로필: 세션은 그대로 두고, ProductComposition의 선택 hook onCredentialRejected({operationId, authProfileId})를 부른다. BFF 제품은 거기서 자기 owner에게 알린다. hook의 throw는 결과를 바꾸지 않는다. - 나머지(템플릿 세션이 낸 자격 증명): 지금처럼 onUnauthenticated(). 버린 대안: ANONYMOUS만 빼기(2줄)는 provider 경로의 과잉 로그아웃이 남는다. owner가 401을 직접 판단하게 하면 owner 계약이 바뀌고 모든 owner가 판단 로직을 쓴다. 위험·한계 - 제품 provider가 템플릿 세션과 같은 세션의 자격 증명을 내는 경우, 제품이 hook을 쓰지 않으면 그 401은 세션을 바꾸지 않는다. 계약 주석과 매뉴얼 02 5절에 적었다. - 401 도착과 계정 전환이 겹치는 경쟁은 여전히 확인하지 않았다. 검증 - RED: 새 테스트 3건(ANONYMOUS 401 demo·external, provider 401)이 수정 전 실패했다. bearer 대조군은 수정 전후 모두 통과. - node scripts/run-vitest.ts run runtime-adapters-{auth-profile,credential-order}, runtime-adapters, product-composition-fixture, reference-runtime-composition → 5 files / 62 tests 통과. check:types 통과. eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-01 --- docs/manual/02-decision-tables.md | 1 + src/bootstrap/product-composition-contract.ts | 10 +++ src/bootstrap/runtime-adapters.ts | 36 +++++++- .../runtime-adapters-auth-profile.test.ts | 82 ++++++++++++++++++- .../runtime-adapters-credential-order.test.ts | 79 +++++++++++++++++- 5 files changed, 203 insertions(+), 5 deletions(-) diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 96fe6213..21a98126 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -191,6 +191,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - `REFERENCE_EXTERNAL_BEARER`는 `EXTERNAL_BEARER`의 옛 이름이다. `@deprecated`이고 한 릴리스 뒤 지운다. 새 코드는 쓰지 않는다. - 제품 프로필 ID는 템플릿 프로필 ID와 겹치면 안 된다. - 쿠키 인증과 CSRF 헤더는 인증 프로필의 헤더 집합으로 표현한다. 예제: `tests/unit/product-composition-fixture.test.ts`. +- 서버가 401을 주면 그 요청의 자격 증명을 낸 쪽만 안다. `ANONYMOUS` 요청의 401은 세션을 바꾸지 않는다. 템플릿 세션이 낸 자격 증명이면 세션이 로그아웃된다. 제품 `credentialProviders`가 낸 자격 증명이면 세션은 그대로이고 `composeProduct`가 돌려준 `onCredentialRejected`가 불린다(선택). **기준**: 백엔드가 그 API에 요구하는 인증을 따른다. 새 프로필은 템플릿 파일이 아니라 제품 소유 파일 두 곳에만 더한다. diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index 0f5190b3..742a1c0f 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -61,4 +61,14 @@ export type ProductComposition = Readonly<{ >; /** Auth profile id → provider. An ANONYMOUS profile never reaches one. */ credentialProviders: Readonly>; + /** + * 1103/09-01. Optional. Called when the server answers 401 to a request + * whose credential one of `credentialProviders` supplied. The template + * session is not told, because it did not supply that credential; a BFF + * product whose provider and session owner share one cookie session tells + * its owner here (`notifyUnauthenticated`). A throw is ignored. + */ + onCredentialRejected?( + binding: Readonly<{ operationId: string; authProfileId: string }>, + ): void; }>; diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index d419621b..85a3acab 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -535,6 +535,30 @@ export async function createRuntimeAdapters( // operation of a feature that has not loaded resolves to nothing and is // refused below, exactly like an operation no feature contributes. const contractRegistry = createInstalledContractRegistry(); + /** + * 1103/09-01. A 401 judges the credential the request carried, so it goes to + * whoever supplied it, decided in the same order as `attachCredentials`. An + * ANONYMOUS request carried none: nobody is told. A product provider's + * credential: the product is told, the session is not. Only the session's + * own credential signs the session out. + */ + function reportServerUnauthenticated( + authProfileId: string, + binding: Readonly<{ operationId: string; authProfileId: string }>, + ): void { + if (INSTALLED_REST_AUTH_PROFILES.get(authProfileId)?.transport === "ANONYMOUS") { + return; + } + if (Object.hasOwn(productCredentialProviders, authProfileId)) { + try { + onProductCredentialRejected?.(Object.freeze(binding)); + } catch { + // A product hook defect cannot change the contract execution outcome. + } + return; + } + authSession.onUnauthenticated(); + } const contractOperations: InstalledHttpOperationExecutor = Object.freeze({ async execute(operation, input, executionContext) { const installed = contractRegistry.resolveHttp( @@ -589,7 +613,10 @@ export async function createRuntimeAdapters( // dispatch for lack of a credential carries no response metadata; telling // the owner would overwrite a recovering session and re-fence the scope. if (outcome.kind === "UNAUTHENTICATED" && outcome.metadata !== undefined) { - authSession.onUnauthenticated(); + reportServerUnauthenticated(executableContract.frontend.authProfileId, { + operationId: executableContract.contract.operationId, + authProfileId: executableContract.frontend.authProfileId, + }); } return outcome; }, @@ -613,8 +640,11 @@ export async function createRuntimeAdapters( http: contractOperations, isScopeReady: () => serverStateScope.getPhase() === "READY", }) satisfies ProductComposition; - const productCredentialProviders: ProductComposition["credentialProviders"] = - product.credentialProviders; + // Read through the contract type: the product's own return type omits the + // optional hook when the product does not use it. + const productContract: ProductComposition = product; + const productCredentialProviders = productContract.credentialProviders; + const onProductCredentialRejected = productContract.onCredentialRejected; // Each installed contribution receives only the capabilities it declares. // The template's own capabilities come last, so a product cannot replace // them. 09-05. `indexedDb` is not built here: IndexedDB is an opt-in diff --git a/tests/unit/runtime-adapters-auth-profile.test.ts b/tests/unit/runtime-adapters-auth-profile.test.ts index 2200b91f..978a3d75 100644 --- a/tests/unit/runtime-adapters-auth-profile.test.ts +++ b/tests/unit/runtime-adapters-auth-profile.test.ts @@ -172,9 +172,11 @@ afterEach(() => { async function compose( authMode: "demo" | "external", host: Record = {}, + respond: () => Response = () => + Response.json([{ id: "entity-1", name: "Entity" }]), ) { const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => - Response.json([{ id: "entity-1", name: "Entity" }]), + respond(), ); current = await createRuntimeAdapters({ runtime: runtimeFor(authMode), @@ -358,6 +360,84 @@ describe("09-01 credentialed operations keep failing closed", () => { }); }); +/** + * 1103/09-01. A server 401 is a verdict on the credential the request carried. + * An ANONYMOUS request carried none of the session's, so its 401 says nothing + * about the session: the signed-in user stays signed in and the server-state + * scope is not fenced. A request that carried the session's credential still + * signs out (R-3.2). + */ +describe("1103/09-01 a 401 is a session verdict only for the session's credential", () => { + const unauthorized = () => new Response(null, { status: 401 }); + + it("keeps a demo session signed in when an ANONYMOUS request gets 401", async () => { + const { http, fetcher, adapters } = await compose("demo", {}, unauthorized); + await signInDemo(adapters); + const scope = adapters.infrastructure.serverStateScope.getSnapshot(); + + const outcome = await http.execute( + ANONYMOUS_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome.kind).toBe("UNAUTHENTICATED"); + expect(fetcher).toHaveBeenCalledOnce(); + expect(sentCredentialHeaders(fetcher.mock.calls[0]?.[1])).toEqual([]); + expect(adapters.outputPorts.session.getState()).toBe("authenticated"); + expect(scope.isCurrent()).toBe(true); + }); + + it("does not tell the external owner about an ANONYMOUS request's 401", async () => { + const owner = externalOwner(); + const notifyUnauthenticated = vi.spyOn(owner, "notifyUnauthenticated"); + const { http } = await compose( + "external", + { __CA_FRONTEND_AUTH_OWNER__: owner }, + unauthorized, + ); + + const outcome = await http.execute( + ANONYMOUS_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome.kind).toBe("UNAUTHENTICATED"); + expect(owner.attachCredential).not.toHaveBeenCalled(); + expect(notifyUnauthenticated).not.toHaveBeenCalled(); + }); + + it("still tells the owner when the session's own credential gets 401", async () => { + const owner = externalOwner(); + const notifyUnauthenticated = vi.spyOn(owner, "notifyUnauthenticated"); + const { http } = await compose( + "external", + { __CA_FRONTEND_AUTH_OWNER__: owner }, + unauthorized, + ); + + const outcome = await http.execute( + BEARER_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome.kind).toBe("UNAUTHENTICATED"); + expect(owner.attachCredential).toHaveBeenCalledOnce(); + expect(notifyUnauthenticated).toHaveBeenCalledOnce(); + }); + + it("still signs a demo session out when its credential gets 401", async () => { + const { http, adapters } = await compose("demo", {}, unauthorized); + await signInDemo(adapters); + + await http.execute(BEARER_OPERATION, { limit: 1 }, { routeId: "TEST_ROUTE" }); + + expect(adapters.outputPorts.session.getState()).toBe("unauthenticated"); + }); +}); + /** * 03-02. An operation no loaded feature contributed is refused before the * executor runs. That refusal must still leave the one diagnostic every V3 diff --git a/tests/unit/runtime-adapters-credential-order.test.ts b/tests/unit/runtime-adapters-credential-order.test.ts index 489b23c2..e3d876ce 100644 --- a/tests/unit/runtime-adapters-credential-order.test.ts +++ b/tests/unit/runtime-adapters-credential-order.test.ts @@ -20,6 +20,7 @@ import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts const fixture = vi.hoisted(() => ({ http: undefined as InstalledHttpOperationExecutor | undefined, providers: {} as Record, + onCredentialRejected: undefined as ((binding: unknown) => void) | undefined, withProfile( contract: T, operationId: string, @@ -81,6 +82,9 @@ vi.mock("../../src/bootstrap/product-composition.ts", () => ({ composeProduct: () => ({ capabilities: {}, credentialProviders: fixture.providers, + ...(fixture.onCredentialRejected === undefined + ? {} + : { onCredentialRejected: fixture.onCredentialRejected }), }), })); @@ -172,14 +176,17 @@ afterEach(() => { current = undefined; fixture.http = undefined; fixture.providers = {}; + fixture.onCredentialRejected = undefined; }); async function compose( authMode: "demo" | "external", host: Record = {}, + respond: () => Response = () => + Response.json([{ id: "entity-1", name: "Entity" }]), ) { const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => - Response.json([{ id: "entity-1", name: "Entity" }]), + respond(), ); current = await createRuntimeAdapters({ runtime: runtimeFor(authMode), @@ -340,3 +347,73 @@ describe("09-02 credential order in the composition root", () => { } }); }); + +/** + * 1103/09-01. A 401 to a credential a product provider supplied is the + * provider's verdict, not the template session's: the session did not supply + * that credential. The product hears it through `onCredentialRejected`. + */ +describe("1103/09-01 a 401 to a product provider's credential", () => { + const unauthorized = () => new Response(null, { status: 401 }); + + it("leaves the session alone and tells the product", async () => { + const owner = externalOwner(); + const notifyUnauthenticated = vi.spyOn(owner, "notifyUnauthenticated"); + const rejected = vi.fn(); + fixture.providers = { EXTERNAL_BEARER: productToken }; + fixture.onCredentialRejected = rejected; + const { http, adapters } = await compose( + "external", + { __CA_FRONTEND_AUTH_OWNER__: owner }, + unauthorized, + ); + const scope = adapters.infrastructure.serverStateScope.getSnapshot(); + + const outcome = await http.execute( + PROFILE_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome.kind).toBe("UNAUTHENTICATED"); + expect(notifyUnauthenticated).not.toHaveBeenCalled(); + expect(scope.isCurrent()).toBe(true); + expect(rejected).toHaveBeenCalledExactlyOnceWith({ + operationId: "TEST_LIST_ENTITIES_BEARER", + authProfileId: "EXTERNAL_BEARER", + }); + }); + + it("keeps the outcome when the product hook throws", async () => { + fixture.providers = { EXTERNAL_BEARER: productToken }; + fixture.onCredentialRejected = () => { + throw new Error("product hook defect"); + }; + const { http } = await compose("demo", {}, unauthorized); + + const outcome = await http.execute( + PROFILE_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome.kind).toBe("UNAUTHENTICATED"); + }); + + it("does not call the product hook for the session's own credential", async () => { + const rejected = vi.fn(); + fixture.onCredentialRejected = rejected; + const owner = externalOwner(); + const notifyUnauthenticated = vi.spyOn(owner, "notifyUnauthenticated"); + const { http } = await compose( + "external", + { __CA_FRONTEND_AUTH_OWNER__: owner }, + unauthorized, + ); + + await http.execute(PROFILE_OPERATION, { limit: 1 }, { routeId: "TEST_ROUTE" }); + + expect(notifyUnauthenticated).toHaveBeenCalledOnce(); + expect(rejected).not.toHaveBeenCalled(); + }); +});