Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 20 additions & 0 deletions .changeset/34171-managed-password-refusal-copy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@object-ui/auth': patch
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
'@object-ui/console': patch
---

fix(auth): a cloud-managed runtime's password refusal is shown in the session's language and points at the identity provider's button

Clause-②: yes (widening) — `@object-ui/auth` `ForgotPasswordFormProps` gains the optional `errorMessages`; `@object-ui/i18n` gains `auth.login.errors.managedPasswordSignIn` and `auth.login.errors.managedPasswordReset` in every locale
Metadata-protocol: none

A cloud-managed runtime refuses the password doors (sign-in, forgot password, reset password, set password) with 409 `RESOURCE_CONFLICT`. Its code never reached the pages. The hosted relay and the set-password route answer in the platform's error envelope, `{ success: false, error: { code, message } }`, which the auth client did not read. Forgot and reset dropped the code where the client threw. So each of those pages showed the server's English sentence or `Auth request failed with status 409`, whatever the language.

- **`@object-ui/auth`.** The client's error builder reads `code`, `message`, `details` and `userMessage` from the envelope's `error` when the flat body has none; a better-auth refusal answers exactly as before. `forgotPassword`, `resetPassword` and `setInitialPassword` now keep the refusal's code and status too. `ForgotPasswordForm` gains an `errorMessages` prop, the same code-to-text map `LoginForm` takes; without it the server's message is shown as before.
- **`@object-ui/app-shell`.** `signInRefusalMessages` maps `RESOURCE_CONFLICT` to a sentence that says the deployment signs people in through its identity provider and points at its button above the form. The new `passwordDoorRefusalMessages` carries the matching sentence for the forgot, reset and set-password doors, and the package's forgot-password page passes it.
- **`@object-ui/i18n`.** Two keys, `auth.login.errors.managedPasswordSignIn` and `auth.login.errors.managedPasswordReset`, in every locale.
- **`@object-ui/console`.** The forgot-password, reset-password and set-password pages show the same sentence.

On the sign-in door only a cloud-managed runtime answers this code, so a self-hosted sign-in is unchanged. On the reset and set-password doors a self-hosted deployment answers the same 409 `RESOURCE_CONFLICT` in two cases: an account its identity provider provisions while SSO-only mode is on, and a pending SSO person not yet signed in. Those pages now show the same localized sentence in place of the server's English one; it is true for that reader too. Nothing to migrate.
2 changes: 2 additions & 0 deletions ui/apps/console/src/pages/auth/ForgotPasswordPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Link } from 'react-router-dom';
import { ForgotPasswordForm } from '@object-ui/auth';
import { useObjectTranslation } from '@object-ui/i18n';
import { Card } from '@object-ui/components';
import { passwordDoorRefusalMessages } from '@object-ui/app-shell';
import { AuthLayout } from './AuthLayout';

function RouterLink(props: { href: string; className?: string; children: React.ReactNode }) {
Expand All @@ -29,6 +30,7 @@ export function ForgotPasswordPage() {
<ForgotPasswordForm
loginUrl="/login"
linkComponent={RouterLink}
errorMessages={passwordDoorRefusalMessages(t)}
title={t('auth.forgotPassword.title', { defaultValue: 'Reset your password' })}
description={t('auth.forgotPassword.description', {
defaultValue: "Enter your email address and we'll send you a link to reset your password",
Expand Down
7 changes: 6 additions & 1 deletion ui/apps/console/src/pages/auth/ResetPasswordPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
import { useAuth } from '@object-ui/auth';
import { useObjectTranslation } from '@object-ui/i18n';
import { passwordDoorRefusalMessages } from '@object-ui/app-shell';
import {
Button,
Card,
Expand Down Expand Up @@ -64,9 +65,13 @@ export function ResetPasswordPage() {
);
navigate('/login');
} catch (err) {
// A refusal with a known code shows its localized sentence: a
// cloud-managed runtime refuses this door with 409 RESOURCE_CONFLICT
// (objectstack#34171). Any other refusal keeps the server's text.
const code = (err as Error & { code?: string }).code;
toast.error(
t('auth.resetPassword.failed', { defaultValue: 'Reset failed' }),
{ description: (err as Error).message },
{ description: (code && passwordDoorRefusalMessages(t)[code]) || (err as Error).message },
);
} finally {
setSubmitting(false);
Expand Down
7 changes: 6 additions & 1 deletion ui/apps/console/src/pages/auth/SetPasswordPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
import { useAuth } from '@object-ui/auth';
import { useObjectTranslation } from '@object-ui/i18n';
import { passwordDoorRefusalMessages } from '@object-ui/app-shell';
import {
Button,
Card,
Expand Down Expand Up @@ -64,9 +65,13 @@ export function SetPasswordPage() {
);
navigate(next);
} catch (err) {
// A refusal with a known code shows its localized sentence: a
// cloud-managed runtime refuses this door with 409 RESOURCE_CONFLICT
// (objectstack#34171). Any other refusal keeps the server's text.
const code = (err as Error & { code?: string }).code;
toast.error(
t('auth.setPassword.failed'),
{ description: (err as Error).message },
{ description: (code && passwordDoorRefusalMessages(t)[code]) || (err as Error).message },
);
} finally {
setSubmitting(false);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/**
* objectstack#34171 — a cloud-managed runtime refuses the reset-password and
* set-password doors with 409 `RESOURCE_CONFLICT`, because no local password is
* set or reset there for anyone. The console's two pages show that refusal in
* the session's language, pointing at the identity provider's button, through
* app-shell's `passwordDoorRefusalMessages`. Any other refusal keeps the
* server's text. Only `useAuth` and the toast are replaced; the pages, the
* refusal map and the zh pack are real.
*/

import '@testing-library/jest-dom/vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { toast } from 'sonner';
import { I18nProvider } from '@object-ui/i18n';
import { builtInLocales, registerBuiltInLocales } from '@object-ui/i18n/locales';

let authState: Record<string, unknown>;
vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => authState,
}));

vi.mock('sonner', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
return { ...actual, toast: { success: vi.fn(), error: vi.fn() } };
});

const { ResetPasswordPage } = await import('../ResetPasswordPage');
const { SetPasswordPage } = await import('../SetPasswordPage');

registerBuiltInLocales();

const zh = builtInLocales['zh-Hans'].auth;
const SERVER_TEXT = 'This environment is cloud-managed: no local password is set or reset here.';

function coded(code: string, message: string): Error {
const err = new Error(message) as Error & { code?: string; status?: number };
err.code = code;
return err;
}

function renderAt(path: string, page: React.ReactElement) {
render(
<I18nProvider config={{ defaultLanguage: 'zh', detectBrowserLanguage: false }} persistLanguage={false}>
<MemoryRouter initialEntries={[path]}>{page}</MemoryRouter>
</I18nProvider>,
);
}

async function fillAndSubmit(labels: { newPassword: string; confirmPassword: string; submit: string }) {
await userEvent.type(await screen.findByLabelText(labels.newPassword), 'new-password-1');
await userEvent.type(screen.getByLabelText(labels.confirmPassword), 'new-password-1');
await userEvent.click(screen.getByRole('button', { name: labels.submit }));
}

/** The description of the one error toast the page raised. */
async function toastDescription(): Promise<unknown> {
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
return (vi.mocked(toast.error).mock.calls[0][1] as { description?: unknown } | undefined)?.description;
}

beforeEach(() => {
window.localStorage.clear();
vi.mocked(toast.error).mockClear();
});

afterEach(() => {
cleanup();
});

describe('ResetPasswordPage — a cloud-managed refusal is localized (objectstack#34171)', () => {
async function refusedWith(err: Error): Promise<unknown> {
authState = { resetPassword: vi.fn().mockRejectedValue(err) };
renderAt('/reset-password?token=tok', <ResetPasswordPage />);
await fillAndSubmit(zh.resetPassword);
return toastDescription();
}

it('RESOURCE_CONFLICT shows the localized reset sentence, not the server text', async () => {
expect(await refusedWith(coded('RESOURCE_CONFLICT', SERVER_TEXT))).toBe(zh.login.errors.managedPasswordReset);
});

it('CONTROL: another refusal keeps its server message', async () => {
expect(await refusedWith(coded('INVALID_TOKEN', 'Invalid token'))).toBe('Invalid token');
});
});

describe('SetPasswordPage — a cloud-managed refusal is localized (objectstack#34171)', () => {
async function refusedWith(err: Error): Promise<unknown> {
authState = {
user: { id: 'u1', name: 'Dana', email: 'dana@example.com' },
isLoading: false,
setInitialPassword: vi.fn().mockRejectedValue(err),
};
renderAt('/set-password', <SetPasswordPage />);
await fillAndSubmit(zh.setPassword);
return toastDescription();
}

it('RESOURCE_CONFLICT shows the localized reset sentence, not the server text', async () => {
expect(await refusedWith(coded('RESOURCE_CONFLICT', SERVER_TEXT))).toBe(zh.login.errors.managedPasswordReset);
});

it('CONTROL: another refusal keeps its server message', async () => {
expect(await refusedWith(coded('CREDENTIAL_ACCOUNT_EXISTS', 'A password is already set'))).toBe(
'A password is already set',
);
});
});

// The same code has two self-hosted producers on these doors (plugin-auth
// `sso-only-local-password.ts`, `pending-sso-marker.ts`). The sentence is true
// for their reader too, so the mapping stands for them: an SSO-only refusal of
// an IdP-provisioned account shows the same localized sentence.
describe('Reset and set-password pages — a self-hosted SSO-only refusal shows the same sentence (objectstack#34171)', () => {
const SSO_ONLY_RESET =
'This environment is in SSO-only mode and your account is provisioned by your identity provider, so you sign in '
+ 'through single sign-on and your local password cannot be reset here. Sign in with SSO. No password was set.';
const SSO_ONLY_SET =
'This environment is in SSO-only mode and your account is provisioned by your identity provider, so you sign in '
+ 'through single sign-on and a local password cannot be set for you here. Sign in with SSO. No password was set.';

it('reset-password: the SSO-only 409 RESOURCE_CONFLICT shows the localized reset sentence', async () => {
authState = { resetPassword: vi.fn().mockRejectedValue(coded('RESOURCE_CONFLICT', SSO_ONLY_RESET)) };
renderAt('/reset-password?token=tok', <ResetPasswordPage />);
await fillAndSubmit(zh.resetPassword);
expect(await toastDescription()).toBe(zh.login.errors.managedPasswordReset);
});

it('set-password: the SSO-only 409 RESOURCE_CONFLICT shows the localized reset sentence', async () => {
authState = {
user: { id: 'u1', name: 'Dana', email: 'dana@example.com' },
isLoading: false,
setInitialPassword: vi.fn().mockRejectedValue(coded('RESOURCE_CONFLICT', SSO_ONLY_SET)),
};
renderAt('/set-password', <SetPasswordPage />);
await fillAndSubmit(zh.setPassword);
expect(await toastDescription()).toBe(zh.login.errors.managedPasswordReset);
});
});
2 changes: 2 additions & 0 deletions ui/packages/app-shell/src/console/auth/ForgotPasswordPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Link } from 'react-router-dom';
import { ForgotPasswordForm, type AuthLinkComponentProps } from '@object-ui/auth';
import { useObjectTranslation } from '@object-ui/i18n';
import { AuthPageLayout } from './AuthPageLayout.js';
import { passwordDoorRefusalMessages } from './signInRefusalMessages.js';

const RouterLink = ({ href, className, children }: AuthLinkComponentProps) => (
<Link to={href} className={className}>{children}</Link>
Expand All @@ -21,6 +22,7 @@ export function ForgotPasswordPage() {
title={t('auth.forgotPassword.title')}
description={t('auth.forgotPassword.description')}
linkComponent={RouterLink}
errorMessages={passwordDoorRefusalMessages(t)}
labels={{
emailLabel: t('auth.forgotPassword.emailLabel'),
emailPlaceholder: t('auth.forgotPassword.emailPlaceholder'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,12 @@ async function submitRefused(
config?: unknown,
extra?: Record<string, unknown>,
): Promise<string> {
const client = createAuthClient({ baseURL: AUTH_URL, fetchFn: refusingServer(status, code, message, config, extra) });
return submitAgainst(refusingServer(status, code, message, config, extra));
}

/** Submit the zh form against `fetchFn`; return the banner text. */
async function submitAgainst(fetchFn: typeof fetch): Promise<string> {
const client = createAuthClient({ baseURL: AUTH_URL, fetchFn });
render(
<I18nProvider config={{ defaultLanguage: 'zh', detectBrowserLanguage: false }} persistLanguage={false}>
<AuthProvider authUrl={AUTH_URL} client={client}>
Expand Down Expand Up @@ -190,3 +195,46 @@ describe('DefaultLoginPage — a SCIM-deactivated sign-in is not shown as a ban
expect(text).toBe(BAN_MESSAGE);
});
});

// objectstack#34171 — a cloud-managed runtime refuses the password sign-in with
// 409 `RESOURCE_CONFLICT` in the ADR-0112 envelope, `{ success: false, error:
// { code, message } }` (plugin-auth `cloudManagedRefusal`, and the hosted relay
// in front of it), not in better-auth's flat body. The whole read path runs:
// `createAuthClient` reads the envelope's code, `LoginForm` looks it up in this
// package's map, and the page shows the zh sentence that points at the
// identity provider's button, never the server's English sentence or the
// client's status line.
describe('DefaultLoginPage — a cloud-managed password refusal is localized (objectstack#34171)', () => {
const HOSTED_SENTENCE =
'This environment is hosted: everyone signs in through the cloud, with their own cloud account, and no local password '
+ 'is kept here for anyone. Sign in with ObjectOS Cloud. No password was set or accepted.';

function envelopeServer(status: number, code: string, message: string): typeof fetch {
const json = (s: number, body: unknown) =>
new Response(JSON.stringify(body), { status: s, headers: { 'Content-Type': 'application/json' } });
return (async (input: string | URL | Request) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
if (url.includes('/sign-in/email')) return json(status, { success: false, error: { code, message } });
if (url.endsWith('/config')) return json(200, {});
return json(200, null);
}) as typeof fetch;
}

it('the zh pack translates the managed sign-in sentence', () => {
expect(zhErrors.managedPasswordSignIn).toBeTruthy();
expect(zhErrors.managedPasswordSignIn).not.toBe(enErrors.managedPasswordSignIn);
});

it('409 RESOURCE_CONFLICT in the envelope shows the localized sentence, not the server or status text', async () => {
const text = await submitAgainst(envelopeServer(409, 'RESOURCE_CONFLICT', HOSTED_SENTENCE));
expect(text).toBe(zhErrors.managedPasswordSignIn);
expect(screen.queryByText(HOSTED_SENTENCE)).toBeNull();
expect(screen.queryByText(/Auth request failed/)).toBeNull();
});

it('CONTROL: another code in the envelope still shows its own server message', async () => {
const raw = 'The server refused this sign-in for a reason the page has no text for.';
const text = await submitAgainst(envelopeServer(400, 'UNMAPPED_REFUSAL_FOR_TEST', raw));
expect(text).toBe(raw);
});
});
Loading
Loading