fix(bootstrap): 401을 그 요청의 자격 증명을 낸 쪽에만 알린다 (1103/09-01)

문제
조립 루트는 응답이 있는 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
This commit is contained in:
DongHyeonka
2026-11-04 20:15:26 +09:00
parent 004a205748
commit 0aada28b91
5 changed files with 203 additions and 5 deletions
+1
View File
@@ -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에 요구하는 인증을 따른다. 새 프로필은 템플릿 파일이 아니라 제품 소유 파일 두 곳에만 더한다.
@@ -61,4 +61,14 @@ export type ProductComposition = Readonly<{
>;
/** Auth profile id → provider. An ANONYMOUS profile never reaches one. */
credentialProviders: Readonly<Record<string, ProductCredentialProvider>>;
/**
* 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;
}>;
+33 -3
View File
@@ -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
@@ -172,9 +172,11 @@ afterEach(() => {
async function compose(
authMode: "demo" | "external",
host: Record<string, unknown> = {},
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
@@ -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<string, unknown>,
onCredentialRejected: undefined as ((binding: unknown) => void) | undefined,
withProfile<T extends { contract: object; frontend: object }>(
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<string, unknown> = {},
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();
});
});