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>
157 lines
4.9 KiB
TypeScript
157 lines
4.9 KiB
TypeScript
import { HttpResponse, http } from "msw";
|
|
import { setupServer } from "msw/node";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
|
|
|
import { createExternalAuthSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
|
|
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
|
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
|
|
|
let responseStatuses: number[] = [];
|
|
const server = setupServer(
|
|
http.get("https://api.test/api/entities", () => {
|
|
const status = responseStatuses.shift() ?? 200;
|
|
if (status !== 200) {
|
|
return HttpResponse.json(
|
|
{
|
|
success: false,
|
|
error: { code: status === 401 ? "UNAUTHENTICATED" : "UNAVAILABLE" },
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
},
|
|
{ status },
|
|
);
|
|
}
|
|
return HttpResponse.json({
|
|
success: true,
|
|
data: [{ id: "resource-1", name: "Example" }],
|
|
meta: { requestId: "request-2", traceId: "trace-1" },
|
|
});
|
|
}),
|
|
);
|
|
|
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
|
afterEach(() => {
|
|
responseStatuses = [];
|
|
server.resetHandlers();
|
|
});
|
|
afterAll(() => server.close());
|
|
|
|
const clock = { now: () => 0, sleep: async () => {} };
|
|
|
|
type HttpDependencies = Parameters<typeof createHttpClient>[0];
|
|
|
|
function testClient(options: HttpDependencies) {
|
|
return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options });
|
|
}
|
|
|
|
type ExternalSessionOwner = Parameters<
|
|
typeof createExternalAuthSessionAdapter
|
|
>[0];
|
|
|
|
function createOwner(
|
|
overrides: Partial<ExternalSessionOwner> = {},
|
|
): ExternalSessionOwner {
|
|
return {
|
|
readState: () => "authenticated",
|
|
readSubject: () => "user-a",
|
|
subscribe: () => () => {},
|
|
beginSignIn: async () => {},
|
|
signOut: async () => {},
|
|
attachCredential: async () => ({ headers: {} }),
|
|
recoverSession: async () => "restored",
|
|
notifyUnauthenticated: () => {},
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
describe("bounded 401 session recovery", () => {
|
|
it("calls recovery once and replays a safe request once", async () => {
|
|
responseStatuses = [401, 200];
|
|
const recoverSession = vi.fn(async () => "restored" as const);
|
|
const authSession = createExternalAuthSessionAdapter(createOwner({
|
|
attachCredential: async () => ({ headers: {} }),
|
|
recoverSession,
|
|
notifyUnauthenticated: vi.fn(),
|
|
}));
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
authSession,
|
|
clock,
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: true,
|
|
});
|
|
expect(recoverSession).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("stops after a second 401 and notifies unauthenticated once", async () => {
|
|
responseStatuses = [401, 401];
|
|
const notifyUnauthenticated = vi.fn();
|
|
const authSession = createExternalAuthSessionAdapter(createOwner({
|
|
attachCredential: async () => ({ headers: {} }),
|
|
recoverSession: async () => "restored",
|
|
notifyUnauthenticated,
|
|
}));
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
authSession,
|
|
clock,
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "AUTH_REQUIRED" },
|
|
});
|
|
expect(notifyUnauthenticated).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
// Q-6.3-11. Recovery is its own single replay, not a retry: an exhausted or
|
|
// disabled retry budget must not turn a recoverable 401 into a logout.
|
|
it.each([
|
|
{ label: "retries are disabled", statuses: [401, 200], maxRetryAttempts: 0 },
|
|
{
|
|
label: "a 503 already used the retry budget",
|
|
statuses: [503, 401, 200],
|
|
maxRetryAttempts: 1,
|
|
},
|
|
])("recovers a 401 when $label", async ({ statuses, maxRetryAttempts }) => {
|
|
responseStatuses = [...statuses];
|
|
const recoverSession = vi.fn(async () => "restored" as const);
|
|
const notifyUnauthenticated = vi.fn();
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
authSession: createExternalAuthSessionAdapter(
|
|
createOwner({ recoverSession, notifyUnauthenticated }),
|
|
),
|
|
clock,
|
|
maxRetryAttempts,
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: true,
|
|
});
|
|
expect(recoverSession).toHaveBeenCalledTimes(1);
|
|
expect(notifyUnauthenticated).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("normalizes attach and invalid recovery failures", async () => {
|
|
const attachFailure = createExternalAuthSessionAdapter(createOwner({
|
|
attachCredential: async () => {
|
|
throw new Error("credential detail");
|
|
},
|
|
recoverSession: async () => "restored",
|
|
notifyUnauthenticated: vi.fn(),
|
|
}));
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
authSession: attachFailure,
|
|
clock,
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "AUTH_INTEGRATION_FAILURE" },
|
|
});
|
|
});
|
|
});
|