Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
190 changes: 190 additions & 0 deletions packages/cli/src/serve/auth/deviceFlow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
DEVICE_FLOW_MAX_EXPIRES_IN_SEC,
DEVICE_FLOW_MAX_INTERVAL_MS,
DEVICE_FLOW_PERSIST_TIMEOUT_MS,
DEVICE_FLOW_POLL_TIMEOUT_MS,
DEVICE_FLOW_SLOW_DOWN_BUMP_MS,
DEVICE_FLOW_START_TIMEOUT_MS,
DEVICE_FLOW_TERMINAL_GRACE_MS,
Expand Down Expand Up @@ -122,6 +123,13 @@ class FakeProvider implements DeviceFlowProvider {
* `DeviceFlowProvider.poll()` `@remarks` sanitization contract by
* throwing raw IdP detail. PR #4255 fold-in 8 #1. */
pollThrowsWith: Error | undefined;
/** Test hook: when `true`, `poll()` returns a Promise that NEVER
* resolves and ignores the supplied `signal`. Models a misbehaving
* provider whose underlying I/O isn't abortable — registry's
* authoritative `Promise.race` against `DEVICE_FLOW_POLL_TIMEOUT_MS`
* is the only thing that can rescue the await. PR #4255 follow-up
* review thread (deepseek-v4-pro). */
pollHangs = false;
/** Most recent `opts.signal` observed by `poll`. Test hook for the
* abort-mid-poll assertion: after `registry.cancel(...)`, this
* signal MUST report `.aborted === true` so the upstream HTTP
Expand Down Expand Up @@ -168,6 +176,12 @@ class FakeProvider implements DeviceFlowProvider {
this.pollThrowsWith = undefined;
throw err;
}
if (this.pollHangs) {
// Never resolves, ignores `signal`. Registry's Promise.race
// timeout is the only path out.
await new Promise<never>(() => {});
throw new Error('unreachable');
}
if (opts.signal.aborted) return { kind: 'pending' };
if (this.pollScript.length === 0) {
return { kind: 'pending' };
Expand Down Expand Up @@ -667,6 +681,65 @@ describe('DeviceFlowRegistry — authoritative timeouts (fold-in 7)', () => {
}
});

it('poll() that hangs past POLL_TIMEOUT_MS surfaces as upstream_error and aborts the entry signal (follow-up review)', async () => {
// PR #4255 follow-up review thread (deepseek-v4-pro): runPollTick
// now races provider.poll() against DEVICE_FLOW_POLL_TIMEOUT_MS so
// a non-abortable provider can no longer pin the per-providerId
// singleton waiting for sweeper-level expiry. Aborts the signal
// first so cooperative providers tear down cleanly; reject
// surfaces in the catch as the bounded `upstream_error` hint.
const provider = new FakeProvider();
provider.pollHangs = true;
const built = buildRegistry(provider);
const { registry, env, events, auditLines } = built;
try {
const { view } = await registry.start({ providerId: 'qwen-oauth' });
// Trigger the first poll tick.
env.clock.tick(DEVICE_FLOW_DEFAULT_INTERVAL_MS + 1);
env.scheduler.flushDue(env.clock.now);
// Let runPollTick reach the await.
await flushAsync();
expect(provider.pollCount).toBe(1);
// Race timer hasn't fired yet — entry is still pending.
expect(registry.get(view.deviceFlowId)?.status).toBe('pending');
// Advance clock past POLL_TIMEOUT_MS; race timer fires, aborts
// the entry signal, and rejects the wrapper promise.
env.clock.tick(DEVICE_FLOW_POLL_TIMEOUT_MS + 1);
env.scheduler.flushDue(env.clock.now);
await flushAsync();
// Signal must be aborted so cooperative providers can abandon
// their in-flight fetch.
expect(provider.lastPollSignal?.aborted).toBe(true);
// The catch block surfaces a bounded upstream_error to SSE.
const failed = events.find(
(e) =>
e.emission.type === 'failed' &&
e.emission.data.deviceFlowId === view.deviceFlowId,
);
expect(failed).toBeDefined();
if (failed && failed.emission.type === 'failed') {
expect(failed.emission.data.errorKind).toBe('upstream_error');
expect(failed.emission.data.hint).toContain(
'see daemon audit log for details',
);
}
// Audit captures the raw timeout error for the operator.
const auditFailure = auditLines.find(
(line) =>
line['status'] === 'failed' && line['errorKind'] === 'upstream_error',
);
expect(auditFailure).toBeDefined();
// PR #4291 follow-up review (Qwen Code review summary 🔵 Low):
// poll-tick must NOT reschedule itself after a timeout-driven
// upstream_error (the entry has already transitioned to error
// state; another poll would be a `entry.status !== 'pending'`
// no-op at best, log noise at worst). Pin the invariant.
expect(provider.pollCount).toBe(1);
} finally {
registry.dispose();
}
});

it('persist() that hangs past PERSIST_TIMEOUT_MS maps to persist_failed (#2)', async () => {
const provider = new FakeProvider();
// Single poll tick returns success whose persist() never resolves.
Expand Down Expand Up @@ -940,6 +1013,123 @@ describe('DeviceFlowRegistry — persist failure paths (fold-in 10 #1)', () => {
}
});

it('cancellerClientId is first-writer-wins across concurrent cancel() calls during persist', async () => {
// PR #4255 follow-up review thread (deepseek-v4-pro): two SDK
// clients racing `cancel()` on the same persist-in-flight entry
// must NOT silently overwrite attribution. The first cancel that
// observes `persistInFlight` is the one that drove the transition;
// the persist-resolution event should be attributed to it. The
// second cancel is functionally a no-op on the entry (it's already
// marked `cancelRequestedDuringPersist`); its caller still appears
// in the audit trail through the `audit.record(...)` path but
// does not overwrite the SSE event's `originatorClientId`.
const provider = new FakeProvider();
let rejectPersist!: (err: Error) => void;
const persistPromise = new Promise<{ expiresAt?: number }>(
(_resolve, reject) => {
rejectPersist = reject;
},
);
provider.pollScript = [
{
kind: 'success',
persist: () => persistPromise,
},
];
const built = buildRegistry(provider);
const { registry, env, events } = built;
try {
const { view } = await registry.start({ providerId: 'qwen-oauth' });
env.clock.tick(DEVICE_FLOW_DEFAULT_INTERVAL_MS + 1);
env.scheduler.flushDue(env.clock.now);
await flushAsync();
// First canceller wins.
const first = registry.cancel(view.deviceFlowId, 'sdk-A');
expect(first).toEqual({ alreadyTerminal: false });
// Second canceller observes `persistInFlight` already set; the
// entry is still marked `cancelRequestedDuringPersist`. Its id
// MUST NOT overwrite the first-writer's attribution.
const second = registry.cancel(view.deviceFlowId, 'sdk-B');
expect(second).toEqual({ alreadyTerminal: false });
// Persist now fails — the registry emits `cancelled` with
// `originatorClientId = entry.cancellerClientId` (sdk-A).
rejectPersist(new Error('aborted: cancel during persist'));
await flushAsync();
const snapshot = registry.get(view.deviceFlowId);
expect(snapshot?.status).toBe('cancelled');
const cancelledEvent = events.find(
(e) =>
e.emission.type === 'cancelled' &&
e.emission.data.deviceFlowId === view.deviceFlowId,
);
expect(cancelledEvent).toBeDefined();
// First-writer-wins: sdk-A drove the transition.
expect(cancelledEvent?.clientId).toBe('sdk-A');
} finally {
registry.dispose();
}
});

it('cancellerClientId is first-writer-wins even when the first canceller is anonymous (no clientId)', async () => {
// PR #4291 follow-up review (Copilot): the first version of the
// first-writer-wins guard used `entry.cancellerClientId === undefined`
// as the gate, which silently broke when the first canceller was
// anonymous: `cancel(id, undefined)` left the field undefined, and
// a later `cancel(id, 'sdk-B')` saw the gate as still open and
// overwrote attribution. The fix decouples the "have we recorded a
// canceller" question (`cancellerRecorded` flag) from the "do we
// have a clientId" question. An anonymous first canceller still
// flips the flag, blocking any later writer.
const provider = new FakeProvider();
let rejectPersist!: (err: Error) => void;
const persistPromise = new Promise<{ expiresAt?: number }>(
(_resolve, reject) => {
rejectPersist = reject;
},
);
provider.pollScript = [
{
kind: 'success',
persist: () => persistPromise,
},
];
const built = buildRegistry(provider);
const { registry, env, events } = built;
try {
const { view } = await registry.start({ providerId: 'qwen-oauth' });
env.clock.tick(DEVICE_FLOW_DEFAULT_INTERVAL_MS + 1);
env.scheduler.flushDue(env.clock.now);
await flushAsync();
// First (anonymous) canceller wins. cancellerClientId stays
// undefined; cancellerRecorded is now true.
const first = registry.cancel(view.deviceFlowId);
expect(first).toEqual({ alreadyTerminal: false });
// Second canceller IS identified — but the first-writer-wins
// gate must reject the overwrite.
const second = registry.cancel(view.deviceFlowId, 'sdk-B');
expect(second).toEqual({ alreadyTerminal: false });
rejectPersist(new Error('aborted: cancel during persist'));
await flushAsync();
const snapshot = registry.get(view.deviceFlowId);
expect(snapshot?.status).toBe('cancelled');
const cancelledEvent = events.find(
(e) =>
e.emission.type === 'cancelled' &&
e.emission.data.deviceFlowId === view.deviceFlowId,
);
expect(cancelledEvent).toBeDefined();
// The deferred SSE event must NOT carry sdk-B as originator —
// the anonymous first writer wins, so `entry.cancellerClientId`
// stays undefined, and the runPollTick deferred-cancel branch
// falls back to `entry.initiatorClientId` (which is also
// undefined here because `start()` itself was anonymous). The
// critical assertion: sdk-B did NOT silently take credit.
expect(cancelledEvent?.clientId).not.toBe('sdk-B');
} finally {
registry.dispose();
}
});

it('records lost_success_after_timeout when persist resolves AFTER the registry timeout (round-12 #8)', async () => {
// PR #4255 round-12 #8 (Cy_ZH): pins the split-brain detector
// for non-conforming providers. fold-in 9 #7 added an
Expand Down
90 changes: 81 additions & 9 deletions packages/cli/src/serve/auth/deviceFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,21 @@ export const DEVICE_FLOW_PERSIST_TIMEOUT_MS = 30_000;
* PR #4255 review fold-in 3 (#2).
*/
export const DEVICE_FLOW_START_TIMEOUT_MS = 30_000;
/**
* Hard ceiling on a single `provider.poll()` tick. Symmetric with
* `DEVICE_FLOW_START_TIMEOUT_MS` and `DEVICE_FLOW_PERSIST_TIMEOUT_MS`,
* which already bound their respective phases. PR #4255 follow-up
* review thread (deepseek-v4-pro): a hung IdP token endpoint (TCP
* established, no response) without this would block the registry's
* poll-tick promise indefinitely. The entry's `cancelController.signal`
* is the cooperative path; this race makes the timeout authoritative
* regardless of provider cooperation. The sweeper would still evict
* the entry once `expiresAt` is past, but until then the per-provider
* singleton stays occupied with no other recovery short of daemon
* restart. 30s is the same generosity the start/persist phases use
* and is well over a healthy IdP's polling round-trip.
*/
export const DEVICE_FLOW_POLL_TIMEOUT_MS = 30_000;
/**
* Operator-safe upper bound on the IdP-provided `expires_in`. RFC
* 8628 §6.1 calls 5–30 minutes "reasonable"; 1 hour is the practical
Expand Down Expand Up @@ -503,6 +518,18 @@ interface DeviceFlowEntry {
* 9 review thread #5.
*/
cancellerClientId?: string;
/**
* First-writer-wins flag. Set the moment ANY `cancel()` call drives
* this entry into `cancelRequestedDuringPersist` — including the
* anonymous case where `cancellerClientId` stays `undefined`. The
* flag is decoupled from `cancellerClientId` because the latter
* being `undefined` is BOTH "no canceller has driven the transition
* yet" AND "an anonymous canceller drove the transition" — using it
* as the gate would let a later identified canceller silently
* overwrite an earlier anonymous one. PR #4255 follow-up review
* (Copilot on #4291): closes the anonymous-first canceller bug.
*/
cancellerRecorded?: boolean;
}

export interface DeviceFlowRegistryDeps {
Expand Down Expand Up @@ -916,8 +943,29 @@ export class DeviceFlowRegistry {
// `originatorClientId` was always `entry.initiatorClientId`,
// which broke any SSE consumer that suppresses self-emitted
// events to avoid double-handling.
if (cancellerClientId) {
entry.cancellerClientId = cancellerClientId;
// PR #4255 follow-up review thread (deepseek-v4-pro): first-writer-
// wins. Two SDK clients racing `cancel()` on the same persist-in-
// flight entry must NOT silently overwrite attribution — the second
// caller's `cancel()` is functionally a no-op (the entry is already
// marked `cancelRequestedDuringPersist`), so the persist-resolution
// event should be attributed to whoever actually drove the
// transition first. Subsequent callers stay in the audit trail
// through their own `audit.record(...)` line below.
//
// PR #4291 follow-up review (Copilot): the gate is `cancellerRecorded`
// (a separate flag), NOT `cancellerClientId === undefined`. The earlier
// shape silently broke when the first canceller was anonymous: their
// `cancel(id, undefined)` left `cancellerClientId` undefined, so the
// next identified `cancel(id, 'sdk-B')` saw the gate as still open
// and overwrote the attribution. Decoupling the "have we recorded a
// canceller" question from the "do we have a clientId" question fixes
// it: an anonymous first canceller still flips the flag, blocking
// any later writer.
if (!entry.cancellerRecorded) {
entry.cancellerRecorded = true;
if (cancellerClientId) {
entry.cancellerClientId = cancellerClientId;
}
}
try {
entry.cancelController.abort(new Error('cancel during persist'));
Expand Down Expand Up @@ -1011,14 +1059,36 @@ export class DeviceFlowRegistry {
entry.lastPolledAt = now;
let result: DeviceFlowPollResult;
let rawProviderError: string | undefined;
// PR #4255 follow-up review thread (deepseek-v4-pro): bound
// `provider.poll()` with the same `Promise.race` shape used by
// `doStart` / persist. The cooperative `entry.cancelController.signal`
// path covers well-behaved providers; this race makes the timeout
// authoritative even when a provider ignores `signal`. A hung IdP
// token endpoint without this would otherwise block the poll-tick
// promise indefinitely (occupying the per-provider singleton until
// sweeper / daemon restart). The rejecting timer aborts the signal
// first so cooperative providers can still tear down cleanly.
let pollTimer: ReturnType<typeof setTimeout> | undefined;
try {
result = await provider.poll(
{
deviceCode: entry.deviceCode,
pkceVerifier: entry.pkceVerifier,
},
{ signal: entry.cancelController.signal },
);
result = await new Promise<DeviceFlowPollResult>((resolve, reject) => {
pollTimer = this.schedule(DEVICE_FLOW_POLL_TIMEOUT_MS, () => {
try {
entry.cancelController.abort(new Error('device-flow poll timeout'));
} catch {
// best-effort
}
reject(new Error('device-flow poll timeout'));
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
});
provider
.poll(
{
deviceCode: entry.deviceCode!,
pkceVerifier: entry.pkceVerifier,
},
{ signal: entry.cancelController.signal },
)
.then(resolve, reject);
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
});
} catch (err: unknown) {
// PR #4255 fold-in 9 review thread #1 (refines fold-in 8 #1):
// a non-conforming provider that violates the `@remarks`
Expand All @@ -1037,6 +1107,8 @@ export class DeviceFlowRegistry {
errorKind: 'upstream_error',
hint: 'provider.poll() failed; see daemon audit log for details',
};
} finally {
if (pollTimer !== undefined) this.clearScheduled(pollTimer);
}
// PR #4255 round-12 #1 (gpt-5.5 review CzSpN): also re-check
// `this.disposed` after the await. `dispose()` clears
Expand Down
Loading
Loading