From ddf411e4e2b6d12617a0a9c202a5ee43f1678f1d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 1 Nov 2026 19:06:13 +0900 Subject: [PATCH] =?UTF-8?q?fix(bootstrap):=20ANONYMOUS=20=ED=94=84?= =?UTF-8?q?=EB=A1=9C=ED=95=84=20=EC=9A=94=EC=B2=AD=EC=9D=84=20=EC=84=B8?= =?UTF-8?q?=EC=85=98=20=EC=83=81=ED=83=9C=EC=99=80=20=EC=83=81=EA=B4=80?= =?UTF-8?q?=EC=97=86=EC=9D=B4=20=EB=B3=B4=EB=82=B8=EB=8B=A4=20(09-01)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 조립 루트의 attachCredentials가 operation의 인증 프로필을 보지 않고 세션 상태만 본다. 그래서 auth: "none" operation(ANONYMOUS 프로필)이 로그아웃이면 UNAUTHENTICATED, 로그인이면 세션 헤더가 붙어 CREDENTIAL_HEADER_NOT_ALLOWED로 거절되고, 외부 owner가 없으면 CREDENTIAL_OWNER_UNAVAILABLE로 끝난다. 어느 상태에서도 fetch가 0회다. scope 확인 바로 다음에 INSTALLED_REST_AUTH_PROFILES에서 operation.authProfileId의 transport를 읽고, ANONYMOUS면 세션을 보지 않고 빈 헤더로 READY를 돌려준다. executor에 넘기는 레지스트리와 같은 값을 같은 객체 안에서 읽는다. 그 밖의 프로필은 기존 경로 그대로다. 버린 대안: - executor(http-execution-v3.ts)가 ANONYMOUS면 attachCredentials를 부르지 않게 하기. adapter 공개 동작이 바뀐다. 지금 executor는 익명 프로필에도 협력자를 부르고 헤더를 내면 거절하며, 이 동작을 고정한 계약 테스트가 있다. 세션을 아는 쪽은 조립 루트라서 판단도 거기 둔다. - 리뷰 R1(attachCredentials를 createCredentialAttacher로 꺼내기). 구조 변경이라 이번 범위를 넘는다. 09-02에서 함께 다룬다. 새 테스트가 실제 createRuntimeAdapters를 거치므로 그때도 그대로 쓸 수 있다. - 새 케이스를 tests/unit/runtime-adapters.test.ts에 넣기. vi.mock은 파일 단위라 설치된 계약 묶음을 바꾸면 그 파일의 기존 테스트에도 번진다. 그래서 runtime-adapters-auth-profile.test.ts를 따로 만들었다. 위험·한계: - 로그인 상태의 익명 호출에 토큰이 붙지 않고 owner에게도 가지 않는다. ANONYMOUS 프로필이 자격증명 헤더를 하나도 허용하지 않으니 의도한 결과다. 인증 통합이 실패한 상태에서도 공개 읽기는 나간다. - scope fence는 익명 분기보다 먼저 본다. 모르는 프로필 id는 executor가 attachCredentials 전에 UNKNOWN_AUTH_PROFILE로 막는다. - 브라우저 화면은 보지 않았다. test:sample-removal도 돌리지 않았다. 새 테스트는 템플릿 소유 fixture와 src/contracts의 프로필만 쓴다. - tech-log 제품 쪽 우회는 다음 동기화 때 지운다. 검증: - RED(수정 전): 새 테스트 11건 중 5건 실패. ANONYMOUS 4개 상태가 expected 'UNAUTHENTICATED' to be 'SUCCESS'(demo 로그아웃), expected 'AUTH_INTEGRATION_FAILURE' to be 'SUCCESS'(demo 로그인, 외부 owner 로그인, owner 없음)로 실패. owner의 attachCredential이 1회 불림. 인증 필요 프로필의 UNAUTHENTICATED, CREDENTIAL_OWNER_ UNAVAILABLE 2건, fence 중 ABORTED_BY_SCOPE, 로그인 후 bearer 전송, 익명 요청의 SCOPE_FENCED 6건은 수정 전후 모두 통과. - GREEN: 새 테스트 11/11 통과. - 회귀: runtime-adapters, http-execution-v3(unit·integration), auth-recovery, legacy-http-credential-authority, tests/features, tests/component, 영역 R1 목록 71 files / 485 tests 통과. - tsc(tsconfig.app.json, tsconfig.test.json) 오류 0. 바꾼 두 파일 eslint 통과. check:architecture(pnpm 대신 exec 대행) 통과, 376 modules. Refs: docs/reviews/2026-11-01-maturity-review/09-app-core.md 09-01 --- src/bootstrap/runtime-adapters.ts | 10 + .../runtime-adapters-auth-profile.test.ts | 349 ++++++++++++++++++ 2 files changed, 359 insertions(+) create mode 100644 tests/unit/runtime-adapters-auth-profile.test.ts diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 2e507e05..7603e0c6 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -502,6 +502,16 @@ export async function createRuntimeAdapters( if (serverStateScope.getPhase() !== "READY") { return Object.freeze({ kind: "SCOPE_FENCED" as const }); } + // 09-01. The operation's installed profile decides first, the session + // second. An ANONYMOUS profile admits no credential header at all, so it + // goes out bare in every session state and never reaches the owner. Every + // other profile still needs a session and never downgrades to anonymous. + if ( + INSTALLED_REST_AUTH_PROFILES.get(operation.authProfileId)?.transport === + "ANONYMOUS" + ) { + return Object.freeze({ kind: "READY" as const, headers: {} }); + } const state = authSession.getState(); if (state === "integration-failed") { return Object.freeze({ kind: "UNAVAILABLE" as const }); diff --git a/tests/unit/runtime-adapters-auth-profile.test.ts b/tests/unit/runtime-adapters-auth-profile.test.ts new file mode 100644 index 00000000..616f7702 --- /dev/null +++ b/tests/unit/runtime-adapters-auth-profile.test.ts @@ -0,0 +1,349 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { DEMO_AUTHORIZATION_MARKER } from "../../src/adapters/auth/index.ts"; +import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { CREDENTIAL_HEADER_NAMES } from "../../src/contracts/rest-profiles.ts"; +import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; + +/** + * 09-01. The composition root decides credentials for every V3 operation. An + * `ANONYMOUS` operation must go out exactly once with no credential header in + * every session state, and a profile that needs a credential must keep failing + * closed. This runs the real `createRuntimeAdapters`; only the installed + * contract set (adds the fixture) and the feature-input composer (to reach the + * `http` capability a feature would receive) are replaced. + */ + +const fixture = vi.hoisted(() => ({ + http: undefined as InstalledHttpOperationExecutor | undefined, + /** The fixture list operation under another id and auth profile. */ + withProfile( + contract: T, + operationId: string, + authProfileId: string, + ): T { + return { + ...contract, + contract: { ...contract.contract, operationId }, + frontend: { ...contract.frontend, authProfileId }, + }; + }, +})); + +vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => { + const original = + await importOriginal(); + const { composeContractContributions } = await import( + "../../src/contracts/external-contract-runtime.ts" + ); + const { TEST_CONTRACT_CONTRIBUTION, TEST_LIST_HTTP_CONTRACT: list } = + await import("../helpers/external-contract-fixture.ts"); + return { + ...original, + COMPOSED_CONTRACT_CONTRIBUTIONS: composeContractContributions([ + { + ...TEST_CONTRACT_CONTRIBUTION, + http: [ + list, + fixture.withProfile(list, "TEST_LIST_ENTITIES_BEARER", "REFERENCE_EXTERNAL_BEARER"), + ] as typeof TEST_CONTRACT_CONTRIBUTION.http, + }, + ]), + }; +}); + +vi.mock("../../src/features/installed-feature-adapters.ts", async (importOriginal) => { + const original = + await importOriginal(); + return { + ...original, + createInstalledFeatureInputs: ( + ...args: Parameters + ) => { + fixture.http = args[0].http; + return original.createInstalledFeatureInputs(...args); + }, + }; +}); + +type Runtime = Parameters[0]["runtime"]; +type Release = Parameters[0]["release"]; +type Adapters = Awaited>; + +function runtimeFor(authMode: "demo" | "external"): Runtime { + return { + config: { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + TELEMETRY_ENABLED: false, + AUTH_MODE: authMode, + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 0, + RELEASE_MANIFEST_URL: "/release-manifest.json", + CONFIG_SCHEMA_VERSION: "2.0", + CAPABILITY_OVERRIDES: { + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DEFAULT", + OFFLINE_COMMANDS: "DEFAULT", + }, + FEATURE_OVERRIDES: {}, + }, + configSchema: "V2", + build: { + buildId: "build-a", + commitSha: "abc123", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + validationDurationMs: 0, + }; +} + +const release: Release = { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, +}; + +const ANONYMOUS_OPERATION = TEST_LIST_HTTP_CONTRACT; +const BEARER_OPERATION = fixture.withProfile( + TEST_LIST_HTTP_CONTRACT, + "TEST_LIST_ENTITIES_BEARER", + "REFERENCE_EXTERNAL_BEARER", +); + +function externalOwner( + attachCredential: () => Promise = async () => ({ + headers: { authorization: "Bearer owner-token" }, + }), +) { + const listeners = new Set<() => void>(); + let subject = "user-a"; + return { + readState: () => "authenticated", + readSubject: () => subject, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: vi.fn(attachCredential), + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + /** Another user signs in on this owner: the scope fences. */ + switchUser() { + subject = "user-b"; + for (const listener of listeners) listener(); + }, + }; +} + +let current: Adapters | undefined; +afterEach(() => { + current?.infrastructure.dispose(); + current = undefined; + fixture.http = undefined; +}); + +async function compose( + authMode: "demo" | "external", + host: Record = {}, +) { + const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => + Response.json([{ id: "entity-1", name: "Entity" }]), + ); + current = await createRuntimeAdapters({ + runtime: runtimeFor(authMode), + release, + host, + fetcher: fetcher as unknown as typeof fetch, + }); + const http = fixture.http; + if (!http) throw new Error("The http capability was not composed"); + return { adapters: current, http, fetcher }; +} + +async function signInDemo(adapters: Adapters) { + await adapters.outputPorts.session.beginSignIn(); + await vi.waitFor(() => { + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"); + }); +} + +function sentCredentialHeaders(init: RequestInit | undefined): string[] { + return [...new Headers(init?.headers).keys()].filter((name) => + (CREDENTIAL_HEADER_NAMES as readonly string[]).includes(name), + ); +} + +describe("09-01 ANONYMOUS operations through the composition root", () => { + it.each([ + { + state: "demo signed out", + setup: () => compose("demo"), + }, + { + state: "demo signed in", + setup: async () => { + const composed = await compose("demo"); + await signInDemo(composed.adapters); + return composed; + }, + }, + { + state: "external owner signed in", + setup: () => + compose("external", { __CA_FRONTEND_AUTH_OWNER__: externalOwner() }), + }, + { + state: "external mode without an owner", + setup: () => compose("external"), + }, + ])("sends once with no credential header ($state)", async ({ setup }) => { + const { http, fetcher } = await setup(); + + const outcome = await http.execute( + ANONYMOUS_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome.kind).toBe("SUCCESS"); + expect(fetcher).toHaveBeenCalledOnce(); + const [url, init] = fetcher.mock.calls[0] ?? []; + expect(String(url)).toBe("http://localhost:8080/api/test-entities?limit=1"); + expect(init?.credentials).toBe("omit"); + expect(sentCredentialHeaders(init)).toEqual([]); + }); + + it("does not hand an ANONYMOUS operation to the external owner", async () => { + const owner = externalOwner(); + const { http } = await compose("external", { + __CA_FRONTEND_AUTH_OWNER__: owner, + }); + + await http.execute(ANONYMOUS_OPERATION, { limit: 1 }, { routeId: "TEST_ROUTE" }); + + expect(owner.attachCredential).not.toHaveBeenCalled(); + }); + + it("still holds an ANONYMOUS operation while the scope is fenced", async () => { + const { http, fetcher, adapters } = await compose("demo"); + // The session change fences the scope synchronously; READY comes later. + void adapters.outputPorts.session.beginSignIn(); + + const outcome = await http.execute( + ANONYMOUS_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome).toMatchObject({ + kind: "CONTRACT_VIOLATION", + violation: { kind: "SCOPE_FENCED" }, + }); + expect(fetcher).not.toHaveBeenCalled(); + }); +}); + +describe("09-01 credentialed operations keep failing closed", () => { + it("refuses without a session instead of downgrading to anonymous", async () => { + const { http, fetcher } = await compose("demo"); + + const outcome = await http.execute( + BEARER_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome).toEqual({ + kind: "UNAUTHENTICATED", + effect: "NOT_APPLICABLE", + }); + expect(fetcher).not.toHaveBeenCalled(); + }); + + it.each([ + { + state: "external mode without an owner", + host: () => ({}), + }, + { + state: "an owner that fails to attach", + host: () => ({ + __CA_FRONTEND_AUTH_OWNER__: externalOwner(async () => { + throw new Error("owner down"); + }), + }), + }, + ])("reports the credential owner unavailable ($state)", async ({ host }) => { + const { http, fetcher } = await compose("external", host()); + + const outcome = await http.execute( + BEARER_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome).toMatchObject({ + kind: "AUTH_INTEGRATION_FAILURE", + reason: "CREDENTIAL_OWNER_UNAVAILABLE", + }); + expect(fetcher).not.toHaveBeenCalled(); + }); + + it("abandons the request when the session changes while the owner attaches", async () => { + const owner = externalOwner(async () => { + owner.switchUser(); + return { headers: { authorization: "Bearer owner-token" } }; + }); + const { http, fetcher } = await compose("external", { + __CA_FRONTEND_AUTH_OWNER__: owner, + }); + + const outcome = await http.execute( + BEARER_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + // A fence during the credential wait aborts the transport (Q-6.3-6). + expect(outcome).toMatchObject({ + kind: "TRANSPORT_FAILURE", + failure: { kind: "ABORTED_BY_SCOPE" }, + }); + expect(fetcher).not.toHaveBeenCalled(); + }); + + it("sends the session credential once signed in", async () => { + const { http, fetcher, adapters } = await compose("demo"); + await signInDemo(adapters); + + const outcome = await http.execute( + BEARER_OPERATION, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome.kind).toBe("SUCCESS"); + expect(fetcher).toHaveBeenCalledOnce(); + const init = fetcher.mock.calls[0]?.[1]; + expect(new Headers(init?.headers).get("authorization")).toBe( + DEMO_AUTHORIZATION_MARKER, + ); + }); +});