diff --git a/.changeset/37506-uploads-injected-fetch.md b/.changeset/37506-uploads-injected-fetch.md new file mode 100644 index 00000000000..919b6fcfdd5 --- /dev/null +++ b/.changeset/37506-uploads-injected-fetch.md @@ -0,0 +1,10 @@ +--- +'@object-ui/data-objectstack': patch +--- + +fix(data-objectstack): `uploadFile` and `uploadFiles` send through the injected `fetch`, not the global one + +Clause-②: no +Metadata-protocol: none + +The two upload methods called the global `fetch`, which sends the session cookie alone. A host that hands the adapter its authenticated fetch (the console hands `createAuthenticatedFetch()`) had every other request signed with the stored bearer, while an upload under a bearer-only session (the cookie replaced, blocked as third-party, or cleared) went out anonymous. Both methods now call the injected `fetch` as given. They still sit outside the connection-state tracking, so an upload's outcome does not move the connection state, as the README already says. The request URL, body and headers are unchanged. diff --git a/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts b/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts index 1f6810d3437..d77033886c9 100644 --- a/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts +++ b/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts @@ -38,6 +38,15 @@ * `same-origin` credentials send the cookie alone just the same. Here the URL is * the only evidence the request is the server's, so it has to be written out. * + * Written out in any of these spellings (objectstack#37505): a literal or + * template, a `+` concatenation with such a part (`base + '/api/v1/x'`), or a + * `const` of this file bound to one of those (`const url = \`${base}/api/…\``). + * And the init's credentials are read through what it is built from: an + * explicit `credentials: 'same-origin'` is the default spelled out (the cookie + * alone), and a `{ ...COOKIE_INIT, method: 'POST' }` spread of a `const` of this + * file carries that const's credentials unless a later key overrides them. A + * spread of anything else (`{ ...init }`) is unknown, and unknown is not bare. + * * The renderer packages (`components`, `fields`, `plugin-*`, …) do not import * `@object-ui/auth`: their channel is the host's authenticated fetch, handed * down as `SchemaRendererProvider`'s `apiFetch` (the console's is @@ -159,25 +168,77 @@ const ALLOWED: Readonly> = { }, }; +/** + * Calls that READ like a bare fetch and are not one, kept here so the reading + * travels with the code (objectstack#37505, objectstack#37507): each is a + * renderer package's injected channel with the global `fetch` as the fallback + * of a host that hands none, which the detector does not count (see the + * header). A row fails once its file no longer holds the spelling, or once the + * scan counts a call in that file: delete or move the row then. + */ +const REGISTERED_CHANNELS: ReadonlyArray<{ file: string; spelling: string; reason: string }> = [ + { + file: 'packages/react/src/hooks/useDatasetDimensionLabels.ts', + spelling: 'const doFetch = apiFetch ?? fetch;', + reason: 'the host\'s `apiFetch` off `SchemaRendererContext` (the console\'s authenticated fetch); the global fetch only where no host mounts one.', + }, + { + file: 'packages/react/src/element-data-source/useElementApiDataSource.ts', + spelling: 'const doFetch: ApiFetch = context?.apiFetch ?? fetch;', + reason: 'the host\'s `apiFetch` off `SchemaRendererContext` (the console\'s authenticated fetch); the global fetch only where no host mounts one.', + }, + { + file: 'packages/auth/src/createAuthClient.ts', + spelling: 'const rawFetch = fetchFn || globalThis.fetch.bind(globalThis);', + reason: + 'the stale-bearer self-heal: `get-session` retried once WITHOUT the stored bearer, on purpose, because an invalid ' + + 'bearer shadows a valid cookie session; every other request of the client goes through `bearerFetch`.', + }, +]; + const GLOBAL_FETCH = new Set(['fetch', 'window.fetch', 'globalThis.fetch', 'self.fetch']); -function carriesInclude(node: ts.Node | undefined): boolean { - return ( - !!node && - ts.isObjectLiteralExpression(node) && - node.properties.some( - (p) => - ts.isPropertyAssignment(p) && - (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && - p.name.text === 'credentials' && - isIncludeLiteral(unwrap(p.initializer)), - ) - ); -} +/** + * What an init sends as `credentials`: a written value (`'include'`, + * `'same-origin'`, `'omit'`, also `as const`), `'none'` when it names none (the + * default `same-origin`: the cookie alone), or `'unknown'` when it cannot be read + * here (a parameter, a computed value, or a spread of anything but a `const` of + * this file with no value written before it). `consts` holds this file's + * `const NAME = { … }` inits, by name. + */ +type Credentials = string; -/** `'include'`, also written `'include' as const`. */ -function isIncludeLiteral(node: ts.Expression): boolean { - return ts.isStringLiteralLike(node) && node.text === 'include'; +function credentialsOf(node: ts.Expression | undefined, consts: ReadonlyMap, seen = new Set()): Credentials { + if (!node) return 'none'; + const n = unwrap(node); + if (ts.isIdentifier(n)) { + const bound = consts.get(n.text); + if (!bound || seen.has(n.text)) return 'unknown'; + return credentialsOf(bound, consts, new Set(seen).add(n.text)); + } + if (!ts.isObjectLiteralExpression(n)) return 'unknown'; + // Later keys win, as they do at run time. A spread this file cannot read + // (`...init`) does not erase a credentials value written before it: the + // caller's init seldom names one, so the written value is the reading. + let credentials: Credentials = 'none'; + for (const p of n.properties) { + if (ts.isSpreadAssignment(p)) { + const spread = credentialsOf(p.expression, consts, seen); + if (spread === 'unknown') { + if (credentials === 'none') credentials = 'unknown'; + } else if (spread !== 'none') { + credentials = spread; + } + } else if ( + (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && + (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && + p.name.text === 'credentials' + ) { + const value = ts.isPropertyAssignment(p) ? unwrap(p.initializer) : undefined; + credentials = value && ts.isStringLiteralLike(value) ? value.text : 'unknown'; + } + } + return credentials; } function unwrap(node: ts.Expression): ts.Expression { @@ -201,31 +262,31 @@ function isGlobalFetchCallee(callee: ts.Expression, sf: ts.SourceFile): boolean return false; } -/** A URL written out as a literal, read only for whether it names an `/api/` path. */ -function namesApiPath(node: ts.Expression | undefined): boolean { +/** + * A URL written out, read only for whether it names an `/api/` path: a literal, + * a template, a `+` concatenation with such a part, or a `const` of this file + * bound to one of those (`urlConsts`, by name). + */ +function namesApiPath(node: ts.Expression | undefined, urlConsts: ReadonlyMap = new Map(), seen = new Set()): boolean { if (!node) return false; const n = unwrap(node); if (ts.isStringLiteralLike(n)) return n.text.includes('/api/'); if (ts.isTemplateExpression(n)) { return [n.head.text, ...n.templateSpans.map((span) => span.literal.text)].some((part) => part.includes('/api/')); } + if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.PlusToken) { + return namesApiPath(n.left, urlConsts, seen) || namesApiPath(n.right, urlConsts, seen); + } + if (ts.isIdentifier(n)) { + const bound = urlConsts.get(n.text); + return !!bound && !seen.has(n.text) && namesApiPath(bound, urlConsts, new Set(seen).add(n.text)); + } return false; } -/** No init, or an inline one with no `credentials` key: the default `same-origin`, the cookie alone. */ -function defaultsCredentials(init: ts.Expression | undefined): boolean { - if (!init) return true; - const n = unwrap(init); - return ( - ts.isObjectLiteralExpression(n) && - !n.properties.some( - (p) => - ts.isSpreadAssignment(p) || - ((ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && - (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && - p.name.text === 'credentials'), - ) - ); +/** The cookie alone: no `credentials` named (the default), or `same-origin` spelled out. */ +function sendsCookieAlone(credentials: Credentials): boolean { + return credentials === 'none' || credentials === 'same-origin'; } /** @@ -242,12 +303,23 @@ function bareCookieOnlyCalls(fileName: string, text: string, builds = true): str true, fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS, ); - // A `const NAME = { credentials: 'include', … }` anywhere in the file: an - // init handed to the call by name. - const includeConsts = new Set(); + // A `const NAME = { … }` anywhere in the file: an init handed to the call by + // name, or spread into one. A `const NAME = `: a URL + // handed to the call by name (objectstack#37505). + const initConsts = new Map(); + const urlConsts = new Map(); const collect = (n: ts.Node): void => { - if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer && carriesInclude(unwrap(n.initializer))) { - includeConsts.add(n.name.text); + if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer) { + const bound = unwrap(n.initializer); + if (ts.isObjectLiteralExpression(bound)) initConsts.set(n.name.text, bound); + else if ( + ts.isStringLiteralLike(bound) || + ts.isTemplateExpression(bound) || + (ts.isBinaryExpression(bound) && bound.operatorToken.kind === ts.SyntaxKind.PlusToken) || + ts.isIdentifier(bound) + ) { + urlConsts.set(n.name.text, bound); + } } ts.forEachChild(n, collect); }; @@ -268,17 +340,15 @@ function bareCookieOnlyCalls(fileName: string, text: string, builds = true): str const c = unwrap(callee); return isGlobalFetchCallee(c, sf) || (ts.isIdentifier(c) && fetchAliases.has(c.text)); }; - const initIncludes = (arg: ts.Expression | undefined): boolean => { - if (!arg) return false; - const a = unwrap(arg); - return carriesInclude(a) || (ts.isIdentifier(a) && includeConsts.has(a.text)); - }; + const initIncludes = (arg: ts.Expression | undefined): boolean => !!arg && credentialsOf(arg, initConsts) === 'include'; const out: string[] = []; const visit = (n: ts.Node): void => { if (ts.isCallExpression(n)) { const bare = (isBareTransport(n.expression) && initIncludes(n.arguments[1])) || - (isBareTransport(n.expression) && namesApiPath(n.arguments[0]) && defaultsCredentials(n.arguments[1])) || + (isBareTransport(n.expression) && + namesApiPath(n.arguments[0], urlConsts) && + sendsCookieAlone(credentialsOf(n.arguments[1], initConsts))) || (unwrap(n.expression).getText(sf) === 'sharedGetJson' && n.arguments.length < 3 && initIncludes(n.arguments[1])); if (bare) { const line = sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1; @@ -361,8 +431,26 @@ describe('cookie-only same-server fetch ratchet (every ui package + console)', ( ["await fetch('/api/v1/x');", 1], ['await fetch(`/api/v1/objects/${name}/fields`);', 1], ["await window.fetch(`${base}/api/v1/x`, { method: 'POST', headers: h });", 1], - ["await fetch('/api/v1/x', { credentials: 'same-origin' });", 0], + // `same-origin` spelled out is the default: the cookie alone (objectstack#37505). + ["await fetch('/api/v1/x', { credentials: 'same-origin' });", 1], + ["const init = { credentials: 'same-origin' as const }; await fetch('/api/v1/x', init);", 1], + ["await fetch('/api/v1/x', { credentials: 'omit' });", 0], + // A spread init is unknown, unless it spreads a `const` of the file (objectstack#37505). ["await fetch('/api/v1/x', { ...init });", 0], + ["const COOKIE = { credentials: 'include' as const }; await fetch(u, { ...COOKIE, method: 'POST' });", 1], + ["const BASE_INIT = { method: 'POST' }; await fetch('/api/v1/x', { ...BASE_INIT });", 1], + ["const COOKIE = { credentials: 'include' as const }; await fetch(u, { ...COOKIE, credentials: 'omit' });", 0], + ["const COOKIE = { credentials: 'include' as const }; await authFetch(u, { ...COOKIE });", 0], + ["await (channel ?? fetch)(`${API_BASE}${path}`, { credentials: 'include', ...init });", 1], + // A URL written as a `+` concatenation or held in a `const` (objectstack#37505). + ["await fetch(base + '/api/v1/x');", 1], + ["await fetch(SERVER_URL + `/api/v1/objects/${name}`, { method: 'POST' });", 1], + ["const url = '/api/v1/x'; await fetch(url);", 1], + ['const url = `${this.baseUrl}/api/data/${encodeURIComponent(r)}/upload`; await fetch(url, { method: \'POST\', body });', 1], + ["const ROUTE = '/api/v1/x'; await window.fetch(origin + ROUTE);", 1], + ["const url = 'https://cdn.example.com/a.json'; await fetch(url);", 0], + ["await fetch(base + '/static/a.json');", 0], + ["const url = '/api/v1/x'; await createAuthenticatedFetch()(url);", 0], ["await fetch(url);", 0], ["await fetch('https://cdn.example.com/a.json');", 0], ["await authFetch('/api/v1/x');", 0], @@ -404,6 +492,15 @@ describe('cookie-only same-server fetch ratchet (every ui package + console)', ( expect(over).toEqual([]); }); + it('every registered channel still reads as written, and is still not counted', () => { + const found = scan(); + const drifted = REGISTERED_CHANNELS.filter(({ file, spelling }) => { + const full = path.join(UI_ROOT, file); + return !existsSync(full) || !readFileSync(full, 'utf8').includes(spelling) || found.has(file); + }).map(({ file }) => file); + expect(drifted).toEqual([]); + }); + it('every allow-list row is still exact (shrink the row when its file sheds a call)', () => { const found = scan(); const stale = Object.entries(ALLOWED) diff --git a/ui/packages/data-objectstack/README.md b/ui/packages/data-objectstack/README.md index 117c57362b2..13aca2e4305 100644 --- a/ui/packages/data-objectstack/README.md +++ b/ui/packages/data-objectstack/README.md @@ -525,8 +525,9 @@ request of its own: Every request goes through the adapter's one fetch, including those made through `getClient()`, except `uploadFile` / `uploadFiles`. Those two call the -global `fetch`, so an upload's outcome does not move the state. The response or -rejection reaches your code unchanged. +same injected `fetch` directly, outside the state tracking, so an upload's +outcome does not move the state. The response or rejection reaches your code +unchanged. ### Auto-Reconnect diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index b26865fc105..5cdf0076182 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -3657,6 +3657,14 @@ export class ObjectStackAdapter implements DataSource { /** One "analytics capability is missing" console line per adapter, not per widget. */ private analyticsCapabilityWarned = false; private fetchImpl: (input: RequestInfo | URL, init?: RequestInit) => Promise; + /** + * The host's injected fetch as given, outside the connection-state observer: + * the transport of `uploadFile` / `uploadFiles` (objectstack#37506). It is the + * host's authenticated fetch, so an upload under a bearer-only session carries + * the bearer like every other request, while its outcome still does not move + * the connection state. + */ + private uploadTransport: (input: RequestInfo | URL, init?: RequestInit) => Promise; // In-flight find() requests keyed by resource + serialized params. // Coalesces concurrent identical reads (e.g. React StrictMode double-mount, // multiple sibling components requesting the same dataset on first paint) @@ -3764,13 +3772,15 @@ export class ObjectStackAdapter implements DataSource { // objectui#12295 — ONE fetch carries every request this adapter makes: the // client's (data, metadata, analytics, and every caller of `getClient()`) // and the adapter's own raw reads alike. The exception is `uploadFile` / - // `uploadFiles`, which call the global `fetch`, so an upload's outcome does - // not move the connection state. This fetch is the single seam where "the + // `uploadFiles`, which call the same injected fetch WITHOUT this observer + // (`uploadTransport`), so an upload's outcome does not move the connection + // state. This fetch is the single seam where "the // server answered" (a Response, whatever its status) can be told apart // from "no HTTP answer at all" (the fetch rejected), so the connection // state follows the requests the host already makes; see // `observeServerAnswer`. const transport = config.fetch || globalThis.fetch.bind(globalThis); + this.uploadTransport = transport; this.fetchImpl = (input, init) => this.observeServerAnswer(() => transport(input, init), init); // objectstack-ai/objectstack#27774 — one origin for the client and for every @@ -8240,7 +8250,7 @@ export class ObjectStackAdapter implements DataSource { const url = `${this.baseUrl}/api/data/${encodeURIComponent(resource)}/upload`; - const response = await fetch(url, { + const response = await this.uploadTransport(url, { method: 'POST', body: formData, headers: { @@ -8302,7 +8312,7 @@ export class ObjectStackAdapter implements DataSource { const url = `${this.baseUrl}/api/data/${encodeURIComponent(resource)}/upload`; - const response = await fetch(url, { + const response = await this.uploadTransport(url, { method: 'POST', body: formData, headers: { diff --git a/ui/packages/data-objectstack/src/uploadTransport-37506.test.ts b/ui/packages/data-objectstack/src/uploadTransport-37506.test.ts new file mode 100644 index 00000000000..4bc44ac215f --- /dev/null +++ b/ui/packages/data-objectstack/src/uploadTransport-37506.test.ts @@ -0,0 +1,137 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37506 — `uploadFile` / `uploadFiles` send through the host's + * injected `fetch`, never the global one. + * + * The host's injected fetch is its authenticated fetch (the console hands + * `createAuthenticatedFetch()`), which sends the stored bearer beside the + * cookie. The two uploads used to call the global `fetch`, which carries the + * cookie alone, so under a bearer-only session (the cookie replaced, blocked as + * third-party, or cleared) an upload went out anonymous while every other + * request of the same adapter was signed in. + * + * The injected fetch here stands in for the host's: it adds the bearer and + * hands the request to a fake network. The control is the global `fetch`, + * stubbed to record and refuse: the pre-fix transport, which sends no bearer. + * + * The uploads still sit outside the connection-state tracking (README, + * "Connection state"): a refused upload moves nothing. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { ObjectStackAdapter, type ConnectionStateEvent } from './index'; +import { clearSharedDiscoveryCache } from './sharedDiscovery'; + +const BASE = 'http://fake-37506.test'; + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +/** What reached the network: URL, method and the Authorization header. */ +type Sent = { url: string; method: string; authorization: string | null }; + +function hostWithBearer() { + const sent: Sent[] = []; + let refuseUploads = false; + const network = async (input: RequestInfo | URL, init?: RequestInit): Promise => { + const url = String(input); + sent.push({ + url, + method: init?.method ?? 'GET', + authorization: new Headers(init?.headers).get('Authorization'), + }); + if (url.includes('/api/v1/discovery')) { + return json({ success: true, data: { name: 'fake', routes: {} } }); + } + if (url.endsWith('/upload')) { + if (refuseUploads) throw new TypeError('Failed to fetch'); + return json({ id: 'file_1', url: '/files/file_1' }); + } + return json({ success: true, data: {} }); + }; + // The host's authenticated fetch: the stored bearer beside whatever the caller set. + const authenticatedFetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers); + headers.set('Authorization', 'Bearer stored-token-37506'); + return network(input, { ...init, headers }); + }); + return { + sent, + authenticatedFetch, + refuse: () => { + refuseUploads = true; + }, + }; +} + +describe('data-objectstack uploads send through the injected fetch (objectstack#37506)', () => { + let globalFetch: ReturnType; + + beforeEach(() => { + clearSharedDiscoveryCache(); + // The control: the global fetch carries no bearer. Nothing may reach it. + globalFetch = vi.fn(async () => { + throw new Error('the global fetch was called: it sends the cookie alone'); + }); + vi.stubGlobal('fetch', globalFetch); + }); + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it('uploadFile goes out through the injected fetch, carrying its bearer', async () => { + const host = hostWithBearer(); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + await expect(adapter.uploadFile('task', new Blob(['a']), { recordId: 'r1' })).resolves.toMatchObject({ + id: 'file_1', + }); + + const upload = host.sent.filter((s) => s.url.endsWith('/upload')); + expect(upload).toEqual([ + { url: `${BASE}/api/data/task/upload`, method: 'POST', authorization: 'Bearer stored-token-37506' }, + ]); + expect(globalFetch).not.toHaveBeenCalled(); + }); + + it('uploadFiles goes out through the injected fetch, carrying its bearer', async () => { + const host = hostWithBearer(); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + await adapter.uploadFiles('task', [new Blob(['a']), new Blob(['b'])]); + + const upload = host.sent.filter((s) => s.url.endsWith('/upload')); + expect(upload).toEqual([ + { url: `${BASE}/api/data/task/upload`, method: 'POST', authorization: 'Bearer stored-token-37506' }, + ]); + expect(globalFetch).not.toHaveBeenCalled(); + }); + + it('a refused upload still leaves the connection state where it was', async () => { + const host = hostWithBearer(); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + await adapter.connect(); + expect(adapter.getConnectionState()).toBe('connected'); + const events: ConnectionStateEvent[] = []; + adapter.onConnectionStateChange((event) => events.push(event)); + + host.refuse(); + await expect(adapter.uploadFile('task', new Blob(['a']))).rejects.toBeInstanceOf(TypeError); + await expect(adapter.uploadFiles('task', [new Blob(['a'])])).rejects.toBeInstanceOf(TypeError); + + expect(adapter.getConnectionState()).toBe('connected'); + expect(events).toEqual([]); + expect(globalFetch).not.toHaveBeenCalled(); + }); +});