fix(auth): report only a server 401 to the session owner (R-3.2)

V3 returned the same UNAUTHENTICATED outcome for "no credential, nothing
sent" and for a server 401, and the composition root called
onUnauthenticated() for both. With the demo owner that overwrote a
recovery-pending session with "unauthenticated", and the demo setState
notified even when the value did not change, which fed the scope-fence loop.

- V3: the server-401 UNAUTHENTICATED outcome now carries its response
  `metadata` (additive optional field). The pre-dispatch one does not.
- runtime-adapters: onUnauthenticated() only when metadata is present.
- demo session: setState is a no-op for the current value.

RED before fix: reference-runtime-composition.test.ts "does not report a
request refused before dispatch as a sign-out" (state became
"unauthenticated"), auth-session-adapter.test.ts "does not notify when the
demo state is set to its current value" (1 notification),
http-execution-v3.test.ts "tells a missing credential apart from a server
401" (no metadata). Pinned: "still signs out when the server answers 401".
Gates: check:architecture, check:types:app, check:types:test, lint,
test:component, test:integration, test:reference-feature, test:contract
pass. test:unit passes except removal-fixture.test.ts (needs generated
artifacts/ release evidence absent in a fresh worktree; unrelated).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 12:25:01 +09:00
co-authored by Claude Opus 5.5
parent a39eed6c11
commit 70158d17c1
6 changed files with 118 additions and 1 deletions
@@ -112,6 +112,9 @@ export function createDemoSessionAdapter(
let state = initialState;
const listeners = new Set<() => void>();
const setState = (next: SessionState) => {
// A notification means "the session changed"; repeating the same value
// would make every subscriber redo its work for nothing.
if (next === state) return;
state = next;
for (const listener of listeners) listener();
};
+8
View File
@@ -134,6 +134,11 @@ export type HttpExecutionOutcome<Value, Problem> =
}>
| Readonly<{
kind: "UNAUTHENTICATED";
/**
* Present only when the server answered 401. Absent means no credential
* existed and nothing was sent; that is not a session verdict.
*/
metadata?: SafeResponseMetadata;
effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED";
}>
| Readonly<{
@@ -1158,6 +1163,7 @@ async function admitResponse<Input, WireOutput, Problem>(
unauthenticated(
certaintyForAbandonedAttempt(attemptState, isCommand),
isCommand,
metadata,
),
"UNAUTHENTICATED",
);
@@ -1652,9 +1658,11 @@ function postDispatchEffect(isCommand: boolean): HttpEffectCertainty {
function unauthenticated<Value, Problem>(
effect: string,
isCommand: boolean,
metadata?: SafeResponseMetadata,
): HttpExecutionOutcome<Value, Problem> {
return Object.freeze({
kind: "UNAUTHENTICATED" as const,
...(metadata === undefined ? {} : { metadata }),
effect: normalizeOptionalEffect(effect, isCommand),
});
}
+4 -1
View File
@@ -517,7 +517,10 @@ export async function createRuntimeAdapters(
? {}
: { execution: executionContext.execution }),
});
if (outcome.kind === "UNAUTHENTICATED") {
// R-3.2. Only a server 401 is a session verdict. A request refused before
// dispatch for lack of a credential carries no response metadata; telling
// the owner would overwrite a recovering session and re-fence the scope.
if (outcome.kind === "UNAUTHENTICATED" && outcome.metadata !== undefined) {
authSession.onUnauthenticated();
}
return outcome;
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { DemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
import { createRuntimeAdapters } from "../../../src/bootstrap/runtime-adapters.ts";
import { createRuntimeIdentityRegistry } from "../../../src/contracts/query-keys.ts";
import { bindQuery } from "../../../src/contracts/server-state.ts";
@@ -210,4 +211,59 @@ describe("reference feature runtime composition", () => {
expect(safeEvidence).not.toContain("private-idempotency-key");
adapters.infrastructure.dispose();
});
/**
* R-3.2. A request refused before dispatch because no credential exists is
* not a session verdict. Reporting it to the owner overwrote a recovering
* session and could loop through the scope fence; only a server 401 may.
*/
it("does not report a request refused before dispatch as a sign-out", async () => {
const fetcher = vi.fn(async () => Response.json([]));
const adapters = await createRuntimeAdapters({
runtime,
release,
host: {},
fetcher,
});
const session = adapters.outputPorts.session as DemoSessionAdapter;
session.setState("recovery-pending");
await vi.waitFor(() =>
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
);
const notifications = vi.fn();
session.subscribe(notifications);
await expect(
referenceInput(adapters).listResources({ limit: 20 }),
).resolves.toMatchObject({ ok: false });
expect(fetcher).not.toHaveBeenCalled();
expect(session.getState()).toBe("recovery-pending");
expect(notifications).not.toHaveBeenCalled();
adapters.infrastructure.dispose();
});
it("still signs out when the server answers 401", async () => {
const fetcher = vi.fn(
async () => new Response(null, { status: 401 }),
);
const adapters = await createRuntimeAdapters({
runtime,
release,
host: {},
fetcher,
});
await adapters.outputPorts.session.beginSignIn();
await vi.waitFor(() =>
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
);
await expect(
referenceInput(adapters).listResources({ limit: 20 }),
).resolves.toMatchObject({ ok: false });
expect(fetcher).toHaveBeenCalledOnce();
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated");
adapters.infrastructure.dispose();
});
});
+21
View File
@@ -89,4 +89,25 @@ describe("external AuthSessionPort adapter", () => {
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);
});
});
+26
View File
@@ -137,6 +137,32 @@ describe("runtime request deadline ceiling", () => {
});
describe("descriptor-driven HTTP execution lifetime", () => {
it("tells a missing credential apart from a server 401", async () => {
const refusedFetcher = vi.fn();
const refused = await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "UNAUTHENTICATED" }),
fetcher: refusedFetcher,
}).execute(installed, { limit: 20 }, { routeId: ROUTE_ID, scope });
const rejected = await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher: async () => new Response(null, { status: 401 }),
}).execute(installed, { limit: 20 }, { routeId: ROUTE_ID, scope });
// Only the server's answer carries response metadata; the composition
// root reports just that one to the session owner.
expect(refusedFetcher).not.toHaveBeenCalled();
expect(refused).toEqual({ kind: "UNAUTHENTICATED", effect: "NOT_APPLICABLE" });
expect(rejected).toMatchObject({
kind: "UNAUTHENTICATED",
effect: "NOT_APPLICABLE",
metadata: { status: 401 },
});
});
it("normalizes a read-side 429 to the non-applicable effect vocabulary", async () => {
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",