Files
clean-architecture-frontend…/tests/recipes/oidc-pkce-session-owner.test.ts
T
DongHyeonka dc7c95b005 fix(recipes): OIDC PKCE 레시피가 sessionStorage 키를 registry에서 가져온다
문제: OIDC PKCE session owner 레시피가 sign-in transaction의
sessionStorage 키를 글자 그대로 적는다
(`"ca-frontend:auth:v1:oidc-pkce-transaction"`). 주석은
`buildPhysicalKey(...)`라고 하지만 함수를 부르지 않는다. 템플릿의 다른
Web Storage 키는 모두 `src/contracts/storage-keys.ts` registry가
`APP_NAMESPACE`로 만들고, 어댑터가 직접 쓰는 키도 `backend: "external"`
행으로 둔다. 그래서 제품이 `APP_NAMESPACE`를 바꾸면(memento 설계가
예정한 일) 이 키만 `ca-frontend:`로 남고, registry는 앱이 쓰는 Web
Storage 키 목록이 아니게 된다. registry로 로그아웃 때 지울 키를 정하는
제품은 버려진 sign-in의 verifier·state·nonce·돌아갈 경로를 지우지 못한다.

고른 방법:
- registry에 `AUTH_REDIRECT_TRANSACTION` 행을 둔다. `scope: "auth"`,
  `name: "oidc-pkce-transaction"`, `backend: "external"`(pulse 키와 같은
  모양, StoragePort는 거절), `ttl: "session"`. 물리 키는 지금 글자와 같다
  (`ca-frontend:auth:v1:oidc-pkce-transaction`)라서 진행 중인 sign-in을
  잃지 않는다.
- 레시피의 `OIDC_PKCE_TRANSACTION_KEY`는 그 행의 `physicalKey`다.
  매뉴얼의 복사 규칙(`../../src/` → `../`)이 새 import에도 그대로 맞는다.
- 분류는 `opaque-cache`다. `sensitive-forbidden`은 "저장하지 않는다"는
  뜻이고 backend가 disabled·forbidden이어야 해서 맞지 않는다. 이 값은
  리다이렉트 한 번 동안 저장하는 것이 설계다.
- FE-REG-STORAGE의 `orphanExemptRows`에 이 행을 더한다
  (`config/contracts/registry-governance.json`). 이 행을 쓰는 곳은 레시피
  하나뿐이고, 레시피는 제품이 지울 수 있다(test:optional-recipe-removal).
  행은 registry로 지울 키를 정하는 제품을 위해 남는다. `AUTH_TOKEN`처럼
  사용처 없이 선언만 하는 행이다. 빼지 않으면 `src`만 복사해
  check:registries를 돌리는 `tests/unit/second-api-feature-registries.test.ts`가
  "has no executable consumer"로 실패한다.
  버린 대안: consumer 폴더에 `recipes`를 더하기. 레시피를 지운 사본(FE-GATE-020)
  에서 다시 사용처가 사라진다.

버린 대안: registry에 새 분류(예: `session-transaction`)를 더하기. 계약
타입의 union과 registry 기준선의 허용 값이 함께 바뀌는데, 분류가 코드
동작을 바꾸는 곳은 `sensitive-forbidden` 검사뿐이라 얻는 것이 없다.

위험·한계:
- `src/contracts/storage-keys.ts`에 행 하나가 더해진다(FE-REG-STORAGE
  additive). CHANGELOG [계약] 행이 필요하다.
- 이미 레시피를 복사한 제품은 자기 복사본을 같은 diff로 고쳐야 키가
  namespace를 따른다.
- orphan 검사가 이 행을 보지 않는다. 레시피가 키를 registry에서 가져오는지는
  `tests/recipes/oidc-pkce-session-owner.test.ts`가 본다.

검증: desktop batch에서 확인
- node scripts/run-vitest.ts run tests/unit/storage-registry.test.ts
  tests/recipes/oidc-pkce-session-owner.test.ts
- corepack pnpm check:registries (additive 행)
- node scripts/run-vitest.ts run tests/unit/second-api-feature-registries.test.ts
- corepack pnpm test:optional-recipe-removal

Refs: 1105/05-01
2026-11-06 02:07:47 +09:00

513 lines
19 KiB
TypeScript

import { createHash } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import type { SessionOwnerFetch } from "../../src/bootstrap/product-composition-contract.ts";
import { STORAGE_REGISTRY } from "../../src/contracts/storage-keys.ts";
import {
createOidcPkceSessionOwner,
OIDC_PKCE_TRANSACTION_KEY,
type OidcPkceSessionOwnerOptions,
} from "../../recipes/session-owners/oidc-pkce-session-owner.ts";
/**
* 1103/09-03. The paired backend's JWT mode: a Spring resource server that
* checks a Keycloak access token's issuer and audience. This owner gets that
* token in the browser with the authorization code flow and PKCE, keeps it in
* memory only, and follows the session state contract on `SessionState`.
*/
// The backend's local issuer (application-local.yml, APP_SECURITY_JWT_ISSUER).
const ISSUER = "http://localhost:8081/realms/ca-skeleton";
const CLIENT_ID = "ca-frontend";
const APP = "http://localhost:5173";
const API_ORIGIN = "http://localhost:8080";
const AUTHORIZE = `${ISSUER}/protocol/openid-connect/auth`;
const TOKEN = `${ISSUER}/protocol/openid-connect/token`;
const END_SESSION = `${ISSUER}/protocol/openid-connect/logout`;
const encode = (value: unknown) =>
Buffer.from(JSON.stringify(value)).toString("base64url");
/** The owner reads claims; it does not verify the signature (OIDC Core 3.1.3.7 (6)). */
const jwt = (claims: Record<string, unknown>) =>
`${encode({ alg: "RS256", typ: "JWT" })}.${encode(claims)}.signature`;
type Call = Readonly<{ url: string; init: Parameters<SessionOwnerFetch>[1] }>;
function harness(
overrides: Partial<OidcPkceSessionOwnerOptions> = {},
setup: Readonly<{ href?: string; storage?: Record<string, string> }> = {},
) {
let now = Date.parse("2026-11-04T00:00:00Z");
let href = setup.href ?? `${APP}/`;
const storage = new Map(Object.entries(setup.storage ?? {}));
const calls: Call[] = [];
const tokenAnswers: Array<() => Response | Promise<Response>> = [];
let tokenCounter = 0;
// The nonce of the sign-in this page load returns from, as Keycloak echoes it.
const nonce = (() => {
try {
return (JSON.parse(storage.get(OIDC_PKCE_TRANSACTION_KEY) ?? "null") as { nonce?: string } | null)
?.nonce;
} catch {
return undefined;
}
})();
const idToken = (claims: Record<string, unknown> = {}) =>
jwt({
iss: ISSUER,
aud: CLIENT_ID,
sub: "user-1",
exp: Math.floor(now / 1000) + 300,
...(nonce === undefined ? {} : { nonce }),
...claims,
});
/** A token response as Keycloak sends one. */
const tokens = (
fields: Record<string, unknown> = {},
claims: Record<string, unknown> = {},
) => {
tokenCounter += 1;
return Response.json({
access_token: `access-${tokenCounter}`,
token_type: "Bearer",
expires_in: 300,
refresh_token: `refresh-${tokenCounter}`,
id_token: idToken(claims),
...fields,
});
};
const discovery = { value: () => Response.json({
issuer: ISSUER,
authorization_endpoint: AUTHORIZE,
token_endpoint: TOKEN,
end_session_endpoint: END_SESSION,
}) };
const fetch = vi.fn<SessionOwnerFetch>(async (input, init) => {
const url = String(input);
calls.push({ url, init });
if (url === `${ISSUER}/.well-known/openid-configuration`) return discovery.value();
if (url === TOKEN) {
const answer = tokenAnswers.shift();
return answer ? answer() : tokens();
}
throw new TypeError(`unexpected ${url}`);
});
const page = {
href: () => href,
replaceUrl: vi.fn((url: string) => {
href = new URL(url, href).href;
}),
assign: vi.fn((url: string) => {
href = url;
}),
};
const redirectStorage = {
getItem: (key: string) => storage.get(key) ?? null,
setItem: (key: string, value: string) => void storage.set(key, value),
removeItem: (key: string) => void storage.delete(key),
};
const create = () =>
createOidcPkceSessionOwner({
issuer: ISSUER,
clientId: CLIENT_ID,
redirectUri: `${APP}/`,
apiOrigins: [API_ORIGIN],
postLogoutRedirectUri: `${APP}/`,
fetch,
page,
redirectStorage,
now: () => now,
...overrides,
});
return {
create,
fetch,
calls,
page,
storage,
tokens,
tokenAnswers,
discovery,
idToken,
advance(ms: number) {
now += ms;
},
tokenRequests: () =>
calls
.filter((call) => call.url === TOKEN)
.map((call) => Object.fromEntries(call.init?.body as URLSearchParams)),
};
}
/** Starts a sign-in on one page and returns the callback URL the IdP sends back. */
async function signInRedirect(
setup: ReturnType<typeof harness>,
returnTo = "/items?limit=1",
params: Readonly<Record<string, string>> = {},
) {
const owner = setup.create();
await owner.beginSignIn(returnTo);
const authorize = new URL(setup.page.assign.mock.calls.at(-1)![0]);
const callback = new URL(`${APP}/`);
callback.searchParams.set("code", "code-1");
callback.searchParams.set("state", authorize.searchParams.get("state")!);
callback.searchParams.set("iss", ISSUER);
for (const [name, value] of Object.entries(params)) callback.searchParams.set(name, value);
return { authorize, callback: callback.href, storage: Object.fromEntries(setup.storage) };
}
/** A signed-in owner, as on the page load that returns from Keycloak. */
async function signedIn(overrides: Partial<OidcPkceSessionOwnerOptions> = {}) {
const first = harness(overrides);
const { callback, storage } = await signInRedirect(first);
const setup = harness(overrides, { href: callback, storage });
const owner = setup.create();
await expect(owner.recoverSession()).resolves.toBe("restored");
return { ...setup, owner };
}
const binding = (origin = API_ORIGIN) =>
Object.freeze({ origin, method: "GET", operationId: "LIST" });
describe("OIDC PKCE session owner: sign-in", () => {
it("starts the code flow with PKCE S256 and keeps only the transaction", async () => {
const setup = harness();
const owner = setup.create();
expect(owner.readState()).toBe("unauthenticated");
await owner.beginSignIn("/items?limit=1");
const authorize = new URL(setup.page.assign.mock.calls[0]![0]);
expect(`${authorize.origin}${authorize.pathname}`).toBe(AUTHORIZE);
const transaction = JSON.parse(setup.storage.get(OIDC_PKCE_TRANSACTION_KEY)!);
expect(Object.fromEntries(authorize.searchParams)).toEqual({
response_type: "code",
client_id: CLIENT_ID,
redirect_uri: `${APP}/`,
scope: "openid",
state: transaction.state,
nonce: transaction.nonce,
code_challenge: s256(transaction.verifier),
code_challenge_method: "S256",
});
expect(transaction.returnTo).toBe("/items?limit=1");
expect(transaction.verifier).toMatch(/^[A-Za-z0-9_-]{43}$/u);
expect(setup.storage.size).toBe(1);
// 1105/05-01. The key is the storage registry's row, so it follows the
// app's APP_NAMESPACE instead of a literal `ca-frontend:` prefix.
expect([...setup.storage.keys()]).toEqual([
STORAGE_REGISTRY.AUTH_REDIRECT_TRANSACTION.physicalKey,
]);
expect(OIDC_PKCE_TRANSACTION_KEY).toBe(
STORAGE_REGISTRY.AUTH_REDIRECT_TRANSACTION.physicalKey,
);
});
it("returns only to a path of this app", async () => {
for (const returnTo of ["//evil.example/x", "https://evil.example/", "/\\evil", "items"]) {
const setup = harness();
await setup.create().beginSignIn(returnTo);
expect(JSON.parse(setup.storage.get(OIDC_PKCE_TRANSACTION_KEY)!).returnTo).toBe("/");
}
});
it("exchanges the code on the page load that returns, and drops it from the URL first", async () => {
const first = harness();
const { callback, storage } = await signInRedirect(first);
const setup = harness({}, { href: callback, storage });
const owner = setup.create();
// Before any network answer: the code is out of the URL and the
// transaction is spent, so a reload cannot replay it.
expect(owner.readState()).toBe("recovery-pending");
expect(setup.page.replaceUrl).toHaveBeenCalledWith("/items?limit=1");
expect(setup.storage.has(OIDC_PKCE_TRANSACTION_KEY)).toBe(false);
await expect(owner.recoverSession()).resolves.toBe("restored");
expect(owner.readState()).toBe("authenticated");
expect(owner.readSubject()).toBe("user-1");
expect(setup.tokenRequests()).toEqual([
{
grant_type: "authorization_code",
code: "code-1",
redirect_uri: `${APP}/`,
client_id: CLIENT_ID,
code_verifier: JSON.parse(storage[OIDC_PKCE_TRANSACTION_KEY]!).verifier,
},
]);
const tokenCall = setup.calls.find((call) => call.url === TOKEN)!;
expect(tokenCall.init).toMatchObject({ method: "POST", credentials: "omit" });
});
it("returns under the router base path", async () => {
const overrides = { redirectUri: `${APP}/app/` };
const first = harness(overrides);
const { callback, storage } = await signInRedirect(first, "/items");
const setup = harness(overrides, { href: callback.replace(`${APP}/`, `${APP}/app/`), storage });
setup.create();
expect(setup.page.replaceUrl).toHaveBeenCalledWith("/app/items");
});
it.each([
["a state that is not the one sent", { state: "forged" }],
["an error from the IdP", { error: "access_denied" }],
["another issuer (RFC 9207)", { iss: "http://evil.example/realms/x" }],
])("signs nobody in on %s", async (_case, params) => {
const first = harness();
const { callback, storage } = await signInRedirect(first, "/items", params);
const setup = harness({}, { href: callback, storage });
const owner = setup.create();
expect(owner.readState()).toBe("unauthenticated");
await expect(owner.recoverSession()).resolves.toBe("no-session");
expect(setup.tokenRequests()).toEqual([]);
expect(setup.page.replaceUrl).toHaveBeenCalled();
expect(setup.storage.has(OIDC_PKCE_TRANSACTION_KEY)).toBe(false);
});
it("signs nobody in from a transaction older than ten minutes", async () => {
const first = harness();
const { callback, storage } = await signInRedirect(first);
const setup = harness({}, { href: callback, storage });
setup.advance(10 * 60_000 + 1);
expect(setup.create().readState()).toBe("unauthenticated");
expect(setup.tokenRequests()).toEqual([]);
});
it.each([
["a nonce that is not the one sent", { nonce: "other" }],
["an id token for another client", { aud: "other-client" }],
["an id token from another issuer", { iss: "http://evil.example" }],
["an id token without a subject", { sub: "" }],
])("refuses %s", async (_case, claims) => {
const first = harness();
const { callback, storage } = await signInRedirect(first);
const setup = harness({}, { href: callback, storage });
const nonce = JSON.parse(storage[OIDC_PKCE_TRANSACTION_KEY]!).nonce;
setup.tokenAnswers.push(() => setup.tokens({}, { nonce, ...claims }));
const owner = setup.create();
await expect(owner.recoverSession()).resolves.toBe("no-session");
expect(owner.readState()).toBe("unauthenticated");
expect(owner.readSubject()).toBeNull();
});
it("refuses a token response that is not a bearer token", async () => {
const first = harness();
const { callback, storage } = await signInRedirect(first);
const setup = harness({}, { href: callback, storage });
setup.tokenAnswers.push(() => setup.tokens({ token_type: "DPoP" }));
await expect(setup.create().recoverSession()).resolves.toBe("no-session");
});
it("leaves a page that is not a sign-in callback alone", () => {
const setup = harness({}, { href: `${APP}/items?code=x&state=y` });
expect(setup.create().readState()).toBe("unauthenticated");
expect(setup.page.replaceUrl).not.toHaveBeenCalled();
});
it("refuses a discovery document for another issuer", async () => {
const setup = harness();
setup.discovery.value = () =>
Response.json({ issuer: "http://evil.example", authorization_endpoint: AUTHORIZE, token_endpoint: TOKEN });
await expect(setup.create().beginSignIn("/")).rejects.toThrow();
expect(setup.page.assign).not.toHaveBeenCalled();
expect(setup.storage.size).toBe(0);
});
it("keeps tokens out of storage", async () => {
const { storage, owner } = await signedIn();
await owner.attachCredential(binding());
expect([...storage.values()].join("")).not.toMatch(/access-|refresh-/u);
});
});
describe("OIDC PKCE session owner: credentials", () => {
it("sends the access token to the API origin and nowhere else", async () => {
const { owner } = await signedIn();
await expect(owner.attachCredential(binding())).resolves.toEqual({
headers: { authorization: "Bearer access-1" },
});
await expect(owner.attachCredential(binding("https://other.example"))).rejects.toThrow(
"API origin",
);
});
it("has no credential while signed out", async () => {
const setup = harness();
await expect(setup.create().attachCredential(binding())).rejects.toThrow();
});
it("refreshes once before expiry, for every waiting request, without a notification", async () => {
const setup = await signedIn();
const listener = vi.fn();
setup.owner.subscribe(listener);
setup.advance(290_000);
const patches = await Promise.all([
setup.owner.attachCredential(binding()),
setup.owner.attachCredential(binding()),
]);
expect(patches.map((patch) => patch.headers.authorization)).toEqual([
"Bearer access-2",
"Bearer access-2",
]);
expect(setup.tokenRequests().at(-1)).toEqual({
grant_type: "refresh_token",
refresh_token: "refresh-1",
client_id: CLIENT_ID,
});
expect(setup.tokenRequests()).toHaveLength(2);
expect(setup.owner.readState()).toBe("authenticated");
expect(setup.owner.readSubject()).toBe("user-1");
expect(listener).not.toHaveBeenCalled();
});
it("signs out when the refresh token is refused", async () => {
const setup = await signedIn();
setup.advance(290_000);
setup.tokenAnswers.push(() => Response.json({ error: "invalid_grant" }, { status: 400 }));
await expect(setup.owner.attachCredential(binding())).rejects.toThrow();
expect(setup.owner.readState()).toBe("unauthenticated");
expect(setup.owner.readSubject()).toBeNull();
});
it("keeps a still-valid token when the refresh cannot be reached", async () => {
const setup = await signedIn();
setup.advance(290_000);
setup.tokenAnswers.push(() => {
throw new DOMException("timed out", "TimeoutError");
});
await expect(setup.owner.attachCredential(binding())).resolves.toEqual({
headers: { authorization: "Bearer access-1" },
});
expect(setup.owner.readState()).toBe("authenticated");
});
it("signs out when a refresh names another subject", async () => {
const setup = await signedIn();
setup.advance(290_000);
setup.tokenAnswers.push(() => setup.tokens({}, { sub: "user-2" }));
await expect(setup.owner.attachCredential(binding())).rejects.toThrow();
expect(setup.owner.readState()).toBe("unauthenticated");
});
});
describe("OIDC PKCE session owner: 401 and recovery", () => {
it("restores the session with the refresh token after a 401, once", async () => {
const setup = await signedIn();
const states: string[] = [];
setup.owner.subscribe(() => states.push(setup.owner.readState()));
setup.owner.notifyUnauthenticated();
expect(setup.owner.readState()).toBe("recovery-pending");
expect(setup.owner.readSubject()).toBeNull();
await expect(setup.owner.recoverSession()).resolves.toBe("restored");
expect(setup.owner.readSubject()).toBe("user-1");
await expect(setup.owner.attachCredential(binding())).resolves.toEqual({
headers: { authorization: "Bearer access-2" },
});
// The fresh token is refused too: a refresh will not help.
setup.owner.notifyUnauthenticated();
expect(setup.owner.readState()).toBe("unauthenticated");
expect(states).toEqual(["recovery-pending", "authenticated", "unauthenticated"]);
expect(setup.tokenRequests()).toHaveLength(2);
});
it("signs out on a 401 when nothing can restore the session", async () => {
const withoutRefresh = harness();
const { callback, storage } = await signInRedirect(withoutRefresh);
const bare = harness({}, { href: callback, storage });
bare.tokenAnswers.push(() => bare.tokens({ refresh_token: undefined }));
const owner = bare.create();
await owner.recoverSession();
owner.notifyUnauthenticated();
expect(owner.readState()).toBe("unauthenticated");
await expect(owner.recoverSession()).resolves.toBe("no-session");
});
it("answers no-session from unauthenticated, never leaving it recovering", async () => {
const owner = harness().create();
await expect(owner.recoverSession()).resolves.toBe("no-session");
expect(owner.readState()).toBe("unauthenticated");
});
it("rejects and stays recovering when the IdP cannot be reached", async () => {
const setup = await signedIn();
setup.tokenAnswers.push(() => Response.json({ error: "temporarily_unavailable" }, { status: 503 }));
setup.owner.notifyUnauthenticated();
await vi.waitFor(() => expect(setup.tokenRequests()).toHaveLength(2));
expect(setup.owner.readState()).toBe("recovery-pending");
await expect(setup.owner.recoverSession()).resolves.toBe("restored");
});
it("answers no-session after a refused refresh, signed out", async () => {
const setup = await signedIn();
setup.tokenAnswers.push(() => Response.json({ error: "invalid_grant" }, { status: 400 }));
setup.owner.notifyUnauthenticated();
await vi.waitFor(() => expect(setup.owner.readState()).toBe("unauthenticated"));
await expect(setup.owner.recoverSession()).resolves.toBe("no-session");
});
});
describe("OIDC PKCE session owner: sign-out and configuration", () => {
it("forgets the tokens and ends the IdP session without an id token in the URL", async () => {
const setup = await signedIn();
await setup.owner.signOut();
expect(setup.owner.readState()).toBe("unauthenticated");
await expect(setup.owner.attachCredential(binding())).rejects.toThrow();
const logout = new URL(setup.page.assign.mock.calls.at(-1)![0]);
expect(`${logout.origin}${logout.pathname}`).toBe(END_SESSION);
expect(Object.fromEntries(logout.searchParams)).toEqual({
client_id: CLIENT_ID,
post_logout_redirect_uri: `${APP}/`,
});
});
it.each([
["a plain-HTTP issuer off this machine", { issuer: "http://idp.example/realms/x" }],
["no client id", { clientId: "" }],
["an API origin that is not an origin", { apiOrigins: ["http://localhost:8080/api"] }],
["no storage to survive the redirect", { redirectStorage: undefined }],
])("fails closed as integration-failed with %s", async (_case, overrides) => {
const owner = harness(overrides as Partial<OidcPkceSessionOwnerOptions>).create();
expect(owner.readState()).toBe("integration-failed");
await expect(owner.beginSignIn("/")).rejects.toThrow();
await expect(owner.recoverSession()).resolves.toBe("no-session");
expect(owner.readState()).toBe("integration-failed");
});
});
function s256(verifier: string): string {
return createHash("sha256").update(verifier).digest("base64url");
}