Merge fix/session-subject-required: require readSubject on the external session owner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-27 13:32:40 +09:00
co-authored by Claude Opus 5.5
10 changed files with 250 additions and 50 deletions
+23
View File
@@ -4,12 +4,14 @@ 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 () => {},
@@ -27,6 +29,7 @@ describe("external AuthSessionPort adapter", () => {
});
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");
});
@@ -34,6 +37,7 @@ describe("external AuthSessionPort adapter", () => {
it("fails invalid recovery states closed", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
@@ -49,6 +53,7 @@ describe("external AuthSessionPort adapter", () => {
it("rejects credential patches that can alter transport-owned headers", async () => {
const adapter = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
@@ -71,6 +76,7 @@ describe("external AuthSessionPort adapter", () => {
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 () => {},
@@ -90,8 +96,25 @@ describe("external AuthSessionPort adapter", () => {
).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");
});
+45
View File
@@ -280,6 +280,51 @@ describe("runtime adapter composition", () => {
expect(adapters.outputPorts.session.getState()).toBe("integration-failed");
});
describe("installed external auth owner shape", () => {
const externalRuntime: Runtime = {
...runtime,
config: { ...runtime.config, AUTH_MODE: "external" },
};
const completeOwner = () => ({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
});
it("uses an owner that implements every method", async () => {
const adapters = await createRuntimeAdapters({
runtime: externalRuntime,
release,
host: { __CA_FRONTEND_AUTH_OWNER__: completeOwner() },
});
expect(adapters.outputPorts.session.getState()).toBe("authenticated");
expect(adapters.outputPorts.session.getSubject()).toBe("user-a");
adapters.infrastructure.dispose();
});
it.each(["readSubject", "readState"])(
"fails closed when the owner lacks %s",
async (method) => {
const owner: Record<string, unknown> = completeOwner();
delete owner[method];
const adapters = await createRuntimeAdapters({
runtime: externalRuntime,
release,
host: { __CA_FRONTEND_AUTH_OWNER__: owner },
});
expect(adapters.outputPorts.session.getState()).toBe(
"integration-failed",
);
adapters.infrastructure.dispose();
},
);
});
it("reports the static selection when no capability override disables it", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
+100 -13
View File
@@ -9,6 +9,7 @@ import {
type ServerStateScopeDependencies,
} from "../../src/adapters/query-cache/server-state-scope-runtime.ts";
import type { SessionState } from "../../src/application/ports/auth-session-port.ts";
import type { DiagnosticRecordInput } from "../../src/contracts/diagnostics.ts";
import type { ClientScopeLifecycleEvent } from "../../src/contracts/server-state-scope.ts";
describe("server-state session generation runtime", () => {
@@ -228,18 +229,26 @@ describe("identity-affecting session changes only", () => {
function scopeFor(session: ServerStateScopeDependencies["session"]) {
const resetLocal = vi.fn(async () => {});
const record = vi.fn<(input: DiagnosticRecordInput) => void>();
const lifecycle: ClientScopeLifecycleEvent[] = [];
let tokenSequence = 0;
const runtime = createServerStateScopeRuntime({
session,
queryInvalidation: { resetLocal },
diagnostics: { record },
tokenFactory: () =>
`scope-identity-token-${String(tokenSequence++).padStart(6, "0")}`,
});
runtime.subscribeLifecycle((event) => lifecycle.push(event));
return { runtime, resetLocal, lifecycle };
return { runtime, resetLocal, record, lifecycle };
}
const SUBJECT_MISSING_RECORD = {
level: "warn",
eventId: "cache.operation.failed",
context: { operation: "SCOPE_FENCE", reason: "SUBJECT_MISSING" },
};
it.each([
["a repeated sign-out", { state: "unauthenticated" as const }],
[
@@ -248,7 +257,7 @@ describe("identity-affecting session changes only", () => {
],
])("does not fence, abort or clear on %s", async (_label, identity) => {
const fake = fakeSession(identity);
const { runtime, resetLocal, lifecycle } = scopeFor(fake.session);
const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session);
const before = runtime.getSnapshot();
fake.notify(identity);
@@ -259,6 +268,7 @@ describe("identity-affecting session changes only", () => {
expect(before.isCurrent()).toBe(true);
expect(before.signal.aborted).toBe(false);
expect(resetLocal).not.toHaveBeenCalled();
expect(record).not.toHaveBeenCalled();
expect(runtime.getPhase()).toBe("READY");
});
@@ -274,18 +284,13 @@ describe("identity-affecting session changes only", () => {
{ state: "authenticated" as const, subject: "user-b" },
],
[
"an authenticated session cannot name its subject",
{ state: "authenticated" as const },
{ state: "authenticated" as const },
],
[
"an authenticated session names an empty subject",
{ state: "authenticated" as const, subject: "" },
{ state: "authenticated" as const, subject: "" },
"the user signs out",
{ state: "authenticated" as const, subject: "user-a" },
{ state: "unauthenticated" as const },
],
])("still fences when %s", async (_label, initial, next) => {
const fake = fakeSession(initial);
const { runtime, resetLocal, lifecycle } = scopeFor(fake.session);
const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session);
const before = runtime.getSnapshot();
fake.notify(next);
@@ -295,6 +300,59 @@ describe("identity-affecting session changes only", () => {
expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 });
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
expect(resetLocal).toHaveBeenCalledOnce();
expect(record).not.toHaveBeenCalled();
});
it.each([
["cannot name its subject", null],
["names an empty subject", ""],
])(
"fences and reports SUBJECT_MISSING on every notification when an authenticated session %s",
async (_label, subject) => {
const fake = fakeSession({ state: "authenticated", subject });
const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session);
const before = runtime.getSnapshot();
fake.notify({ state: "authenticated", subject });
expect(before.isCurrent()).toBe(false);
expect(before.signal.aborted).toBe(true);
expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 });
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
expect(record.mock.calls).toEqual([[SUBJECT_MISSING_RECORD]]);
fake.notify({ state: "authenticated", subject });
await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledTimes(2));
expect(record.mock.calls).toEqual([
[SUBJECT_MISSING_RECORD],
[SUBJECT_MISSING_RECORD],
]);
// Signing out is an ordinary fence, not a misbehaving owner.
fake.notify({ state: "unauthenticated" });
await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledTimes(3));
expect(record).toHaveBeenCalledTimes(2);
},
);
it("keeps fencing if diagnostics throws while reporting SUBJECT_MISSING", async () => {
const fake = fakeSession({ state: "authenticated", subject: null });
const runtime = createServerStateScopeRuntime({
session: fake.session,
queryInvalidation: { resetLocal: async () => {} },
diagnostics: {
record() {
throw new Error("diagnostics down");
},
},
tokenFactory: () => "scope-diagnostics-token-001",
});
const before = runtime.getSnapshot();
fake.notify({ state: "authenticated", subject: null });
expect(before.isCurrent()).toBe(false);
expect(runtime.getPhase()).toBe("FENCED");
});
it("does not fence when the demo session re-announces the same user", async () => {
@@ -323,10 +381,11 @@ describe("identity-affecting session changes only", () => {
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
});
it("fences every authenticated notification from an external owner without readSubject", async () => {
it("fences and reports every authenticated notification from an external owner whose readSubject returns null", async () => {
let notify: () => void = () => {};
const session = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => null,
subscribe(listener) {
notify = listener;
return () => {};
@@ -337,7 +396,7 @@ describe("identity-affecting session changes only", () => {
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
});
const { runtime, resetLocal, lifecycle } = scopeFor(session);
const { runtime, resetLocal, record, lifecycle } = scopeFor(session);
const before = runtime.getSnapshot();
notify();
@@ -346,6 +405,34 @@ describe("identity-affecting session changes only", () => {
expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 });
await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY"));
expect(resetLocal).toHaveBeenCalledOnce();
expect(record.mock.calls).toEqual([[SUBJECT_MISSING_RECORD]]);
});
it("keeps the cache when an external owner refreshes a token for the same subject", async () => {
let notify: () => void = () => {};
const session = createExternalAuthSessionAdapter({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe(listener) {
notify = listener;
return () => {};
},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
});
const { runtime, resetLocal, record, lifecycle } = scopeFor(session);
const before = runtime.getSnapshot();
notify();
await Promise.resolve();
expect(lifecycle).toEqual([]);
expect(before.isCurrent()).toBe(true);
expect(resetLocal).not.toHaveBeenCalled();
expect(record).not.toHaveBeenCalled();
});
it("retries a failed reset on a notification with the same identity", async () => {