diff --git a/.changeset/32686-upload-before-record.md b/.changeset/32686-upload-before-record.md new file mode 100644 index 00000000000..635615057f5 --- /dev/null +++ b/.changeset/32686-upload-before-record.md @@ -0,0 +1,16 @@ +--- +'@objectstack/service-storage': patch +'@objectstack/mcp': patch +'@objectstack/runtime': patch +--- + +feat(storage,mcp): an upload link for a file field of a record not yet created, so an agent can create a record whose file field is required + +Clause-②: yes (widening) +Metadata-protocol: none + +`create_upload_link` takes no `recordId` when it names a `field`: the link names the object and the file field only, and its answer carries `fileIds`, the id the upload is stored under. The user opens the link signed in and uploads; the agent then calls `create_record` with the field set to `fileIds[0]`. An expense line with a required e-invoice is created in two agent calls and one upload, and the field's `required` rule is unchanged. + +Minting such a link asks the object's create permission for the user, and the field must be writable for them and not read-only; an attachments link still needs its record. The upload is checked against the field's `accept` and `maxSize` before the link is spent. The stored file is bound to the uploading user, the object and the field for one hour: until a record holds it, only that user's own write, into that field of that object, may use it, and within the hour no second record may take it while the first holds it. The uploader's write into another field or object, or after the hour, is refused at the field with the reason; another user's or a system write is refused as a file they cannot open. Once the hour has passed with a record holding it, or once a record lets it go, it is judged as any other record's file. Before the upload, the id takes no write but the uploader's, which is refused as an upload that never completed. Until a record has held the file, only its uploader may download it. The page the link opens says the file was received, and tells the user to go back to the assistant. + +`fileIds` is an array so that a link for several files can answer several ids without a new key. Hosts whose storage service predates this keep `recordId` required on the tool, and the agent skill teaches the no-record form only where the host serves it. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 7fefea84a83..c2c20ec64cb 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -316,6 +316,26 @@ record means no file**, refused with the same `RECORD_NOT_FOUND`. `RECORD_LOCKED`). A field that becomes read-only after the link was made refuses the upload when it arrives, attaching nothing. Sending a file's bytes through the MCP protocol itself is not supported yet. +- **A record not created yet.** A record whose file field is `required` (an + expense line and its invoice, say) cannot be created before the file + exists, so `create_upload_link` also takes `objectName` and `field` with no + `recordId`. That needs a user who may create records of the object and + write the field, and a field that is not `readonly`; an attachments link + still needs its record. The answer carries `fileIds`, the id the upload is + stored under. Once the user has uploaded (the page says the file was + received), the agent calls `create_record` with the field set to + `fileIds[0]`, or the array for a multi-file field; before the upload that + create is refused as an upload that never completed. The field's own + `accept` and `maxSize` are checked when the file arrives, before the link is + spent. Until a record holds the file, the id works only for that user's own + `create_record` or `update_record` into that field of that object, within + one hour of the upload: the uploader's write into another field or object, + or after the hour, is refused at the field with the reason, and another + user's or a system write is refused as a file they cannot open. Within the + hour, a second record naming it while the first holds it is refused too. + After that it is the record's file like any other, and a file the record + lets go is judged as any released file. Until a record has held the file, + only the user who uploaded it can download it. Reading a PDF or Word document's text runs on a pool of worker threads, so the server keeps answering other requests while it does. Two host settings bound it, so diff --git a/content/docs/api/plugin-endpoints.mdx b/content/docs/api/plugin-endpoints.mdx index 5dc04186533..6047198bcee 100644 --- a/content/docs/api/plugin-endpoints.mdx +++ b/content/docs/api/plugin-endpoints.mdx @@ -162,7 +162,7 @@ other adapter. | GET | `/storage/files/:fileId/url` | `storage.getDownloadUrl` | Resolve a short-lived signed download URL | | GET | `/storage/files/:fileId` | — | Stable browser URL; 302s to the same signed URL (what file fields carry) | | GET | `/storage/upload-links/:token` | — | The page a single-use upload link opens (minted by the MCP `create_upload_link` tool) for the signed-in user it was made for: a file picker | -| PUT | `/storage/upload-links/:token` | — | Spend the link on the request body, as that signed-in user; the file lands on the record and field the link is bound to | +| PUT | `/storage/upload-links/:token` | — | Spend the link on the request body, as that signed-in user; the file lands on the record and field the link is bound to, or, for a link that names no record, is stored for that field under the file id the link answered, for the user's create or update to name | `storage.upload(file)` runs steps 1–3 for you, including the direct-to-storage `PUT` in step 2. Step 1 refuses an empty `mimeType` with `400 INVALID_REQUEST`, diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index edf3ca697ee..aba2ae61116 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -192,8 +192,8 @@ One of the largest consumers of the flag; | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | | 47d | The print service REFUSES the system context: `printRecordToFile` admits a human user acting for themselves alone | service-print | Get: nothing — a system caller is refused (`PERMISSION_DENIED`) before any page is read, session minted or browser started. Lose: nothing a user held — the PDF is rendered as the requesting user and never as the system, so a record is archived only by someone who could read it | `refuseUnlessHumanCaller` | -| 47e | The caller-scoped attach verbs REFUSE the system context: `attachFileAs` and `assertMayAttach` admit a signed-in user alone, and so do the caller-scoped record-file verbs the MCP `read_file` and `create_upload_link` tools call (`listRecordFilesAs`, `readRecordFileAs`, `createUploadLinkAs`) | service-storage | Get: nothing — a system caller is refused (`PERMISSION_DENIED`); the system attaches through `attachFile`, whose rows name no user. Lose: nothing a user held — the caller-scoped verbs insert the attachment under the caller's context so every insert gate judges that user and both rows name them, and the record-file verbs read the record and judge the file as that user, and bind an upload link to them | `packages/services/service-storage/src/file-attachment-service.ts#requireUserContext`, `packages/services/service-storage/src/record-file-access.ts#requireUserContext` | -| 47f | The file-reference claim path asks no read verdict of a system write: a record write claims or copies a referenced file only as its caller may read it (the download door's verdict), and a system write carries no caller to ask | service-storage | Get: a system write claims or copies any file the organization-scoped lookup reaches, as before #25692; a deliberate server-side copy between records runs this way. Lose: nothing a user held — a user write is judged by the download door's verdict, and a context-less programmatic write is not asked either | `referencingCallerOf` | +| 47e | The caller-scoped attach verbs REFUSE the system context: `attachFileAs` and `assertMayAttach` admit a signed-in user alone, and so do the caller-scoped record-file verbs the MCP `read_file` and `create_upload_link` tools call (`listRecordFilesAs`, `readRecordFileAs`, `createUploadLinkAs`, `createUploadLinkForNewRecordAs`) | service-storage | Get: nothing — a system caller is refused (`PERMISSION_DENIED`); the system attaches through `attachFile`, whose rows name no user. Lose: nothing a user held — the caller-scoped verbs insert the attachment under the caller's context so every insert gate judges that user and both rows name them, and the record-file verbs read the record and judge the file as that user, and bind an upload link to them; `createUploadLinkForNewRecordAs` names no record, so it asks the object's create verdict and the field's writability as that user instead | `packages/services/service-storage/src/file-attachment-service.ts#requireUserContext`, `packages/services/service-storage/src/record-file-access.ts#requireUserContext` | +| 47f | The file-reference claim path asks no read verdict of a system write: a record write claims or copies a referenced file only as its caller may read it (the download door's verdict), and a system write carries no caller to ask | service-storage | Get: a system write claims or copies any file the organization-scoped lookup reaches, as before #25692; a deliberate server-side copy between records runs this way. The exception is a file uploaded through an upload link that names no record (#32686), and the id such a link answers before its upload: until a record has held the file, only its uploader's own write takes it, so a system write naming it is refused at the field. Once a record holds it, a system write copies it as any; once a record lets it go, it is judged as any released file. Lose: nothing a user held — a user write is judged by the download door's verdict, and a context-less programmatic write is not asked either | `referencingCallerOf` | | 47g | The `sys_file` storage-owned columns guard returns early on create: a system insert keeps the `key`, `mime_type`, `size`, `status` and `etag` it writes | service-storage | Get: the storage service's own inserts (the upload doors, the field-file copy and backfill) write those five columns. Lose: nothing a user held — a non-system create has them dropped and starts `pending`, and on update the same columns are `readonly`, so the UPDATE `readonly` strip keeps them for every non-system caller | `installSysFileStorageOwnedColumnsGuard` | ### 5. Actions, metadata plane, provenance, the organization wall diff --git a/packages/mcp/src/file-content.ts b/packages/mcp/src/file-content.ts index 3eb580376d3..d218bf45d1c 100644 --- a/packages/mcp/src/file-content.ts +++ b/packages/mcp/src/file-content.ts @@ -311,6 +311,16 @@ export interface McpUploadLink { expiresAt: string; } +/** + * [#32686] A single-use upload link for a file field of a record not yet + * created, with the file id(s) the upload is stored under: the value the + * agent writes into the field when it creates the record. An array so that a + * link taking several files answers more entries, not a second key. + */ +export interface McpNewRecordUploadLink extends McpUploadLink { + fileIds: string[]; +} + /** * [#30892] The file seam of the HTTP MCP tools, implemented by the runtime * over the storage plugin's `file-attachments` service. Every member runs AS @@ -331,6 +341,12 @@ export interface McpFileBridge { ): Promise; /** A single-use upload link bound to exactly this record and field (or its attachments). */ createUploadLink?(object: string, recordId: string, target: McpUploadLinkTarget): Promise; + /** + * [#32686] A single-use upload link for a file field of a record the caller + * is about to create. Optional on its own: a host without it serves links + * for existing records only, and `create_upload_link` then needs `recordId`. + */ + createUploadLinkForNewRecord?(object: string, target: { field: string }): Promise; } /** One MCP tool-result content block `read_file` answers with. */ diff --git a/packages/mcp/src/mcp-file-tools.test.ts b/packages/mcp/src/mcp-file-tools.test.ts index cdf86285dce..9e31d51124c 100644 --- a/packages/mcp/src/mcp-file-tools.test.ts +++ b/packages/mcp/src/mcp-file-tools.test.ts @@ -472,6 +472,104 @@ describe('create_upload_link', () => { }); }); +/** [#32686] A bridge that also serves a link for a record not yet created. */ +function newRecordBridge() { + const bridge = fullBridge(); + Object.assign(bridge, { + async createUploadLinkForNewRecord(object: string, target: { field: string }) { + bridge.calls.push(['createUploadLinkForNewRecord', object, target]); + if (object === 'locked') { + throw Object.assign(new Error('You cannot upload a file for a new locked: you cannot create locked records.'), { + code: 'PERMISSION_DENIED', + status: 403, + }); + } + return { + url: 'https://acme.test/api/v1/storage/upload-links/f9.sec', + expiresAt: '2026-11-13T12:10:00.000Z', + fileIds: ['f9'], + }; + }, + } satisfies McpFileBridge); + return bridge; +} + +async function uploadLinkSchema(runtime: MCPServerRuntime, bridge: unknown) { + const json = await rpc(runtime, bridge, undefined, { jsonrpc: '2.0', id: 1, method: 'tools/list' }); + const tool = (json.result?.tools ?? []).find((t: { name: string }) => t.name === 'create_upload_link'); + return tool as { description: string; inputSchema: { required?: string[]; properties: Record } }; +} + +describe('[#32686] create_upload_link for a record not yet created', () => { + let runtime: MCPServerRuntime; + beforeEach(() => { + runtime = new MCPServerRuntime({ name: 'file-tools', version: '0.0.0' }); + }); + + it('with no recordId and a field, mints through the bridge and answers the file id the create names', async () => { + const bridge = newRecordBridge(); + const result = await callTool(runtime, bridge, 'create_upload_link', { objectName: 'expense_line', field: 'invoice' }); + expect(result.isError).toBeFalsy(); + expect(bridge.calls).toEqual([['createUploadLinkForNewRecord', 'expense_line', { field: 'invoice' }]]); + const facts = factsOf(result); + expect(facts).toMatchObject({ + url: 'https://acme.test/api/v1/storage/upload-links/f9.sec', + expiresAt: '2026-11-13T12:10:00.000Z', + singleUse: true, + objectName: 'expense_line', + field: 'invoice', + fileIds: ['f9'], + }); + expect(facts).not.toHaveProperty('recordId'); + expect(facts.instructions).toContain('fileIds[0]'); + }); + + it('with a recordId, still asks for that record\'s link, never the new-record one', async () => { + const bridge = newRecordBridge(); + await callTool(runtime, bridge, 'create_upload_link', { objectName: 'claim', recordId: 'c1', field: 'policy' }); + expect(bridge.calls).toEqual([['createUploadLink', 'claim', 'c1', { field: 'policy' }]]); + }); + + it('refuses an attachments link with no record before asking the bridge', async () => { + const bridge = newRecordBridge(); + const result = await callTool(runtime, bridge, 'create_upload_link', { objectName: 'claim', attachments: true }); + expect(result.isError).toBe(true); + expect(textOf(result.content[0])).toContain('An attachment needs its record'); + expect(bridge.calls).toEqual([]); + }); + + it('relays the minting refusal with its code', async () => { + const result = await callTool(runtime, newRecordBridge(), 'create_upload_link', { objectName: 'locked', field: 'invoice' }); + expect(result.isError).toBe(true); + expect(JSON.parse(textOf(result.content[0])).error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + }); + + it('lists recordId as optional, and says how, only where the bridge serves it', async () => { + const served = await uploadLinkSchema(runtime, newRecordBridge()); + expect(served.inputSchema.required ?? []).not.toContain('recordId'); + expect(served.description).toContain('omit recordId and name the field'); + const notServed = await uploadLinkSchema(runtime, fullBridge()); + expect(notServed.inputSchema.required).toContain('recordId'); + expect(notServed.description).not.toContain('omit recordId'); + }); + + it('a bridge without it refuses a call with no recordId, asking nothing', async () => { + const bridge = fullBridge(); + const result = await callTool(runtime, bridge, 'create_upload_link', { objectName: 'expense_line', field: 'invoice' }); + expect(result.isError).toBe(true); + expect(bridge.calls).toEqual([]); + }); + + it('the skill teaches the two-call flow only where the host says the bridge serves it, and only with data:write', () => { + const marker = 'omit `recordId` and name `field`'; + expect(renderSkillMarkdown({ fileTools: true, newRecordUploadLinks: true })).toContain(marker); + expect(renderSkillMarkdown({ fileTools: true })).not.toContain(marker); + expect(renderSkillMarkdown({ fileTools: true, newRecordUploadLinks: true, grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] })).not.toContain(marker); + expect(renderSkillMarkdown({ fileTools: true, newRecordUploadLinks: true, grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] })).toContain(marker); + expect(renderSkillMarkdown({ newRecordUploadLinks: true })).not.toContain(marker); + }); +}); + describe('the skill teaches the file tools exactly where they register', () => { it('names both for a host that carries them, and each only for the scope that registers it', () => { const all = renderSkillMarkdown({ fileTools: true }); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 04173a96357..ecfd77e409e 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3363,6 +3363,16 @@ export function registerFileTools( if (canWrite && typeof bridge.createUploadLink === 'function') { const linkFn = bridge.createUploadLink.bind(bridge); + // [#32686] Ruling A: a link for a file field of a record not yet created, + // where the bridge serves it. + const newRecordLinkFn = + typeof bridge.createUploadLinkForNewRecord === 'function' ? bridge.createUploadLinkForNewRecord.bind(bridge) : undefined; + // `recordId` is optional exactly where a link can name no record, so the + // listed schema says what the handler takes; the handler reads it as + // possibly absent either way. + const uploadLinkRecordId: z.ZodType = newRecordLinkFn + ? z.string().optional().describe(`${RECORD_ID_DESCRIPTION} Omit it for a record not yet created (with field).`) + : z.string().describe(RECORD_ID_DESCRIPTION); server.registerTool( note('create_upload_link'), { @@ -3373,7 +3383,14 @@ export function registerFileTools( 'only, and expires (see expiresAt). The upload is stored as the user, so they must be able to edit the ' + 'record (and the field): a record a pending approval locks, a read-only field, or a field read-only on ' + 'this record in its current state (readonlyWhen), gets no link, and an ' + - 'upload the field cannot take when it arrives is refused with the reason, attaching nothing.', + 'upload the field cannot take when it arrives is refused with the reason, attaching nothing.' + + (newRecordLinkFn + ? ' For a record you have not created yet (a required file field), omit recordId and name the field: ' + + 'the user must be able to create such records, and the answer carries fileIds, the id(s) the upload ' + + 'is stored under. Once the user has uploaded, create the record with the field set to fileIds[0] ' + + '(the array, for a multi-file field). The id works only for this user\'s own write into that field ' + + 'of that object, in one record, within an hour of the upload.' + : ''), inputSchema: strictToolInput( { surface: 'this create_upload_link call', @@ -3387,7 +3404,7 @@ export function registerFileTools( }, { objectName: z.string().describe('The object/table name'), - recordId: z.string().describe(RECORD_ID_DESCRIPTION), + recordId: uploadLinkRecordId, field: z.string().optional().describe('A file or image field of the record the upload fills'), attachments: z .literal(true) @@ -3403,6 +3420,34 @@ export function registerFileTools( if ((field === undefined) === (attachments === undefined)) { return errorResult('Say where the upload lands: either field (a file field of the record) or attachments: true.'); } + if (recordId === undefined) { + // [#32686] No record yet: a file field only, where the bridge serves it. + if (field === undefined) { + return errorResult( + 'An attachment needs its record: create the record first, then ask for a link with its recordId. ' + + 'For a file field of a record not yet created, name the field instead.', + ); + } + if (!newRecordLinkFn) return errorResult('recordId is required: name the record the upload lands on.'); + try { + const link = await newRecordLinkFn(objectName, { field }); + return textResult({ + url: link.url, + expiresAt: link.expiresAt, + singleUse: true, + objectName, + field, + fileIds: link.fileIds, + instructions: + 'Give this link to the user to open in a browser where they are signed in to this deployment, and ' + + 'pick the file. It works only for them, once, until expiresAt. Once they have uploaded, create the ' + + `record with ${field} set to fileIds[0] (the array, for a multi-file field). Before the upload, ` + + 'that create is refused as an upload that never completed.', + }); + } catch (err) { + return errorResultWithCode(err); + } + } try { const target = field !== undefined ? { field } : { attachments: true as const }; const link = await linkFn(objectName, recordId, target); diff --git a/packages/mcp/src/skill-md.ts b/packages/mcp/src/skill-md.ts index 791bac50d4c..20f890459b2 100644 --- a/packages/mcp/src/skill-md.ts +++ b/packages/mcp/src/skill-md.ts @@ -109,6 +109,14 @@ export interface RenderSkillOptions { * see the bridge, so the host says so. */ fileTools?: boolean; + /** + * [#32686] Whether the host's bridge also serves an upload link for a + * record not yet created (`createUploadLinkForNewRecord`), so + * `create_upload_link` takes no `recordId` with a `field`. Renders only + * with `create_upload_link`'s own entry ({@link fileTools}, `data:write`). + * Default false: the renderer cannot see the bridge, so the host says so. + */ + newRecordUploadLinks?: boolean; /** * [ADR-0149 D2] Whether the host's bridge carries the dataset pair * (`list_datasets` / `query_dataset`, `registerDatasetTools`). The entries, @@ -220,6 +228,21 @@ const UPLOAD_LINK_TOOL_LINES = `- **create_upload_link({ objectName, recordId, f as the user, so they must be able to edit the record. `; +/** + * [#32686] The two-call flow for a record whose file field must be filled + * when it is created, rendered under `create_upload_link`'s entry where the + * bridge serves a link with no record. + */ +const NEW_RECORD_UPLOAD_LINK_LINES = ` For a record you have not created yet (a required file field, such as an + expense line's invoice), omit \`recordId\` and name \`field\`: the answer + carries \`fileIds\`. Once the user has uploaded, call \`create_record\` with + the field set to \`fileIds[0]\` (the array, for a multi-file field); before + the upload, that create is refused as an upload that never completed. The + id goes only into that field of that object, in one record, by this + user's own write, within an hour of the upload. The user must be able to + create such records. +`; + /** * [ADR-0149 D2/D3] The dataset pair's entries and the selection rule that * tells a client when a governed metric answers instead of an object query. @@ -267,7 +290,10 @@ function renderFileToolLines(options: RenderSkillOptions): string { // Mirrors the gates in `registerFileTools` (`!scopes || scopes.includes(…)`). const read = !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_READ); const write = !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_WRITE); - return (read ? READ_FILE_TOOL_LINES : '') + (write ? UPLOAD_LINK_TOOL_LINES : ''); + return ( + (read ? READ_FILE_TOOL_LINES : '') + + (write ? UPLOAD_LINK_TOOL_LINES + (options.newRecordUploadLinks === true ? NEW_RECORD_UPLOAD_LINK_LINES : '') : '') + ); } /** diff --git a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts index ab4e9f10c36..4349e42c396 100644 --- a/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-mcp-record-files.dogfood.test.ts @@ -30,6 +30,13 @@ // nothing and keeps no file — never "attached" for a change the engine // ignored. // +// [#32686] And a record that cannot be created without its file: an extra +// object, `dogfood_expense_line`, whose `invoice` file field is required. The +// agent asks for a link naming the object and the field (no record), the +// member uploads through it, and the agent's `create_record` names the file id +// the link answered: two agent calls and one upload, over the real +// `/api/v1/mcp` and the real upload-link route. +// // Not eligible for the shared showcase project: it boots its own plugins. import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; @@ -69,12 +76,15 @@ const memberSet = PermissionSetSchema.parse({ showcase_invoice_line: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, sys_attachment: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, dogfood_upload_claim: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, + dogfood_expense_line: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, }, rowLevelSecurity: [RLS.ownerPolicy('showcase_invoice', 'created_by')], }); /** [#32734] An expense claim whose invoices lock once it is approved. */ const UPLOAD_CLAIM = 'dogfood_upload_claim'; +/** [#32686] An expense line whose e-invoice is required. */ +const EXPENSE_LINE = 'dogfood_expense_line'; const uploadClaimApp = { name: 'com.dogfood.upload-claim', type: 'standard' as const, @@ -95,6 +105,15 @@ const uploadClaimApp = { status: { type: 'text', label: 'Status' }, invoices: { type: 'file', label: 'Invoices', multiple: true, readonlyWhen: "record.status == 'approved'" }, }, + }, { + // [#32686] An expense line that cannot be saved without its e-invoice. + name: EXPENSE_LINE, + label: 'Expense Line', + fields: { + invoice_no: { type: 'text', label: 'Invoice No.' }, + amount: { type: 'number', label: 'Amount' }, + invoice: { type: 'file', label: 'E-invoice', required: true }, + }, }], }); }, @@ -496,4 +515,86 @@ describe('[#30892] showcase: an agent reads and attaches a record\'s files over ); }); }); + + // [#32686] Ruling A: an agent creates a record whose file field is + // required. The link names the object and the field, no record; the member + // uploads; the create names the file id the link answered. + describe('[#32686] a required file field, filled when the record is created (`dogfood_expense_line.invoice`)', () => { + const lineOf = (id: string) => ql.findOne(EXPENSE_LINE, { where: { id }, ...SYS }); + const invoiceOf = async (id: string): Promise => { + const value = (await lineOf(id))?.invoice; + return value == null ? null : String(typeof value === 'object' ? value.id : value); + }; + + it('two agent calls and one upload: create_upload_link with no record, the upload, create_record naming fileIds[0]', async () => { + // Without the file the line cannot be created: the precondition the card measures. + const missing = await refused(memberToken, 'create_record', { objectName: EXPENSE_LINE, data: { invoice_no: 'FP-0001', amount: 88 } }); + expect(JSON.stringify(missing), 'the required e-invoice refuses the create').toContain('invoice'); + + // Agent call 1: a link for the field of a record not yet created. + const { path, answer } = await mint({ objectName: EXPENSE_LINE, field: 'invoice' }); + expect(answer).toMatchObject({ singleUse: true, objectName: EXPENSE_LINE, field: 'invoice' }); + expect(answer).not.toHaveProperty('recordId'); + expect(answer.fileIds).toHaveLength(1); + const [fileId] = answer.fileIds as string[]; + + // The browser: the page the member opens says what is wanted and that + // the file will be received (no record holds it yet), and names nothing. + const page = await open(path); + expect(page.status).toBe(200); + const html = await page.text(); + expect(html).toContain('The file was received'); + expect(html).not.toContain(EXPENSE_LINE); + expect(html).not.toContain(MEMBER_EMAIL); + + // The upload, as the page's script sends it. + const pdf = minimalPdf('E-invoice FP-0001'); + const res = await put(path, pdf, { 'x-file-name': 'fp-0001.pdf' }); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data).toEqual({ fileId, size: pdf.length, field: 'invoice' }); + expect(await fileRow(fileId)).toMatchObject({ status: 'committed', size: pdf.length, ref_id: null, name: 'fp-0001.pdf' }); + + // Agent call 2: the create names the file id; the record holds the file. + const { json } = await ok(memberToken, 'create_record', { + objectName: EXPENSE_LINE, + data: { invoice_no: 'FP-0001', amount: 88, invoice: fileId }, + }); + const lineId = String(json.id ?? json.record?.id); + expect(await invoiceOf(lineId)).toBe(fileId); + expect(await fileRow(fileId)).toMatchObject({ ref_object: EXPENSE_LINE, ref_id: lineId, ref_field: 'invoice' }); + + // read_file reads it back through the record, as for any record's file. + const read = await ok(memberToken, 'read_file', { objectName: EXPENSE_LINE, recordId: lineId, field: 'invoice' }); + expect(read.content.map((c: any) => c.text ?? '').join('\n')).toContain('E-invoice FP-0001'); + }); + + it('another user\'s create naming the member\'s upload is refused as a file they cannot open, and the file stays unclaimed', async () => { + const { path, answer } = await mint({ objectName: EXPENSE_LINE, field: 'invoice' }); + const [fileId] = answer.fileIds as string[]; + expect((await put(path, minimalPdf('E-invoice FP-0002'), { 'x-file-name': 'fp-0002.pdf' })).status).toBe(200); + + const error = await refused(adminToken, 'create_record', { objectName: EXPENSE_LINE, data: { invoice_no: 'FP-0002', invoice: fileId } }); + expect(JSON.stringify(error)).toContain('it is not a file you can open'); + expect(await fileRow(fileId)).toMatchObject({ status: 'committed', ref_id: null }); + // Nor can that user download it while no record holds it. + const download = await stack.apiAs(adminToken, 'GET', `/storage/files/${fileId}/url`); + const downloadBody: any = await download.json(); + expect(download.status, JSON.stringify(downloadBody)).toBe(403); + expect(downloadBody.error?.code).toBe('FILE_DOWNLOAD_DENIED'); + + // The member's own create still takes it. + const { json } = await ok(memberToken, 'create_record', { objectName: EXPENSE_LINE, data: { invoice_no: 'FP-0002', invoice: fileId } }); + expect(await invoiceOf(String(json.id ?? json.record?.id))).toBe(fileId); + }); + + it('a member who cannot create the object gets no link: the create verdict refuses it before anything is reserved', async () => { + const linksBefore = (await ql.find('sys_file', { where: { name: 'upload-link', status: 'pending' }, ...SYS })).length; + // `showcase_task` is not in the member's set; its `cover` is an image field. + const error = await refused(memberToken, 'create_upload_link', { objectName: 'showcase_task', field: 'cover' }); + expect(error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(error.message).toBe('You cannot upload a file for a new showcase_task: you cannot create showcase_task records.'); + expect((await ql.find('sys_file', { where: { name: 'upload-link', status: 'pending' }, ...SYS })).length).toBe(linksBefore); + }); + }); }); diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index db6c35ea19d..0ab4d2977d6 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -275,10 +275,14 @@ export async function handleMcpSkillRequest(deps: DomainHandlerDeps, method: str } // [#30892] The file pair is taught where the bridge would carry it. - const fileTools = (await resolveMcpRecordFileService(deps, context)) !== undefined; + const recordFiles = await resolveMcpRecordFileService(deps, context); + const fileTools = recordFiles !== undefined; + // [#32686] …and the upload link for a record not yet created, where the + // storage plugin serves it. + const newRecordUploadLinks = typeof recordFiles?.createUploadLinkForNewRecordAs === 'function'; // [ADR-0149 D2] …and the dataset pair, with the D3 selection rule. const datasetTools = (await resolveMcpDatasetToolsService(deps, context)) !== undefined; - const markdown: string = mcp.renderSkill({ mcpUrl, fileTools, datasetTools }); + const markdown: string = mcp.renderSkill({ mcpUrl, fileTools, newRecordUploadLinks, datasetTools }); // Raw text must NOT ride the `response` channel — `sendResult` JSON- // encodes those bodies unconditionally. The `result` stream channel is // the one raw pipe through every adapter (string events are written @@ -1371,6 +1375,16 @@ export interface McpRecordFileService { target: { field: string } | { attachments: true }, context: unknown, ): Promise<{ path: string; expiresAt: string }>; + /** + * [#32686] A link for a file field of a record not yet created, with the + * file id(s) the upload is stored under. Optional: a storage plugin that + * predates it serves links for existing records only. + */ + createUploadLinkForNewRecordAs?( + object: string, + target: { field: string }, + context: unknown, + ): Promise<{ path: string; expiresAt: string; fileIds: string[] }>; } /** @@ -1455,6 +1469,8 @@ function recordFileMembers( }); } }; + const newRecordLinkAs = + typeof service.createUploadLinkForNewRecordAs === 'function' ? service.createUploadLinkForNewRecordAs.bind(service) : undefined; return { listRecordFiles: async (object: string, recordId: string) => { await readRecordFirst(object, recordId); @@ -1479,6 +1495,20 @@ function recordFileMembers( const grant = await service.createUploadLinkAs(object, recordId, target, ec); return { url: absoluteUrl(grant.path, await publicOrigin(deps, context)), expiresAt: grant.expiresAt }; }, + // [#32686] No record to read first: the storage service asks the + // object's create verdict and the field's writability for the caller. + ...(newRecordLinkAs + ? { + createUploadLinkForNewRecord: async (object: string, target: { field: string }) => { + const grant = await newRecordLinkAs(object, target, ec); + return { + url: absoluteUrl(grant.path, await publicOrigin(deps, context)), + expiresAt: grant.expiresAt, + fileIds: [...grant.fileIds], + }; + }, + } + : {}), }; } diff --git a/packages/runtime/src/mcp-record-file-bridge.test.ts b/packages/runtime/src/mcp-record-file-bridge.test.ts index 4a0d6e2acce..55fbeec9fad 100644 --- a/packages/runtime/src/mcp-record-file-bridge.test.ts +++ b/packages/runtime/src/mcp-record-file-bridge.test.ts @@ -94,6 +94,28 @@ describe('#30892 — the MCP bridge\'s file members', () => { expect(link).toEqual({ url: 'https://acme.test/api/v1/storage/upload-links/id.secret', expiresAt: '2026-11-06T12:10:00.000Z' }); }); + it('[#32686] answers a link for a record not yet created as an absolute URL with its file ids, reading no record', async () => { + const { service, ctx, deps, protocol } = harness(); + const withNew = { + ...service, + createUploadLinkForNewRecordAs: vi.fn(async () => ({ + path: '/api/v1/storage/upload-links/f9.secret', + expiresAt: '2026-11-13T12:10:00.000Z', + fileIds: ['f9'], + })), + } satisfies McpRecordFileService; + const bridge = buildMcpBridge(deps, ctx, { recordFiles: withNew }); + const link = await bridge.createUploadLinkForNewRecord!('expense_line', { field: 'invoice' }); + expect(withNew.createUploadLinkForNewRecordAs).toHaveBeenCalledWith('expense_line', { field: 'invoice' }, EC); + expect(link).toEqual({ url: 'https://acme.test/api/v1/storage/upload-links/f9.secret', expiresAt: '2026-11-13T12:10:00.000Z', fileIds: ['f9'] }); + expect(protocol.getData).not.toHaveBeenCalled(); + }); + + it('[#32686] a storage service without it gives the bridge no such member', () => { + const { service, ctx, deps } = harness(); + expect(buildMcpBridge(deps, ctx, { recordFiles: service }).createUploadLinkForNewRecord).toBeUndefined(); + }); + it('a bridge built without the seam carries no file member, so neither tool is listed', () => { const { ctx, deps } = harness(); const bridge = buildMcpBridge(deps, ctx); diff --git a/packages/services/service-storage/src/file-attachment-service.ts b/packages/services/service-storage/src/file-attachment-service.ts index 4913e391018..1b2c8e123d5 100644 --- a/packages/services/service-storage/src/file-attachment-service.ts +++ b/packages/services/service-storage/src/file-attachment-service.ts @@ -57,6 +57,8 @@ import { type UploadLinkGrant, type UploadLinkOutcome, type UploadLinkTarget, + type NewRecordUploadLinkGrant, + type NewRecordUploadLinkTarget, type UploadLinkUpload, type UploadLinkView, } from './record-file-access.js'; @@ -361,6 +363,14 @@ export class FileAttachmentService return this.recordFilesOrRefuse().createUploadLinkAs(object, recordId, target, context); } + async createUploadLinkForNewRecordAs( + object: string, + target: NewRecordUploadLinkTarget, + context: ExecutionContext, + ): Promise { + return this.recordFilesOrRefuse().createUploadLinkForNewRecordAs(object, target, context); + } + async inspectUploadLink(token: string, callerUserId: string): Promise { return this.recordFilesOrRefuse().inspectUploadLink(token, callerUserId); } diff --git a/packages/services/service-storage/src/file-reference-lifecycle.ts b/packages/services/service-storage/src/file-reference-lifecycle.ts index 3728282f17e..ae59cb38c22 100644 --- a/packages/services/service-storage/src/file-reference-lifecycle.ts +++ b/packages/services/service-storage/src/file-reference-lifecycle.ts @@ -13,6 +13,11 @@ import { unreadableFileMessage, type FileReferenceReadAuthorizer, } from './referenceable-file.js'; +import { + PRE_RECORD_CLAIM_WINDOW_SECONDS, + preRecordReferenceRefusal, + type PreRecordReferenceRefusal, +} from './pre-record-upload.js'; export type { FileReferenceReadAuthorizer } from './referenceable-file.js'; @@ -93,6 +98,20 @@ export type { FileReferenceReadAuthorizer } from './referenceable-file.js'; * and keep any other id as written; neither is a file the anonymous caller * may provide. An empty or absent file field is written as before. * + * ### A file uploaded before its record goes into one slot + * + * [#32686] An upload link that names an object and a file field but no + * record (ruling A) answers a file id the agent writes when it creates the + * record. The file carries a binding (`pre-record-upload.ts`): its uploader, + * the object and field, and a deadline. Asked after the read check, before + * the completed-upload check: while no record holds the file, only the + * uploader's write into that object and field, before the deadline, takes + * it; once a record holds it, no user's write puts it in a second record + * until the deadline. Every refusal is one `invalid_value` entry at the + * field, and a writer who is not the uploader gets the unreadable-file words. + * Once a record has let the file go, the binding no longer applies: the file + * is that record's released file, judged as the section below says. + * * ### A released file keeps its record's rule * * [#26046] Releasing a file clears its ownership columns, and the download @@ -337,6 +356,40 @@ function refuseIncompleteUpload( }; } +/** The user a write runs as, or `null` for a system or context-less write. */ +function writerUserIdOf(caller: ExecutionContext | null): string | null { + return caller && typeof caller.userId === 'string' && caller.userId.length > 0 ? caller.userId : null; +} + +/** + * [#32686] The refusal of a field naming a file uploaded before its record + * exists, by the file's own uploader, for a slot it may not go into: it was + * uploaded for another field, it is in another record already, or its time to + * be used ran out. The writer is the uploader, so it names the file and the + * remedy. (Any other writer gets {@link refuseUnreadableFile}.) + */ +function refusePreRecordFile( + engine: FileReferenceEngine, + object: string, + field: string, + fileId: string, + refusal: Exclude, +): FileFieldRefusal { + const label = fieldLabelOf(engine, object, field); + const why = + refusal.kind === 'other_slot' + ? `it was uploaded through an upload link for ${refusal.object}.${refusal.field}, and goes into that field only` + : refusal.kind === 'spent' + ? 'it was uploaded through an upload link and is already in another record; a file from an upload link goes into one record' + : `it was uploaded through an upload link, and no record took it within ${PRE_RECORD_CLAIM_WINDOW_SECONDS / 60} minutes of the upload`; + return { + field, + code: 'invalid_value', + message: `${label} cannot reference file ${fileId}: ${why}. Ask for a new upload link for this field and upload the file again.`, + label, + }; +} + /** * [#25694] Ruling C at every anonymous write door: an anonymous write carries * no file. A file is provided by a signed-in caller, through the authenticated @@ -572,7 +625,7 @@ function matchesAcceptEntry(entry: string, mime: string, name: string): boolean * `mime_type` cannot fail an `accept` test, and one with no `size` cannot fail * `maxSize`. Missing metadata is not evidence of a violation. */ -function assertFileConstraints( +export function assertFileConstraints( fieldDef: any, field: string, file: Record, @@ -753,6 +806,7 @@ async function applyCopyOnClaim( const rows: Array<[string, Record]> = []; const incomplete: string[] = []; let fieldRefused = false; + let boundRefusal: FileFieldRefusal | null = null; for (const token of [...new Set(tokens)]) { const found = await findReferenceableFile(engine, token, organizationId, caller, authorizeRead); // [#26043] A file this write's caller may not read, or one the acting @@ -766,14 +820,29 @@ async function applyCopyOnClaim( // (`systemReadContext`). Left verbatim — the read resolver ignores it // for the same reason. if (!found) continue; + const held = recordId !== null && isSameSlot(found, object, recordId, field); + // [#32686] A file uploaded before its record exists goes only into the + // slot it was uploaded for, by its uploader's write, in time — asked + // after the read check, so a file the caller may not read is refused + // with that check's words above. Another writer is answered in the same + // words, so the refusal says nothing about whose upload it is. + const bound = preRecordReferenceRefusal(found, { object, field, heldHere: held }, writerUserIdOf(caller), Date.now()); + if (bound?.kind === 'not_yours') { + fieldRefused = true; + break; + } + if (bound) { + boundRefusal = refusePreRecordFile(engine, object, field, token, bound); + break; + } // [#26479] A file the caller may read, whose upload never completed — // unless this slot already holds it (an update rewriting the value it // has), which claims nothing. - const held = recordId !== null && isSameSlot(found, object, recordId, field); if (caller && !held && !isCompletedUpload(found)) incomplete.push(token); else rows.push([token, found]); } if (fieldRefused) refused.push(refuseUnreadableFile(engine, object, field)); + else if (boundRefusal) refused.push(boundRefusal); else if (incomplete.length > 0) refused.push(refuseIncompleteUpload(engine, object, field, incomplete)); else if (rows.length > 0) named.push({ field, value, rows }); } diff --git a/packages/services/service-storage/src/pre-record-upload.test.ts b/packages/services/service-storage/src/pre-record-upload.test.ts new file mode 100644 index 00000000000..ad3125c70e4 --- /dev/null +++ b/packages/services/service-storage/src/pre-record-upload.test.ts @@ -0,0 +1,165 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32686] The binding a file uploaded before its record carries, judged on + * its own: which write may put it in a field, and who may read it while no + * record holds it. The doors that ask it are pinned end to end in + * `record-file-access.integration.test.ts`; there, another user's write is + * refused twice over (the read check denies first), so each arm of the rule + * is pinned here alone. + */ + +import { describe, it, expect } from 'vitest'; +import { + PRE_RECORD_UPLOAD_KIND, + isUploaderOnlyFile, + preRecordBindingMetadata, + preRecordBindingOf, + preRecordReferenceRefusal, +} from './pre-record-upload.js'; + +const NOW = Date.parse('2026-11-13T12:00:00.000Z'); +const LATER = '2026-11-13T13:00:00.000Z'; +const EARLIER = '2026-11-13T11:00:00.000Z'; + +function bound(over: Partial> = {}, claimUntil = LATER): Record { + return { + id: 'f1', + owner_id: 'u1', + status: 'committed', + ref_object: null, + ref_id: null, + ref_field: null, + metadata: preRecordBindingMetadata({ + kind: PRE_RECORD_UPLOAD_KIND, + object: 'expense_line', + field: 'invoice', + user_id: 'u1', + organization_id: 'o1', + claim_until: claimUntil, + }), + ...over, + }; +} + +const SLOT = { object: 'expense_line', field: 'invoice', heldHere: false }; + +describe('preRecordReferenceRefusal — a file no record holds yet', () => { + it('admits its uploader\'s write into its slot within the window', () => { + expect(preRecordReferenceRefusal(bound(), SLOT, 'u1', NOW)).toBeNull(); + }); + + it('refuses another user, answered as a file they cannot open', () => { + expect(preRecordReferenceRefusal(bound(), SLOT, 'u2', NOW)).toEqual({ kind: 'not_yours' }); + }); + + it('refuses a system or context-less write: it names no user whose upload this is', () => { + expect(preRecordReferenceRefusal(bound(), SLOT, null, NOW)).toEqual({ kind: 'not_yours' }); + }); + + it('refuses the uploader\'s write into another field or object, naming the slot it was uploaded for', () => { + const slot = { kind: 'other_slot', object: 'expense_line', field: 'invoice' }; + expect(preRecordReferenceRefusal(bound(), { ...SLOT, field: 'receipt' }, 'u1', NOW)).toEqual(slot); + expect(preRecordReferenceRefusal(bound(), { ...SLOT, object: 'claim' }, 'u1', NOW)).toEqual(slot); + }); + + it('refuses the uploader\'s write after the window', () => { + expect(preRecordReferenceRefusal(bound({}, EARLIER), SLOT, 'u1', NOW)).toEqual({ kind: 'expired' }); + // The deadline itself is past. + expect(preRecordReferenceRefusal(bound(), SLOT, 'u1', Date.parse(LATER))).toEqual({ kind: 'expired' }); + }); + + it('a damaged binding is bound to nobody: every write is refused', () => { + const damaged = bound({ metadata: JSON.stringify({ kind: PRE_RECORD_UPLOAD_KIND, object: 'expense_line' }) }); + expect(preRecordBindingOf(damaged)).toMatchObject({ user_id: '', field: '', claim_until: '' }); + expect(preRecordReferenceRefusal(damaged, SLOT, 'u1', NOW)).toEqual({ kind: 'not_yours' }); + }); +}); + +describe('preRecordReferenceRefusal — a file a record holds', () => { + const held = bound({ ref_object: 'expense_line', ref_id: 'r1', ref_field: 'invoice' }); + + it('within the window, no user\'s write puts it in a second record', () => { + expect(preRecordReferenceRefusal(held, SLOT, 'u1', NOW)).toEqual({ kind: 'spent' }); + expect(preRecordReferenceRefusal(held, SLOT, 'u2', NOW)).toEqual({ kind: 'not_yours' }); + }); + + it('the slot that holds it rewriting its own value takes nothing, and is admitted', () => { + expect(preRecordReferenceRefusal(held, { ...SLOT, heldHere: true }, 'u1', NOW)).toBeNull(); + }); + + it('a system write, or any write after the window, is judged as for any file a record holds', () => { + expect(preRecordReferenceRefusal(held, SLOT, null, NOW)).toBeNull(); + expect(preRecordReferenceRefusal(held, SLOT, 'u2', Date.parse(LATER) + 1)).toBeNull(); + }); +}); + +describe('preRecordReferenceRefusal — a file a record held and let go (#26046)', () => { + const letGo = bound({ released_ref_object: 'expense_line', released_ref_id: 'r1' }); + + it('is that record\'s released file: the binding refuses no write, within the window or after it', () => { + expect(preRecordReferenceRefusal(letGo, SLOT, 'u1', NOW)).toBeNull(); + expect(preRecordReferenceRefusal(letGo, SLOT, 'u2', NOW)).toBeNull(); + expect(preRecordReferenceRefusal(letGo, SLOT, null, NOW)).toBeNull(); + expect(preRecordReferenceRefusal(letGo, { ...SLOT, field: 'receipt' }, 'u1', NOW)).toBeNull(); + expect(preRecordReferenceRefusal(letGo, SLOT, 'u1', Date.parse(LATER) + 1)).toBeNull(); + }); + + it('and is not uploader-only: the download doors read it by the releasing record\'s rule', () => { + expect(isUploaderOnlyFile(letGo)).toBe(false); + }); +}); + +describe('preRecordReferenceRefusal — the pending row a link with no record reserved, before the upload', () => { + const reserved = { + id: 'f1', + owner_id: 'u1', + status: 'pending', + ref_id: null, + metadata: JSON.stringify({ kind: 'upload_link', target: 'field', object: 'expense_line', field: 'invoice' }), + }; + + it('refuses a system or context-less write and another user, as a file they cannot open', () => { + expect(preRecordReferenceRefusal(reserved, SLOT, null, NOW)).toEqual({ kind: 'not_yours' }); + expect(preRecordReferenceRefusal(reserved, SLOT, 'u2', NOW)).toEqual({ kind: 'not_yours' }); + }); + + it('leaves its uploader\'s write to the incomplete-upload check', () => { + expect(preRecordReferenceRefusal(reserved, SLOT, 'u1', NOW)).toBeNull(); + }); + + it('says nothing about a link row for a record', () => { + const recordLink = { ...reserved, metadata: JSON.stringify({ kind: 'upload_link', target: 'field', record_id: 'r1', field: 'invoice' }) }; + expect(preRecordReferenceRefusal(recordLink, SLOT, null, NOW)).toBeNull(); + }); +}); + +describe('a file with no binding', () => { + it('is judged as before, by every write and door', () => { + const plain = { id: 'f2', owner_id: 'u1', status: 'committed', ref_id: null, metadata: null }; + expect(preRecordBindingOf(plain)).toBeNull(); + expect(preRecordReferenceRefusal(plain, SLOT, 'u2', NOW)).toBeNull(); + expect(isUploaderOnlyFile(plain)).toBe(false); + // Metadata of another kind, even naming the word, is no binding. + const other = { ...plain, metadata: JSON.stringify({ note: PRE_RECORD_UPLOAD_KIND }) }; + expect(preRecordBindingOf(other)).toBeNull(); + expect(isUploaderOnlyFile(other)).toBe(false); + }); +}); + +describe('isUploaderOnlyFile — read only by its uploader while no record holds it', () => { + it('a bound file no record holds', () => { + expect(isUploaderOnlyFile(bound())).toBe(true); + }); + + it('the pending row a link with no record reserved as its file', () => { + const link = { id: 'f1', ref_id: null, metadata: JSON.stringify({ kind: 'upload_link', target: 'field', object: 'expense_line', field: 'invoice' }) }; + expect(isUploaderOnlyFile(link)).toBe(true); + }); + + it('not a link for a record, nor a bound file once a record holds it', () => { + const recordLink = { id: 'l1', ref_id: null, metadata: JSON.stringify({ kind: 'upload_link', target: 'field', record_id: 'r1', field: 'invoice' }) }; + expect(isUploaderOnlyFile(recordLink)).toBe(false); + expect(isUploaderOnlyFile(bound({ ref_object: 'expense_line', ref_id: 'r1', ref_field: 'invoice' }))).toBe(false); + }); +}); diff --git a/packages/services/service-storage/src/pre-record-upload.ts b/packages/services/service-storage/src/pre-record-upload.ts new file mode 100644 index 00000000000..05cd50e78b4 --- /dev/null +++ b/packages/services/service-storage/src/pre-record-upload.ts @@ -0,0 +1,226 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32686] A file uploaded before its record exists, and the binding that + * decides which write may take it. + * + * An agent cannot create a record whose file field is required: the record + * needs the file, and an upload link used to need the record. So an upload + * link can name an object and a file field with no record (ruling A): the + * agent hands the link to its user, the user uploads, and the agent creates + * the record naming the file id the link answered — the order the console's + * own form uses (upload, then save). The `required` rule is not touched. + * + * Such a file is a committed `sys_file` row owned by the uploader, which no + * record holds yet. What makes it different from any other unclaimed upload + * is the binding its `metadata` carries, written when the bytes land + * (`record-file-access.ts`): the user, the object, the file field, the + * organization and the deadline for using it. The binding is read in two + * places, both asking this module: + * + * - **A record write naming the file** (`file-reference-lifecycle.ts`, + * before the driver runs): {@link preRecordReferenceRefusal}. While no + * record holds it, only a write by the bound user, on the bound object and + * field, before the deadline, may take it; another user, a system or + * context-less write, another object or field, or a write after the + * deadline is refused at the field. Once a record holds it, no user's + * write puts it in a second record until the deadline; after that it is + * that record's file like any other. + * - **The download doors** (`storage-service-plugin.ts`): while no record + * has held it, only its uploader may read it. The deadline does not change + * that. + * + * The binding governs only until a record has held the file. A record that + * lets it go (its field cleared or replaced, or the record deleted) leaves + * `released_ref_*` on the row (#26046), and from then on the binding is + * ignored: the file is that record's released file, read by that record's + * rule and taken again by whoever may read it, exactly as any other. The + * binding itself is never rewritten, so it records what the upload was for. + * + * Before the upload, the id the link answered is the link's own `pending` + * row. No write takes it but its uploader's own, which the incomplete-upload + * check refuses until the upload completes. + * + * Every value is a string because `sys_file.metadata` is a JSON object of + * strings. No secret is kept: the link's own secret is gone once it is used. + */ + +import { UPLOAD_LINK_KIND } from './upload-link-wire.js'; + +/** The marker a bound file's `metadata` carries, so no other row reads as one. */ +export const PRE_RECORD_UPLOAD_KIND = 'pre_record_upload'; + +/** + * How long after the upload the file may be put in its field, in seconds: one + * hour. Long enough for the agent to read the file and create the record in + * the same conversation; short enough that an id left in a transcript is + * soon worth nothing. + */ +export const PRE_RECORD_CLAIM_WINDOW_SECONDS = 60 * 60; + +/** What a file uploaded before its record is bound to. */ +export interface PreRecordUploadBinding { + kind: typeof PRE_RECORD_UPLOAD_KIND; + /** The object whose record may take the file. */ + object: string; + /** The file field it may go into. */ + field: string; + /** The user who uploaded it, and the only one whose write may use it. */ + user_id: string; + /** The organization the link was issued in, when there was one. */ + organization_id?: string; + /** Until when a write may put it in its field (ISO 8601). */ + claim_until: string; +} + +function nonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} + +/** `sys_file.metadata` for a binding. */ +export function preRecordBindingMetadata(binding: PreRecordUploadBinding): string { + return JSON.stringify({ + kind: binding.kind, + object: binding.object, + field: binding.field, + user_id: binding.user_id, + ...(binding.organization_id !== undefined ? { organization_id: binding.organization_id } : {}), + claim_until: binding.claim_until, + }); +} + +/** + * The binding a `sys_file` row carries, or `null` when it carries none (every + * file not uploaded through a link that named no record). A row whose + * metadata names the kind but not every value is answered as bound to nobody + * — no user, object or deadline that any write can meet — so a damaged + * binding refuses rather than reading as an ordinary file. + */ +export function preRecordBindingOf(row: Record | null | undefined): PreRecordUploadBinding | null { + const raw = row?.metadata; + if (typeof raw !== 'string' || !raw.includes(PRE_RECORD_UPLOAD_KIND)) return null; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return null; + } + const s = parsed as Partial | null; + if (!s || typeof s !== 'object' || s.kind !== PRE_RECORD_UPLOAD_KIND) return null; + return { + kind: PRE_RECORD_UPLOAD_KIND, + object: nonEmptyString(s.object) ? s.object : '', + field: nonEmptyString(s.field) ? s.field : '', + user_id: nonEmptyString(s.user_id) ? s.user_id : '', + ...(nonEmptyString(s.organization_id) ? { organization_id: s.organization_id } : {}), + claim_until: nonEmptyString(s.claim_until) ? s.claim_until : '', + }; +} + +/** Whether no record's field holds the file now. */ +function unheld(row: Record): boolean { + return row.ref_id == null || row.ref_id === ''; +} + +/** + * Whether a record held the file and let it go (#26046: `releaseOwnership` + * keeps the record, `claimFile` clears it when another record takes the + * file). A released file is that record's file to judge, never the upload's. + */ +function released(row: Record): boolean { + return nonEmptyValue(row.released_ref_id) || nonEmptyValue(row.released_ref_object); +} + +function nonEmptyValue(value: unknown): boolean { + return value != null && value !== ''; +} + +/** Whether no record holds the file now and none has held it since the upload. */ +function neverHeld(row: Record): boolean { + return unheld(row) && !released(row); +} + +/** + * Whether `row` is an open or spent upload link that names no record: the + * `pending` row a link without a record reserves as its file (its id is the + * file id the link answered), before the upload turns it into the file. + */ +function isPreRecordLinkRow(row: Record): boolean { + const raw = row.metadata; + if (typeof raw !== 'string' || !raw.includes(UPLOAD_LINK_KIND)) return false; + try { + const s = JSON.parse(raw) as Record | null; + return !!s && s.kind === UPLOAD_LINK_KIND && s.target === 'field' && !nonEmptyString(s.record_id); + } catch { + return false; + } +} + +/** + * Whether a file uploaded before its record, or the row its link reserved, + * is read only by its uploader now: while no record has held it. The download + * doors ask this after their uploader arm, so a `true` here means "deny + * everyone else". Every other file, a released one included, is judged as + * before. + */ +export function isUploaderOnlyFile(row: Record): boolean { + return neverHeld(row) && (preRecordBindingOf(row) !== null || isPreRecordLinkRow(row)); +} + +/** Why a write may not put a bound file in a field. */ +export type PreRecordReferenceRefusal = + /** The writer is not the uploader (or there is no writer): answered as a file they cannot open. */ + | { kind: 'not_yours' } + /** The uploader's own write, into a slot the file was not uploaded for. */ + | { kind: 'other_slot'; object: string; field: string } + /** The uploader's own write, with the file already in another record within its window. */ + | { kind: 'spent' } + /** The uploader's own write, after the deadline, with no record holding it. */ + | { kind: 'expired' }; + +/** + * May this write put `row` (a file it names) into `object`.`field`? `null` + * admits it, or says nothing about it (a file with no binding, or one a + * record has let go); otherwise the reason it is refused. `heldHere` is + * whether this very slot already holds the file (an update rewriting its own + * value), which takes nothing and is always admitted. `writerUserId` is the + * user the write runs as; a system or context-less write has none. + */ +export function preRecordReferenceRefusal( + row: Record, + target: { object: string; field: string; heldHere: boolean }, + writerUserId: string | null, + now: number, +): PreRecordReferenceRefusal | null { + if (target.heldHere) return null; + const binding = preRecordBindingOf(row); + if (!binding) { + // The link's own `pending` row, before the upload: its uploader's write + // is refused by the incomplete-upload check; every other writer, a + // system or context-less write included, is refused here, so the + // published id reserves nothing for anyone else. + if (isPreRecordLinkRow(row) && neverHeld(row) && (writerUserId === null || String(row.owner_id ?? '') !== writerUserId)) { + return { kind: 'not_yours' }; + } + return null; + } + // A record held it and let it go: that record's released file (#26046). + if (unheld(row) && released(row)) return null; + const deadline = Date.parse(binding.claim_until); + const open = Number.isFinite(deadline) && now < deadline; + if (!unheld(row)) { + // In a record already. After its window it is that record's file like + // any other, which the read check and copy-on-claim judge; within it, no + // user's write puts it into a second slot. A system write copies it as + // it copies any file a record holds: it names no user whose upload this + // could be, and the record that holds the file keeps it. + if (!open || writerUserId === null) return null; + return writerUserId === binding.user_id ? { kind: 'spent' } : { kind: 'not_yours' }; + } + if (writerUserId === null || writerUserId !== binding.user_id) return { kind: 'not_yours' }; + if (target.object !== binding.object || target.field !== binding.field) { + return { kind: 'other_slot', object: binding.object, field: binding.field }; + } + if (!open) return { kind: 'expired' }; + return null; +} diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index aa87111abd4..276dad4e0ac 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -32,6 +32,15 @@ * `beforeUpdate` hook refusing an edit of one as the record-lock hook does * (`RECORD_LOCKED`, its status declared as `statusCode: 409`). * + * #32686 — a link that names no record (ruling A): the user uploads, then + * the creating write names the file id the link answered. Pinned through + * the same doors: an expense line with a required e-invoice is refused + * without it and taken with it; the id goes only into the uploader's write, + * into the object and field it was uploaded for, into one record, within its + * window; only the uploader downloads it until a record holds it; and a + * console-style upload and save is taken as before. The create verdict is a + * `security` service stood in for the span of the case that asks it. + * * #32712 — the page, and the refusals it shows, in the request's language: * `Accept-Language`, else the workspace default, else English. The workspace * default is the fixture's `settings` service, answering the `localization` @@ -54,6 +63,8 @@ import type { SwappableStorageService } from './swappable-storage-service.js'; import type { FileAttachmentService } from './file-attachment-service.js'; import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-organization.testkit.js'; import { UPLOAD_LINK_TTL_SECONDS } from './record-file-access.js'; +import { PRE_RECORD_CLAIM_WINDOW_SECONDS } from './pre-record-upload.js'; +import { resolveThrownHttpError } from '@objectstack/types'; import { UPLOAD_LINK_UNUSABLE_MESSAGE } from './upload-link-wire.js'; import { UPLOAD_LINK_COPY } from './upload-link-copy.js'; @@ -86,6 +97,8 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o let files: FileAttachmentService; let storage: SwappableStorageService; const routes = new Map(); + /** The kernel's services; [#32686] a case may add a `security` service for its own span. */ + const services = new Map(); const ids: Record = {}; /** [#32734] The claims a pending approval locks. */ const locked = new Set(); @@ -123,7 +136,6 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o }, }); - const services = new Map(); const phases = new Map unknown>>(); const mount = (m: string) => (path: string, handler: RouteHandler) => { routes.set(`${m}:${path}`, handler); }; const ctx = { @@ -206,6 +218,14 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o invoices: { name: 'invoices', label: 'Invoices', type: 'file', multiple: true, readonlyWhen: "record.status == 'approved'" }, stamp: { name: 'stamp', label: 'Stamp', type: 'file', readonly: true }, }, + }, { + // [#32686] The measured case: an expense line whose e-invoice is required. + name: 'expense_line', + label: 'Expense line', + fields: { + invoice_no: { name: 'invoice_no', type: 'text' }, + invoice: { name: 'invoice', label: 'E-invoice', type: 'file', required: true }, + }, }], } as never); await engine.syncSchemas(); @@ -894,4 +914,269 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o .toBe(zh.recordLocked); }); }); + + describe('#32686 — a link that names no record: the user uploads, then the creating write names the file id', () => { + const failureOf = (write: Promise) => write.then(() => null, (e: unknown) => resolveThrownHttpError(e)); + const insertAs = (who: { userId: string; tenantId?: string } | typeof SYS, object: string, data: Record) => + engine.insert(object, data, { context: who } as never); + const updateAs = (who: { userId: string; tenantId?: string }, object: string, id: string, data: Record) => + engine.update(object, data, { where: { id }, context: who } as never); + /** The one located refusal a write naming a file is answered with, as the HTTP boundary answers it. */ + const refusedAt = (field: string, label: string, message: string) => ({ + status: 400, + code: 'VALIDATION_FAILED', + details: { fields: [{ field, code: 'invalid_value', message, label }] }, + }); + const unreadable = (label: string) => + `${label} cannot reference this file: it is not a file you can open. Choose a file you can open, or upload it again.`; + const REMEDY = 'Ask for a new upload link for this field and upload the file again.'; + /** Mint a link for `object`.`field` with no record as `who`, and use it once with `bytes`. */ + const uploadForNewRecord = async ( + object: string, + field: string, + bytes: Buffer = Buffer.from('%PDF-1.4 invoice'), + who: { userId: string; tenantId: string } = OWNER, + ) => { + const grant = await files.createUploadLinkForNewRecordAs(object, { field }, who as never); + const res = await useLink(tokenOf(grant.path), bytes, {}, who.userId); + expect(res._status, JSON.stringify(res._json)).toBe(200); + return { grant, fileId: grant.fileIds[0] as string }; + }; + const refOf = async (fileId: string) => { + const row = await fileRow(fileId); + return [row?.ref_object ?? null, row?.ref_id ?? null, row?.ref_field ?? null]; + }; + const UNCLAIMED = [null, null, null]; + /** The download door's answer to `user` for a file. */ + const downloadUrlAs = (fileId: string, user: string) => + call('GET', `${BASE}/files/:fileId/url`, { params: { fileId }, headers: sessionOf(user) }); + /** [#32686] Stand a security service in for the span of `fn`: the object create verdict and the writable fields. */ + const withSecurity = async (security: Record, fn: () => Promise) => { + services.set('security', security); + try { + await fn(); + } finally { + services.delete('security'); + } + }; + + it('the measured case: an expense line is refused without its required e-invoice, and taken naming the uploaded file id', async () => { + // Reading 1: the record cannot exist without the file. + const bare = await failureOf(insertAs(OWNER, 'expense_line', { invoice_no: 'INV-0' })); + expect(bare).toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); + expect(JSON.stringify(bare)).toContain('invoice'); + + // Call 1: the link names the object and the field, no record, and answers the file id up front. + const before = Date.now(); + const grant = await files.createUploadLinkForNewRecordAs('expense_line', { field: 'invoice' }, OWNER as never); + expect(grant).toMatchObject({ object: 'expense_line', field: 'invoice', path: `${BASE}/upload-links/${grant.token}` }); + expect(grant.fileIds).toEqual([grant.token.split('.')[0]]); + const ttl = Date.parse(grant.expiresAt) - before; + expect(ttl).toBeGreaterThan(UPLOAD_LINK_TTL_SECONDS * 1000 - 5_000); + expect(ttl).toBeLessThanOrEqual(UPLOAD_LINK_TTL_SECONDS * 1000 + 1_000); + const fileId = grant.fileIds[0]; + const reserved = await fileRow(fileId); + expect(reserved).toMatchObject({ status: 'pending', owner_id: OWNER.userId, name: 'upload-link' }); + expect(JSON.parse(reserved.metadata)).not.toHaveProperty('record_id'); + + // Before the upload, the create naming it is refused as an upload that never completed. + const early = await failureOf(insertAs(OWNER, 'expense_line', { invoice_no: 'INV-1', invoice: fileId })); + expect(early).toMatchObject(refusedAt( + 'invoice', 'E-invoice', `E-invoice cannot reference file ${fileId}: its upload was never completed. Complete the upload, then save again.`, + )); + + // The browser upload: the bytes land under the id the link answered, on no record. + const res = await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 taxi receipt')); + expect(res._status, JSON.stringify(res._json)).toBe(200); + expect(res._json).toEqual({ success: true, data: { fileId, size: 21, field: 'invoice' } }); + const landed = await fileRow(fileId); + expect(landed).toMatchObject({ + status: 'committed', owner_id: OWNER.userId, size: 21, name: 'scan 1.pdf', mime_type: 'application/pdf', + ref_object: null, ref_id: null, ref_field: null, + }); + const binding = JSON.parse(landed.metadata); + expect(binding).toMatchObject({ kind: 'pre_record_upload', object: 'expense_line', field: 'invoice', user_id: OWNER.userId, organization_id: ORG }); + expect(String(landed.metadata)).not.toContain(grant.token.split('.')[1]); + const window = Date.parse(binding.claim_until) - Date.now(); + expect(window).toBeGreaterThan(PRE_RECORD_CLAIM_WINDOW_SECONDS * 1000 - 60_000); + expect(window).toBeLessThanOrEqual(PRE_RECORD_CLAIM_WINDOW_SECONDS * 1000); + expect((await storage.download(landed.key)).toString()).toBe('%PDF-1.4 taxi receipt'); + // The link is spent. + expect((await useLink(tokenOf(grant.path), Buffer.from('again')))._status).toBe(404); + + // Call 2: the create naming the file id is taken, and the record owns the file. + const line = await insertAs(OWNER, 'expense_line', { invoice_no: 'INV-1', invoice: fileId }); + expect(await refOf(fileId)).toEqual(['expense_line', String(line.id), 'invoice']); + }); + + it('the page says the file was received, not attached: no record holds it yet', async () => { + const grant = await files.createUploadLinkForNewRecordAs('claim', { field: 'policy' }, OWNER as never); + const html = String((await openLink(tokenOf(grant.path)))._sent); + expect(html).toContain(UPLOAD_LINK_COPY.en.received); + expect(html).not.toContain(UPLOAD_LINK_COPY.en.attached); + expect(html).not.toContain('policy'); + }); + + it('another user\'s write is refused with the unreadable-file words, and the file stays unclaimed', async () => { + const { fileId } = await uploadForNewRecord('claim', 'policy'); + const failure = await failureOf(insertAs(REVIEWER, 'claim', { name: 'R', owner: REVIEWER.userId, policy: fileId })); + expect(failure).toMatchObject(refusedAt('policy', 'Policy', unreadable('Policy'))); + expect(await refOf(fileId)).toEqual(UNCLAIMED); + }); + + it('a system write is refused too: it names no user whose upload this is', async () => { + const { fileId } = await uploadForNewRecord('claim', 'policy'); + const failure = await failureOf(insertAs(SYS, 'claim', { name: 'S', owner: OWNER.userId, policy: fileId })); + expect(failure).toMatchObject(refusedAt('policy', 'Policy', unreadable('Policy'))); + expect(await refOf(fileId)).toEqual(UNCLAIMED); + }); + + it('the uploader\'s write into another field or another object is refused, naming the field it was uploaded for', async () => { + const { fileId } = await uploadForNewRecord('claim', 'policy'); + const why = 'it was uploaded through an upload link for claim.policy, and goes into that field only'; + expect(await failureOf(insertAs(OWNER, 'claim', { name: 'F', owner: OWNER.userId, receipt: fileId }))) + .toMatchObject(refusedAt('receipt', 'Receipt', `Receipt cannot reference file ${fileId}: ${why}. ${REMEDY}`)); + expect(await failureOf(insertAs(OWNER, 'expense_line', { invoice_no: 'INV-X', invoice: fileId }))) + .toMatchObject(refusedAt('invoice', 'E-invoice', `E-invoice cannot reference file ${fileId}: ${why}. ${REMEDY}`)); + expect(await refOf(fileId)).toEqual(UNCLAIMED); + }); + + it('goes into one record: a second record naming it within the window is refused, and the first keeps it', async () => { + const { fileId } = await uploadForNewRecord('claim', 'policy'); + const first = await insertAs(OWNER, 'claim', { name: 'first', owner: OWNER.userId, policy: fileId }); + const second = await failureOf(insertAs(OWNER, 'claim', { name: 'second', owner: OWNER.userId, policy: fileId })); + expect(second).toMatchObject(refusedAt('policy', 'Policy', `Policy cannot reference file ${fileId}: it was uploaded through an upload link and is already in another record; a file from an upload link goes into one record. ${REMEDY}`)); + expect(await refOf(fileId)).toEqual(['claim', String(first.id), 'policy']); + expect((await claim(String(first.id))).policy).toBe(fileId); + // Rewriting the record's own value takes nothing and is not refused. + await updateAs(OWNER, 'claim', String(first.id), { policy: fileId, name: 'first again' }); + expect((await claim(String(first.id))).name).toBe('first again'); + }); + + it('expires: once the window has passed with no record holding it, the uploader\'s own write is refused', async () => { + const { fileId } = await uploadForNewRecord('claim', 'policy'); + const binding = JSON.parse((await fileRow(fileId)).metadata); + await engine.update('sys_file', { metadata: JSON.stringify({ ...binding, claim_until: new Date(Date.now() - 1_000).toISOString() }) }, { where: { id: fileId }, context: SYS } as never); + const failure = await failureOf(insertAs(OWNER, 'claim', { name: 'late', owner: OWNER.userId, policy: fileId })); + expect(failure).toMatchObject(refusedAt('policy', 'Policy', `Policy cannot reference file ${fileId}: it was uploaded through an upload link, and no record took it within ${PRE_RECORD_CLAIM_WINDOW_SECONDS / 60} minutes of the upload. ${REMEDY}`)); + expect(await refOf(fileId)).toEqual(UNCLAIMED); + }); + + it('a record that lets the file go keeps it as any released file: its readers read it, and the binding no longer applies', async () => { + const { fileId } = await uploadForNewRecord('claim', 'policy'); + const first = await insertAs(OWNER, 'claim', { name: 'held', owner: OWNER.userId, policy: fileId }); + // The record lets it go: its field cleared. + await updateAs(OWNER, 'claim', String(first.id), { policy: null }); + const letGo = await fileRow(fileId); + expect(letGo).toMatchObject({ ref_id: null, released_ref_object: 'claim', released_ref_id: String(first.id) }); + // #26046: the releasing record's readers still read it (the reviewer reads every claim). + const read = await downloadUrlAs(fileId, REVIEWER.userId); + expect(read._status, JSON.stringify(read._json)).toBe(200); + // Past the hour, the uploader's restore and a second record take it as they take any released file. + const binding = JSON.parse(letGo.metadata); + await engine.update('sys_file', { metadata: JSON.stringify({ ...binding, claim_until: new Date(Date.now() - 1_000).toISOString() }) }, { where: { id: fileId }, context: SYS } as never); + const second = await insertAs(OWNER, 'claim', { name: 'second', owner: OWNER.userId, policy: fileId }); + expect(await refOf(fileId)).toEqual(['claim', String(second.id), 'policy']); + expect((await claim(String(second.id))).policy).toBe(fileId); + }); + + it('before the upload, the id it answered takes no write but its uploader\'s: a system write and another user are refused, and the upload still lands', async () => { + const grant = await files.createUploadLinkForNewRecordAs('claim', { field: 'policy' }, OWNER as never); + const fileId = grant.fileIds[0] as string; + expect(await failureOf(insertAs(SYS, 'claim', { name: 'S', owner: OWNER.userId, policy: fileId }))) + .toMatchObject(refusedAt('policy', 'Policy', unreadable('Policy'))); + expect(await failureOf(insertAs(REVIEWER, 'claim', { name: 'R', owner: REVIEWER.userId, policy: fileId }))) + .toMatchObject(refusedAt('policy', 'Policy', unreadable('Policy'))); + expect(await fileRow(fileId)).toMatchObject({ status: 'pending', ref_object: null, ref_id: null, ref_field: null }); + const res = await useLink(tokenOf(grant.path), Buffer.from('%PDF-1.4 hotel')); + expect(res._status, JSON.stringify(res._json)).toBe(200); + const taken = await insertAs(OWNER, 'claim', { name: 'O', owner: OWNER.userId, policy: fileId }); + expect(await refOf(fileId)).toEqual(['claim', String(taken.id), 'policy']); + }); + + it('the uploader\'s update of an existing record takes it as the create does', async () => { + const id = (await engine.insert('claim', { name: 'U', owner: OWNER.userId, organization_id: ORG }, { context: SYS } as never)).id; + const { fileId } = await uploadForNewRecord('claim', 'policy'); + await updateAs(OWNER, 'claim', String(id), { policy: fileId }); + expect((await claim(String(id))).policy).toBe(fileId); + expect(await refOf(fileId)).toEqual(['claim', String(id), 'policy']); + }); + + it('downloads: only the uploader while no record holds it; then the record\'s readers', async () => { + const { fileId } = await uploadForNewRecord('claim', 'policy'); + expect((await downloadUrlAs(fileId, OWNER.userId))._status).toBe(200); + const denied = await downloadUrlAs(fileId, REVIEWER.userId); + expect(denied._status, JSON.stringify(denied._json)).toBe(403); + expect(denied._json).toMatchObject({ success: false, error: { code: 'FILE_DOWNLOAD_DENIED' } }); + // Claimed: the record's read rule, and the reviewer reads every claim. + await insertAs(OWNER, 'claim', { name: 'D', owner: OWNER.userId, policy: fileId }); + expect((await downloadUrlAs(fileId, REVIEWER.userId))._status).toBe(200); + }); + + it('control: a console-style upload (presign, PUT, complete) and save is taken as before, with no binding', async () => { + const presigned = await call('POST', `${BASE}/upload/presigned`, { + headers: sessionOf(OWNER.userId), + body: { filename: 'form.pdf', mimeType: 'application/pdf', size: 8 }, + }); + expect(presigned._status, JSON.stringify(presigned._json)).toBe(200); + const { fileId, uploadUrl } = presigned._json.data as { fileId: string; uploadUrl: string }; + const put = await call('PUT', `${BASE}/_local/raw/:token`, { + params: { token: uploadUrl.slice(uploadUrl.lastIndexOf('/') + 1) }, + rawBody: async () => Buffer.from('%PDF-1.4'), + }); + expect(put._status, JSON.stringify(put._json)).toBe(200); + const done = await call('POST', `${BASE}/upload/complete`, { headers: sessionOf(OWNER.userId), body: { fileId } }); + expect(done._status, JSON.stringify(done._json)).toBe(200); + expect(String((await fileRow(fileId)).metadata ?? '')).not.toContain('pre_record_upload'); + const saved = await insertAs(OWNER, 'claim', { name: 'console', owner: OWNER.userId, policy: fileId }); + expect(await refOf(fileId)).toEqual(['claim', String(saved.id), 'policy']); + }); + + describe('minting', () => { + it('refuses the system context, a field that is not a file field, a read-only field, and no field at all', async () => { + expect(await refusalOf(files.createUploadLinkForNewRecordAs('claim', { field: 'policy' }, SYS as never))) + .toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(await refusalOf(files.createUploadLinkForNewRecordAs('claim', { field: 'owner' }, OWNER as never))) + .toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(await refusalOf(files.createUploadLinkForNewRecordAs('claim', { field: 'stamp' }, OWNER as never))) + .toMatchObject({ code: 'FIELD_NOT_ACCESSIBLE', status: 403 }); + expect(await refusalOf(files.createUploadLinkForNewRecordAs('claim', {} as never, OWNER as never))) + .toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + }); + + it('asks the object\'s create verdict and the field\'s writability, as the security service answers them', async () => { + const asked: Array<{ object: string; operation: string }> = []; + let mayCreate = false; + let writable: string[] | undefined = undefined; + await withSecurity({ + explain: async (request: { object: string; operation: string }) => { + asked.push({ object: request.object, operation: request.operation }); + return { allowed: mayCreate }; + }, + getWritableFields: async () => writable, + }, async () => { + expect(await refusalOf(files.createUploadLinkForNewRecordAs('claim', { field: 'policy' }, OWNER as never))) + .toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(asked).toEqual([{ object: 'claim', operation: 'create' }]); + mayCreate = true; + writable = ['name']; + expect(await refusalOf(files.createUploadLinkForNewRecordAs('claim', { field: 'policy' }, OWNER as never))) + .toMatchObject({ code: 'FIELD_NOT_ACCESSIBLE', status: 403 }); + writable = ['name', 'policy']; + const grant = await files.createUploadLinkForNewRecordAs('claim', { field: 'policy' }, OWNER as never); + expect(grant.fileIds).toHaveLength(1); + }); + }); + }); + + it('a file the field\'s own maxSize refuses is refused when it arrives, nothing stored and the link not spent', async () => { + const grant = await files.createUploadLinkForNewRecordAs('claim', { field: 'receipt' }, OWNER as never); + const big = await useLink(tokenOf(grant.path), Buffer.alloc(100, 1)); + expect(big._status, JSON.stringify(big._json)).toBe(400); + expect(big._json.error.code).toBe('ERR_FILE_CONSTRAINT'); + expect(await fileRow(grant.fileIds[0])).toMatchObject({ status: 'pending', name: 'upload-link' }); + const small = await useLink(tokenOf(grant.path), Buffer.from('ok')); + expect(small._status, JSON.stringify(small._json)).toBe(200); + }); + }); }); diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index 8e052dc1505..d7c08779813 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -41,11 +41,20 @@ import { // The upload doors' own storage-key layout, and the download doors' link. import { buildKey, mintDownloadUrl } from './storage-routes.js'; import { + UPLOAD_LINK_KIND, UPLOAD_LINK_SEGMENT, UPLOAD_LINK_UNUSABLE_CODE, UPLOAD_LINK_UNUSABLE_MESSAGE, UPLOAD_LINK_UNUSABLE_STATUS, } from './upload-link-wire.js'; +// [#32686] A file uploaded before its record: the binding the upload writes, +// and the field's own `accept` / `maxSize`, judged when the bytes arrive. +import { + PRE_RECORD_CLAIM_WINDOW_SECONDS, + PRE_RECORD_UPLOAD_KIND, + preRecordBindingMetadata, +} from './pre-record-upload.js'; +import { assertFileConstraints } from './file-reference-lifecycle.js'; /** * [#30892] A record's files for a caller the host has already resolved: read @@ -108,6 +117,37 @@ import { * other columns (the record, the field, the organization) rest on `sys_file` * edit being an administrative grant. * + * ## A link that names no record + * + * [#32686] Ruling A: a link can name an object and a file field and no + * record ({@link RecordFileAccess.createUploadLinkForNewRecordAs}), so an + * agent can file a record whose file field is required: the user uploads, + * then the agent creates the record naming the file id the link answered. + * + * - **Minting** asks what the record's creation will need, of the caller: + * the object's CREATE permission (`explain(…, 'create')`, the verdict + * `assertMayAttach` asks of `sys_attachment`), the field's writability as + * the security service answers it, and the field's own `readonly` + * declaration. A conditional lock (`readonlyWhen`) and every other rule + * are judged by the create itself. Only a file field: an attachment needs + * its record. + * - **The file id is the link row's id**, answered at once (`fileIds`), so + * the flow is two calls and one upload. Until the upload, the uploader's + * write naming it is refused as an upload that never completed, and every + * other write, a system one included, as a file it cannot open. + * - **Using it** stores the bytes and turns the link row into the user's + * committed file, which no record holds, carrying the binding a write is + * judged by (`pre-record-upload.ts`): only that user's write, into that + * object and field, within {@link PRE_RECORD_CLAIM_WINDOW_SECONDS} of the + * upload, and into one record. Once a record has let it go, it is that + * record's released file like any other. The field's `accept` / `maxSize` are + * judged when the bytes arrive, so a file the field cannot take is refused + * then, and nothing is stored. + * - **What reclaims it**: a link never used is a `pending` row, reaped by + * the pending-upload retention. A file uploaded and never put in a record + * is a committed file no record holds, as an upload the console's form + * never saved is; `verify-file-references` reports it. + * * ## What counts the upload * * The bytes go through the doors' own size verdict (`max_upload_mb`, 413 @@ -122,9 +162,6 @@ export const UPLOAD_LINK_TTL_SECONDS = 10 * 60; /** The upload link's secret: 32 random bytes (256 bits), base64url in the link. */ const UPLOAD_LINK_SECRET_BYTES = 32; -/** The marker a link row's `metadata` carries, so no other pending row reads as a link. */ -const UPLOAD_LINK_KIND = 'upload_link'; - /** * A link row's `name` while the link is open, and once it is used. The state * lives in `name` because the one conditional write that spends a link @@ -145,6 +182,9 @@ export type RecordFileTarget = { field: string; fileId?: string } | { attachment /** Where an upload link lands: a file field, or the record's attachments list. */ export type UploadLinkTarget = { field: string } | { attachments: true }; +/** [#32686] Where a link that names no record lands: a file field of the record to be created. */ +export type NewRecordUploadLinkTarget = { field: string }; + /** One file a record carries, as {@link RecordFileAccess.listRecordFilesAs} lists it. */ export interface RecordFileEntry { fileId: string; @@ -190,6 +230,28 @@ export interface UploadLinkGrant { export interface UploadLinkView { expiresAt: string; target: 'field' | 'attachments'; + /** [#32686] The link names no record: the file waits for the record the agent creates. */ + newRecord?: true; +} + +/** + * [#32686] {@link RecordFileAccess.createUploadLinkForNewRecordAs}'s answer: + * the link, and the ids the upload is stored under, to write into the field + * when the record is created. One id: a link takes one file. An array so + * that a link taking several files answers more entries, not a second key. + */ +export interface NewRecordUploadLinkGrant { + /** The link's token: the pending row's id and the secret. Shown once, never stored. */ + token: string; + /** The link's path on this server: the storage base path, the segment and the token. */ + path: string; + /** When the link stops working (ISO 8601). */ + expiresAt: string; + object: string; + /** The file field the upload is for. */ + field: string; + /** The file id(s) the upload is stored under. */ + fileIds: string[]; } /** One upload arriving through a link. */ @@ -202,7 +264,8 @@ export interface UploadLinkUpload { /** Where an upload through a link landed. */ export interface UploadLinkOutcome { object: string; - recordId: string; + /** The record it landed on; absent for a link that names no record ([#32686]). */ + recordId?: string; fileId: string; size: number; /** The file field it now fills, for a field link. */ @@ -237,6 +300,15 @@ export interface ICallerRecordFileService { target: UploadLinkTarget, context: ExecutionContext, ): Promise; + /** + * [#32686] A single-use upload link for a file field of a record not yet + * created, answering the file id the upload is stored under. + */ + createUploadLinkForNewRecordAs( + object: string, + target: NewRecordUploadLinkTarget, + context: ExecutionContext, + ): Promise; } /** @@ -296,7 +368,7 @@ export interface RecordFileAccessDeps { getBasePath(): string; getSharing?(): AttachmentSharingLike | null | undefined; getSecurity?(): - | (AttachmentSecurityLike & Partial>) + | (AttachmentSecurityLike & Partial>) | null | undefined; /** @@ -317,7 +389,8 @@ interface UploadLinkState { secret_sha256: string; expires_at: string; object: string; - record_id: string; + /** The record the upload lands on; absent for a field link that names no record ([#32686]). */ + record_id?: string; target: 'field' | 'attachments'; field?: string; user_id: string; @@ -404,11 +477,14 @@ function openLinkStateOf(row: FileRecord | null): UploadLinkState | null { } const s = parsed as Partial | null; if (!s || typeof s !== 'object' || s.kind !== UPLOAD_LINK_KIND) return null; - for (const key of ['secret_sha256', 'expires_at', 'object', 'record_id', 'user_id'] as const) { + for (const key of ['secret_sha256', 'expires_at', 'object', 'user_id'] as const) { if (!nonEmptyString(s[key])) return null; } if (s.target !== 'field' && s.target !== 'attachments') return null; if (s.target === 'field' && !nonEmptyString(s.field)) return null; + // [#32686] Only a field link may name no record: an attachment needs its record. + if (s.target === 'attachments' && !nonEmptyString(s.record_id)) return null; + if (s.record_id !== undefined && !nonEmptyString(s.record_id)) return null; return s as UploadLinkState; } @@ -419,7 +495,7 @@ function linkMetadata(state: UploadLinkState): string { secret_sha256: state.secret_sha256, expires_at: state.expires_at, object: state.object, - record_id: state.record_id, + ...(state.record_id !== undefined ? { record_id: state.record_id } : {}), target: state.target, ...(state.field !== undefined ? { field: state.field } : {}), user_id: state.user_id, @@ -714,6 +790,79 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo } } + const link = await this.mintLink(engine, caller, object, recordId, field); + return { + token: link.token, + path: link.path, + expiresAt: link.expiresAt, + object, + recordId, + ...(field !== undefined ? { field } : {}), + }; + } + + /** + * [#32686] Ruling A: a link for a file field of a record the caller is + * about to create. Asks what creating it will need of the caller (see the + * module comment), mints the same single-use link, and answers the link + * row's id as the file id the upload is stored under. + */ + async createUploadLinkForNewRecordAs( + object: string, + target: NewRecordUploadLinkTarget, + context: ExecutionContext, + ): Promise { + const caller = requireUserContext(context); + const engine = this.engineOrRefuse(); + const field = target && typeof target === 'object' ? (target as { field?: unknown }).field : undefined; + if (!nonEmptyString(field)) { + refuse( + 'VALIDATION_ERROR', + 400, + 'A link for a record not yet created fills a file field: name the field. An attachment needs its record; create the record first.', + ); + } + const fieldDef = requireFileField(engine, object, field); + // The object's create verdict, as the security service answers it for + // the caller with no write. A kernel with no security service enforces + // no object permission on the create either, so there is nothing to ask. + const security = this.deps.getSecurity?.(); + if (security && typeof security.explain === 'function') { + const decision = await security.explain({ object, operation: 'create' }, caller); + if (!decision?.allowed) { + refuse('PERMISSION_DENIED', 403, `You cannot upload a file for a new ${object}: you cannot create ${object} records.`); + } + } + const writable = await security?.getWritableFields?.(object, caller); + if (Array.isArray(writable) && !writable.includes(field)) { + refuse('FIELD_NOT_ACCESSIBLE', 403, `You cannot upload a file for ${object}.${field}: you cannot edit that field.`); + } + if (fieldDef.readonly === true) { + refuse('FIELD_NOT_ACCESSIBLE', 403, `You cannot upload a file for ${object}.${field}: the field is read-only.`); + } + const link = await this.mintLink(engine, caller, object, undefined, field); + return { + token: link.token, + path: link.path, + expiresAt: link.expiresAt, + object, + field, + fileIds: [link.id], + }; + } + + /** + * Write the link's `pending` row, owned by the caller, holding the binding + * and the SHA-256 of the secret, and answer the token. `recordId` absent: + * a field link that names no record ([#32686]). + */ + private async mintLink( + engine: RecordFileEngine, + caller: ExecutionContext, + object: string, + recordId: string | undefined, + field: string | undefined, + ): Promise<{ id: string; token: string; path: string; expiresAt: string }> { const organizationId = nonEmptyString(caller.tenantId) ? caller.tenantId : null; const id = randomUUID(); const secret = randomBytes(UPLOAD_LINK_SECRET_BYTES).toString('base64url'); @@ -723,7 +872,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo secret_sha256: sha256Hex(secret), expires_at: expiresAt, object, - record_id: recordId, + ...(recordId !== undefined ? { record_id: recordId } : {}), target: field === undefined ? 'attachments' : 'field', ...(field !== undefined ? { field } : {}), user_id: caller.userId as string, @@ -745,14 +894,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo { organizationId }, ); const token = `${id}.${secret}`; - return { - token, - path: `${this.deps.getBasePath()}/${UPLOAD_LINK_SEGMENT}/${token}`, - expiresAt, - object, - recordId, - ...(field !== undefined ? { field } : {}), - }; + return { id, token, path: `${this.deps.getBasePath()}/${UPLOAD_LINK_SEGMENT}/${token}`, expiresAt }; } /** @@ -783,7 +925,11 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo async inspectUploadLink(token: string, callerUserId: string): Promise { const { state } = await this.openLink(new StorageMetadataStore(this.engineOrRefuse()), token, callerUserId); - return { expiresAt: state.expires_at, target: state.target }; + return { + expiresAt: state.expires_at, + target: state.target, + ...(state.record_id === undefined ? { newRecord: true as const } : {}), + }; } async consumeUploadLink(token: string, upload: UploadLinkUpload, callerUserId: string): Promise { @@ -814,6 +960,18 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo ); } + const mimeType = nonEmptyString(upload.mimeType) ? upload.mimeType : 'application/octet-stream'; + // [#32686] A link that names no record writes no record now, so nothing + // judges the field's own `accept` / `maxSize` until the create does: they + // are judged here, before the link is spent, as the record's write would + // judge them, and a file the field cannot take is refused with nothing + // stored. + const newRecord = state.record_id === undefined; + if (newRecord) { + const def = requireFileField(engine, state.object, state.field as string); + assertFileConstraints(def, state.field as string, { name: upload.filename, mime_type: mimeType, size: upload.data.byteLength }); + } + // Spend the link: exactly one use turns it from open to used. const writeContext: StorageWriteContext = { organizationId }; const spent = await updateFileIfUnchanged( @@ -825,12 +983,17 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo ); if (!spent) refuseUnusableLink(); + // [#32686] The link row becomes the file: its id is the one the link answered. + const recordId = state.record_id; + if (recordId === undefined) { + return await this.fileForNewRecordThroughLink(storage, store, row, state, upload, mimeType, writeContext); + } + try { - const mimeType = nonEmptyString(upload.mimeType) ? upload.mimeType : 'application/octet-stream'; const outcome = state.target === 'attachments' - ? await this.attachThroughLink(state, user, upload, mimeType, organizationId) - : await this.fillFieldThroughLink(engine, storage, store, state, user, upload, mimeType, writeContext); + ? await this.attachThroughLink(state, recordId, user, upload, mimeType, organizationId) + : await this.fillFieldThroughLink(engine, storage, store, state, recordId, user, upload, mimeType, writeContext); return outcome; } finally { // The link row has done its work, used or refused: it holds no bytes, @@ -847,8 +1010,58 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo } } + /** + * [#32686] Store the bytes and turn the link's row into the user's + * committed file, which no record holds yet, under the id the link + * answered. Its `metadata` becomes the binding a record write is judged by + * (`pre-record-upload.ts`); the link's own secret digest goes with the old + * metadata. A failed store discards the bytes and the row, so the id is + * refused as unknown rather than ever reading as a file. + */ + private async fileForNewRecordThroughLink( + storage: IStorageService, + store: StorageMetadataStore, + row: FileRecord, + state: UploadLinkState, + upload: UploadLinkUpload, + mimeType: string, + writeContext: StorageWriteContext, + ): Promise { + const field = state.field as string; + const fileId = row.id; + const key = buildKey(FIELD_UPLOAD_SCOPE, fileId, upload.filename); + const size = upload.data.byteLength; + try { + await storage.upload(key, upload.data, { contentType: mimeType }); + await store.updateFile( + fileId, + { + key, + name: upload.filename, + mime_type: mimeType, + size, + status: 'committed', + metadata: preRecordBindingMetadata({ + kind: PRE_RECORD_UPLOAD_KIND, + object: state.object, + field, + user_id: state.user_id, + ...(state.organization_id !== undefined ? { organization_id: state.organization_id } : {}), + claim_until: new Date(this.now() + PRE_RECORD_CLAIM_WINDOW_SECONDS * 1000).toISOString(), + }), + }, + writeContext, + ); + } catch (err) { + await this.discard(storage, store, fileId, key, writeContext); + throw err; + } + return { object: state.object, fileId, size, field }; + } + private async attachThroughLink( state: UploadLinkState, + recordId: string, user: ExecutionContext, upload: UploadLinkUpload, mimeType: string, @@ -857,7 +1070,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo const attached = await this.deps.attachments.attachFileAs( { parentObject: state.object, - parentId: state.record_id, + parentId: recordId, filename: upload.filename, mimeType, data: upload.data, @@ -867,7 +1080,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo ); return { object: state.object, - recordId: state.record_id, + recordId, fileId: attached.fileId, size: attached.size, attachmentId: attached.attachmentId, @@ -887,6 +1100,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo storage: IStorageService, store: StorageMetadataStore, state: UploadLinkState, + recordId: string, user: ExecutionContext, upload: UploadLinkUpload, mimeType: string, @@ -917,7 +1131,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo await store.updateFile(fileId, { status: 'committed' }, writeContext); let value: string | string[] = fileId; if (def.multiple === true) { - const current = await this.readRecordAs(engine, state.object, state.record_id, user); + const current = await this.readRecordAs(engine, state.object, recordId, user); value = [...fileIdsIn(current[field]), fileId]; } // [#32734] Strict: a field the update would strip (`readonly`, or a @@ -927,19 +1141,19 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo const updated = await engine.update( state.object, { [field]: value }, - { where: { id: state.record_id }, context: user, strictReadonlyWrites: true }, + { where: { id: recordId }, context: user, strictReadonlyWrites: true }, ); // A row the user's update no longer reaches (deleted, or out of their // scope since the link was minted) is refused, never answered as landed. if (updated == null || updated === 0) { - refuse('RECORD_NOT_FOUND', 404, `Record "${state.record_id}" not found in "${state.object}"`); + refuse('RECORD_NOT_FOUND', 404, `Record "${recordId}" not found in "${state.object}"`); } } catch (err) { await this.discard(storage, store, fileId, key, writeContext); readonlyRefusalOf(err, state.object, field); throw err; } - return { object: state.object, recordId: state.record_id, fileId, size, field }; + return { object: state.object, recordId, fileId, size, field }; } /** Undo a refused field upload: the bytes, then the row. Best-effort; the refusal is what is thrown. */ diff --git a/packages/services/service-storage/src/storage-service-plugin.ts b/packages/services/service-storage/src/storage-service-plugin.ts index 58520009800..dd9101c8833 100644 --- a/packages/services/service-storage/src/storage-service-plugin.ts +++ b/packages/services/service-storage/src/storage-service-plugin.ts @@ -79,6 +79,7 @@ import type { UploadLinkWorkspaceLocale, } from './storage-routes.js'; import type { RecordFileAccessDeps, UploadLinkDoor } from './record-file-access.js'; +import { isUploaderOnlyFile } from './pre-record-upload.js'; import { installAttachmentLifecycleHooks, createSysFileReapGuard, createUploadSessionReapGuard, findFileHolder, findHeldFiles } from './attachment-lifecycle.js'; import { installFileReferenceHooks, type FileReferenceEngine } from './file-reference-lifecycle.js'; import { installSysFileStorageOwnedColumnsGuard } from './sys-file-storage-owned-columns.js'; @@ -1976,6 +1977,11 @@ async function judgeFileRead( // Uploader / owner may always download. if (file.owner_id && String(file.owner_id) === String(context.userId)) return 'allow'; + // [#32686] A file uploaded through a link that names no record (or the row + // such a link reserved), while no record holds it: its uploader's alone, + // answered by the arm above. Every other file is judged below as before. + if (isUploaderOnlyFile(file as unknown as Record)) return 'deny'; + // Field-owned (ADR-0104 D3 wave 2): exactly ONE record's field holds // this file, so access is that record's READ access — never a union. // The verdict is `readableFieldOwners`, asked for this one owner: the diff --git a/packages/services/service-storage/src/upload-link-copy.ts b/packages/services/service-storage/src/upload-link-copy.ts index 9f366b936c5..c748e8f4f8e 100644 --- a/packages/services/service-storage/src/upload-link-copy.ts +++ b/packages/services/service-storage/src/upload-link-copy.ts @@ -68,6 +68,11 @@ export interface UploadLinkCopy extends UploadLinkRefusalCopy { send: string; uploading: string; attached: string; + /** + * [#32686] Done, for a link that names no record: the file was stored and + * waits for the record the assistant creates, so nothing was attached yet. + */ + received: string; /** The upload failed and the answer carried no sentence to show. */ failed: string; connectionLost: string; @@ -91,6 +96,7 @@ export const UPLOAD_LINK_COPY: Record = { send: 'Send', uploading: 'Uploading…', attached: 'Done. The file was attached; you can close this page.', + received: 'Done. The file was received; go back to the assistant to finish.', failed: 'The upload failed.', connectionLost: 'The upload failed: the connection was lost. Ask for a new link if this one no longer works.', unusableTitle: 'Upload link', @@ -122,6 +128,7 @@ export const UPLOAD_LINK_COPY: Record = { send: '发送', uploading: '正在上传…', attached: '完成,文件已添加。你可以关闭此页面。', + received: '完成,文件已收到。请回到助手那里完成后续操作。', failed: '上传失败。', connectionLost: '上传失败:连接已中断。如果此链接已无法使用,请索取新的链接。', unusableTitle: '上传链接', @@ -151,6 +158,7 @@ export const UPLOAD_LINK_COPY: Record = { send: '傳送', uploading: '正在上傳…', attached: '完成,檔案已新增。你可以關閉此頁面。', + received: '完成,檔案已收到。請回到助理那裡完成後續操作。', failed: '上傳失敗。', connectionLost: '上傳失敗:連線已中斷。如果此連結已無法使用,請索取新的連結。', unusableTitle: '上傳連結', @@ -180,6 +188,7 @@ export const UPLOAD_LINK_COPY: Record = { send: '送信', uploading: 'アップロード中…', attached: '完了しました。ファイルが追加されました。このページは閉じてかまいません。', + received: '完了しました。ファイルを受け取りました。アシスタントに戻って続きを進めてください。', failed: 'アップロードに失敗しました。', connectionLost: 'アップロードに失敗しました: 接続が切れました。このリンクが使えなくなった場合は、新しいリンクを依頼してください。', unusableTitle: 'アップロードリンク', @@ -209,6 +218,7 @@ export const UPLOAD_LINK_COPY: Record = { send: '보내기', uploading: '업로드 중…', attached: '완료되었습니다. 파일이 추가되었으니 이 페이지를 닫아도 됩니다.', + received: '완료되었습니다. 파일을 받았습니다. 어시스턴트로 돌아가 마무리하세요.', failed: '업로드에 실패했습니다.', connectionLost: '업로드에 실패했습니다: 연결이 끊어졌습니다. 이 링크가 더 이상 작동하지 않으면 새 링크를 요청하세요.', unusableTitle: '업로드 링크', @@ -238,6 +248,7 @@ export const UPLOAD_LINK_COPY: Record = { send: 'Enviar', uploading: 'Subiendo…', attached: 'Listo. El archivo se ha adjuntado; puedes cerrar esta página.', + received: 'Listo. Se ha recibido el archivo; vuelve al asistente para terminar.', failed: 'La subida ha fallado.', connectionLost: 'La subida ha fallado: se ha perdido la conexión. Pide un enlace nuevo si este ya no funciona.', unusableTitle: 'Enlace de subida', @@ -267,6 +278,7 @@ export const UPLOAD_LINK_COPY: Record = { send: 'إرسال', uploading: 'جارٍ الرفع…', attached: 'تم. أُرفق الملف؛ يمكنك إغلاق هذه الصفحة.', + received: 'تم. استُلم الملف؛ عد إلى المساعد لإكمال العملية.', failed: 'فشل الرفع.', connectionLost: 'فشل الرفع: انقطع الاتصال. اطلب رابطًا جديدًا إذا لم يعد هذا الرابط يعمل.', unusableTitle: 'رابط الرفع', @@ -296,6 +308,7 @@ export const UPLOAD_LINK_COPY: Record = { send: 'Envoyer', uploading: 'Envoi en cours…', attached: 'Terminé. Le fichier a été joint ; vous pouvez fermer cette page.', + received: 'Terminé. Le fichier a été reçu ; revenez à l’assistant pour terminer.', failed: 'L’envoi a échoué.', connectionLost: 'L’envoi a échoué : la connexion a été perdue. Demandez un nouveau lien si celui-ci ne fonctionne plus.', unusableTitle: 'Lien d’envoi', @@ -325,6 +338,7 @@ export const UPLOAD_LINK_COPY: Record = { send: 'Enviar', uploading: 'Enviando…', attached: 'Pronto. O arquivo foi anexado; você pode fechar esta página.', + received: 'Pronto. O arquivo foi recebido; volte ao assistente para concluir.', failed: 'O envio falhou.', connectionLost: 'O envio falhou: a conexão foi perdida. Peça um novo link se este não funcionar mais.', unusableTitle: 'Link de envio', @@ -354,6 +368,7 @@ export const UPLOAD_LINK_COPY: Record = { send: 'Отправить', uploading: 'Загрузка…', attached: 'Готово. Файл прикреплён; эту страницу можно закрыть.', + received: 'Готово. Файл получен; вернитесь к ассистенту, чтобы завершить.', failed: 'Не удалось загрузить файл.', connectionLost: 'Не удалось загрузить файл: соединение прервалось. Если эта ссылка больше не работает, попросите новую.', unusableTitle: 'Ссылка для загрузки', @@ -383,6 +398,7 @@ export const UPLOAD_LINK_COPY: Record = { send: 'Senden', uploading: 'Wird hochgeladen…', attached: 'Fertig. Die Datei wurde angehängt; Sie können diese Seite schließen.', + received: 'Fertig. Die Datei ist angekommen; kehren Sie zum Assistenten zurück, um abzuschließen.', failed: 'Das Hochladen ist fehlgeschlagen.', connectionLost: 'Das Hochladen ist fehlgeschlagen: Die Verbindung wurde unterbrochen. Fordern Sie einen neuen Link an, wenn dieser nicht mehr funktioniert.', unusableTitle: 'Upload-Link', diff --git a/packages/services/service-storage/src/upload-link-page.ts b/packages/services/service-storage/src/upload-link-page.ts index d4f50535c0b..0770d8f3f90 100644 --- a/packages/services/service-storage/src/upload-link-page.ts +++ b/packages/services/service-storage/src/upload-link-page.ts @@ -137,7 +137,9 @@ export function sendUploadLinkPage(res: IHttpResponse, view: UploadLinkView, cop '

'; const text = scriptLiteral({ uploading: copy.uploading, - attached: copy.attached, + // [#32686] A link that names no record attaches nothing: the file waits + // for the record the assistant creates. + attached: view.newRecord === true ? copy.received : copy.attached, failed: copy.failed, connectionLost: copy.connectionLost, }); diff --git a/packages/services/service-storage/src/upload-link-wire.ts b/packages/services/service-storage/src/upload-link-wire.ts index e9001b0b4b6..21d28a66f33 100644 --- a/packages/services/service-storage/src/upload-link-wire.ts +++ b/packages/services/service-storage/src/upload-link-wire.ts @@ -9,6 +9,9 @@ import type { StandardErrorCode } from '@objectstack/spec/api'; * own so the doors import no service code. */ +/** The marker a link row's `metadata` carries, so no other pending row reads as a link. */ +export const UPLOAD_LINK_KIND = 'upload_link'; + /** The path segment the upload-link doors are mounted under, below the storage base path. */ export const UPLOAD_LINK_SEGMENT = 'upload-links';