Files
clean-architecture-frontend…/tests/unit/auth-session-adapter.test.ts
T
DongHyeonkaandClaude Opus 5.5 c6300e9d40 feat(auth): require readSubject so a token refresh keeps server state
An external owner without readSubject made every authenticated
notification (every token refresh) abort requests and clear the
server-state cache. readSubject is now a required owner method and
getSubject a required SessionGateway method.

- ExternalSessionOwner.readSubject(): required; the host owner check
  (EXTERNAL_OWNER_METHODS) rejects an owner without it, so the session
  fails closed as integration-failed like any other missing method.
- SessionGateway.getSubject(): required. Anonymous and unavailable
  adapters return null; demo already returned its fixed user.
- Scope runtime: same (state, subject) still skips the fence; a state
  or subject change still fences. An authenticated session with a
  null/empty subject still fences (fail closed) and now records
  cache.operation.failed {operation: SCOPE_FENCE, reason:
  SUBJECT_MISSING} once per fence. Bootstrap passes diagnostics in.
- Docs: starter-experience external owner section and port comments
  describe what readSubject returns, the fail-closed diagnostic and a
  migration note.

RED before the change (vitest tests/unit/server-state-scope-runtime.test.ts
tests/unit/runtime-adapters.test.ts): 4 failed | 31 passed
- fails closed when the owner lacks readSubject:
  expected 'authenticated' to be 'integration-failed'
- fences and reports SUBJECT_MISSING ... null / empty subject, and the
  external owner whose readSubject returns null:
  expected [] to deeply equal [[{ level: 'warn', ... }]]
- type level: an owner literal without readSubject compiled (tsc exit
  0). The new @ts-expect-error pin fails check:types:test with TS2578
  if readSubject becomes optional again.
Pins that stayed green: same-subject token refresh keeps the cache,
subject change fences, sign-out fences, owner missing readState is
rejected.

GREEN: check:architecture, check:types:app, check:types:test, lint,
test:unit (2084), test:component (182), test:reference-feature (59),
test:integration (151), verify:documentation, check:diagnostics,
check:ci all pass.

BREAKING: external auth owners must implement readSubject(); code that
implements AuthSessionPort/SessionGateway directly must implement
getSubject().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 16:25:22 +09:00

159 lines
5.3 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
createAnonymousSessionAdapter,
createDemoSessionAdapter,
createExternalAuthSessionAdapter,
type ExternalSessionOwner,
} from "../../src/adapters/auth/external-session-adapter.ts";
describe("external AuthSessionPort adapter", () => {
it("attaches opaque credentials without exposing a token-shaped session", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({
headers: { Authorization: "Bearer opaque" },
}),
recoverSession: async () => "restored",
notifyUnauthenticated: vi.fn(),
});
const patch = await adapter.credentialPatch({
origin: "https://api.test",
method: "GET",
operationId: "GET_RESOURCE",
});
expect(patch.headers.authorization).toBe("Bearer opaque");
expect(adapter.getState()).toBe("authenticated");
expect(adapter.getSubject()).toBe("user-a");
expect(adapter).not.toHaveProperty("accessToken");
expect(adapter).not.toHaveProperty("refreshToken");
});
it("fails invalid recovery states closed", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
// @ts-expect-error Deliberately violates the external-owner contract.
recoverSession: async () => "unexpected",
notifyUnauthenticated: vi.fn(),
});
await expect(adapter.recover()).rejects.toThrow("invalid recovery state");
});
it("rejects credential patches that can alter transport-owned headers", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({
headers: { Host: "attacker.test" },
}),
recoverSession: async () => "restored",
notifyUnauthenticated: vi.fn(),
});
await expect(
adapter.credentialPatch({
origin: "https://api.test",
method: "GET",
operationId: "GET_RESOURCE",
}),
).rejects.toThrow("forbidden credential patch");
});
it("rejects credential headers that differ only in case instead of merging them", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({
headers: { Authorization: "Bearer a", authorization: "Bearer b" },
}),
recoverSession: async () => "restored",
notifyUnauthenticated: vi.fn(),
});
await expect(
adapter.credentialPatch({
origin: "https://api.test",
method: "GET",
operationId: "GET_RESOURCE",
}),
).rejects.toThrow("forbidden credential patch");
});
it("requires the owner to name its subject", () => {
// An owner without readSubject would clear server state on every token
// refresh; check:types:test fails if this ever compiles again.
// @ts-expect-error readSubject is a required owner method.
const owner: ExternalSessionOwner = {
readState: () => "authenticated",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "restored",
notifyUnauthenticated: () => {},
};
expect(owner).not.toHaveProperty("readSubject");
});
it("provides a safe anonymous adapter", async () => {
const adapter = createAnonymousSessionAdapter();
expect(adapter.getSubject()).toBeNull();
expect(adapter.getState()).toBe("unauthenticated");
await expect(adapter.recover()).resolves.toBe("no-session");
});
it("provides a reactive credential-free demo seam", async () => {
const adapter = createDemoSessionAdapter();
let notifications = 0;
const unsubscribe = adapter.subscribe(() => {
notifications += 1;
});
expect(adapter.getState()).toBe("unauthenticated");
await adapter.beginSignIn();
expect(adapter.getState()).toBe("authenticated");
await adapter.signOut();
expect(adapter.getState()).toBe("unauthenticated");
expect(notifications).toBe(2);
unsubscribe();
});
it("does not notify when the demo state is set to its current value", async () => {
const adapter = createDemoSessionAdapter("recovery-pending");
let notifications = 0;
adapter.subscribe(() => {
notifications += 1;
});
adapter.setState("recovery-pending");
expect(notifications).toBe(0);
adapter.setState("authenticated");
await adapter.beginSignIn();
expect(notifications).toBe(1);
adapter.onUnauthenticated();
adapter.onUnauthenticated();
await adapter.signOut();
expect(adapter.getState()).toBe("unauthenticated");
expect(notifications).toBe(2);
});
});