diff --git a/.changeset/38163-uploads-storage-presigned.md b/.changeset/38163-uploads-storage-presigned.md new file mode 100644 index 00000000000..9ef359a2b03 --- /dev/null +++ b/.changeset/38163-uploads-storage-presigned.md @@ -0,0 +1,18 @@ +--- +'@object-ui/data-objectstack': patch +--- + +fix(data-objectstack): `uploadFile` and `uploadFiles` upload through the storage service's presigned flow + +Clause-②: no +Metadata-protocol: none + +The two methods posted the file to `/api/data//upload`, a route the standard server does not serve, so every call failed with 404 `ENDPOINT_NOT_FOUND`. They now upload through the storage service, the way `createObjectStackUploadAdapter` does: `POST /api/v1/storage/upload/presigned`, the byte `PUT`, then `POST /api/v1/storage/upload/complete`. `uploadFiles` uploads its files one after another. + +- `recordId` attaches the file to that record of `resource` in the completing call (scope `attachments`), and the result's `metadata.attachmentId` names the attachment. Without `recordId` the file is stored under the server's default scope. +- The result is the stored file: `id` is the `sys_file` id, `url` the stable download URL. +- `onProgress` still receives 0 to 100. +- `fieldName` and `metadata` are now refused with `UNSUPPORTED_OPERATION` before any request, because neither presigned request carries them. Before, they were sent to the missing route. To fill a file field, upload without them, then write the returned file onto the record with `update()`. +- A refused storage request rejects with `UPLOAD_ERROR`, the server's status, and its error code in `details.serverCode`. When a file in `uploadFiles` is refused, the batch stops there. The error's `details` carry `failedIndex` and, as `uploaded`, the files already stored. + +The requests still go through the injected `fetch`, outside the connection-state tracking, and the adapter's `token` is sent on every request to this server. A presigned byte URL on another origin does not get it: the same-origin check compares resolved origins, so a protocol-relative or backslash-spelled URL that resolves to another host is not this server. diff --git a/packages/qa/dogfood/package.json b/packages/qa/dogfood/package.json index 1098d66a012..c2169b15775 100644 --- a/packages/qa/dogfood/package.json +++ b/packages/qa/dogfood/package.json @@ -43,6 +43,7 @@ "@objectstack/verify": "workspace:*" }, "devDependencies": { + "@object-ui/data-objectstack": "workspace:*", "@objectstack/account": "workspace:*", "@objectstack/cli": "workspace:*", "@objectstack/cloud-connection": "workspace:*", diff --git a/packages/qa/dogfood/test/data-objectstack-upload-route-38163.dogfood.test.ts b/packages/qa/dogfood/test/data-objectstack-upload-route-38163.dogfood.test.ts new file mode 100644 index 00000000000..eb88dc7173b --- /dev/null +++ b/packages/qa/dogfood/test/data-objectstack-upload-route-38163.dogfood.test.ts @@ -0,0 +1,110 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#38163] `uploadFile` / `uploadFiles` of the ObjectStack data source +// (`@object-ui/data-objectstack`) upload through the route a standard server +// serves: the storage service's presigned flow. They used to post to +// `/api/data//upload`, which this stack answers 404 +// `ENDPOINT_NOT_FOUND`, so every call failed. +// +// The data source runs against a real stack (`bootStack` with +// `StorageServicePlugin` and the attachments fixture), through a fetch that +// hands each request to the stack's Hono app. The session is bearer-only: +// no cookie exists on this transport, so a request that lost the bearer would +// be anonymous and refused. What the pin reads: the call resolves, the +// returned id names a committed `sys_file` row, a `recordId` upload wrote the +// `sys_attachment` row, and no request reached an upload path the server does +// not serve. +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { mkdtempSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { StorageServicePlugin } from '@objectstack/service-storage'; +import { AuditPlugin } from '@objectstack/plugin-audit'; +import { ObjectStackAdapter } from '@object-ui/data-objectstack'; +import { attachmentsFixtureStack, attachmentsFixtureSecurity } from './fixtures/attachments-fixture.js'; + +const ORIGIN = 'http://stack-38163.test'; +const SYS = { isSystem: true } as const; +/** An upload path the standard server does not serve: the data source's old one, with or without a version. */ +const UNSERVED_UPLOAD = /\/api\/(v\d+\/)?data\/[^/]+\/upload/; + +describe('data-objectstack uploads reach the storage service on a real stack (#38163)', () => { + let stack: VerifyStack; + let admin: string; + let ql: any; + let caseId: string; + const paths: string[] = []; + + /** The stack's Hono app as a fetch; `withBearer` plays a host's authenticated fetch. */ + const stackFetch = + (withBearer: string | null) => + async (input: RequestInfo | URL, init?: RequestInit): Promise => { + const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, ORIGIN); + if (url.origin !== ORIGIN) throw new Error(`request left the stack: ${url.href}`); + paths.push(`${init?.method ?? 'GET'} ${url.pathname}`); + const headers = new Headers(init?.headers); + if (withBearer) headers.set('Authorization', `Bearer ${withBearer}`); + return stack.raw(`${url.pathname}${url.search}`, { ...init, headers }); + }; + + beforeAll(async () => { + const rootDir = mkdtempSync(join(tmpdir(), 'upload-route-38163-')); + stack = await bootStack(attachmentsFixtureStack as never, { + security: attachmentsFixtureSecurity(), + extraPlugins: [ + new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false }), + new AuditPlugin(), + ], + }); + admin = await stack.signIn(); + ql = await stack.kernel.getServiceAsync('objectql'); + const created = await stack.apiAs(admin, 'POST', '/data/att_case', { name: 'Upload target' }); + expect(created.status, 'create att_case').toBeLessThan(300); + const body = (await created.json()) as any; + caseId = String(body.id ?? body.record?.id ?? body.data?.id); + }, 180_000); + afterAll(async () => { + await stack?.stop(); + }); + + it('uploadFile with recordId stores the file and attaches it to the record, under the token alone', async () => { + paths.length = 0; + const source = new ObjectStackAdapter({ baseUrl: ORIGIN, token: admin, fetch: stackFetch(null), autoReconnect: false }); + + const result = await source.uploadFile('att_case', new File(['hello'], 'hello.txt', { type: 'text/plain' }), { + recordId: caseId, + }); + + expect(result).toMatchObject({ filename: 'hello.txt', mimeType: 'text/plain', size: 5 }); + const file = await ql.findOne('sys_file', { where: { id: result.id }, context: SYS }); + expect(file, 'sys_file row').toBeTruthy(); + expect(file.status).toBe('committed'); + const attachment = await ql.findOne('sys_attachment', { where: { file_id: result.id }, context: SYS }); + expect(attachment, 'sys_attachment row').toBeTruthy(); + expect(attachment.parent_object).toBe('att_case'); + expect(String(attachment.parent_id)).toBe(caseId); + expect(result.metadata?.attachmentId).toBe(attachment.id); + expect(paths.filter((p) => UNSERVED_UPLOAD.test(p))).toEqual([]); + }, 60_000); + + it('uploadFiles stores every file, through a host fetch that carries the bearer', async () => { + paths.length = 0; + const source = new ObjectStackAdapter({ baseUrl: ORIGIN, fetch: stackFetch(admin), autoReconnect: false }); + + const results = await source.uploadFiles('att_case', [ + new File(['one'], 'one.txt', { type: 'text/plain' }), + new File(['two!'], 'two.txt', { type: 'text/plain' }), + ]); + + expect(results.map((r) => [r.filename, r.size])).toEqual([ + ['one.txt', 3], + ['two.txt', 4], + ]); + for (const r of results) { + const file = await ql.findOne('sys_file', { where: { id: r.id }, context: SYS }); + expect(file?.status, `sys_file ${r.id}`).toBe('committed'); + } + expect(paths.filter((p) => UNSERVED_UPLOAD.test(p))).toEqual([]); + }, 60_000); +}); diff --git a/packages/qa/dogfood/vitest.config.ts b/packages/qa/dogfood/vitest.config.ts index 90121a7db49..194774a8a4f 100644 --- a/packages/qa/dogfood/vitest.config.ts +++ b/packages/qa/dogfood/vitest.config.ts @@ -245,6 +245,10 @@ export default defineConfig({ // alias it to SOURCE so the pin is a verdict about the checkout, // not about a build artifact (#7668 is what a dist-resolved pin // costs). + { + find: /^@object-ui\/data-objectstack$/, + replacement: path.resolve(__dirname, '../../../ui/packages/data-objectstack/src/index.ts'), + }, { find: /^@objectstack\/metadata-core$/, replacement: path.resolve(__dirname, '../../metadata-core/src/index.ts'), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e5b7ea3de1f..ac5e8f378b8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2555,6 +2555,9 @@ importers: specifier: workspace:* version: link:../../verify devDependencies: + '@object-ui/data-objectstack': + specifier: workspace:* + version: link:../../../ui/packages/data-objectstack '@objectstack/account': specifier: workspace:* version: link:../../apps/account diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index 5cdf0076182..fa3702456f9 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -80,6 +80,7 @@ import type { ImportJobUndoResult, ListImportJobsOptions, ListViewGroupHeaderAnswer, + UploadResult, } from '@object-ui/types'; import { errorCodeIs, errorCodeIsAnyOf } from '@object-ui/types'; import { @@ -114,6 +115,7 @@ import { // re-exported from this entry point: it is internal, and exporting it would // widen this package's published face. import { readErrorEnvelope } from './error-envelope'; +import { createObjectStackUploadAdapter } from './upload-adapter'; /** * Map human-readable filter operator names produced by SDUI view configs @@ -3546,6 +3548,49 @@ function isCallerAbort(error: unknown, init?: RequestInit): boolean { return (error as { name?: unknown } | null)?.name === 'AbortError'; } +/** + * Whether `url` is a request to this data source's server (objectstack#38163), + * judged by the URL parser rather than by spelling: `url` is resolved against + * the server, which is `baseUrl`, or the page's origin when `baseUrl` is `''`, + * and it is this server only when the resolved origin is the server's and, for + * a `baseUrl` with a path, the resolved path lies under that path. A server + * that cannot be read, or a URL that does not parse, is not this server. + */ +function isRequestToServer(url: string, baseUrl: string): boolean { + const base = baseUrl !== '' ? baseUrl : (globalThis as { location?: { origin?: unknown } }).location?.origin; + if (typeof base !== 'string' || base === '') return false; + try { + const server = new URL(base); + const resolved = new URL(url, server); + if (resolved.origin !== server.origin) return false; + const path = server.pathname.replace(/\/+$/, ''); + return path === '' || resolved.pathname.startsWith(`${path}/`); + } catch { + return false; + } +} + +/** + * `uploadFile` / `uploadFiles` refuse `fieldName` and `metadata` before any + * request (objectstack#38163): the storage service's presigned flow, the one + * upload route the standard server serves, carries neither, so sending the + * upload without them would drop them silently. + */ +function refuseUnsentUploadOptions( + method: 'uploadFile' | 'uploadFiles', + options: { fieldName?: string; metadata?: Record } | undefined, +): void { + const unsent = (['fieldName', 'metadata'] as const).filter((key) => options?.[key] !== undefined); + if (unsent.length === 0) return; + throw new ObjectStackError( + `${method}() cannot send ${unsent.join(' or ')}: it uploads through the storage service's presigned flow ` + + '(POST /api/v1/storage/upload/presigned, then POST /api/v1/storage/upload/complete), which carries ' + + 'neither. Upload without them, then write the returned file onto the record with update() to fill a ' + + 'file field.', + 'UNSUPPORTED_OPERATION', + ); +} + /** The message of a rejection, after the client error is normalised. */ function rowErrorMessage(err: unknown): string { const normalised = normaliseClientError(err); @@ -3665,6 +3710,13 @@ export class ObjectStackAdapter implements DataSource { * the connection state. */ private uploadTransport: (input: RequestInfo | URL, init?: RequestInit) => Promise; + /** + * The fetch `uploadFile` / `uploadFiles` hand the presigned storage adapter + * (objectstack#38163): `uploadTransport`, with the adapter's `token` added to + * every request to this server. A presigned byte URL on another origin (an + * S3 bucket) gets no token: its own signature is its authority. + */ + private storageUploadFetch: (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) @@ -3814,6 +3866,15 @@ export class ObjectStackAdapter implements DataSource { this.reconnectDelay = config.reconnectDelay ?? 1000; this.baseUrl = baseUrl; this.token = config.token; + this.storageUploadFetch = (input, init) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + if (!isRequestToServer(url, this.baseUrl)) return transport(input, init); + const headers = new Headers(init?.headers); + for (const [name, value] of Object.entries(this.getAuthHeaders())) { + if (!headers.has(name)) headers.set(name, value); + } + return transport(input, { ...init, headers }); + }; } /** @@ -8215,13 +8276,34 @@ export class ObjectStackAdapter implements DataSource { } /** - * Upload a single file to a resource. - * Posts the file as multipart/form-data to the ObjectStack server. - * - * @param resource - The resource/object name to attach the file to + * Upload a single file through the server's storage service. + * + * The file goes through the storage service's presigned flow, the one + * `createObjectStackUploadAdapter` speaks (`POST /api/v1/storage/upload/presigned`, + * the byte `PUT`, `POST /api/v1/storage/upload/complete`): the standard server + * serves no other upload route (objectstack#38163). The answer is the stored + * `sys_file` row's id, the stable download URL and what the adapter reports. + * + * - `recordId` attaches the file to that record of `resource` in the call that + * completes it (`attachTo`, scope `attachments`): the server commits the file + * and writes its `sys_attachment` row as one unit, as the signed-in caller, + * and `metadata.attachmentId` names the new attachment. Without `recordId` + * the file is stored under the server's default scope and `resource` is not + * sent. + * - `onProgress` receives 0–100. + * - `fieldName` and `metadata` are refused before any request: neither + * presigned request carries them. + * + * The requests go through the injected `fetch` (outside the connection-state + * tracking), with the adapter's `token` on every request to this server. + * + * @param resource - The object whose record `options.recordId` names * @param file - File object or Blob to upload - * @param options - Additional upload options (recordId, fieldName, metadata) - * @returns Promise resolving to the upload result (file URL, metadata) + * @param options - Upload options (recordId, onProgress) + * @returns Promise resolving to the upload result (file id, URL, metadata) + * @throws ObjectStackError `UPLOAD_ERROR` with the server's status when a + * storage request is refused; `UNSUPPORTED_OPERATION` for `fieldName` / + * `metadata` */ async uploadFile( resource: string, @@ -8233,55 +8315,31 @@ export class ObjectStackAdapter implements DataSource { onProgress?: (percent: number) => void; }, ): Promise { + refuseUnsentUploadOptions('uploadFile', options); await this.connect(); - - const formData = new FormData(); - formData.append('file', file); - - if (options?.recordId) { - formData.append('recordId', options.recordId); - } - if (options?.fieldName) { - formData.append('fieldName', options.fieldName); - } - if (options?.metadata) { - formData.append('metadata', JSON.stringify(options.metadata)); - } - - const url = `${this.baseUrl}/api/data/${encodeURIComponent(resource)}/upload`; - - const response = await this.uploadTransport(url, { - method: 'POST', - body: formData, - headers: { - ...(this.getAuthHeaders()), - }, - }); - - if (!response.ok) { - const errorBody = await response.json().catch(() => ({ message: response.statusText })); - // #9594 - share the DIALECT READING only. This site's envelope is not the - // four ladders': a different error class, a hard-coded `UPLOAD_ERROR` - // code, and its own last rung, all of which stay exactly as they were. - const envelope = readErrorEnvelope(errorBody); - throw new ObjectStackError( - envelope.message ?? `Upload failed with status ${response.status}`, - 'UPLOAD_ERROR', - response.status, - ); - } - - return response.json(); + const onProgress = options?.onProgress; + return this.uploadThroughStorage( + resource, + file, + options?.recordId, + onProgress ? (ratio) => onProgress(ratio * 100) : undefined, + ); } /** - * Upload multiple files to a resource. - * Posts all files as a single multipart/form-data request. + * Upload several files through the server's storage service: one presigned + * upload per file, in order, each exactly as {@link uploadFile} sends it. + * + * `onProgress` receives 0–100 across the whole batch. The first refused file + * stops the batch: the files before it are already stored (and attached, with + * `recordId`), and the rejection is an `UPLOAD_ERROR` whose `details` carry + * `failedIndex` and those files' results as `uploaded`, so a caller can tell + * what landed. The files after it are not sent. * - * @param resource - The resource/object name to attach the files to + * @param resource - The object whose record `options.recordId` names * @param files - Array of File objects or Blobs to upload - * @param options - Additional upload options - * @returns Promise resolving to array of upload results + * @param options - Upload options (recordId, onProgress) + * @returns Promise resolving to array of upload results, in input order */ async uploadFiles( resource: string, @@ -8293,47 +8351,76 @@ export class ObjectStackAdapter implements DataSource { onProgress?: (percent: number) => void; }, ): Promise { + refuseUnsentUploadOptions('uploadFiles', options); await this.connect(); - - const formData = new FormData(); - files.forEach((file, idx) => { - formData.append(`files`, file, (file as File).name || `file-${idx}`); - }); - - if (options?.recordId) { - formData.append('recordId', options.recordId); - } - if (options?.fieldName) { - formData.append('fieldName', options.fieldName); - } - if (options?.metadata) { - formData.append('metadata', JSON.stringify(options.metadata)); + const onProgress = options?.onProgress; + const uploaded: FileUploadResult[] = []; + for (let index = 0; index < files.length; index++) { + try { + uploaded.push( + await this.uploadThroughStorage( + resource, + files[index], + options?.recordId, + onProgress ? (ratio) => onProgress(((index + ratio) / files.length) * 100) : undefined, + ), + ); + } catch (err) { + const cause = err as { message?: unknown; statusCode?: unknown; details?: Record }; + throw new ObjectStackError( + `Upload of file ${index + 1} of ${files.length} failed, after ${index} stored: ${String(cause?.message ?? err)}`, + 'UPLOAD_ERROR', + typeof cause?.statusCode === 'number' ? cause.statusCode : undefined, + { ...(cause?.details ?? {}), failedIndex: index, uploaded: [...uploaded], cause: err }, + ); + } } + return uploaded; + } - const url = `${this.baseUrl}/api/data/${encodeURIComponent(resource)}/upload`; - - const response = await this.uploadTransport(url, { - method: 'POST', - body: formData, - headers: { - ...(this.getAuthHeaders()), - }, + /** + * One file through the storage service's presigned flow, mapped to + * `FileUploadResult`. The adapter is built per call because `attachTo` is + * one of its options; the fetch it sends through is the data source's one + * `storageUploadFetch`. + */ + private async uploadThroughStorage( + resource: string, + file: File | Blob, + recordId: string | undefined, + onProgress: ((ratio: number) => void) | undefined, + ): Promise { + const storage = createObjectStackUploadAdapter({ + baseUrl: this.baseUrl, + fetchImpl: this.storageUploadFetch, + ...(recordId + ? { scope: 'attachments' as const, attachTo: { parentObject: resource, parentId: recordId } } + : {}), }); - - if (!response.ok) { - const errorBody = await response.json().catch(() => ({ message: response.statusText })); - // #9594 - share the DIALECT READING only. This site's envelope is not the - // four ladders': a different error class, a hard-coded `UPLOAD_ERROR` - // code, and its own last rung, all of which stay exactly as they were. - const envelope = readErrorEnvelope(errorBody); + let result: UploadResult; + try { + result = await storage.upload(file, onProgress ? { onProgress } : undefined); + } catch (err) { + const refusal = err as { message?: unknown; status?: unknown; code?: unknown }; + // A refused storage request carries the server's status (and its error + // code when the answer was the declared envelope); a failure with no + // HTTP answer reaches the caller unchanged. + if (typeof refusal?.status !== 'number') throw err; throw new ObjectStackError( - envelope.message ?? `Upload failed with status ${response.status}`, + String(refusal.message), 'UPLOAD_ERROR', - response.status, + refusal.status, + typeof refusal.code === 'string' ? { serverCode: refusal.code } : undefined, ); } - - return response.json(); + return { + id: result.meta?.fileId as string, + filename: result.name, + mimeType: result.mimeType, + size: result.size, + url: result.url, + ...(result.meta ? { metadata: result.meta } : {}), + }; } /** diff --git a/ui/packages/data-objectstack/src/upload-adapter.ts b/ui/packages/data-objectstack/src/upload-adapter.ts index 46bb834e63b..16ba775cad0 100644 --- a/ui/packages/data-objectstack/src/upload-adapter.ts +++ b/ui/packages/data-objectstack/src/upload-adapter.ts @@ -121,8 +121,10 @@ export function createObjectStackUploadAdapter( }); if (!presignRes.ok) { const text = await presignRes.text().catch(() => ''); - throw new Error( + throw refusalOf( `Presigned upload request failed (${presignRes.status}): ${text || presignRes.statusText}`, + presignRes.status, + text, ); } const presignBody = await presignRes.json(); @@ -156,16 +158,10 @@ export function createObjectStackUploadAdapter( // The server's refusal code and status ride on the error, so a caller // maps a refused attach (`ATTACHMENT_PARENT_ACCESS`, `FILES_DISABLED`, // `PERMISSION_DENIED`…) without parsing the message. - let code: string | undefined; - try { - const parsed = JSON.parse(text); - if (typeof parsed?.error?.code === 'string') code = parsed.error.code; - } catch { - // Not the declared envelope — the message keeps the raw text. - } - throw Object.assign( - new Error(`Upload completion failed (${completeRes.status}): ${text || completeRes.statusText}`), - { status: completeRes.status, ...(code ? { code } : {}) }, + throw refusalOf( + `Upload completion failed (${completeRes.status}): ${text || completeRes.statusText}`, + completeRes.status, + text, ); } const completeBody = opts.attachTo ? await completeRes.json().catch(() => null) : null; @@ -188,6 +184,22 @@ export function createObjectStackUploadAdapter( }; } +/** + * The error a refused storage request throws: the message as given, the HTTP + * `status`, and the server's error `code` when the answer was the declared + * envelope. + */ +function refusalOf(message: string, status: number, text: string): Error & { status: number; code?: string } { + let code: string | undefined; + try { + const parsed = JSON.parse(text); + if (typeof parsed?.error?.code === 'string') code = parsed.error.code; + } catch { + // Not the declared envelope — the message keeps the raw text. + } + return Object.assign(new Error(message), { status, ...(code ? { code } : {}) }); +} + interface UploadFetchOptions extends UploadOptions { method: string; headers?: Record; @@ -221,7 +233,7 @@ async function uploadWithProgress( headers: options.headers, signal: options.signal, }); - if (!res.ok) throw new Error(`Upload failed with status ${res.status}`); + if (!res.ok) throw Object.assign(new Error(`Upload failed with status ${res.status}`), { status: res.status }); options.onProgress?.(1); } return; @@ -250,7 +262,7 @@ function xhrUpload(url: string, body: Blob, options: UploadFetchOptions): Promis options.onProgress?.(1); resolve(); } else { - reject(new Error(`Upload failed with status ${xhr.status}`)); + reject(Object.assign(new Error(`Upload failed with status ${xhr.status}`), { status: xhr.status })); } }; xhr.onerror = () => reject(new Error('Network error during upload')); diff --git a/ui/packages/data-objectstack/src/uploadTransport-37506.test.ts b/ui/packages/data-objectstack/src/uploadTransport-37506.test.ts index 4bc44ac215f..73c6a3d2f82 100644 --- a/ui/packages/data-objectstack/src/uploadTransport-37506.test.ts +++ b/ui/packages/data-objectstack/src/uploadTransport-37506.test.ts @@ -17,6 +17,11 @@ * third-party, or cleared) an upload went out anonymous while every other * request of the same adapter was signed in. * + * objectstack#38163 — and they send to the storage service's presigned flow, + * the one upload route the standard server serves. They used to post to + * `/api/data//upload`, which the server answers 404; the fake network + * below answers that path the same way. + * * 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. @@ -27,9 +32,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { ObjectStackAdapter, type ConnectionStateEvent } from './index'; +import { ObjectStackError } from './errors'; import { clearSharedDiscoveryCache } from './sharedDiscovery'; const BASE = 'http://fake-37506.test'; +const STORAGE = `${BASE}/api/v1/storage`; function json(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { @@ -38,25 +45,59 @@ function json(body: unknown, status = 200): Response { }); } -/** What reached the network: URL, method and the Authorization header. */ -type Sent = { url: string; method: string; authorization: string | null }; +/** What reached the network: URL, method, the Authorization header and the JSON body. */ +type Sent = { url: string; method: string; authorization: string | null; body: unknown }; -function hostWithBearer() { +/** + * A fake ObjectStack server: discovery, the storage service's three presigned + * steps, and a 404 `ENDPOINT_NOT_FOUND` for anything else under an upload path, + * as the standard server answers `/api/data//upload`. + */ +function fakeServer(opts: { uploadUrlOf?: (fileId: string) => string } = {}) { const sent: Sent[] = []; let refuseUploads = false; + let refuseCompleteOf: string | null = null; + let nextFile = 0; 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'), - }); + const method = init?.method ?? 'GET'; + let body: unknown; + if (typeof init?.body === 'string') body = JSON.parse(init.body); + sent.push({ url, method, authorization: new Headers(init?.headers).get('Authorization'), body }); if (url.includes('/api/v1/discovery')) { return json({ success: true, data: { name: 'fake', routes: {} } }); } - if (url.endsWith('/upload')) { + if (url === `${STORAGE}/upload/presigned` && method === 'POST') { if (refuseUploads) throw new TypeError('Failed to fetch'); - return json({ id: 'file_1', url: '/files/file_1' }); + nextFile++; + const fileId = `file_${nextFile}`; + return json({ + success: true, + data: { + uploadUrl: opts.uploadUrlOf ? opts.uploadUrlOf(fileId) : `/api/v1/storage/_local/raw/tok-${fileId}`, + method: 'PUT', + fileId, + expiresIn: 3600, + downloadUrl: `/api/v1/storage/files/${fileId}/url`, + }, + }); + } + if (method === 'PUT' && (url.includes('/_local/raw/') || url.startsWith('https://bucket.'))) { + return json({ success: true, data: { key: 'k' } }); + } + if (url === `${STORAGE}/upload/complete` && method === 'POST') { + const fileId = (body as { fileId: string }).fileId; + if (refuseCompleteOf === fileId) { + return json( + { success: false, error: { code: 'ATTACHMENT_PARENT_ACCESS', message: 'No edit access to the record' } }, + 403, + ); + } + const attachTo = (body as { attachTo?: unknown }).attachTo; + return json({ success: true, data: { id: fileId, ...(attachTo ? { attachmentId: `att_${fileId}` } : {}) } }); + } + if (url.includes('/upload')) { + return json({ success: false, error: { code: 'ENDPOINT_NOT_FOUND', message: 'Not found' } }, 404); } return json({ success: true, data: {} }); }; @@ -66,60 +107,68 @@ function hostWithBearer() { headers.set('Authorization', 'Bearer stored-token-37506'); return network(input, { ...init, headers }); }); + const plainFetch = vi.fn(network); return { sent, authenticatedFetch, + plainFetch, + uploads: () => sent.filter((s) => !s.url.includes('/api/v1/discovery')), refuse: () => { refuseUploads = true; }, + refuseComplete: (fileId: string) => { + refuseCompleteOf = fileId; + }, }; } -describe('data-objectstack uploads send through the injected fetch (objectstack#37506)', () => { - let globalFetch: ReturnType; +const file = (name: string, text = 'hello') => new File([text], name, { type: 'text/plain' }); - 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(); +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(); +}); +describe('data-objectstack uploads send through the injected fetch (objectstack#37506)', () => { it('uploadFile goes out through the injected fetch, carrying its bearer', async () => { - const host = hostWithBearer(); + const host = fakeServer(); const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); - await expect(adapter.uploadFile('task', new Blob(['a']), { recordId: 'r1' })).resolves.toMatchObject({ + await expect(adapter.uploadFile('task', file('a.txt'), { 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(host.uploads().map((s) => s.authorization)).toEqual([ + 'Bearer stored-token-37506', + 'Bearer stored-token-37506', + 'Bearer stored-token-37506', ]); expect(globalFetch).not.toHaveBeenCalled(); }); it('uploadFiles goes out through the injected fetch, carrying its bearer', async () => { - const host = hostWithBearer(); + const host = fakeServer(); const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); - await adapter.uploadFiles('task', [new Blob(['a']), new Blob(['b'])]); + await adapter.uploadFiles('task', [file('a.txt'), file('b.txt')]); - 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' }, - ]); + const uploads = host.uploads(); + expect(uploads).toHaveLength(6); + expect(uploads.every((s) => s.authorization === 'Bearer stored-token-37506')).toBe(true); expect(globalFetch).not.toHaveBeenCalled(); }); it('a refused upload still leaves the connection state where it was', async () => { - const host = hostWithBearer(); + const host = fakeServer(); const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); await adapter.connect(); expect(adapter.getConnectionState()).toBe('connected'); @@ -127,11 +176,178 @@ describe('data-objectstack uploads send through the injected fetch (objectstack# 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); + await expect(adapter.uploadFile('task', file('a.txt'))).rejects.toBeInstanceOf(TypeError); + const batch = await adapter.uploadFiles('task', [file('a.txt')]).catch((e: unknown) => e); + expect(batch).toBeInstanceOf(ObjectStackError); + expect((batch as ObjectStackError).details?.cause).toBeInstanceOf(TypeError); expect(adapter.getConnectionState()).toBe('connected'); expect(events).toEqual([]); expect(globalFetch).not.toHaveBeenCalled(); }); }); + +describe('data-objectstack uploads go to the storage service, the route the server serves (objectstack#38163)', () => { + it('neither method sends a request to /api/data//upload; each file is presigned, PUT and completed', async () => { + const host = fakeServer(); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + await adapter.uploadFile('task', file('a.txt')); + await adapter.uploadFiles('task', [file('b.txt'), file('c.txt')]); + + const uploads = host.uploads(); + expect(uploads.filter((s) => /\/api\/(v\d+\/)?data\/[^/]+\/upload/.test(s.url))).toEqual([]); + expect(uploads.map((s) => `${s.method} ${s.url.replace(BASE, '')}`)).toEqual([ + 'POST /api/v1/storage/upload/presigned', + 'PUT /api/v1/storage/_local/raw/tok-file_1', + 'POST /api/v1/storage/upload/complete', + 'POST /api/v1/storage/upload/presigned', + 'PUT /api/v1/storage/_local/raw/tok-file_2', + 'POST /api/v1/storage/upload/complete', + 'POST /api/v1/storage/upload/presigned', + 'PUT /api/v1/storage/_local/raw/tok-file_3', + 'POST /api/v1/storage/upload/complete', + ]); + }); + + it('recordId attaches the file to that record of the resource, in the completing call', async () => { + const host = fakeServer(); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + const result = await adapter.uploadFile('task', file('a.txt', 'hello'), { recordId: 'r1' }); + + const [presign, , complete] = host.uploads(); + expect(presign.body).toEqual({ filename: 'a.txt', mimeType: 'text/plain', size: 5, scope: 'attachments' }); + expect(complete.body).toEqual({ fileId: 'file_1', attachTo: { parentObject: 'task', parentId: 'r1' } }); + expect(result).toEqual({ + id: 'file_1', + filename: 'a.txt', + mimeType: 'text/plain', + size: 5, + url: `${STORAGE}/files/file_1`, + metadata: { fileId: 'file_1', scope: 'attachments', attachmentId: 'att_file_1' }, + }); + }); + + it('without recordId the file is stored under the server default scope and attached to nothing', async () => { + const host = fakeServer(); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + const result = await adapter.uploadFile('task', file('a.txt')); + + const [presign, , complete] = host.uploads(); + expect(presign.body).toEqual({ filename: 'a.txt', mimeType: 'text/plain', size: 5 }); + expect(complete.body).toEqual({ fileId: 'file_1' }); + expect(result.metadata).toEqual({ fileId: 'file_1', scope: undefined }); + }); + + it.each([ + ['fieldName', { fieldName: 'contract' }], + ['metadata', { metadata: { source: 'scan' } }], + ] as const)('%s is refused before any request: the presigned flow cannot carry it', async (key, options) => { + const host = fakeServer(); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + for (const call of [ + () => adapter.uploadFile('task', file('a.txt'), options), + () => adapter.uploadFiles('task', [file('a.txt')], options), + ]) { + const err = await call().catch((e: unknown) => e); + expect(err).toBeInstanceOf(ObjectStackError); + expect((err as ObjectStackError).code).toBe('UNSUPPORTED_OPERATION'); + expect((err as ObjectStackError).message).toContain(key); + expect((err as ObjectStackError).message).toContain('/api/v1/storage/upload/presigned'); + } + expect(host.sent).toEqual([]); + }); + + it("the adapter's token signs every request to this server, and never a presigned URL on another origin", async () => { + const host = fakeServer({ uploadUrlOf: (fileId) => `https://bucket.s3.example/${fileId}?X-Amz-Signature=s` }); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, token: 'config-token', fetch: host.plainFetch }); + + await adapter.uploadFile('task', file('a.txt')); + + expect(host.uploads().map((s) => [s.method, s.url.startsWith(BASE), s.authorization])).toEqual([ + ['POST', true, 'Bearer config-token'], + ['PUT', false, null], + ['POST', true, 'Bearer config-token'], + ]); + }); + + it.each([ + ['a protocol-relative', '//other.example/bucket/x'], + ['a slash-backslash', '/\\other.example/x'], + ['a double-backslash', '\\\\other.example/x'], + ])('%s presigned URL is not treated as this server: it gets no token', async (_kind, uploadUrl) => { + // Same-origin data source (`baseUrl: ''`): this server is the page's origin, and its own + // requests are paths on it. The unit project runs in node, so the page is stubbed. + vi.stubGlobal('location', { origin: 'http://app-38163.test' }); + const sent: Array<{ url: string; method: string; authorization: string | null }> = []; + const network = vi.fn(async (input: RequestInfo | URL, init?: RequestInit): Promise => { + const url = String(input); + const method = init?.method ?? 'GET'; + sent.push({ url, method, authorization: new Headers(init?.headers).get('Authorization') }); + if (url.endsWith('/upload/presigned')) { + return json({ success: true, data: { uploadUrl, method: 'PUT', fileId: 'file_1' } }); + } + if (url.endsWith('/upload/complete')) return json({ success: true, data: { id: 'file_1' } }); + if (method === 'PUT') return json({ success: true, data: {} }); + return json({ success: true, data: { name: 'fake', routes: {} } }); + }); + const adapter = new ObjectStackAdapter({ baseUrl: '', token: 'config-token', fetch: network }); + + await adapter.uploadFile('task', file('a.txt')); + + expect(sent.filter((s) => !s.url.includes('/api/v1/discovery'))).toEqual([ + { url: '/api/v1/storage/upload/presigned', method: 'POST', authorization: 'Bearer config-token' }, + { url: uploadUrl, method: 'PUT', authorization: null }, + { url: '/api/v1/storage/upload/complete', method: 'POST', authorization: 'Bearer config-token' }, + ]); + }); + + it('a refused storage request rejects UPLOAD_ERROR with the server status and code', async () => { + const host = fakeServer(); + host.refuseComplete('file_1'); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + const err = await adapter.uploadFile('task', file('a.txt'), { recordId: 'r1' }).catch((e: unknown) => e); + + expect(err).toBeInstanceOf(ObjectStackError); + expect((err as ObjectStackError).code).toBe('UPLOAD_ERROR'); + expect((err as ObjectStackError).statusCode).toBe(403); + expect((err as ObjectStackError).details).toEqual({ serverCode: 'ATTACHMENT_PARENT_ACCESS' }); + }); + + it('uploadFiles stops at the first refused file and reports what was already stored', async () => { + const host = fakeServer(); + host.refuseComplete('file_2'); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + const err = await adapter + .uploadFiles('task', [file('a.txt'), file('b.txt'), file('c.txt')], { recordId: 'r1' }) + .catch((e: unknown) => e); + + expect(err).toBeInstanceOf(ObjectStackError); + const refusal = err as ObjectStackError; + expect(refusal.code).toBe('UPLOAD_ERROR'); + expect(refusal.statusCode).toBe(403); + expect(refusal.details?.failedIndex).toBe(1); + expect(refusal.details?.serverCode).toBe('ATTACHMENT_PARENT_ACCESS'); + expect((refusal.details?.uploaded as Array<{ id: string }>).map((r) => r.id)).toEqual(['file_1']); + // The third file is never sent. + expect(host.uploads().filter((s) => s.url.endsWith('/upload/presigned'))).toHaveLength(2); + }); + + it('onProgress reports percent: 100 for one file, and across the batch for several', async () => { + const host = fakeServer(); + const adapter = new ObjectStackAdapter({ baseUrl: BASE, fetch: host.authenticatedFetch }); + + const one: number[] = []; + await adapter.uploadFile('task', file('a.txt'), { onProgress: (p) => one.push(p) }); + const batch: number[] = []; + await adapter.uploadFiles('task', [file('a.txt'), file('b.txt')], { onProgress: (p) => batch.push(p) }); + + expect(one).toEqual([100]); + expect(batch).toEqual([50, 100]); + }); +});