Skip to content

Commit cbcd315

Browse files
committed
test(ui): widen the bearer ratchet to every ui package; pin the renderer reads under a bearer-only session
Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude <noreply@anthropic.com>
1 parent 26debb5 commit cbcd315

2 files changed

Lines changed: 299 additions & 21 deletions

File tree

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The renderer packages' same-server requests ride the host's authenticated
5+
* fetch (objectstack#37225): the share dialog (`@object-ui/components`) and the
6+
* chatbot hooks (`@object-ui/plugin-chatbot`) send through
7+
* `SchemaRendererProvider`'s `apiFetch`, which the console builds as
8+
* `createAuthenticatedFetch({ sameOriginOnly: true })` (`ConsoleShell`).
9+
*
10+
* The defect: each sent the bare global `fetch` with `credentials: 'include'`,
11+
* the session cookie and nothing else. A session held by its bearer token alone
12+
* (no cookie: a cross-site embed, a blocked third-party cookie) was answered as
13+
* anonymous: no share links, no agents, no models, no pending approvals, and an
14+
* in-chat approval refused. Against a server that refuses any request without
15+
* the bearer, mounted the way the console mounts them:
16+
*
17+
* - with a token stored, each loads (or decides), and its request carries
18+
* `Authorization: Bearer <token>` beside the cookie (`credentials: 'include'`),
19+
* and a `401` reaches the console's session-ended check;
20+
* - CONTROL, no token stored (a cookie session): the same requests go out
21+
* cookie-only, as before.
22+
*/
23+
24+
import type { ReactNode } from 'react';
25+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
26+
import { act, cleanup, render, renderHook, screen, waitFor } from '@testing-library/react';
27+
import { SchemaRendererProvider } from '@object-ui/react';
28+
import { TokenStorage, createAuthenticatedFetch } from '@object-ui/auth';
29+
import { sessionEndEvents } from '../../../auth/src/session-end-events';
30+
import { ShareDialog } from '@object-ui/components';
31+
import { useAgents, useAiModels, useHitlInChat, usePendingActions } from '@object-ui/plugin-chatbot';
32+
import { __resetAgentsCatalog } from '../../../plugin-chatbot/src/useAgents';
33+
import { resetAiModelsSession } from '../../../plugin-chatbot/src/useAiModels';
34+
35+
const TOKEN = 'stored-session-token';
36+
const AI = '/api/v1/ai';
37+
38+
const reply = (body: unknown, status = 200) =>
39+
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
40+
41+
type Sent = { path: string; method: string; credentials: RequestCredentials | undefined; authorization: string | null };
42+
let sent: Sent[] = [];
43+
44+
function answer(path: string, method: string): Response {
45+
if (path === '/api/v1/share-links' && method === 'GET') {
46+
return reply({ links: [{ id: 'sl_1', token: 'tok_1', permission: 'view', audience: 'link_only', label: 'Board review link' }] });
47+
}
48+
if (path === `${AI}/agents`) return reply({ agents: [{ name: 'helper', label: 'Helper', active: true }] });
49+
if (path === `${AI}/models`) {
50+
return reply({ models: [{ id: 'm_fast', label: 'Fast' }, { id: 'm_deep', label: 'Deep' }], defaultModelId: 'm_fast' });
51+
}
52+
if (path === `${AI}/pending-actions` && method === 'GET') {
53+
return reply({ items: [{ id: 'pa_1', toolName: 'delete_record', status: 'pending' }], total: 1 });
54+
}
55+
if (path === `${AI}/pending-actions/pa_1/approve` && method === 'POST') {
56+
return reply({ id: 'pa_1', status: 'executed', result: { ok: true } });
57+
}
58+
return reply({ error: { code: 'NOT_FOUND', message: `no route ${method} ${path}` } }, 404);
59+
}
60+
61+
/** A server that answers only the bearer: no cookie rides in a unit test, so a request without it is refused. */
62+
function bearerOnlyServer(input: RequestInfo | URL, init?: RequestInit): Response {
63+
const path = new URL(String(input instanceof Request ? input.url : input), 'http://console.test').pathname;
64+
const method = (init?.method ?? 'GET').toUpperCase();
65+
const authorization = new Headers(init?.headers).get('Authorization');
66+
sent.push({ path, method, credentials: init?.credentials, authorization });
67+
if (authorization !== `Bearer ${TOKEN}`) {
68+
return reply({ error: { code: 'UNAUTHENTICATED', message: 'Authentication is required to access this endpoint.' } }, 401);
69+
}
70+
return answer(path, method);
71+
}
72+
73+
/** The console's composition: the renderers' `apiFetch` is the authenticated fetch (`ConsoleShell`). */
74+
const hostFetch = createAuthenticatedFetch({ sameOriginOnly: true });
75+
const wrapper = ({ children }: { children: ReactNode }) => (
76+
<SchemaRendererProvider dataSource={null} apiFetch={hostFetch}>
77+
{children}
78+
</SchemaRendererProvider>
79+
);
80+
81+
const withBearer = { credentials: 'include', authorization: `Bearer ${TOKEN}` } as const;
82+
const cookieOnly = { credentials: 'include', authorization: null } as const;
83+
84+
let sessionEnds = 0;
85+
let unsubscribe: () => void = () => {};
86+
87+
beforeEach(() => {
88+
sent = [];
89+
sessionEnds = 0;
90+
unsubscribe = sessionEndEvents.subscribe(() => {
91+
sessionEnds += 1;
92+
});
93+
__resetAgentsCatalog();
94+
resetAiModelsSession();
95+
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => bearerOnlyServer(input, init)));
96+
});
97+
98+
afterEach(() => {
99+
cleanup();
100+
unsubscribe();
101+
__resetAgentsCatalog();
102+
resetAiModelsSession();
103+
vi.unstubAllGlobals();
104+
TokenStorage.clear();
105+
});
106+
107+
describe('the share dialog (components) under a bearer-only session', () => {
108+
const dialog = () =>
109+
render(
110+
<ShareDialog open onOpenChange={() => {}} objectName="ai_conversations" recordId="c1" apiBase="/api" />,
111+
{ wrapper },
112+
);
113+
114+
it("lists the record's links, sending the stored bearer beside the cookie", async () => {
115+
TokenStorage.set(TOKEN);
116+
dialog();
117+
expect(await screen.findByText('Board review link')).toBeTruthy();
118+
expect(sent).toEqual([{ path: '/api/v1/share-links', method: 'GET', ...withBearer }]);
119+
});
120+
121+
it('CONTROL: with no token stored the read goes out cookie-only, and its 401 reaches the session-ended check', async () => {
122+
dialog();
123+
expect(await screen.findByTestId('share-dialog-error')).toBeTruthy();
124+
expect(sent).toEqual([{ path: '/api/v1/share-links', method: 'GET', ...cookieOnly }]);
125+
expect(sessionEnds).toBe(1);
126+
});
127+
});
128+
129+
describe('the chatbot hooks (plugin-chatbot) under a bearer-only session', () => {
130+
it('useAgents loads the agent catalog with the stored bearer', async () => {
131+
TokenStorage.set(TOKEN);
132+
const { result } = renderHook(() => useAgents({ apiBase: AI }), { wrapper });
133+
await waitFor(() => expect(result.current.agents.map((a) => a.name)).toEqual(['helper']));
134+
expect(sent).toEqual([{ path: `${AI}/agents`, method: 'GET', ...withBearer }]);
135+
});
136+
137+
it('useAiModels loads the model allowlist with the stored bearer', async () => {
138+
TokenStorage.set(TOKEN);
139+
const { result } = renderHook(() => useAiModels({ apiBase: AI }), { wrapper });
140+
await waitFor(() => expect(result.current.models.map((m) => m.id)).toEqual(['m_fast', 'm_deep']));
141+
expect(sent).toEqual([{ path: `${AI}/models`, method: 'GET', ...withBearer }]);
142+
});
143+
144+
it('usePendingActions lists and approves with the stored bearer', async () => {
145+
TokenStorage.set(TOKEN);
146+
const { result } = renderHook(() => usePendingActions({ apiBase: AI, pollInterval: 0 }), { wrapper });
147+
await waitFor(() => expect(result.current.items.map((row) => row.id)).toEqual(['pa_1']));
148+
await act(async () => {
149+
await result.current.approve('pa_1');
150+
});
151+
expect(sent.slice(0, 2)).toEqual([
152+
{ path: `${AI}/pending-actions`, method: 'GET', ...withBearer },
153+
{ path: `${AI}/pending-actions/pa_1/approve`, method: 'POST', ...withBearer },
154+
]);
155+
expect(sent.every((request) => request.authorization === `Bearer ${TOKEN}`)).toBe(true);
156+
});
157+
158+
it('useHitlInChat sends the in-chat approval with the stored bearer', async () => {
159+
TokenStorage.set(TOKEN);
160+
const messages = [
161+
{
162+
id: 'm1',
163+
role: 'assistant' as const,
164+
content: '',
165+
toolInvocations: [
166+
{ toolCallId: 'call_1', toolName: 'delete_record', pendingActionId: 'pa_1', state: 'approval-requested' as const },
167+
],
168+
},
169+
];
170+
const { result } = renderHook(() => useHitlInChat({ messages: messages as never, apiBase: AI }), { wrapper });
171+
await act(async () => {
172+
await result.current.decide('call_1', true);
173+
});
174+
expect(sent).toEqual([{ path: `${AI}/pending-actions/pa_1/approve`, method: 'POST', ...withBearer }]);
175+
expect(result.current.decisions.call_1?.state).not.toBe('error');
176+
});
177+
178+
it('CONTROL: with no token stored the agent read goes out cookie-only, refused as before', async () => {
179+
const { result } = renderHook(() => useAgents({ apiBase: AI }), { wrapper });
180+
await waitFor(() => expect(result.current.error).toBeDefined());
181+
expect(sent).toEqual([{ path: `${AI}/agents`, method: 'GET', ...cookieOnly }]);
182+
expect(sessionEnds).toBe(1);
183+
});
184+
});

‎ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts‎

Lines changed: 115 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
/**
1010
* Ratchet — a request that sends the session cookie (`credentials: 'include'`)
1111
* goes through the console's authenticated fetch, never the bare global
12-
* `fetch`, in app-shell and the console.
12+
* `fetch`, in the console and in every `ui/packages/*` source tree (app-shell,
13+
* and since objectstack#37225 the renderer packages beside it).
1314
*
1415
* The defect this closes: a bare `fetch('/api/…', { credentials: 'include' })`
1516
* carries the session cookie and nothing else. A session held by its bearer
@@ -27,42 +28,67 @@
2728
* fallback of `??` / `||`), and `sharedGetJson` without its transport argument
2829
* (its default is the global `fetch`), when the init it is handed — written
2930
* inline, or a `const` of this file named as the argument — carries
30-
* `credentials: 'include'`. The URL is not judged: a request to another origin
31-
* that must not see the bearer is an allow-list row with that reason.
31+
* `credentials: 'include'`. The URL is not judged there: a request to another
32+
* origin that must not see the bearer is an allow-list row with that reason.
3233
*
33-
* If this fails on a new call: route it through `createAuthenticatedFetch`
34-
* (`{ sameOriginOnly: true }` when the URL is author-written and may name
35-
* another host). If the call must stay bare, add a row to {@link ALLOWED} with
36-
* the reason. If it fails on a row: a row whose count went down is shrunk or
37-
* deleted in the same change. ⛔ Never raise a count to make room.
34+
* Also bare (objectstack#37225): the global `fetch` on a written `/api/` path
35+
* with NO init, or an inline init that names no `credentials` — the default
36+
* `same-origin` credentials send the cookie alone just the same. Here the URL is
37+
* the only evidence the request is the server's, so it has to be written out.
38+
*
39+
* The renderer packages (`components`, `fields`, `plugin-*`, …) do not import
40+
* `@object-ui/auth`: their channel is the host's authenticated fetch, handed
41+
* down as `SchemaRendererProvider`'s `apiFetch` (the console's is
42+
* `createAuthenticatedFetch({ sameOriginOnly: true })`), read straight off
43+
* `SchemaRendererContext` and falling back to the global `fetch` only in a host
44+
* that mounts none. App-shell and the console build `createAuthenticatedFetch`
45+
* per call.
46+
*
47+
* If this fails on a new call: route it through the host's `apiFetch` (a
48+
* renderer package) or `createAuthenticatedFetch` (app-shell, the console;
49+
* `{ sameOriginOnly: true }` when the URL is author-written and may name another
50+
* host). If the call must stay bare, add a row to {@link ALLOWED} with the
51+
* reason. If it fails on a row: a row whose count went down is shrunk or deleted
52+
* in the same change. ⛔ Never raise a count to make room.
3853
*/
3954

4055
import { describe, it, expect } from 'vitest';
41-
import { readdirSync, readFileSync } from 'node:fs';
56+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
4257
import path from 'node:path';
4358
import { fileURLToPath } from 'node:url';
4459
import ts from 'typescript';
4560

4661
const HERE = path.dirname(fileURLToPath(import.meta.url));
4762
/** `ui/packages/app-shell/src` */
4863
const APP_SHELL_SRC = HERE;
64+
/** `ui/packages`, whose every package's `src` is scanned. */
65+
const PACKAGES_ROOT = path.resolve(HERE, '../..');
4966
/** `ui/apps/console/src` */
5067
const CONSOLE_SRC = path.resolve(HERE, '../../../apps/console/src');
51-
/** Both trees' paths are written relative to `ui/`. */
68+
/** Every tree's paths are written relative to `ui/`. */
5269
const UI_ROOT = path.resolve(HERE, '../../..');
5370

71+
/**
72+
* The renderer packages objectstack#37225 named: each must be read, so a scan
73+
* that silently lost one of them fails here rather than passing over it.
74+
*/
75+
const RENDERER_PACKAGES = [
76+
'components',
77+
'fields',
78+
'permissions',
79+
'plugin-charts',
80+
'plugin-chatbot',
81+
'plugin-dashboard',
82+
'plugin-detail',
83+
'plugin-grid',
84+
'plugin-report',
85+
] as const;
86+
5487
/**
5588
* The bare cookie-only calls left, per file, with the reason each stays.
5689
* SHRINK-ONLY: a row's count only goes down, a row only goes away.
5790
*/
5891
const ALLOWED: Readonly<Record<string, { count: number; reason: string }>> = {
59-
'apps/console/src/LocalizationFetchProvider.tsx': {
60-
count: 1,
61-
reason:
62-
'the boot read of `/api/v1/auth/me/localization`, shared in flight with the language seed and the early ' +
63-
'request `index.html` sends, by a key built from this init; a session it cannot see reads ' +
64-
'`authenticated: false` and falls back to the browser language rather than failing. Its transport is its own decision.',
65-
},
6692
'apps/console/src/components/FormPage.tsx': {
6793
count: 1,
6894
reason: 'the channel is the bare global fetch on the PUBLIC form route on purpose; the internal route hands the authenticated fetch.',
@@ -121,6 +147,16 @@ const ALLOWED: Readonly<Record<string, { count: number; reason: string }>> = {
121147
count: 1,
122148
reason: 'the test request of an `api` action preview, sent to the author-written target; its transport is not decided here.',
123149
},
150+
'packages/auth/src/LoginForm.tsx': {
151+
count: 1,
152+
reason: 'the SSO sign-in request, sent before a session, and so a bearer, exists.',
153+
},
154+
'packages/permissions/src/MePermissionsProvider.tsx': {
155+
count: 1,
156+
reason:
157+
'the fallback of the injected `fetcher` (`fetcher ?? fetch`): the console hands its authenticated fetch ' +
158+
'(`AppContent`), and a host that hands none has only the cookie. The package depends on `@object-ui/types` alone.',
159+
},
124160
};
125161

126162
const GLOBAL_FETCH = new Set(['fetch', 'window.fetch', 'globalThis.fetch', 'self.fetch']);
@@ -165,6 +201,33 @@ function isGlobalFetchCallee(callee: ts.Expression, sf: ts.SourceFile): boolean
165201
return false;
166202
}
167203

204+
/** A URL written out as a literal, read only for whether it names an `/api/` path. */
205+
function namesApiPath(node: ts.Expression | undefined): boolean {
206+
if (!node) return false;
207+
const n = unwrap(node);
208+
if (ts.isStringLiteralLike(n)) return n.text.includes('/api/');
209+
if (ts.isTemplateExpression(n)) {
210+
return [n.head.text, ...n.templateSpans.map((span) => span.literal.text)].some((part) => part.includes('/api/'));
211+
}
212+
return false;
213+
}
214+
215+
/** No init, or an inline one with no `credentials` key: the default `same-origin`, the cookie alone. */
216+
function defaultsCredentials(init: ts.Expression | undefined): boolean {
217+
if (!init) return true;
218+
const n = unwrap(init);
219+
return (
220+
ts.isObjectLiteralExpression(n) &&
221+
!n.properties.some(
222+
(p) =>
223+
ts.isSpreadAssignment(p) ||
224+
((ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) &&
225+
(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) &&
226+
p.name.text === 'credentials'),
227+
)
228+
);
229+
}
230+
168231
/** The bare cookie-only calls in one source text, as `line :: call` strings. */
169232
function bareCookieOnlyCalls(fileName: string, text: string): string[] {
170233
const sf = ts.createSourceFile(
@@ -194,6 +257,7 @@ function bareCookieOnlyCalls(fileName: string, text: string): string[] {
194257
if (ts.isCallExpression(n)) {
195258
const bare =
196259
(isGlobalFetchCallee(n.expression, sf) && initIncludes(n.arguments[1])) ||
260+
(isGlobalFetchCallee(n.expression, sf) && namesApiPath(n.arguments[0]) && defaultsCredentials(n.arguments[1])) ||
197261
(unwrap(n.expression).getText(sf) === 'sharedGetJson' && n.arguments.length < 3 && initIncludes(n.arguments[1]));
198262
if (bare) {
199263
const line = sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1;
@@ -220,19 +284,40 @@ function sourceFiles(root: string): string[] {
220284
return out;
221285
}
222286

287+
/** Every `ui/packages/<name>/src` that exists, by package directory name. */
288+
function packageSourceRoots(): Map<string, string> {
289+
const roots = new Map<string, string>();
290+
for (const entry of readdirSync(PACKAGES_ROOT, { withFileTypes: true })) {
291+
if (!entry.isDirectory()) continue;
292+
const src = path.join(PACKAGES_ROOT, entry.name, 'src');
293+
if (existsSync(src)) roots.set(entry.name, src);
294+
}
295+
return roots;
296+
}
297+
298+
let scanned: Map<string, string[]> | undefined;
299+
300+
/** The whole scan, once per run: two cases read it. */
223301
function scan(): Map<string, string[]> {
302+
if (scanned) return scanned;
224303
const found = new Map<string, string[]>();
225-
for (const file of [...sourceFiles(APP_SHELL_SRC), ...sourceFiles(CONSOLE_SRC)]) {
304+
const files = [...[...packageSourceRoots().values()].flatMap(sourceFiles), ...sourceFiles(CONSOLE_SRC)];
305+
for (const file of files) {
226306
const calls = bareCookieOnlyCalls(file, readFileSync(file, 'utf8'));
227307
if (calls.length) found.set(path.relative(UI_ROOT, file).split(path.sep).join('/'), calls);
228308
}
309+
scanned = found;
229310
return found;
230311
}
231312

232-
describe('cookie-only same-server fetch ratchet (app-shell + console)', () => {
233-
it('reads both trees (guards a broken scan path)', () => {
313+
describe('cookie-only same-server fetch ratchet (every ui package + console)', () => {
314+
it('reads every tree (guards a broken scan path)', () => {
234315
expect(sourceFiles(APP_SHELL_SRC).length).toBeGreaterThan(500);
235316
expect(sourceFiles(CONSOLE_SRC).length).toBeGreaterThan(100);
317+
const roots = packageSourceRoots();
318+
expect(roots.size).toBeGreaterThan(30);
319+
const unread = RENDERER_PACKAGES.filter((name) => !roots.has(name) || sourceFiles(roots.get(name)!).length === 0);
320+
expect(unread).toEqual([]);
236321
});
237322

238323
it('the detector sees every bare spelling, and none of the authenticated ones', () => {
@@ -249,7 +334,16 @@ describe('cookie-only same-server fetch ratchet (app-shell + console)', () => {
249334
["await (apiFetch ?? createAuthenticatedFetch())('/api/v1/x', { credentials: 'include' });", 0],
250335
["await sharedGetJson(u, { credentials: 'include' }, authFetch);", 0],
251336
["await fetch('https://cdn.example.com/a.json', { credentials: 'omit' });", 0],
252-
["await fetch('/api/v1/x');", 0],
337+
// No init, or no `credentials`, on a written `/api/` path: the cookie alone (objectstack#37225).
338+
["await fetch('/api/v1/x');", 1],
339+
['await fetch(`/api/v1/objects/${name}/fields`);', 1],
340+
["await window.fetch(`${base}/api/v1/x`, { method: 'POST', headers: h });", 1],
341+
["await fetch('/api/v1/x', { credentials: 'same-origin' });", 0],
342+
["await fetch('/api/v1/x', { ...init });", 0],
343+
["await fetch(url);", 0],
344+
["await fetch('https://cdn.example.com/a.json');", 0],
345+
["await authFetch('/api/v1/x');", 0],
346+
["await doFetch(`/api/v1/objects/${name}/fields`);", 0],
253347
];
254348
for (const [code, expected] of cases) {
255349
// Inside an async function: at a script's top level `await (x)(…)` parses as a call of `await`.

0 commit comments

Comments
 (0)