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(); + }); +});