Skip to content

Commit 916ded0

Browse files
committed
test(ui): pin the field selector and the me/localization legs under a bearer-only session; changesets
Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude <noreply@anthropic.com>
1 parent cbcd315 commit 916ded0

6 files changed

Lines changed: 209 additions & 5 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/plugin-chatbot': patch
3+
---
4+
5+
fix(plugin-chatbot): the agent list, the model picker, the pending-approvals inbox and in-chat approvals send through the host's authenticated fetch, so a session held by its sign-in token alone sees its agents and can approve
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`useAgents`, `useAiModels`, `usePendingActions` and `useHitlInChat` asked the AI service with the session cookie only. A session held by its sign-in (bearer) token alone (a cross-site embed, a cookie the browser blocked as third-party) was refused there: no agents, no models, an empty approvals inbox, and an in-chat approval that failed. They now send through the host's authenticated fetch, the `apiFetch` a host hands `SchemaRendererProvider` (the console's sends the stored token), as the renderers' own reads already do. The session cookie is still sent, a cookie session behaves exactly as before, and in the console a refused request now reaches its session-ended check. A host that mounts no provider keeps the plain `fetch`, as before. The hooks' options, including `headers`, are unchanged.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(app-shell): the metadata form's field picker reads an object's fields with the stored sign-in token, so a session held by its token alone can pick fields
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The `field-selector` picker in the metadata forms read an object's field catalog with the session cookie only, so a session held by its sign-in (bearer) token alone was refused and the picker showed a load failure. It now sends the stored token as well, as the other same-server console requests do. The session cookie is still sent, a cookie session behaves exactly as before, and a refused request now reaches the console's session-ended check.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/console': patch
3+
---
4+
5+
fix(console): the boot read of the signed-in user's language, currency and time zone sends the stored sign-in token, so a session held by its token alone boots in the user's own language and formats
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`GET /api/v1/auth/me/localization` was read with the session cookie only, on all three of its legs: the request `index.html` sends during parse, the language seed before the app mounts, and the regional-defaults provider. A session held by its sign-in (bearer) token alone was answered as signed out, so the console booted in the browser's language and formatted numbers, currencies and dates without the user's own settings. All three now state the stored token, read from the same storage the other console requests read it from, and they still share one request: the three send the same request, and its identity includes the token. With no token stored the request is exactly as before. Nothing changes in what the server accepts.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/components': patch
3+
---
4+
5+
fix(components): the share dialog lists, creates and revokes share links through the host's authenticated fetch, so a session held by its sign-in token alone sees its links
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`ShareDialog` asked this server for a record's share links (and created and revoked them) with the session cookie only. A session held by its sign-in (bearer) token alone (a cross-site embed, a cookie the browser blocked as third-party) was refused there: the dialog showed an error and no links. It now sends through the host's authenticated fetch, the `apiFetch` a host hands `SchemaRendererProvider` (the console's sends the stored token), as the renderers' own reads already do. The session cookie is still sent, a cookie session behaves exactly as before, and in the console a refused request now reaches its session-ended check. A host that mounts no provider keeps the plain `fetch`, as before. The `fetchHeaders` prop is unchanged.

‎ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx‎

Lines changed: 115 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ import { readConsoleDiscovery } from '../lib/early-discovery';
2727
import { getSharedDiscovery } from '@object-ui/data-objectstack';
2828
import { clearSharedDiscoveryCache } from '../../../../packages/data-objectstack/src/sharedDiscovery';
2929
import { SessionUserScope } from '../../../../packages/auth/src/ActiveOrganizationStorage';
30-
import { resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight';
30+
import { inflightGetKey, resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight';
3131
import { readCachedLanguageSeed, useLocalization } from '@object-ui/i18n';
3232
import { PLATFORM_LOCALE_READ_ALIASES, PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system';
33-
import { __resetPreferredLocaleForTests, pickPreferredLocale, seedTenantLanguage } from '../languageSeed';
33+
import { __resetPreferredLocaleForTests, meLocalizationInit, pickPreferredLocale, seedTenantLanguage } from '../languageSeed';
3434
import { LocalizationFetchProvider } from '../LocalizationFetchProvider';
3535

3636
const TOKEN = 'tok_valid';
@@ -898,3 +898,116 @@ describe("the language seed's me/localization starts at parse time beside discov
898898
expect(localizationCalls()).toHaveLength(1);
899899
});
900900
});
901+
902+
describe('a bearer-only session: the stored Bearer rides me/localization on all three legs, and they still share one request (objectstack#37225)', () => {
903+
const DISCOVERY_SLOT = Symbol.for('objectui.earlyDiscovery');
904+
const SEED_SLOT = Symbol.for('objectui.earlyLanguageSeed');
905+
const ME = '/api/v1/auth/me/localization';
906+
const BEARER = 'tok_bearer_only';
907+
const SIGNED_IN = { authenticated: true, locale: 'zh-CN', currency: 'CNY', timezone: 'Asia/Shanghai' };
908+
const localizationCalls = () => fetchStub.mock.calls.filter(([input]) => urlOf(input).includes('/me/localization'));
909+
const authorizationOf = (call: unknown[] | undefined) =>
910+
new Headers((call?.[1] as RequestInit | undefined)?.headers).get('Authorization');
911+
const parse = () => {
912+
runScript('startEarlyDiscovery');
913+
runScript('startEarlyLanguageSeed');
914+
};
915+
const forget = () => {
916+
const holder = globalThis as unknown as Record<symbol, unknown>;
917+
delete holder[DISCOVERY_SLOT];
918+
delete holder[SEED_SLOT];
919+
clearSharedDiscoveryCache();
920+
resetInflightGetsForTesting();
921+
__resetPreferredLocaleForTests();
922+
};
923+
924+
function Value() {
925+
const { locale, currency } = useLocalization();
926+
return <span data-testid="localization">{`${locale ?? '-'}/${currency ?? '-'}`}</span>;
927+
}
928+
929+
beforeEach(() => {
930+
forget();
931+
discoveryAnswer = () => json({ locale: { default: 'en', supported: ['en', 'zh-CN'] } });
932+
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('zh-CN');
933+
// A server that sees only the bearer: no cookie rides in a unit test, so a
934+
// read without it is a caller it cannot see.
935+
localizationAnswer = () =>
936+
authorizationOf(fetchStub.mock.lastCall) === `Bearer ${BEARER}` ? json(SIGNED_IN) : json({ authenticated: false });
937+
});
938+
afterEach(forget);
939+
940+
it('one cold load, one me/localization: parse time, seed and provider share it, and it carries the Bearer', async () => {
941+
localStorage.setItem('auth-session-token', BEARER);
942+
parse();
943+
await settle();
944+
945+
await seedTenantLanguage('', 1_000);
946+
expect(readCachedLanguageSeed()).toBe('zh-CN');
947+
render(
948+
<LocalizationFetchProvider endpoint={ME}>
949+
<Value />
950+
</LocalizationFetchProvider>,
951+
);
952+
expect(await screen.findByText('zh-CN/CNY')).toBeTruthy();
953+
954+
expect(localizationCalls()).toHaveLength(1);
955+
const [, init] = localizationCalls()[0]!;
956+
expect(init).toMatchObject({ credentials: 'include' });
957+
expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`);
958+
expect(new Headers(init?.headers).get('Accept-Language')).toBe('zh-CN');
959+
});
960+
961+
it("the share key still matches: index.html's request is keyed as the seed's and the provider's init", async () => {
962+
localStorage.setItem('auth-session-token', BEARER);
963+
parse();
964+
await settle();
965+
const slot = (globalThis as unknown as Record<symbol, { url: string; init: RequestInit }>)[SEED_SLOT]!;
966+
expect(inflightGetKey(slot.url, slot.init)).toBe(inflightGetKey(ME, meLocalizationInit('zh-CN')));
967+
expect(inflightGetKey(ME, meLocalizationInit('zh-CN'))).toContain(`authorization=Bearer ${BEARER}`);
968+
});
969+
970+
it('every later boot (a cached seed): the provider reads alone, with the Bearer, and is answered as the user', async () => {
971+
localStorage.setItem('auth-session-token', BEARER);
972+
localStorage.setItem('objectui-locale-seed', 'zh-CN');
973+
render(
974+
<LocalizationFetchProvider endpoint={ME}>
975+
<Value />
976+
</LocalizationFetchProvider>,
977+
);
978+
expect(await screen.findByText('zh-CN/CNY')).toBeTruthy();
979+
expect(localizationCalls()).toHaveLength(1);
980+
expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`);
981+
});
982+
983+
it('CONTROL: no stored token, the cookie session: one request, no Authorization, as before', async () => {
984+
parse();
985+
await settle();
986+
await seedTenantLanguage('', 1_000);
987+
render(
988+
<LocalizationFetchProvider endpoint={ME}>
989+
<Value />
990+
</LocalizationFetchProvider>,
991+
);
992+
await settle();
993+
expect(localizationCalls()).toHaveLength(1);
994+
expect(localizationCalls()[0]![1]).toMatchObject({ credentials: 'include' });
995+
expect(authorizationOf(localizationCalls()[0])).toBeNull();
996+
// The bearer-only server cannot see it: nothing of the user's is cached or shown.
997+
expect(readCachedLanguageSeed()).toBeNull();
998+
expect(screen.getByTestId('localization').textContent).toBe('-/-');
999+
});
1000+
1001+
it('CONTROL: a token stored since parse time is not answered by the parse-time request; the seed asks once itself, with it', async () => {
1002+
parse();
1003+
await settle();
1004+
localStorage.setItem('auth-session-token', BEARER);
1005+
1006+
await seedTenantLanguage('', 1_000);
1007+
1008+
expect(localizationCalls()).toHaveLength(2);
1009+
expect(authorizationOf(localizationCalls()[0])).toBeNull();
1010+
expect(authorizationOf(localizationCalls()[1])).toBe(`Bearer ${BEARER}`);
1011+
expect(readCachedLanguageSeed()).toBe('zh-CN');
1012+
});
1013+
});

‎ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx‎

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
import '@testing-library/jest-dom/vitest';
6262
import { describe, it, expect, vi, afterEach } from 'vitest';
6363
import { render, screen, cleanup, waitFor } from '@testing-library/react';
64+
import { TokenStorage } from '@object-ui/auth';
6465
import { WIDGETS } from './widgets';
6566
import { t } from './i18n';
6667

@@ -82,12 +83,14 @@ const FAILURE_TESTID = 'field-selector-load-failed';
8283
*/
8384
const ADD_FIELDS = t('engine.form.addFields', 'en-US');
8485

86+
// `headers`: the read goes through the console's authenticated fetch, which
87+
// reads a rotated session token off every answer (objectstack#37225).
8588
function okResponse(body: unknown): Response {
86-
return { ok: true, status: 200, json: async () => body } as unknown as Response;
89+
return { ok: true, status: 200, headers: new Headers(), json: async () => body } as unknown as Response;
8790
}
8891

8992
function jsonErrorResponse(status: number, body: unknown): Response {
90-
return { ok: false, status, json: async () => body } as unknown as Response;
93+
return { ok: false, status, headers: new Headers(), json: async () => body } as unknown as Response;
9194
}
9295

9396
/** A promise the test resolves by hand, so the loading arm is observable. */
@@ -119,6 +122,7 @@ afterEach(() => {
119122
cleanup();
120123
vi.unstubAllGlobals();
121124
vi.restoreAllMocks();
125+
TokenStorage.clear();
122126
});
123127

124128
describe('field-selector — a failed field fetch is not an empty field list (objectui#5227)', () => {
@@ -146,7 +150,7 @@ describe('field-selector — a failed field fetch is not an empty field list (ob
146150
// …and the loading flag cleared.
147151
expect(screen.queryByDisplayValue(LOADING_FIELDS)).not.toBeInTheDocument();
148152

149-
expect(fetchMock).toHaveBeenCalledWith(FIELDS_URL);
153+
expect(fetchMock).toHaveBeenCalledWith(FIELDS_URL, expect.objectContaining({ credentials: 'include' }));
150154
});
151155

152156
it('mouth 2: a NON-OK response with a parseable JSON body is a fault, not an empty catalog', async () => {
@@ -173,6 +177,7 @@ describe('field-selector — a failed field fetch is not an empty field list (ob
173177
const fetchMock = vi.fn().mockResolvedValue({
174178
ok: false,
175179
status: 500,
180+
headers: new Headers(),
176181
// A non-JSON body — the parse throws, and that must not be mistaken for
177182
// a refusal that said nothing to report.
178183
json: async () => {
@@ -279,3 +284,49 @@ describe('field-selector — a failed field fetch is not an empty field list (ob
279284
expect(onChange).toHaveBeenCalledWith([]);
280285
});
281286
});
287+
288+
/**
289+
* objectstack#37225 — the catalog read went out as a bare `fetch` with no init:
290+
* the default `same-origin` credentials, the session cookie alone. A session
291+
* held by its bearer token alone was answered `401` and the picker showed a
292+
* failure for every object. Against a server that refuses any request without
293+
* the bearer, the read now carries it beside the cookie; with no token stored
294+
* (a cookie session) it goes out cookie-only, as before.
295+
*/
296+
describe('field-selector — the catalog read under a bearer-only session (objectstack#37225)', () => {
297+
const TOKEN = 'stored-session-token';
298+
const sent: Array<{ credentials: RequestCredentials | undefined; authorization: string | null }> = [];
299+
const bearerOnlyServer = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
300+
const authorization = new Headers(init?.headers).get('Authorization');
301+
sent.push({ credentials: init?.credentials, authorization });
302+
return authorization === `Bearer ${TOKEN}`
303+
? okResponse({ fields: [{ name: 'name', label: 'Name', type: 'text' }] })
304+
: jsonErrorResponse(401, { error: { message: 'Authentication is required to access this endpoint.' } });
305+
});
306+
307+
afterEach(() => {
308+
sent.length = 0;
309+
bearerOnlyServer.mockClear();
310+
});
311+
312+
it('loads the catalog, sending the stored bearer beside the cookie', async () => {
313+
TokenStorage.set(TOKEN);
314+
vi.stubGlobal('fetch', bearerOnlyServer);
315+
316+
renderWidget();
317+
318+
await waitFor(() => expect(screen.getByRole('combobox')).toBeEnabled());
319+
expect(screen.queryByTestId(FAILURE_TESTID)).not.toBeInTheDocument();
320+
expect(bearerOnlyServer.mock.calls.map(([url]) => url)).toEqual([FIELDS_URL]);
321+
expect(sent).toEqual([{ credentials: 'include', authorization: `Bearer ${TOKEN}` }]);
322+
});
323+
324+
it('CONTROL: with no token stored the read goes out cookie-only, and is refused as before', async () => {
325+
vi.stubGlobal('fetch', bearerOnlyServer);
326+
327+
renderWidget();
328+
329+
await waitFor(() => expect(screen.getByTestId(FAILURE_TESTID)).toBeInTheDocument());
330+
expect(sent).toEqual([{ credentials: 'include', authorization: null }]);
331+
});
332+
});

0 commit comments

Comments
 (0)