문제
유일한 bearer 인증 프로필 이름이 샘플 이름 REFERENCE_EXTERNAL_BEARER다.
세션이 필요한 제품 기능은 지운 샘플의 이름을 계속 쓰거나 템플릿 소유
파일에 프로필을 더해야 한다. 샘플 제거 드릴의 잔여 검사 정규식도 이
이름을 잡지 않아 샘플을 지운 제품에 그대로 남는다. 리뷰 (2) 오류
메시지는 abf3ce5가 했고 (1) 이름 변경이 남았다.
고른 방법 (2026-11-03 결정)
- 프로필 이름을 EXTERNAL_BEARER로 바꿨다. 참조 기능의 V2 operation 3개와
V3 descriptor 3개, external-session-adapter 주석, 테스트, VD-23 문서를
새 이름으로 옮겼다.
- 옛 이름은 한 릴리스 동안 REST_AUTH_PROFILES에 별칭 한 줄로 남기고
JSDoc @deprecated를 붙였다. 레지스트리는 키와 authProfileId가 같아야
하므로 별칭은 EXTERNAL_BEARER를 펼치고 id만 옛 이름으로 둔 객체다.
그래서 옛 이름을 적은 다운스트림 operation도 같은 transport·헤더로
해석된다.
- scripts/scale의 PLATFORM_TOKENS에서 이 이름을 뺐다. 참조 기능에 더는
"REFERENCE"가 든 프로필 이름이 없어 이름 바꾸기에서 보호할 것이 없다.
- 새 테스트 두 개: 별칭이 id만 빼고 EXTERNAL_BEARER와 같게 설치되는지,
src에 옛 이름이 별칭 한 줄 외에 없는지(완료 기준).
버린 대안
- 별칭 없이 바로 바꾸기: 옛 이름을 쓰는 다운스트림 기능이 모듈 로드에서
바로 실패한다. 공개 이름을 깨는 변경은 BREAKING 결정이 있을 때만 한다.
- 조회 시점의 이름 매핑(alias 표): resolve·executor·composition 세 곳이
매핑을 알아야 한다. 프로필 항목 하나가 더 작다.
위험·한계
- 설치된 프로필이 셋이 된다. 같은 설정이 두 id로 있을 뿐 권한이 넓어지지
않는다. 별칭은 다음 minor에서 지우고 CHANGELOG [계약] 행을 남긴다.
그때 "src only on the alias line" 테스트의 기대값을 빈 목록으로 바꾼다.
- 다운스트림 문자열 id("REFERENCE_EXTERNAL_BEARER")에는 @deprecated 표시가
보이지 않는다. CHANGELOG로 알린다.
- FE-REG-API 행 3개의 authProfileId가 바뀐다. breakingFields가 아니라
behavior-change이므로 증거 없이 게이트를 통과한다. 기준선 재승인은 이번
작업 묶음 끝에서 한 번에 한다.
- 초기 JS gzip(초기 청크 파일별 gzip 합) 203,818 → 203,840 B(+22 B). 별칭
항목이 rest-profiles가 있는 초기 청크에 실린다. 참조 기능 계약은 lazy
청크라 초기 크기에 영향이 없다.
검증
- RED(수정 전): rest-profile-contract.test.ts 새 사례 2건 실패("expected
undefined to match object { transport: 'BEARER_HEADER', …(1) }",
"expected [ …(9) ] to deeply equal [ Array(1) ]").
- GREEN: 같은 파일 10/10 통과. check-registries "11 registries PASS"
(FE-REG-API authProfileId 3건 behavior-change).
- 회귀: tests/{unit,integration,features,contract,runtime-schema}
207 파일 2,366건 통과(pnpm·corepack을 띄우는 6개 제외:
http-scenario-evidence, ci-workflow-generation, lab-performance,
fixture-node-modules, deployment-admission, security-followup-archive).
tsc app·test·node rc=0, 바꾼 파일 eslint rc=0. vite build 성공.
- 미실행: check:architecture, test:sample-removal(pnpm 필요), e2e.
Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md
241 lines
7.3 KiB
TypeScript
241 lines
7.3 KiB
TypeScript
import { HttpResponse, http } from "msw";
|
|
import { setupServer } from "msw/node";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
|
|
|
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
|
import { defineRestOperation } from "../../src/contracts/api-operations.ts";
|
|
import { createRestProviderProfile } from "../../src/contracts/rest-profiles.ts";
|
|
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
|
|
|
/**
|
|
* LEG-01 / LEG-02. The V2 client is not the default path any more, but a
|
|
* rollback re-activates it, so its credential and recovery authority must match
|
|
* V3 rather than diverge quietly.
|
|
*/
|
|
|
|
const BEARER_LIST = defineRestOperation({
|
|
method: "GET",
|
|
path: "/api/entities",
|
|
operationId: "LIST_ENTITIES",
|
|
auth: "external-session",
|
|
timeoutMs: null,
|
|
idempotency: "safe",
|
|
retry: "runtime",
|
|
requestSource: "search",
|
|
requestSchema: "EntityListQuery",
|
|
responseSchema: "EntityListPayload",
|
|
owner: "test-fixture",
|
|
contractVersion: 2,
|
|
protocol: "REST",
|
|
semantics: "QUERY",
|
|
replayPolicy: "SAFE",
|
|
idempotencyKeyPolicy: "NONE",
|
|
mapperId: "EntityListMapper",
|
|
successStatuses: [200],
|
|
responseMediaTypes: ["application/json"],
|
|
maxResponseBytes: 32_768,
|
|
providerId: "PRIMARY_API",
|
|
authProfileId: "EXTERNAL_BEARER",
|
|
csrfProfileId: "NO_CSRF_BEARER",
|
|
pathSchema: "NoRequest",
|
|
pathParameterNames: [],
|
|
maxEncodedSearchBytes: 1_024,
|
|
});
|
|
|
|
let observedAuthorization: string | null = null;
|
|
let requestCount = 0;
|
|
let nextStatus = 200;
|
|
|
|
const server = setupServer(
|
|
http.get("https://api.test/api/entities", ({ request }) => {
|
|
requestCount += 1;
|
|
observedAuthorization = request.headers.get("authorization");
|
|
if (nextStatus === 401) {
|
|
return HttpResponse.json(
|
|
{
|
|
success: false,
|
|
error: { code: "UNAUTHENTICATED" },
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
},
|
|
{ status: 401 },
|
|
);
|
|
}
|
|
return HttpResponse.json({
|
|
success: true,
|
|
data: [{ id: "resource-1", name: "Example" }],
|
|
meta: { requestId: "request-2", traceId: "trace-1" },
|
|
});
|
|
}),
|
|
);
|
|
|
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
|
afterEach(() => {
|
|
observedAuthorization = null;
|
|
requestCount = 0;
|
|
nextStatus = 200;
|
|
server.resetHandlers();
|
|
});
|
|
afterAll(() => server.close());
|
|
|
|
const clock = { now: () => 0, sleep: async () => {} };
|
|
|
|
type HttpDependencies = Parameters<typeof createHttpClient>[0];
|
|
|
|
function bearerClient(options: Partial<HttpDependencies>) {
|
|
return createHttpClient({
|
|
...TEST_HTTP_CONTRACT,
|
|
getOperation: (operationId: string) => {
|
|
if (operationId !== "LIST_ENTITIES") {
|
|
throw new Error(`Unknown test operation: ${operationId}`);
|
|
}
|
|
return BEARER_LIST;
|
|
},
|
|
baseUrl: "https://api.test",
|
|
providerProfile: createRestProviderProfile("PRIMARY_API", "https://api.test", [
|
|
"omit",
|
|
]),
|
|
// The V2 fixture declares `NoRequest` for its path codec, which the shared
|
|
// schema registry does not carry.
|
|
validatePath: () => ({ success: true as const, data: {} }),
|
|
clock,
|
|
...options,
|
|
} as HttpDependencies);
|
|
}
|
|
|
|
function sessionStub(
|
|
overrides: Partial<{
|
|
getState: () => "authenticated" | "unauthenticated" | "recovery-pending" | "integration-failed";
|
|
credentialPatch: (...args: never[]) => Promise<{ headers: Record<string, string> }>;
|
|
recover: (...args: never[]) => Promise<"restored" | "no-session">;
|
|
onUnauthenticated: () => void;
|
|
}> = {},
|
|
) {
|
|
return {
|
|
getState: () => "authenticated" as const,
|
|
subscribe: () => () => {},
|
|
beginSignIn: async () => {},
|
|
signOut: async () => {},
|
|
credentialPatch: async () => ({ headers: { authorization: "Bearer t" } }),
|
|
recover: async () => "restored" as const,
|
|
onUnauthenticated: () => {},
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
describe("LEG-02 the bearer profile's required header is enforced", () => {
|
|
it("refuses to dispatch when a READY patch omits authorization", async () => {
|
|
const client = bearerClient({
|
|
authSession: sessionStub({
|
|
credentialPatch: async () => ({ headers: {} }),
|
|
}) as never,
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "AUTH_INTEGRATION_FAILURE" },
|
|
});
|
|
expect(requestCount).toBe(0);
|
|
});
|
|
|
|
it("rejects a malformed or duplicated authorization value", async () => {
|
|
const hostilePatches: readonly Record<string, string>[] = [
|
|
{ authorization: "" },
|
|
{ authorization: "Bearer bad\nvalue" },
|
|
{ Authorization: "Bearer a", authorization: "Bearer b" },
|
|
];
|
|
for (const headers of hostilePatches) {
|
|
const client = bearerClient({
|
|
authSession: sessionStub({
|
|
credentialPatch: async () => ({ headers }),
|
|
}) as never,
|
|
});
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "AUTH_INTEGRATION_FAILURE" },
|
|
});
|
|
}
|
|
expect(requestCount).toBe(0);
|
|
});
|
|
|
|
it("dispatches with the admitted authorization header", async () => {
|
|
const client = bearerClient({
|
|
authSession: sessionStub() as never,
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: true,
|
|
});
|
|
expect(observedAuthorization).toBe("Bearer t");
|
|
});
|
|
});
|
|
|
|
describe("LEG-01 recovery notification follows the adopted result", () => {
|
|
it("does not sign the user out when recovery answers after the deadline", async () => {
|
|
nextStatus = 401;
|
|
const onUnauthenticated = vi.fn();
|
|
let elapsed = 0;
|
|
const client = bearerClient({
|
|
clock: {
|
|
now: () => elapsed,
|
|
sleep: async () => {},
|
|
},
|
|
timeoutMs: 20,
|
|
authSession: sessionStub({
|
|
onUnauthenticated,
|
|
recover: async () => {
|
|
// The request's own deadline expires while recovery is still out.
|
|
elapsed = 10_000;
|
|
await new Promise((resolve) => setTimeout(resolve, 30));
|
|
return "no-session" as const;
|
|
},
|
|
}) as never,
|
|
});
|
|
|
|
const outcome = await client.execute("LIST_ENTITIES");
|
|
expect(outcome.ok).toBe(false);
|
|
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
expect(onUnauthenticated).toHaveBeenCalledTimes(0);
|
|
});
|
|
|
|
it("signs the user out exactly once for an adopted no-session result", async () => {
|
|
nextStatus = 401;
|
|
const onUnauthenticated = vi.fn();
|
|
const client = bearerClient({
|
|
authSession: sessionStub({
|
|
onUnauthenticated,
|
|
recover: async () => "no-session" as const,
|
|
}) as never,
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "AUTH_REQUIRED" },
|
|
});
|
|
expect(onUnauthenticated).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("stays bounded when recovery never settles", async () => {
|
|
nextStatus = 401;
|
|
const onUnauthenticated = vi.fn();
|
|
let elapsed = 0;
|
|
const client = bearerClient({
|
|
clock: {
|
|
now: () => {
|
|
elapsed += 5;
|
|
return elapsed;
|
|
},
|
|
sleep: async () => {},
|
|
},
|
|
timeoutMs: 20,
|
|
authSession: sessionStub({
|
|
onUnauthenticated,
|
|
recover: () => new Promise<"restored">(() => {}),
|
|
}) as never,
|
|
});
|
|
|
|
const outcome = await client.execute("LIST_ENTITIES");
|
|
expect(outcome.ok).toBe(false);
|
|
expect(onUnauthenticated).toHaveBeenCalledTimes(0);
|
|
});
|
|
});
|