diff --git a/.changeset/32768-upload-link-readonly-when-at-issue.md b/.changeset/32768-upload-link-readonly-when-at-issue.md new file mode 100644 index 00000000000..00101bd928a --- /dev/null +++ b/.changeset/32768-upload-link-readonly-when-at-issue.md @@ -0,0 +1,19 @@ +--- +'@objectstack/objectql': patch +'@objectstack/service-storage': patch +'@objectstack/mcp': patch +--- + +fix(service-storage)!: an upload link is refused at issue for a file field whose `readonlyWhen` holds now (#32768) + +Clause-②: yes (narrowing) — `create_upload_link` (`createUploadLinkAs`) issues no link for a file field whose `readonlyWhen` holds on the record as it stands, where it issued one and the upload was refused when it arrived. The engine gains one write-free judgement, `ObjectQL#judgeFieldWriteLock` (widening). +Metadata-protocol: none + + + +**BREAKING** for a caller that minted an upload link onto a file field while its `readonlyWhen` held. + +FROM: `create_upload_link` answered a link, and the upload through it was refused when it arrived (`403 FIELD_NOT_ACCESSIBLE`, "Nothing was attached: …", since #32734), after the person had picked and sent the file. +TO: the call itself is refused, `403 FIELD_NOT_ACCESSIBLE`, `You cannot attach a file to OBJECT.FIELD: the field is read-only in the target record's current state (a TRUE \`readonlyWhen\` predicate).`, and no link is written. The fix for a caller: mint the link once the record's state unlocks the field, or use the record's attachments, which carry no field lock and are unchanged. + +The verdict is the engine's own: `ObjectQL#judgeFieldWriteLock(object, id, field, { context })` runs the update's `readonlyWhen` strip over the update's stored-row read and master-detail header, without writing, and answers the reason the update reports the field under (`readonly_when`) with the words its strict refusal uses. A field with no `readonlyWhen` costs no read. A static `readonly` field and a record a pending approval locks are refused at issue as before. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index faceec7f522..76094d9158e 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -306,7 +306,15 @@ record means no file**, refused with the same `RECORD_NOT_FOUND`. `401`, and a second use, an expired link, an unknown link and another user's link all get the same `404`. The upload is stored as that user, with their access checked again when the file arrives, and it meets the storage - service's maximum upload size before the link is spent. Sending a file's + service's maximum upload size before the link is spent. A field that cannot + take the upload now gets no link: a `readonly` field, or one whose + `readonlyWhen` holds on this record as it stands (refused `403` + `FIELD_NOT_ACCESSIBLE`, naming the lock in the words the engine update's + strict refusal (`strictReadonlyWrites`) uses for it; `update_record` reports + the same lock under `droppedFields` with reason `readonly_when`), and a + record a pending approval locks (`409` + `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. Reading a PDF or Word document's text runs on a pool of worker threads, so the diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 9e582d09845..a7101461854 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3362,7 +3362,8 @@ export function registerFileTools( 'as an attachment (attachments: true). Give the link to the user to open in a browser where they are ' + 'signed in to this deployment as themselves; it works only for them, once, for this record and field ' + '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, or a read-only field, gets no link, and an ' + + '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.', inputSchema: strictToolInput( { diff --git a/packages/objectql/src/engine-field-write-lock.test.ts b/packages/objectql/src/engine-field-write-lock.test.ts new file mode 100644 index 00000000000..ce46f42cd06 --- /dev/null +++ b/packages/objectql/src/engine-field-write-lock.test.ts @@ -0,0 +1,174 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// #32768 — `ObjectQL#judgeFieldWriteLock`: the update's own `readonlyWhen` +// verdict on one field of one record, asked without writing. A door that hands +// out a promise to write a field later (the upload link) asks it first. +// +// Pinned against the write itself: for every row below, the judgement says +// LOCKED exactly when an update of the field reports it dropped under +// `readonly_when`, and nothing the judgement does reaches the driver's write +// verbs. + +import { describe, it, expect, beforeEach } from 'vitest'; +import type { DroppedFieldsEvent } from '@objectstack/spec/data'; +import { ObjectQL } from './engine.js'; + +function makeDriver() { + const stores = new Map>(); + const writes: string[] = []; + const storeFor = (o: string) => { + let s = stores.get(o); + if (!s) { s = new Map(); stores.set(o, s); } + return s; + }; + const matches = (row: any, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + return Object.entries(where).every(([k, v]: [string, any]) => { + if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + return row?.[k] === v; + }); + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(object: string, ast: any) { + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return r; + return null; + }, + async create(object: string, data: Record) { + writes.push(`create ${object}`); + const row = { ...data, id: data.id as string }; + storeFor(object).set(row.id, row); + return row; + }, + async update(object: string, id: string, data: Record) { + writes.push(`update ${object}`); + const s = storeFor(object); + const row = { ...s.get(id), ...data, id }; + s.set(id, row); + return row; + }, + async updateMany() { writes.push('updateMany'); return 0; }, + async delete() { writes.push('delete'); return true; }, + async count() { return 0; }, + async bulkCreate() { writes.push('bulkCreate'); return []; }, + async bulkUpdate() { writes.push('bulkUpdate'); return []; }, async bulkDelete() { writes.push('bulkDelete'); }, + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, storeFor, writes }; +} + +const PHRASE = "read-only in the target record's current state (a TRUE `readonlyWhen` predicate)"; + +describe('judgeFieldWriteLock: the update\'s readonlyWhen verdict, without the write (#32768)', () => { + let engine: ObjectQL; + let d: ReturnType; + let warns: string[]; + + beforeEach(async () => { + warns = []; + const logger: any = { + warn: (m: string) => warns.push(String(m)), + debug() {}, info() {}, error() {}, trace() {}, fatal() {}, + child() { return logger; }, + }; + engine = new ObjectQL({ logger }); + d = makeDriver(); + engine.registerDriver(d.driver, true); + await engine.init(); + + engine.registry.registerObject({ + name: 'expense_claim', + fields: { + name: { type: 'text' }, + status: { type: 'text' }, + invoices: { type: 'file', multiple: true, readonlyWhen: "record.status == 'approved'" }, + note: { type: 'text' }, + broken: { type: 'text', readonlyWhen: 'record.no_such_field == 1' }, + }, + } as any, 'test'); + engine.registry.registerObject({ + name: 'expense_report', + fields: { name: { type: 'text' }, status: { type: 'text' } }, + } as any, 'test'); + engine.registry.registerObject({ + name: 'expense_line', + fields: { + report: { type: 'master_detail', reference: 'expense_report', required: true }, + receipt: { type: 'file', readonlyWhen: "parent.status == 'paid'" }, + }, + } as any, 'test'); + + d.storeFor('expense_claim').set('c_draft', { id: 'c_draft', name: 'Lyon', status: 'draft', invoices: null, note: null, broken: null }); + d.storeFor('expense_claim').set('c_approved', { id: 'c_approved', name: 'Rome', status: 'approved', invoices: null, note: null, broken: null }); + d.storeFor('expense_report').set('r_paid', { id: 'r_paid', name: 'Q3', status: 'paid' }); + d.storeFor('expense_report').set('r_open', { id: 'r_open', name: 'Q4', status: 'open' }); + d.storeFor('expense_line').set('l_paid', { id: 'l_paid', report: 'r_paid', receipt: null }); + d.storeFor('expense_line').set('l_open', { id: 'l_open', report: 'r_open', receipt: null }); + }); + + /** What the update itself reports for `field` on `id`: dropped under `readonly_when`, or kept. */ + async function updateDrops(object: string, id: string, field: string, value: unknown = 'f_new'): Promise { + const events: DroppedFieldsEvent[] = []; + await engine.update(object, { [field]: value }, { + where: { id }, + context: { isSystem: true }, + onFieldsDropped: (e: DroppedFieldsEvent) => { events.push(e); }, + } as any); + return events.some((e) => e.reason === 'readonly_when' && e.fields.includes(field)); + } + + it('a field whose readonlyWhen holds now is locked, with the update\'s reason and its strict refusal\'s words', async () => { + const lock = await engine.judgeFieldWriteLock('expense_claim', 'c_approved', 'invoices', { context: { isSystem: true } as any }); + expect(lock).toEqual({ reason: 'readonly_when', phrase: PHRASE }); + expect(d.writes).toEqual([]); + expect(await updateDrops('expense_claim', 'c_approved', 'invoices', ['f_new'])).toBe(true); + }); + + it('the same field while the condition is false is writable', async () => { + expect(await engine.judgeFieldWriteLock('expense_claim', 'c_draft', 'invoices', { context: { isSystem: true } as any })).toBeNull(); + expect(d.writes).toEqual([]); + expect(await updateDrops('expense_claim', 'c_draft', 'invoices', ['f_new'])).toBe(false); + }); + + it('a parent-scoped lock reads the master-detail header, as the update does', async () => { + expect(await engine.judgeFieldWriteLock('expense_line', 'l_paid', 'receipt', { context: { isSystem: true } as any })) + .toEqual({ reason: 'readonly_when', phrase: PHRASE }); + expect(await engine.judgeFieldWriteLock('expense_line', 'l_open', 'receipt', { context: { isSystem: true } as any })).toBeNull(); + expect(d.writes).toEqual([]); + expect(await updateDrops('expense_line', 'l_paid', 'receipt')).toBe(true); + expect(await updateDrops('expense_line', 'l_open', 'receipt')).toBe(false); + }); + + it('a field that declares no readonlyWhen is writable and costs no read', async () => { + const findOne = d.driver.findOne; + let reads = 0; + d.driver.findOne = async (...a: any[]) => { reads += 1; return findOne(...a); }; + expect(await engine.judgeFieldWriteLock('expense_claim', 'c_approved', 'note', { context: { isSystem: true } as any })).toBeNull(); + expect(reads).toBe(0); + }); + + it('a predicate that faults refuses as the write refuses it, and writes nothing', async () => { + const err = await engine.judgeFieldWriteLock('expense_claim', 'c_draft', 'broken', { context: { isSystem: true } as any }) + .then(() => null, (e: unknown) => e as { code?: string; name?: string }); + expect(err).not.toBeNull(); + expect(err?.name).toBe('ValidationError'); + expect(d.writes).toEqual([]); + }); + + it('a record that is not there answers as the by-id update answers it', async () => { + const err = await engine.judgeFieldWriteLock('expense_claim', 'c_missing', 'invoices', { context: { isSystem: true } as any }) + .then(() => null, (e: unknown) => e as { code?: string; status?: number }); + expect(err).toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 }); + }); + + it('logs no strip line: nothing was written, so "ignoring incoming change" is not true', async () => { + await engine.judgeFieldWriteLock('expense_claim', 'c_approved', 'invoices', { context: { isSystem: true } as any }); + expect(warns.filter((w) => w.includes('ignoring incoming change'))).toEqual([]); + }); +}); diff --git a/packages/objectql/src/engine-field-write-lock.ts b/packages/objectql/src/engine-field-write-lock.ts new file mode 100644 index 00000000000..67f2e54561b --- /dev/null +++ b/packages/objectql/src/engine-field-write-lock.ts @@ -0,0 +1,109 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32768] The body of `ObjectQL#judgeFieldWriteLock`: is `field` writable on + * the record `id` names, NOW, as far as its `readonlyWhen` lock goes — asked + * without writing anything. + * + * ## Why it exists + * + * A door that hands out a promise to write a field later (the upload link + * `create_upload_link` mints) needs the update's verdict on that field before + * the write happens. The update preview (`validate`) names `readonlyWhen` as a + * limit it does not run (`ValidateDataResponse`), and the field-access read + * (`getRecordFieldAccess`) leaves conditional read-only out. So the door could + * only learn the lock by attempting the write. This answers it without one. + * + * ## The same evaluation, not a second one + * + * The verdict is the update's own conditional strip + * ({@link stripReadonlyWhenFields}), run over the inputs the by-id update + * hands it: the stored row as `previous`, read by the update's own prior-row + * read ({@link ObjectQL.readUpdatePriorRow}); the master-detail header as + * `parent`, resolved by the update's own resolver and under the same gate + * ({@link hasParentScopedReadonlyWhenInPayload}); and a payload carrying the + * field. The field is LOCKED when that strip would take it back out. A + * predicate that faults refuses here as it refuses the write (the + * `ValidationError` the strip throws), and an unbound root holds the lock, as + * on the write. No logger is handed to the strip: nothing is written, so no + * "ignoring incoming change" line is true. + * + * ## What it judges the field with + * + * The payload carries the value the field holds NOW (the stored row's), so a + * predicate reads the record exactly as it stands: `record` is the stored row, + * `previous` is the stored row. A lock whose predicate reads the INCOMING + * value of its own field cannot be judged before that value exists; it is + * judged here against the value already there. + * + * ## Named limits + * + * - The update's `beforeUpdate` hooks are not run. A hook that rewrites a + * field a predicate reads moves the write's verdict and not this one. + * - Static `readonly` is not judged here: it is a property of the field's + * definition, readable off the schema without the record. + * - Neither are the update's other refusals (permissions, an approval's + * record lock, validation rules): they belong to their own doors. + * + * ## Reads + * + * None for a field that declares no `readonlyWhen`. Otherwise: the READ DOOR + * first, under the caller's own context — a row the caller cannot read is a + * row that does not exist, answered `recordNotFoundError` as the by-id update + * answers it — then the stored row, then the header when a predicate on the + * field reads `parent`. + */ + +import { recordNotFoundError } from '@objectstack/core'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { ObjectQL } from './engine.js'; +import { readonlyDropReasonPhrase } from './readonly-strict-errors.js'; +import { hasParentScopedReadonlyWhenInPayload, stripReadonlyWhenFields } from './validation/rule-validator.js'; + +/** + * A lock that keeps a field from taking a caller's write now. `reason` is the + * `DroppedFieldsEvent['reason']` the update reports the field under + * (`onFieldsDropped`, `droppedFields`); `phrase` is how the update's strict + * refusal (`ReadonlyFieldRejectedError`) names that reason. + */ +export interface FieldWriteLock { + readonly reason: 'readonly_when'; + readonly phrase: string; +} + +/** The members of `ObjectQL` the judgement reads. */ +export interface FieldWriteLockHost { + resolveObjectName: ObjectQL['resolveObjectName']; + readonly _registry: ObjectQL['_registry']; + findOne: ObjectQL['findOne']; + readUpdatePriorRow: ObjectQL['readUpdatePriorRow']; + resolveMasterDetailParent: ObjectQL['resolveMasterDetailParent']; +} + +/** The body of `ObjectQL#judgeFieldWriteLock`; the method's docblock there is its contract. */ +export async function judgeFieldWriteLock( + this: FieldWriteLockHost, + objectName: string, + id: unknown, + field: string, + options?: { context?: ExecutionContext }, +): Promise { + const object = this.resolveObjectName(objectName); + const schema = this._registry.getObject(object) as { fields?: Record } | undefined; + const def = schema?.fields?.[field]; + if (!def || !def.readonlyWhen) return null; + + const context = options?.context; + const visible = await this.findOne(object, { where: { id }, context } as EngineQueryOptions); + const prior = visible && typeof visible === 'object' ? await this.readUpdatePriorRow(object, id, context) : null; + if (!prior) throw recordNotFoundError(object, id as string); + + const payload: Record = { [field]: Object.prototype.hasOwnProperty.call(prior, field) ? prior[field] : null }; + const parent = hasParentScopedReadonlyWhenInPayload(schema as never, payload) + ? await this.resolveMasterDetailParent(schema, payload, prior, context) + : undefined; + const kept = stripReadonlyWhenFields(schema as never, payload, prior, undefined, parent); + if (kept && Object.prototype.hasOwnProperty.call(kept, field)) return null; + return { reason: 'readonly_when', phrase: readonlyDropReasonPhrase('readonly_when') }; +} diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 152f232d8d4..5d84cb5566a 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -276,6 +276,9 @@ import { collectCascadeDeleteSet, deleteRestrictedError, recordReferenceCheckEle // members it reads (`ValidateHost`). Imported after every module that body // imports, so the engine's module evaluation order is what it was. import { validate } from './engine-validate.js'; +// [#32768] The write-free `readonlyWhen` judgement's body; `judgeFieldWriteLock` +// below hands it the members it reads (`FieldWriteLockHost`). +import { judgeFieldWriteLock, type FieldWriteLock } from './engine-field-write-lock.js'; // [#25522 cut 20] The `where`-lowering bodies (`QueryLoweringHost`), imported // after every module they import, so module evaluation order is unchanged. import { lowerRelationConditions, resolveSearchQueryableFields, resolveWhereTokens } from './engine-query-lowering.js'; @@ -4584,6 +4587,46 @@ export class ObjectQL implements IObjectQLEngine { return validate.call(host, object, data, options); } + /** + * [#32768] Is `field` writable on the record `id` names NOW, as far as its + * `readonlyWhen` lock goes — judged without writing anything. + * + * Answers `null` when an update by this caller would keep the field, and a + * {@link FieldWriteLock} when the update's conditional strip would take it + * back out: `reason` is the `DroppedFieldsEvent['reason']` the update + * reports it under (`'readonly_when'`), `phrase` the words its strict + * refusal (`ReadonlyFieldRejectedError`) names that reason with. + * + * The verdict is the update's own: the same strip, over the same stored row + * (the update's prior-row read), master-detail header and gate, with the + * field carrying the value it holds now. A predicate that faults refuses as + * the write refuses it; an unbound root holds the lock. A row the caller + * cannot read through the read door answers as not found, as the by-id + * update answers it. A field with no `readonlyWhen` reads nothing. + * + * Named limits: `beforeUpdate` hooks are not run, so a hook that rewrites a + * field a predicate reads moves the write's verdict and not this one; static + * `readonly`, permissions and validation rules are not judged here. See + * `engine-field-write-lock.ts`. + */ + async judgeFieldWriteLock( + object: string, + id: unknown, + field: string, + options?: { context?: ExecutionContext }, + ): Promise { + // [#32768] The body lives in `engine-field-write-lock.ts` (see `FieldWriteLockHost`). + const readRegistry = () => this._registry; + const host: ThisParameterType = { + resolveObjectName: (...a) => this.resolveObjectName(...a), + get _registry() { return readRegistry(); }, + findOne: (...a) => this.findOne(...a), + readUpdatePriorRow: (...a) => this.readUpdatePriorRow(...a), + resolveMasterDetailParent: (...a) => this.resolveMasterDetailParent(...a), + }; + return judgeFieldWriteLock.call(host, object, id, field, options); + } + private updateByIdExpecting( driver: IDataDriver, object: string, diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index d1c9ac4b50a..fe7d449c9f2 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -303,6 +303,9 @@ export type { SummaryRecomputeFailure } from './summary-errors.js'; // holding the other realm's copy of the class gets `instanceof` === false, // silently. export { ReadonlyFieldRejectedError, READONLY_FIELD_REJECTED_CODE } from './readonly-strict-errors.js'; +// [#32768] What `ObjectQL#judgeFieldWriteLock` answers for a field its +// `readonlyWhen` locks now: the drop reason and the strict refusal's phrase. +export type { FieldWriteLock } from './engine-field-write-lock.js'; // [#14095] Thrown by `engine.insert` when a driver refuses a row as a unique // violation. Exported so an application implementing the platform's own // "declare a unique index, attempt the insert, swallow the violation" idiom can diff --git a/packages/objectql/src/readonly-strict-errors.ts b/packages/objectql/src/readonly-strict-errors.ts index a8888fad2ae..bc82906ff25 100644 --- a/packages/objectql/src/readonly-strict-errors.ts +++ b/packages/objectql/src/readonly-strict-errors.ts @@ -99,6 +99,17 @@ const REASON_PHRASE: Record = { 'value sent differs from the computed one, so it would have been replaced', }; +/** + * [#32768] How the strict refusal names `reason` to a human — the phrase + * {@link ReadonlyFieldRejectedError}'s per-reason sentence speaks. Exported + * for the write-free lock judgement (`engine-field-write-lock.ts`), so a door + * that refuses ahead of the write names the lock in the write's own words + * rather than re-spelling them. Not re-exported from the package entry. + */ +export function readonlyDropReasonPhrase(reason: DroppedFieldsEvent['reason']): string { + return REASON_PHRASE[reason] ?? reason; +} + /** * The per-reason breakdown sentence, e.g. * `id — the primary key, …; amount — read-only in the target record's …`. 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 f02db8a8206..ab4e9f10c36 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 @@ -464,5 +464,36 @@ describe('[#30892] showcase: an agent reads and attaches a record\'s files over // Spent: the link is not usable a second time. expect((await put(late.path, minimalPdf('Taxi invoice'))).status).toBe(404); }); + + // [#32768] The issue-time half: once the lock holds, the agent gets no + // link at all, refused for the lock `update_record` reports on the same + // field (`droppedFields`, reason `readonly_when`), in the words the + // update's strict refusal uses for it. + it('after approval create_upload_link gets no link, refused 403 for the lock update_record reports on the field', async () => { + const users = (await ql.find('sys_user', { where: { email: MEMBER_EMAIL }, ...SYS })) as Array<{ id: string }>; + const created = await ql.insert(UPLOAD_CLAIM, { name: 'Trip to Porto', status: 'draft', created_by: users[0]!.id, owner_id: users[0]!.id }, SYS); + const claimId = String(created?.id ?? created?.record?.id ?? created); + const draft = await mint({ objectName: UPLOAD_CLAIM, recordId: claimId, field: 'invoices' }); + const first = await put(draft.path, minimalPdf('Train invoice'), { 'x-file-name': 'train-invoice.pdf' }); + const firstBody: any = await first.json(); + expect(first.status, JSON.stringify(firstBody)).toBe(200); + + await ql.update(UPLOAD_CLAIM, { status: 'approved' }, { where: { id: claimId }, ...SYS }); + const linksBefore = (await ql.find('sys_file', { where: { name: 'upload-link', status: 'pending' }, ...SYS })).length; + const error = await refused(memberToken, 'create_upload_link', { objectName: UPLOAD_CLAIM, recordId: claimId, field: 'invoices' }); + expect(error.code).toBe('FIELD_NOT_ACCESSIBLE'); + expect(error.message).toBe( + `You cannot attach a file to ${UPLOAD_CLAIM}.invoices: the field is read-only in the target record's current state ` + + '(a TRUE `readonlyWhen` predicate).', + ); + expect((await ql.find('sys_file', { where: { name: 'upload-link', status: 'pending' }, ...SYS })).length).toBe(linksBefore); + + const { json } = await ok(memberToken, 'update_record', { + objectName: UPLOAD_CLAIM, recordId: claimId, data: { invoices: [firstBody.data.fileId] }, + }); + expect(json.droppedFields, JSON.stringify(json)).toEqual( + expect.arrayContaining([expect.objectContaining({ reason: 'readonly_when', fields: ['invoices'] })]), + ); + }); }); }); 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 a2333aeefc4..aa87111abd4 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 @@ -650,6 +650,37 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o expect(await openLinkRows()).toBe(before); }); + // [#32768] The issue-time half of the `readonlyWhen` refusal: the engine's + // own write-free verdict (`judgeFieldWriteLock`), asked before any link row + // is written, in the words the update's strict refusal uses for the lock. + it('minting refuses a field whose readonlyWhen holds now 403 FIELD_NOT_ACCESSIBLE, in the update\'s words, and writes no link', async () => { + const id = await draftClaim('approved before mint'); + await engine.update('claim', { status: 'approved' }, { where: { id }, context: SYS } as never); + const before = await openLinkRows(); + const r = await refusalOf(files.createUploadLinkAs('claim', id, { field: 'invoices' }, OWNER as never)); + expect(r).toMatchObject({ code: 'FIELD_NOT_ACCESSIBLE', status: 403 }); + expect(r?.message).toBe( + "You cannot attach a file to claim.invoices: the field is read-only in the target record's current state " + + '(a TRUE `readonlyWhen` predicate).', + ); + expect(await openLinkRows()).toBe(before); + }); + + it('the same field while its readonlyWhen is false gets a link; a static readonly field keeps its refusal; the attachments list is not judged', async () => { + const draft = await draftClaim('draft at mint'); + const grant = await files.createUploadLinkAs('claim', draft, { field: 'invoices' }, OWNER as never); + expect(grant.path).toBe(`${BASE}/upload-links/${grant.token}`); + + const r = await refusalOf(files.createUploadLinkAs('claim', draft, { field: 'stamp' }, OWNER as never)); + expect(r).toMatchObject({ code: 'FIELD_NOT_ACCESSIBLE', status: 403 }); + expect(r?.message).toBe('You cannot attach a file to claim.stamp: the field is read-only.'); + + const approved = await draftClaim('approved, attachments'); + await engine.update('claim', { status: 'approved' }, { where: { id: approved }, context: SYS } as never); + const attach = await files.createUploadLinkAs('claim', approved, { attachments: true }, OWNER as never); + expect(attach.path).toBe(`${BASE}/upload-links/${attach.token}`); + }); + it('minting refuses a record a pending approval locks 409 RECORD_LOCKED and writes no link; once unlocked, it mints', async () => { const id = await draftClaim('locked at mint'); locked.add(id); diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index f190f9617cf..8e052dc1505 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -253,7 +253,22 @@ export interface UploadLinkDoor { } /** The data-engine surface these verbs use: the reads and writes every engine has, plus its schema read. */ -export type RecordFileEngine = IDataEngine & { getObject?(objectName: string): unknown }; +export interface RecordFileEngine extends IDataEngine { + getObject?(objectName: string): unknown; + /** + * [#32768] The engine's write-free verdict on whether `field` takes the + * caller's write on this record now (ObjectQL's `judgeFieldWriteLock`): its + * own `readonlyWhen` evaluation, with the reason the update reports the + * field under and the words its strict refusal uses. Optional: an engine + * without it is not asked, and the upload's own write still refuses. + */ + judgeFieldWriteLock?( + object: string, + id: unknown, + field: string, + options?: { context?: ExecutionContext }, + ): Promise<{ reason: string; phrase: string } | null>; +} /** What {@link RecordFileAccess} is composed over — each read at call time. */ export interface RecordFileAccessDeps { @@ -672,6 +687,16 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo if (fieldDef?.readonly === true) { refuse('FIELD_NOT_ACCESSIBLE', 403, `You cannot attach a file to ${object}.${field}: the field is read-only.`); } + // [#32768] Nor a field whose `readonlyWhen` holds now: the update would + // take it back out, so the upload would be refused when it arrives. The + // engine's own judgement, not a second evaluation here; the refusal + // names the lock in the words the update's strict refusal uses. + if (typeof engine.judgeFieldWriteLock === 'function') { + const lock = await engine.judgeFieldWriteLock(object, recordId, field, { context: caller }); + if (lock) { + refuse('FIELD_NOT_ACCESSIBLE', 403, `You cannot attach a file to ${object}.${field}: the field is ${lock.phrase}.`); + } + } // [#32734] Nor does a record a pending approval locks: every edit of it // is refused until the approval is decided, recalled or rejected. The // approvals service's own answer, judged as the record-lock hook judges