Skip to content

Commit ca4ec2a

Browse files
fix(auth): a hung "Sign in with SSO" request gives the login page back after the 20 s sign-in watchdog (#35737)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoA1ALjVcUcAuAA15MyUocBx)_ Fixes #34861 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:登录页按“使用 SSO 登录”后若服务器一直不回应,约 20 秒后转圈停止、提示登录超时,邮箱框和按钮恢复可用,可以直接重试;此前会一直转圈直到刷新页面。 - 为什么做:修复单点登录用户在身份提供方接口卡住时被困在登录页的问题,与其他登录按钮已有的 20 秒超时保护对齐。 - 出错会怎样:只影响按邮箱走单点登录的那一步;最坏情况是超时提示出现得过早或不出现,可直接撤回本次改动恢复原样。 - 要你做什么:无 ## What changes - `ui/packages/auth/src/LoginForm.tsx`, `handleSso`: the `POST /api/v1/auth/sign-in/sso` request now carries an `AbortController` signal, aborted after `SSO_SIGN_IN_TIMEOUT_MS` (20 000 ms). On that abort the form shows `SSO_SIGN_IN_TIMEOUT_TEXT` and clears `ssoSubmitting`, so the SSO button and the SSO email field are usable again (retry path). The timer is cleared in `finally` on every settle; a successful answer still navigates to `data.url` and keeps the pending state through teardown. - The window and the sentence are the same as the provider buttons' watchdog (`SIGN_IN_TIMEOUT_MS` / `withTimeout` inside `signInWithProvider` in `createAuthClient.ts`). They are module constants in `LoginForm.tsx`, not imported: `createAuthClient.ts` is outside this card's file surface, and the watchdog there is a local of `signInWithProvider` with nothing exported to share. - The body read (`res.json()`) is also under the signal: an abort during the body read surfaces as the timeout, not as the "No SSO provider" fallback. - Changeset: `@object-ui/auth` patch. ## Why A hung SSO request left the button spinning and the email field disabled until a reload (reproduced by QA twice under SSO-only mode). The card's expected behaviour: "after about 20 s the watchdog recovers the button with an error and a retry path." ## Tests New top-level `describe` in the shared harness `ui/packages/auth/src/__tests__/LoginForm.test.tsx` (SSO-only mode, fake `setTimeout`/`clearTimeout`): - Pin: the SSO fetch never answers. At 19 999 ms the button and the email field are still disabled, the request's signal is not aborted and no alert shows; at 20 000 ms the signal is aborted, the alert reads as a timeout, and the button and the email field are enabled. - CONTROL: an answering fetch still sets `window.location.href` to the IdP URL; after 20 s the signal is not aborted, the button keeps its pending state, and no alert shows. <details><summary>Readings at head 171e0ee (after merging origin/main a3a74f2)</summary> - `pnpm --dir ui exec vitest run packages/auth/` under the verify lock: `Test Files 48 passed (48)`, `Tests 493 passed (493)`, VERDICT command-exit 0. - `pnpm --filter @object-ui/auth type-check` (`tsc --noEmit && tsc -p tsconfig.test.json`; the second program includes `src/**/*.test.tsx`): VERDICT command-exit 0. - Ablation (at c00af54, the fix committed first; the test imports `../LoginForm` from source, no dist in the path): `node scripts/ablation-replace.mjs` replaced the timer body `controller.abort();` / `SSO_SIGN_IN_TIMEOUT_MS` with a no-op and a 1e9 ms delay (anchor x1 to x0, replacement x0 to x1, blob 990a9ef to 60b77598). Pin RED: `expected false to be true` on `signal.aborted`; CONTROL green. Restored: blob equals HEAD (990a9ef), `git diff HEAD` empty. </details> ## Acceptance notes - The 20 s value and the timeout sentence now live in two places (`LoginForm.tsx` module constants and the local inside `signInWithProvider`). Moving the watchdog into one shared module is a follow-up for whoever next edits `createAuthClient.ts`; not done here because that file was outside this card's surface. - The timeout sentence is not localized, same as the provider buttons' watchdog sentence (shown via the error's message). No new `LoginFormLabels` key was added. - `onError` is not called on the SSO path, as before this change. ## Verification Read first: `ui/packages/auth/src/LoginForm.tsx` `handleSso` (risk hunk: the `res.json().catch` rethrow on timeout and the `finally` clearing the timer, which must not fire after a successful navigation). Two-minute check: `pnpm --dir ui exec vitest run packages/auth/src/__tests__/LoginForm.test.tsx -t "aborted after 20 s"` shows 2 passed. <details><summary>Local gate readings</summary> - `node scripts/pm/dispatch-gates.mjs --commands` derived 38 families for this diff. 37 ran at head 171e0ee, all exit 0. `--ran` reconciliation: "38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED". - `pnpm --dir ui exec vitest run scripts/` ran once at c00af54 (before the merge): exit 1, 2 files red of 173 (`date-only-zone-pins-10183.test.ts`, which drives other ui packages' zone tests, and a closure-budget test that needs a built Console bundle: "Budgeted chunk `ui-components` is ABSENT from the eager closure"). Neither reads `ui/packages/auth`. Read as an unbuilt-workspace reading, not a verdict, and left to CI's `Test UI`. - `node scripts/pm/overlap-check.mjs --branch=HEAD` and `--pr=35575`: VERDICT clean exit 0. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [ ] 3. No formatter ran; `pnpm lint` passes. (No formatter ran; `pnpm lint` is a repo-wide scan left to CI, not run locally.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibyy9KSA69EGZtjDj9c Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1e692d1 commit ca4ec2a

3 files changed

Lines changed: 100 additions & 4 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/auth': patch
3+
---
4+
5+
fix(auth): a "Sign in with SSO" request that never answers gives the sign-in page back after 20 seconds
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On the login page, when the request behind "Sign in with SSO" got no answer, the button kept spinning and the email field stayed locked until the page was reloaded. The request now runs under the same 20-second limit as the identity-provider buttons: once it passes, the request is cancelled, the page says the sign-in timed out, and the email field and the button can be used again to retry. An answering request still sends the browser to the identity provider as before.

‎ui/packages/auth/src/LoginForm.tsx‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,14 @@ function refusalText(error: Error, errorMessages: Record<string, string> | undef
187187
);
188188
}
189189

190+
/**
191+
* The "Sign in with SSO" request's watchdog: the same window and sentence as
192+
* the provider buttons' sign-in watchdog (`signInWithProvider` in
193+
* `createAuthClient.ts`), so both doors recover a hung request alike.
194+
*/
195+
const SSO_SIGN_IN_TIMEOUT_MS = 20_000;
196+
const SSO_SIGN_IN_TIMEOUT_TEXT = 'Sign-in timed out — the server did not respond. Please try again.';
197+
190198
const DefaultLink = ({ href, className, children }: AuthLinkComponentProps) => (
191199
<a href={href} className={className}>{children}</a>
192200
);
@@ -536,15 +544,28 @@ export function LoginForm({
536544
return;
537545
}
538546
setSsoSubmitting(true);
547+
// A request that never answers is aborted after the same window the
548+
// provider buttons' sign-in watchdog uses, so the button and the email
549+
// field always come back with an error and a retry path.
550+
const controller = new AbortController();
551+
let timedOut = false;
552+
const timer = setTimeout(() => {
553+
timedOut = true;
554+
controller.abort();
555+
}, SSO_SIGN_IN_TIMEOUT_MS);
539556
try {
540557
const base = window.location.pathname.replace(/\/login(?:\/.*)?$/, '');
541558
const res = await fetch('/api/v1/auth/sign-in/sso', {
542559
method: 'POST',
543560
headers: { 'content-type': 'application/json' },
544561
body: JSON.stringify({ email: identifier, callbackURL: base + '/home' }),
545562
credentials: 'include',
563+
signal: controller.signal,
546564
});
547-
const data = (await res.json().catch(() => ({}))) as { url?: string; message?: string };
565+
const data = (await res.json().catch((e: unknown) => {
566+
if (timedOut) throw e;
567+
return {};
568+
})) as { url?: string; message?: string };
548569
if (res.ok && typeof data.url === 'string') {
549570
// Navigating to the IdP — keep the pending state through teardown.
550571
window.location.href = data.url;
@@ -553,8 +574,10 @@ export function LoginForm({
553574
setError(data.message || 'No SSO provider is configured for this email domain.');
554575
setSsoSubmitting(false);
555576
} catch (err) {
556-
setError(err instanceof Error ? err.message : String(err));
577+
setError(timedOut ? SSO_SIGN_IN_TIMEOUT_TEXT : err instanceof Error ? err.message : String(err));
557578
setSsoSubmitting(false);
579+
} finally {
580+
clearTimeout(timer);
558581
}
559582
};
560583

‎ui/packages/auth/src/__tests__/LoginForm.test.tsx‎

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
*/
99

1010
import React from 'react';
11-
import { describe, it, expect, vi } from 'vitest';
12-
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
11+
import { describe, it, expect, vi, afterEach } from 'vitest';
12+
import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react';
1313
import { AuthProvider } from '../AuthProvider';
1414
import { LoginForm, type LoginFormProps } from '../LoginForm';
1515
import type { AuthClient, AuthPublicConfig } from '../types';
@@ -551,3 +551,66 @@ describe('LoginForm — a refusal with a cause is mapped by CODE:cause (objectst
551551
expect(text).toBe(BAN_MESSAGE);
552552
});
553553
});
554+
555+
// objectstack#34861 — the "Sign in with SSO" request runs under the same 20 s
556+
// watchdog as the provider buttons: a request that never answers is aborted,
557+
// and the button and the email field come back with an error.
558+
describe('LoginForm — a hung "Sign in with SSO" request is aborted after 20 s (objectstack#34861)', () => {
559+
const originalLocation = window.location;
560+
afterEach(() => {
561+
vi.useRealTimers();
562+
vi.restoreAllMocks();
563+
Object.defineProperty(window, 'location', { writable: true, value: originalLocation });
564+
});
565+
566+
async function pressSso(answer: (signal: AbortSignal) => Promise<Response>) {
567+
const fetchSpy = vi
568+
.spyOn(globalThis, 'fetch')
569+
.mockImplementation((_url, init) => answer(init!.signal!));
570+
renderLogin(createMockClient({ features: { sso: true, ssoEnforced: true } }));
571+
const button = await screen.findByRole('button', SSO_BUTTON);
572+
const emailField = screen.getByLabelText('Email');
573+
fireEvent.change(emailField, { target: { value: 'a@corp.example' } });
574+
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
575+
fireEvent.click(button);
576+
const signal = fetchSpy.mock.calls[0][1]!.signal!;
577+
return { button, emailField, signal };
578+
}
579+
580+
it('keeps the request pending for 20 s, then aborts it and gives the button and email field back', async () => {
581+
const { button, emailField, signal } = await pressSso(
582+
(sig) => new Promise<Response>((_resolve, reject) => {
583+
sig.addEventListener('abort', () => reject(new DOMException('The operation was aborted.', 'AbortError')));
584+
}),
585+
);
586+
587+
await act(async () => { await vi.advanceTimersByTimeAsync(19_999); });
588+
expect(button).toBeDisabled();
589+
expect(emailField).toBeDisabled();
590+
expect(signal.aborted).toBe(false);
591+
expect(screen.queryByRole('alert')).toBeNull();
592+
593+
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
594+
expect(signal.aborted).toBe(true);
595+
expect(screen.getByRole('alert').textContent).toMatch(/timed out/i);
596+
expect(button).not.toBeDisabled();
597+
expect(emailField).not.toBeDisabled();
598+
});
599+
600+
it('CONTROL: an answering request still navigates to the IdP, and the watchdog never aborts it', async () => {
601+
Object.defineProperty(window, 'location', {
602+
writable: true,
603+
value: { ...originalLocation, pathname: '/_console/login', href: 'http://localhost/_console/login' },
604+
});
605+
const { button, signal } = await pressSso(async () => new Response(
606+
JSON.stringify({ url: 'https://idp.example.com/authorize' }),
607+
{ status: 200, headers: { 'content-type': 'application/json' } },
608+
));
609+
610+
await act(async () => { await vi.advanceTimersByTimeAsync(20_000); });
611+
expect(window.location.href).toBe('https://idp.example.com/authorize');
612+
expect(signal.aborted).toBe(false);
613+
expect(button).toBeDisabled();
614+
expect(screen.queryByRole('alert')).toBeNull();
615+
});
616+
});

0 commit comments

Comments
 (0)