From 36656b03837a050079c9ce6a028dea62eaa74bc9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 05:23:06 +0000 Subject: [PATCH 1/7] feat(service-storage): sys_attachment verifies the caller may open the referenced file Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_017xRBcScm27Q3R5mkYLPWdB --- .../src/attachment-access-hooks.test.ts | 135 ++++++++++++++++++ .../src/attachment-access-hooks.ts | 83 +++++++++++ .../src/file-reference-lifecycle.ts | 80 ++--------- .../service-storage/src/referenceable-file.ts | 104 ++++++++++++++ .../src/storage-service-plugin.ts | 12 +- 5 files changed, 341 insertions(+), 73 deletions(-) create mode 100644 packages/services/service-storage/src/referenceable-file.ts diff --git a/packages/services/service-storage/src/attachment-access-hooks.test.ts b/packages/services/service-storage/src/attachment-access-hooks.test.ts index ab29075cb5b..32852ce1419 100644 --- a/packages/services/service-storage/src/attachment-access-hooks.test.ts +++ b/packages/services/service-storage/src/attachment-access-hooks.test.ts @@ -1877,3 +1877,138 @@ describe('a kernel that judges no by-id update keeps the record-sharing and mast }); }); }); + +describe('attachment access — the file a row names must be one the caller may open', () => { + const OWN_FILE = { id: 'f-own', owner_id: 'u1', scope: 'attachments', status: 'committed' }; + const OTHER_FILE = { id: 'f-other', owner_id: 'u-admin', scope: 'attachments', status: 'committed' }; + const ROW = { id: 'a1', parent_object: 'task', parent_id: 't1', file_id: 'f-own', uploaded_by: 'u1' }; + + /** + * The gate with a bound file-read verdict: `openable` lists the file ids the + * caller may open; `fileReads` records every `sys_file` lookup the gate made. + */ + function installWithFiles(opts: { openable: string[]; bound?: boolean; canEditParent?: boolean }) { + const hooks = new Map Promise>(); + const files = [OWN_FILE, OTHER_FILE]; + const fileReads: any[] = []; + const authorizeFileRead = vi.fn(async (file: Record, context: any) => { + expect(context.userId).toBe('u1'); + return opts.openable.includes(String(file.id)); + }); + const engine: AttachmentLifecycleEngine & { getObject: (name: string) => unknown } = { + registerHook: (event, handler) => { + hooks.set(event, handler as any); + }, + getObject: (name) => (name === 'sys_attachment' ? { fields: { file_id: { label: 'File' } } } : undefined), + find: async () => [], + findOne: async (object, options: any) => { + assertEngineFindOnePredicate(object, options); + if (object === 'sys_file') { + fileReads.push(options); + return files.find((f) => f.id === options.where.id) ?? null; + } + return object === 'sys_attachment' && options.where.id === ROW.id ? { ...ROW } : null; + }, + update: async () => ({}), + }; + const canEdit = opts.canEditParent ?? true; + installAttachmentAccessHooks( + engine, + () => ({ checkEdit: async () => (canEdit ? ('allow' as const) : ('deny' as const)) }), + silentLogger(), + undefined, + () => null, + opts.bound === false ? undefined : authorizeFileRead, + ); + return { + beforeInsert: hooks.get('beforeInsert')!, + beforeUpdate: hooks.get('beforeUpdate')!, + authorizeFileRead, + fileReads, + }; + } + + const attach = (fileId: unknown, session: Record = { userId: 'u1', organizationId: 'org-1' }) => ({ + object: 'sys_attachment', + event: 'beforeInsert', + input: { + data: { parent_object: 'task', parent_id: 't1', file_id: fileId, file_name: 'x.png' }, + options: { context: { userId: 'u1', tenantId: 'org-1', permissions: [] } }, + }, + session, + api: apiFor(['task/t1']), + }); + + const repoint = (data: Record) => ({ + object: 'sys_attachment', + event: 'beforeUpdate', + input: { id: 'a1', data, options: { context: { userId: 'u1', tenantId: 'org-1', permissions: [] } } }, + session: { userId: 'u1', organizationId: 'org-1' }, + api: apiFor(['task/t1']), + }); + + const refusal = { + code: 'VALIDATION_FAILED', + fields: [ + { + field: 'file_id', + code: 'invalid_value', + label: 'File', + message: 'File cannot reference this file: it is not a file you can open. Choose a file you can open, or upload it again.', + }, + ], + }; + + it('insert refuses a file reference the caller cannot open, with the file-field door envelope', async () => { + const { beforeInsert, fileReads } = installWithFiles({ openable: ['f-own'] }); + await expect(beforeInsert(attach('f-other'))).rejects.toMatchObject(refusal); + // Looked up as the acting organization reaches it. + expect(fileReads[0].context).toMatchObject({ isSystem: true, tenantId: 'org-1' }); + }); + + it('insert answers an id that names no file exactly as a file the caller cannot open', async () => { + const { beforeInsert } = installWithFiles({ openable: ['f-own', 'f-missing'] }); + await expect(beforeInsert(attach('f-missing'))).rejects.toMatchObject(refusal); + }); + + it('insert admits a file the caller may open (control)', async () => { + const { beforeInsert, authorizeFileRead } = installWithFiles({ openable: ['f-own'] }); + await expect(beforeInsert(attach('f-own'))).resolves.toBeUndefined(); + expect(authorizeFileRead).toHaveBeenCalledTimes(1); + }); + + it('a system insert is not judged (control)', async () => { + const { beforeInsert, authorizeFileRead } = installWithFiles({ openable: [] }); + await expect(beforeInsert(attach('f-other', { isSystem: true }))).resolves.toBeUndefined(); + expect(authorizeFileRead).not.toHaveBeenCalled(); + }); + + it('a caller the parent rule refuses keeps the parent refusal, and no file is judged', async () => { + const { beforeInsert, authorizeFileRead } = installWithFiles({ openable: [], canEditParent: false }); + await expect(beforeInsert(attach('f-other'))).rejects.toMatchObject({ code: 'ATTACHMENT_PARENT_ACCESS', status: 403 }); + expect(authorizeFileRead).not.toHaveBeenCalled(); + }); + + it('with no file-read verdict bound, the file is not judged', async () => { + const { beforeInsert, fileReads } = installWithFiles({ openable: [], bound: false }); + await expect(beforeInsert(attach('f-other'))).resolves.toBeUndefined(); + expect(fileReads).toHaveLength(0); + }); + + it('update refuses changing file_id to a file the caller cannot open', async () => { + const { beforeUpdate } = installWithFiles({ openable: ['f-own'] }); + await expect(beforeUpdate(repoint({ file_id: 'f-other' }))).rejects.toMatchObject(refusal); + }); + + it('update admits changing file_id to a file the caller may open (control)', async () => { + const { beforeUpdate } = installWithFiles({ openable: ['f-own', 'f-other'] }); + await expect(beforeUpdate(repoint({ file_id: 'f-other' }))).resolves.toBeUndefined(); + }); + + it('update that leaves file_id as it is, or does not name it, judges no file (control)', async () => { + const { beforeUpdate, authorizeFileRead } = installWithFiles({ openable: [] }); + await expect(beforeUpdate(repoint({ file_id: 'f-own', file_name: 'y.png' }))).resolves.toBeUndefined(); + await expect(beforeUpdate(repoint({ file_name: 'z.png' }))).resolves.toBeUndefined(); + expect(authorizeFileRead).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/services/service-storage/src/attachment-access-hooks.ts b/packages/services/service-storage/src/attachment-access-hooks.ts index aea52d91205..ad7d83772db 100644 --- a/packages/services/service-storage/src/attachment-access-hooks.ts +++ b/packages/services/service-storage/src/attachment-access-hooks.ts @@ -12,6 +12,7 @@ import type { import { ReadableIds } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { renderOperationMessage, type ValidationMessageTranslator } from '@objectstack/spec/system'; +import { validationFailure } from '@objectstack/types'; import { createRefusedAttachTombstoner, @@ -19,6 +20,7 @@ import { type AttachmentLifecycleLogger, type AttachmentReadMiddlewareCtx, } from './attachment-lifecycle.js'; +import { findReferenceableFile, unreadableFileMessage, type FileReferenceReadAuthorizer } from './referenceable-file.js'; /** * sys_attachment access enforcement (#2755, ADR-0049 enforce-or-remove). @@ -55,6 +57,9 @@ import { * platform's not-visible refusal instead of the named one (#21755) — see * {@link refuseNotVisible}. The named refusals below are what a caller who * can read the parent, but may not edit it, receives. + * - Both write verbs: the `file_id` a row names must be a file the caller + * may open — on insert, and on an update that changes it. See "The file + * an attachment names" below. * - beforeDelete: the caller must be the uploader OR hold edit on the * parent record (see "Parent EDIT" below). Fail-closed 403 * `ATTACHMENT_DELETE_DENIED`; a @@ -111,6 +116,25 @@ import { * create or delete bit write files onto every master-detail child record of * the org — including records whose own update refuses them. * + * ## The file an attachment names + * + * An attachment is how an `attachments`-scope file becomes readable: the + * download door admits a caller through any parent record the file is + * attached to. So linking a file to a record hands its bytes to that record's + * readers, and the gate asks of every insert, and of every update that changes + * `file_id`, the question a file-class field asks before it claims a file: + * may this caller open the file it names? One predicate, + * `findReferenceableFile` (`referenceable-file.ts`), bound by the storage + * plugin to the download door's own verdict — so the uploader of a file, and a + * caller who can already open it through another record, attach it as before. + * A file the caller may not open, and an id that names no file the acting + * organization reaches, get one answer: the file-field door's `400 + * VALIDATION_FAILED`, one ADR-0114 `invalid_value` entry for `file_id`, naming + * nothing about the file. Asked after the parent rule, so a caller the parent + * rule refuses keeps that refusal. Not asked where no verdict is bound (a + * kernel that composes no download gate serves every file, and so every file + * may be referenced). + * * System-context operations (engine self-writes, seeds, lifecycle sweeps) * bypass all three gates, as do context-less programmatic calls on bare * kernels (no principal to authorize — REST always carries a context). @@ -498,6 +522,11 @@ async function sharingAndMasterAdmit( * asked on a record-sharing abstention instead; absent too, a * `controlled_by_parent` parent meets no master check here, exactly as its own * update meets none. + * + * `authorizeFileRead` is the download door's verdict on one file for one + * caller — the same binding the file-reference lifecycle receives — asked of + * the file a row's `file_id` names (see "The file an attachment names" in the + * module header). Absent, that question is not asked. */ export function installAttachmentAccessHooks( engine: AttachmentLifecycleEngine, @@ -505,6 +534,7 @@ export function installAttachmentAccessHooks( logger: AttachmentLifecycleLogger, messageTranslator?: () => ValidationMessageTranslator | undefined, getSecurity?: () => AttachmentSecurityLike | null | undefined, + authorizeFileRead?: FileReferenceReadAuthorizer, ): void { /** * [#22466] What a refused attach does about its file. Created HERE, at @@ -536,6 +566,29 @@ export function installAttachmentAccessHooks( ctx.api.object(object).findOne({ where: { id: recordId } }), ); + /** + * Refuse a `file_id` the caller may not open — see "The file an attachment + * names" in the module header. A value that is no id at all (absent, `null`, + * empty, not a scalar) names no file to judge, and is left to validation. + */ + const assertMayReferenceFile = async (ctx: any, fileId: unknown): Promise => { + if (!authorizeFileRead) return; + if (typeof fileId !== 'string' && typeof fileId !== 'number') return; + if (fileId === '') return; + const org = ctx?.session?.organizationId; + const found = await findReferenceableFile( + engine, + String(fileId), + typeof org === 'string' && org.length > 0 ? org : null, + callerContext(ctx), + authorizeFileRead, + ); + if (found !== 'refused') return; + const label = fileIdLabelOf(engine); + const message = unreadableFileMessage(label); + throw validationFailure(message, [{ field: 'file_id', code: 'invalid_value', message, label }]); + }; + /** Resolve every sys_attachment row a write matches, under SYSTEM context * — the caller may legitimately be unable to READ rows they are allowed to * touch (and the read-visibility middleware below must not narrow the @@ -695,6 +748,9 @@ export function installAttachmentAccessHooks( parentObject, ); } + + // The file this row links must be one the caller may open. + await assertMayReferenceFile(ctx, data.file_id); }, { object: 'sys_attachment', packageId: PACKAGE_ID }, ); @@ -734,6 +790,15 @@ export function installAttachmentAccessHooks( // Mirrors the comment kit's thread re-point rule (#4630). const data: any = ctx?.input?.data; if (!data || typeof data !== 'object') return; + + // Re-pointing `file_id` links a different file to the parent: the new + // file must be one the caller may open, as on insert. Asked once — the + // payload names one file for every matched row — and only when some row + // actually changes file. + if (data.file_id !== undefined && rows.some((row) => String(row.file_id ?? '') !== String(data.file_id ?? ''))) { + await assertMayReferenceFile(ctx, data.file_id); + } + if (data.parent_object === undefined && data.parent_id === undefined) return; /** Attach-rule verdicts memoized per effective (object, id) target. */ @@ -818,6 +883,24 @@ export function installAttachmentAccessHooks( ); } +/** + * The declared label of `sys_attachment.file_id`, which the refusal names the + * way the file-field door names its field — or the field's name, on an engine + * that serves no object metadata here. + */ +function fileIdLabelOf(engine: AttachmentLifecycleEngine): string { + const getObject = (engine as { getObject?: (name: string) => unknown }).getObject; + let label: unknown; + try { + label = typeof getObject === 'function' + ? (getObject.call(engine, 'sys_attachment') as any)?.fields?.file_id?.label + : undefined; + } catch { + label = undefined; + } + return typeof label === 'string' && label.trim().length > 0 ? label.trim() : 'file_id'; +} + /** No real row matches — the fail-closed sentinel (mirrors plugin-sharing's * `{ id: '__deny_all__' }` read-filter deny). */ const READ_DENY_ALL = { id: '__attachment_parent_denied__' } as const; diff --git a/packages/services/service-storage/src/file-reference-lifecycle.ts b/packages/services/service-storage/src/file-reference-lifecycle.ts index f111b144ce0..9242dc8d0e3 100644 --- a/packages/services/service-storage/src/file-reference-lifecycle.ts +++ b/packages/services/service-storage/src/file-reference-lifecycle.ts @@ -7,6 +7,14 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import { isEmptyForRequired } from '@objectstack/core'; import { validationFailure } from '@objectstack/types'; import { callerContext } from './attachment-access-hooks.js'; +import { + findReferenceableFile, + systemReadContext, + unreadableFileMessage, + type FileReferenceReadAuthorizer, +} from './referenceable-file.js'; + +export type { FileReferenceReadAuthorizer } from './referenceable-file.js'; /** * Field-reference file ownership (ADR-0104 D3 wave 2). @@ -188,30 +196,6 @@ function systemWriteContext(organizationId?: string | null): Record { - return typeof organizationId === 'string' && organizationId.length > 0 - ? { ...SYSTEM_CTX, tenantId: organizationId } : { ...SYSTEM_CTX }; } @@ -233,23 +217,6 @@ function actingOrganizationOf(ctx: any): string | null { return typeof org === 'string' && org.length > 0 ? org : null; } -/** - * [#25692] "May the caller of this record write read this file?" — the - * download door's verdict on the file's bytes, asked of the write's caller. - * - * Supplied by the storage plugin, which binds it to the door's own judgement - * (`storage-service-plugin.ts`), and never decided in this module: one file, - * one access rule, so the bytes, the metadata and a reference to them are - * judged by one predicate. `true` admits; `false` refuses. A throw is not a - * verdict — the plugin's binding lets only an authorization-store outage - * through, and it propagates, so an unreadable store fails the write rather - * than reading as either answer. - */ -export type FileReferenceReadAuthorizer = ( - file: Record, - context: ExecutionContext, -) => Promise; - /** * The caller to ask {@link FileReferenceReadAuthorizer} about, or `null` when * there is none: a context-less programmatic call (no session — a bare kernel, @@ -300,34 +267,6 @@ function claimingCallerOf(ctx: any, fileId: string, caller: ExecutionContext | n return key && mintedCopies.get(key)?.has(fileId) ? null : caller; } -/** - * The `sys_file` row a field's id token names, as THIS write may reference it. - * Both halves of the claim path — copy-on-claim before the write, the claim - * after it — ask through here, so they cannot disagree about which file a - * write may take. - * - * 1. The row as the acting organization reaches it ({@link systemReadContext}). - * 2. [#25692] Then, when the plugin bound a read verdict and the write has a - * caller, whether that caller may read it. - * - * [#26043] When a caller is asked about, a file it may not read and an id the - * lookup cannot see are one answer, `'refused'`, which copy-on-claim refuses - * at the field. With no caller to ask, an id the lookup cannot see is `null`: - * an id the platform does not manage, kept as written. - */ -async function findReferenceableFile( - engine: FileReferenceEngine, - fileId: string, - organizationId: string | null, - caller: ExecutionContext | null, - authorizeRead: FileReferenceReadAuthorizer | undefined, -): Promise | 'refused' | null> { - const row = await engine.findOne('sys_file', { where: { id: fileId }, context: systemReadContext(organizationId) }); - if (!caller || !authorizeRead) return row ?? null; - if (!row) return 'refused'; - return (await authorizeRead(row, caller)) ? row : 'refused'; -} - /** One field a file-field judgement refuses: the ADR-0114 entry the form door's envelope carries. */ interface FileFieldRefusal { field: string; @@ -362,8 +301,7 @@ function refuseUnreadableFile(engine: FileReferenceEngine, object: string, field return { field, code: 'invalid_value', - message: `${label} cannot reference this file: it is not a file you can open. ` - + 'Choose a file you can open, or upload it again.', + message: unreadableFileMessage(label), label, }; } diff --git a/packages/services/service-storage/src/referenceable-file.ts b/packages/services/service-storage/src/referenceable-file.ts new file mode 100644 index 00000000000..b60fbb30345 --- /dev/null +++ b/packages/services/service-storage/src/referenceable-file.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +import { RAW_FILE_VALUES_CONTEXT_KEY } from '@objectstack/spec/data'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; + +/** + * "May this write reference that file?" — the ONE predicate every write that + * names a `sys_file` id asks of its caller, wherever the id is written: + * + * - a file-class FIELD on a record (`file-reference-lifecycle.ts`, ADR-0104 + * D3 wave 2), before it claims or copies the file; + * - a `sys_attachment` row's `file_id` (`attachment-access-hooks.ts`), on + * insert and on an update that changes it — an attachment is how a file + * becomes readable through a parent record, so linking one is a way to + * hand its bytes to that parent's readers. + * + * Both doors ask it here, so a file a caller may not open cannot be referenced + * through either of them, and the two cannot disagree about which files a + * caller may take. The verdict itself is the download door's + * ({@link FileReferenceReadAuthorizer}, bound by the storage plugin): one file, + * one access rule. + */ + +/** + * [#25692] "May the caller of this write read this file?" — the download + * door's verdict on the file's bytes, asked of the write's caller. + * + * Supplied by the storage plugin, which binds it to the door's own judgement + * (`storage-service-plugin.ts`), and never decided by a write gate: one file, + * one access rule, so the bytes, the metadata and a reference to them are + * judged by one predicate. `true` admits; `false` refuses. A throw is not a + * verdict — the plugin's binding lets only an authorization-store outage + * through, and it propagates, so an unreadable store fails the write rather + * than reading as either answer. + */ +export type FileReferenceReadAuthorizer = ( + file: Record, + context: ExecutionContext, +) => Promise; + +/** The slice of the data engine the lookup reads through. */ +export interface ReferenceableFileEngine { + findOne(object: string, options: Record): Promise | null>; +} + +// Bookkeeping reads want the STORED form — never the read resolver's expanded +// shape. +const SYSTEM_READ_CTX = { isSystem: true, [RAW_FILE_VALUES_CONTEXT_KEY]: true } as const; + +/** + * The bookkeeping context for LOOKING UP a file a write references, carrying + * the acting organization when the triggering write had one. + * + * A write references a file only as its own organization can reach it: the + * organization travels as `tenantId`, and the driver's tenant term (the + * wall's verdict for the posture in force, ADR-0131 D8) decides which rows the + * lookup can see. ⛔ No organization comparison is written here: whether + * `sys_file` has a tenant column, what a row with no organization means and + * whether the posture walls at all (`single` does not) are the platform's + * answers. No organization ⇒ the key is absent and the lookup reads as a plain + * system read. + */ +export function systemReadContext(organizationId?: string | null): Record { + return typeof organizationId === 'string' && organizationId.length > 0 + ? { ...SYSTEM_READ_CTX, tenantId: organizationId } + : { ...SYSTEM_READ_CTX }; +} + +/** + * The `sys_file` row an id names, as THIS write may reference it. + * + * 1. The row as the acting organization reaches it ({@link systemReadContext}). + * 2. [#25692] Then, when the plugin bound a read verdict and the write has a + * caller, whether that caller may read it. + * + * [#26043] When a caller is asked about, a file it may not read and an id the + * lookup cannot see are one answer, `'refused'`, so a write door cannot tell + * "may not read" from "does not exist". With no caller to ask (a system write, + * a context-less programmatic call) or no verdict bound, an id the lookup + * cannot see is `null`. + */ +export async function findReferenceableFile( + engine: ReferenceableFileEngine, + fileId: string, + organizationId: string | null, + caller: ExecutionContext | null, + authorizeRead: FileReferenceReadAuthorizer | undefined, +): Promise | 'refused' | null> { + const row = await engine.findOne('sys_file', { where: { id: fileId }, context: systemReadContext(organizationId) }); + if (!caller || !authorizeRead) return row ?? null; + if (!row) return 'refused'; + return (await authorizeRead(row, caller)) ? row : 'refused'; +} + +/** + * [#26043] The sentence a write door answers a `'refused'` file with, for the + * field (`label`) that named it. It names the field only: the same words for a + * file the caller may not open and for an id that does not exist, and nothing + * about the file or who holds it. + */ +export function unreadableFileMessage(label: string): string { + return `${label} cannot reference this file: it is not a file you can open. ` + + 'Choose a file you can open, or upload it again.'; +} diff --git a/packages/services/service-storage/src/storage-service-plugin.ts b/packages/services/service-storage/src/storage-service-plugin.ts index 1d69d9546e7..71831c52b14 100644 --- a/packages/services/service-storage/src/storage-service-plugin.ts +++ b/packages/services/service-storage/src/storage-service-plugin.ts @@ -62,7 +62,8 @@ import type { TenancyPosture } from '@objectstack/spec/security'; import { registerStorageFamily } from './storage-routes.js'; import type { FileReadVerdict, StorageGatedSessionReader, StorageUploadSession } from './storage-routes.js'; import { installAttachmentLifecycleHooks, createSysFileReapGuard, createUploadSessionReapGuard, findFileHolder, findHeldFiles } from './attachment-lifecycle.js'; -import { installFileReferenceHooks, type FileReferenceEngine, type FileReferenceReadAuthorizer } from './file-reference-lifecycle.js'; +import { installFileReferenceHooks, type FileReferenceEngine } from './file-reference-lifecycle.js'; +import type { FileReferenceReadAuthorizer } from './referenceable-file.js'; import { installAttachmentAccessHooks, installAttachmentReadVisibility } from './attachment-access-hooks.js'; import { contributeAttachmentDeleteFloorAlternate } from './attachment-delete-floor-alternate.js'; import { FileAttachmentService, type FileAttachmentEngine } from './file-attachment-service.js'; @@ -483,6 +484,11 @@ export class StorageServicePlugin implements Plugin { // lifecycle sweep. Both degrade silently on bare kernels. if (engine && typeof (engine as any).registerHook === 'function') { installAttachmentLifecycleHooks(engine as any, ctx.logger); + // [#25692] The download door's verdict on one file for one caller, + // bound once from the live registry and handed to BOTH write doors + // that name a `sys_file` id — a file-class field and a + // `sys_attachment` row — so a reference and the door cannot diverge. + const authorizeFileReference = buildFileReferenceReadAuthorizer(toGateRegistry(ctx), engine); // Parent-derived access on the join rows (#2755, ADR-0049) — the // sharing service resolves lazily so plugin order doesn't matter. installAttachmentAccessHooks( @@ -516,6 +522,8 @@ export class StorageServicePlugin implements Plugin { return null; } }, + // The file a row's `file_id` names must be one the caller may open. + authorizeFileReference, ); // [#21729] The gate's parent-editor DELETE limb, made reachable: the // alternate match that stops the platform's `created_by` delete floor @@ -560,7 +568,7 @@ export class StorageServicePlugin implements Plugin { engine as any, () => this.storage, ctx.logger, - buildFileReferenceReadAuthorizer(toGateRegistry(ctx), engine), + authorizeFileReference, ); // "Is anything still holding this tombstone?" for RECORD FILE-FIELD // HYDRATION (commit c3c72a4bc). The download path got this question in #10246; From 2cb50c68bac4846b49bd1510e08a28df5f6afc1b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 05:27:34 +0000 Subject: [PATCH 2/7] fix(service-storage): drop leftover lines from the predicate move Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_017xRBcScm27Q3R5mkYLPWdB --- .../service-storage/src/file-reference-lifecycle.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/services/service-storage/src/file-reference-lifecycle.ts b/packages/services/service-storage/src/file-reference-lifecycle.ts index 9242dc8d0e3..42221907e6d 100644 --- a/packages/services/service-storage/src/file-reference-lifecycle.ts +++ b/packages/services/service-storage/src/file-reference-lifecycle.ts @@ -9,7 +9,6 @@ import { validationFailure } from '@objectstack/types'; import { callerContext } from './attachment-access-hooks.js'; import { findReferenceableFile, - systemReadContext, unreadableFileMessage, type FileReferenceReadAuthorizer, } from './referenceable-file.js'; @@ -62,7 +61,7 @@ export type { FileReferenceReadAuthorizer } from './referenceable-file.js'; * field, before the driver runs and before any file is copied: one * `400 VALIDATION_FAILED` with an ADR-0114 `invalid_value` entry per field, * naming the field and nothing about the file ({@link refuseUnreadableFile}). - * An id the organization-scoped lookup cannot see ({@link systemReadContext}) + * An id the organization-scoped lookup cannot see (`systemReadContext` in `referenceable-file.ts`) * gets the same answer, so the write door cannot tell "may not read" from * "does not exist". It replaces #25951's quiet answer, which kept the id as * written: that left a slot holding a file it does not own, the state @@ -196,9 +195,6 @@ function systemWriteContext(organizationId?: string | null): Record Date: Thu, 29 Oct 2026 05:29:49 +0000 Subject: [PATCH 3/7] refactor(service-storage): install the attachment file gate as its own registration Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_017xRBcScm27Q3R5mkYLPWdB --- .../src/attachment-access-hooks.test.ts | 18 ++- .../src/attachment-access-hooks.ts | 130 ++++++++++++------ .../src/storage-service-plugin.test.ts | 6 + .../src/storage-service-plugin.ts | 11 +- 4 files changed, 111 insertions(+), 54 deletions(-) diff --git a/packages/services/service-storage/src/attachment-access-hooks.test.ts b/packages/services/service-storage/src/attachment-access-hooks.test.ts index 32852ce1419..242bffb5659 100644 --- a/packages/services/service-storage/src/attachment-access-hooks.test.ts +++ b/packages/services/service-storage/src/attachment-access-hooks.test.ts @@ -7,6 +7,7 @@ import type { ControlledByParentWriteOutcome, ExplainAccessRequest } from '@obje import type { ExplainDecision } from '@objectstack/spec/security'; import { installAttachmentAccessHooks, + installAttachmentFileReferenceGate, mayEditAttachmentParent, type AttachmentSecurityLike, type AttachmentSharingLike, @@ -1888,7 +1889,9 @@ describe('attachment access — the file a row names must be one the caller may * caller may open; `fileReads` records every `sys_file` lookup the gate made. */ function installWithFiles(opts: { openable: string[]; bound?: boolean; canEditParent?: boolean }) { - const hooks = new Map Promise>(); + // Every handler per event, in registration order — the engine's own order + // for same-priority hooks. + const hooks = new Map Promise>>(); const files = [OWN_FILE, OTHER_FILE]; const fileReads: any[] = []; const authorizeFileRead = vi.fn(async (file: Record, context: any) => { @@ -1897,7 +1900,7 @@ describe('attachment access — the file a row names must be one the caller may }); const engine: AttachmentLifecycleEngine & { getObject: (name: string) => unknown } = { registerHook: (event, handler) => { - hooks.set(event, handler as any); + hooks.set(event, [...(hooks.get(event) ?? []), handler as any]); }, getObject: (name) => (name === 'sys_attachment' ? { fields: { file_id: { label: 'File' } } } : undefined), find: async () => [], @@ -1918,11 +1921,14 @@ describe('attachment access — the file a row names must be one the caller may silentLogger(), undefined, () => null, - opts.bound === false ? undefined : authorizeFileRead, ); + if (opts.bound !== false) installAttachmentFileReferenceGate(engine, authorizeFileRead); + const chain = (event: string) => async (ctx: any) => { + for (const handler of hooks.get(event) ?? []) await handler(ctx); + }; return { - beforeInsert: hooks.get('beforeInsert')!, - beforeUpdate: hooks.get('beforeUpdate')!, + beforeInsert: chain('beforeInsert'), + beforeUpdate: chain('beforeUpdate'), authorizeFileRead, fileReads, }; @@ -1989,7 +1995,7 @@ describe('attachment access — the file a row names must be one the caller may expect(authorizeFileRead).not.toHaveBeenCalled(); }); - it('with no file-read verdict bound, the file is not judged', async () => { + it('without the file gate installed, the file is not judged', async () => { const { beforeInsert, fileReads } = installWithFiles({ openable: [], bound: false }); await expect(beforeInsert(attach('f-other'))).resolves.toBeUndefined(); expect(fileReads).toHaveLength(0); diff --git a/packages/services/service-storage/src/attachment-access-hooks.ts b/packages/services/service-storage/src/attachment-access-hooks.ts index ad7d83772db..92bab49a4c8 100644 --- a/packages/services/service-storage/src/attachment-access-hooks.ts +++ b/packages/services/service-storage/src/attachment-access-hooks.ts @@ -59,7 +59,7 @@ import { findReferenceableFile, unreadableFileMessage, type FileReferenceReadAut * can read the parent, but may not edit it, receives. * - Both write verbs: the `file_id` a row names must be a file the caller * may open — on insert, and on an update that changes it. See "The file - * an attachment names" below. + * an attachment names" below ({@link installAttachmentFileReferenceGate}). * - beforeDelete: the caller must be the uploader OR hold edit on the * parent record (see "Parent EDIT" below). Fail-closed 403 * `ATTACHMENT_DELETE_DENIED`; a @@ -130,10 +130,10 @@ import { findReferenceableFile, unreadableFileMessage, type FileReferenceReadAut * A file the caller may not open, and an id that names no file the acting * organization reaches, get one answer: the file-field door's `400 * VALIDATION_FAILED`, one ADR-0114 `invalid_value` entry for `file_id`, naming - * nothing about the file. Asked after the parent rule, so a caller the parent - * rule refuses keeps that refusal. Not asked where no verdict is bound (a - * kernel that composes no download gate serves every file, and so every file - * may be referenced). + * nothing about the file. Installed by {@link installAttachmentFileReferenceGate} + * right after the gates above, so it runs after them on each verb and a caller + * the parent or row rule refuses keeps that refusal. A kernel that composes no + * download gate serves every file, and so every file may be referenced there. * * System-context operations (engine self-writes, seeds, lifecycle sweeps) * bypass all three gates, as do context-less programmatic calls on bare @@ -522,11 +522,7 @@ async function sharingAndMasterAdmit( * asked on a record-sharing abstention instead; absent too, a * `controlled_by_parent` parent meets no master check here, exactly as its own * update meets none. - * - * `authorizeFileRead` is the download door's verdict on one file for one - * caller — the same binding the file-reference lifecycle receives — asked of - * the file a row's `file_id` names (see "The file an attachment names" in the - * module header). Absent, that question is not asked. + */ export function installAttachmentAccessHooks( engine: AttachmentLifecycleEngine, @@ -534,7 +530,6 @@ export function installAttachmentAccessHooks( logger: AttachmentLifecycleLogger, messageTranslator?: () => ValidationMessageTranslator | undefined, getSecurity?: () => AttachmentSecurityLike | null | undefined, - authorizeFileRead?: FileReferenceReadAuthorizer, ): void { /** * [#22466] What a refused attach does about its file. Created HERE, at @@ -566,29 +561,6 @@ export function installAttachmentAccessHooks( ctx.api.object(object).findOne({ where: { id: recordId } }), ); - /** - * Refuse a `file_id` the caller may not open — see "The file an attachment - * names" in the module header. A value that is no id at all (absent, `null`, - * empty, not a scalar) names no file to judge, and is left to validation. - */ - const assertMayReferenceFile = async (ctx: any, fileId: unknown): Promise => { - if (!authorizeFileRead) return; - if (typeof fileId !== 'string' && typeof fileId !== 'number') return; - if (fileId === '') return; - const org = ctx?.session?.organizationId; - const found = await findReferenceableFile( - engine, - String(fileId), - typeof org === 'string' && org.length > 0 ? org : null, - callerContext(ctx), - authorizeFileRead, - ); - if (found !== 'refused') return; - const label = fileIdLabelOf(engine); - const message = unreadableFileMessage(label); - throw validationFailure(message, [{ field: 'file_id', code: 'invalid_value', message, label }]); - }; - /** Resolve every sys_attachment row a write matches, under SYSTEM context * — the caller may legitimately be unable to READ rows they are allowed to * touch (and the read-visibility middleware below must not narrow the @@ -748,9 +720,6 @@ export function installAttachmentAccessHooks( parentObject, ); } - - // The file this row links must be one the caller may open. - await assertMayReferenceFile(ctx, data.file_id); }, { object: 'sys_attachment', packageId: PACKAGE_ID }, ); @@ -791,14 +760,6 @@ export function installAttachmentAccessHooks( const data: any = ctx?.input?.data; if (!data || typeof data !== 'object') return; - // Re-pointing `file_id` links a different file to the parent: the new - // file must be one the caller may open, as on insert. Asked once — the - // payload names one file for every matched row — and only when some row - // actually changes file. - if (data.file_id !== undefined && rows.some((row) => String(row.file_id ?? '') !== String(data.file_id ?? ''))) { - await assertMayReferenceFile(ctx, data.file_id); - } - if (data.parent_object === undefined && data.parent_id === undefined) return; /** Attach-rule verdicts memoized per effective (object, id) target. */ @@ -883,6 +844,85 @@ export function installAttachmentAccessHooks( ); } +/** + * Install the file half of the `sys_attachment` write gate: the `file_id` a + * row names must be a file the caller may open — on insert, and on an update + * that changes it. See "The file an attachment names" in the module header. + * + * `authorizeFileRead` is the download door's verdict on one file for one + * caller, the same binding the file-reference lifecycle receives. Installed + * AFTER {@link installAttachmentAccessHooks} (the engine runs same-priority + * hooks in registration order), so the parent and row rules answer first. + * System-context and context-less writes are not judged, as at every gate in + * this module. + */ +export function installAttachmentFileReferenceGate( + engine: AttachmentLifecycleEngine, + authorizeFileRead: FileReferenceReadAuthorizer, +): void { + /** + * Refuse a `file_id` the caller may not open. A value that is no id at all + * (absent, `null`, empty, not a scalar) names no file to judge, and is left + * to validation. + */ + const assertMayReferenceFile = async (ctx: any, fileId: unknown): Promise => { + if (typeof fileId !== 'string' && typeof fileId !== 'number') return; + if (fileId === '') return; + const org = ctx?.session?.organizationId; + const found = await findReferenceableFile( + engine, + String(fileId), + typeof org === 'string' && org.length > 0 ? org : null, + callerContext(ctx), + authorizeFileRead, + ); + if (found !== 'refused') return; + const label = fileIdLabelOf(engine); + const message = unreadableFileMessage(label); + throw validationFailure(message, [{ field: 'file_id', code: 'invalid_value', message, label }]); + }; + + engine.registerHook( + 'beforeInsert', + async (ctx: any) => { + if (ctx?.session?.isSystem) return; + if (!ctx?.session) return; // context-less programmatic call (bare kernel) + const data: any = ctx?.input?.data; + if (!data || typeof data !== 'object') return; + await assertMayReferenceFile(ctx, data.file_id); + }, + { object: 'sys_attachment', packageId: PACKAGE_ID }, + ); + + engine.registerHook( + 'beforeUpdate', + async (ctx: any) => { + if (ctx?.session?.isSystem) return; + if (!ctx?.session) return; // context-less programmatic call (bare kernel) + const data: any = ctx?.input?.data; + if (!data || typeof data !== 'object' || data.file_id === undefined) return; + // Asked once — the payload names one file for every matched row — and + // only when a matched row actually changes file. The per-row dispatch + // binds `input.id`; a call naming no id is judged outright (the unscoped + // shape is refused by the row rule before this hook runs). + const ids = asIdList(ctx?.input?.id); + if (ids) { + let changes = false; + for (const id of ids) { + const row = await engine.findOne('sys_attachment', { where: { id }, context: { ...SYSTEM_CTX } }); + if (row && String(row.file_id ?? '') !== String(data.file_id ?? '')) { + changes = true; + break; + } + } + if (!changes) return; + } + await assertMayReferenceFile(ctx, data.file_id); + }, + { object: 'sys_attachment', packageId: PACKAGE_ID }, + ); +} + /** * The declared label of `sys_attachment.file_id`, which the refusal names the * way the file-field door names its field — or the field's name, on an engine diff --git a/packages/services/service-storage/src/storage-service-plugin.test.ts b/packages/services/service-storage/src/storage-service-plugin.test.ts index 809473fab0b..635d387796d 100644 --- a/packages/services/service-storage/src/storage-service-plugin.test.ts +++ b/packages/services/service-storage/src/storage-service-plugin.test.ts @@ -474,12 +474,18 @@ describe('StorageServicePlugin: sys_file orphan lifecycle wiring (#2755)', () => // context per phase (#5574). The id now comes from `ctx.previous`, so the // registration has no work left and is gone; a second `beforeDelete` // reappearing here means the stash mechanism came back with it. + // + // The second `beforeInsert`/`beforeUpdate` pair is the file half of the + // write gate (`installAttachmentFileReferenceGate`): the `file_id` a row + // names must be a file its caller may open. expect(hookEvents.sort()).toEqual([ 'afterDelete', 'afterInsert', 'afterUpdate', 'beforeDelete', 'beforeInsert', + 'beforeInsert', + 'beforeUpdate', 'beforeUpdate', ]); // Field-reference ownership: claim/copy on write, release on delete diff --git a/packages/services/service-storage/src/storage-service-plugin.ts b/packages/services/service-storage/src/storage-service-plugin.ts index 71831c52b14..00a7d0699d2 100644 --- a/packages/services/service-storage/src/storage-service-plugin.ts +++ b/packages/services/service-storage/src/storage-service-plugin.ts @@ -64,7 +64,11 @@ import type { FileReadVerdict, StorageGatedSessionReader, StorageUploadSession } import { installAttachmentLifecycleHooks, createSysFileReapGuard, createUploadSessionReapGuard, findFileHolder, findHeldFiles } from './attachment-lifecycle.js'; import { installFileReferenceHooks, type FileReferenceEngine } from './file-reference-lifecycle.js'; import type { FileReferenceReadAuthorizer } from './referenceable-file.js'; -import { installAttachmentAccessHooks, installAttachmentReadVisibility } from './attachment-access-hooks.js'; +import { + installAttachmentAccessHooks, + installAttachmentFileReferenceGate, + installAttachmentReadVisibility, +} from './attachment-access-hooks.js'; import { contributeAttachmentDeleteFloorAlternate } from './attachment-delete-floor-alternate.js'; import { FileAttachmentService, type FileAttachmentEngine } from './file-attachment-service.js'; import { FieldFileService } from './field-file-service.js'; @@ -522,9 +526,10 @@ export class StorageServicePlugin implements Plugin { return null; } }, - // The file a row's `file_id` names must be one the caller may open. - authorizeFileReference, ); + // The file a `sys_attachment` row names must be one its caller may + // open — installed after the gates above, so they answer first. + installAttachmentFileReferenceGate(engine as any, authorizeFileReference); // [#21729] The gate's parent-editor DELETE limb, made reachable: the // alternate match that stops the platform's `created_by` delete floor // answering for `sys_attachment` before the gate above runs. Contributed From c83d18422ff31ef289bc1f938d803057dba1adda Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 05:39:36 +0000 Subject: [PATCH 4/7] test(dogfood): sys_attachment file_id names a file the caller may open Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_017xRBcScm27Q3R5mkYLPWdB --- ...achments-permission-matrix.dogfood.test.ts | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/packages/qa/dogfood/test/attachments-permission-matrix.dogfood.test.ts b/packages/qa/dogfood/test/attachments-permission-matrix.dogfood.test.ts index c30eff7de6f..affb7486488 100644 --- a/packages/qa/dogfood/test/attachments-permission-matrix.dogfood.test.ts +++ b/packages/qa/dogfood/test/attachments-permission-matrix.dogfood.test.ts @@ -480,6 +480,60 @@ describe('attachments permission matrix (#2755)', () => { expect(anon302.status).toBe(401); }); + // ── (h) the file a row names must be one the caller may open ───────── + describe('(h) sys_attachment.file_id names a file the caller may open', () => { + /** The file-field door's refusal, for the `file_id` field. */ + const expectFileRefusal = async (res: Response) => { + expect(res.status, await res.clone().text()).toBe(400); + const body = (await res.json()) as any; + expect(body.code).toBe('VALIDATION_FAILED'); + expect((body.fields ?? []).map((f: any) => [f.field, f.code])).toEqual([['file_id', 'invalid_value']]); + }; + + it('insert refuses a file reference the caller cannot open, and no row lands; the caller own upload attaches (control)', async () => { + const adminFile = await uploadFile(stack, adminTok); + expect((await attach(adminTok, 'att_secret', secretId, adminFile)).status).toBeLessThan(300); + expect((await stack.apiAs(memberATok, 'GET', `/storage/files/${adminFile}/url`)).status).toBe(403); + + await expectFileRefusal(await attach(memberATok, 'att_case', caseAId, adminFile)); + const landed = await ql.find('sys_attachment', { + where: { parent_object: 'att_case', parent_id: caseAId, file_id: adminFile }, + context: SYS, + }); + expect(landed).toHaveLength(0); + expect((await stack.apiAs(memberATok, 'GET', `/storage/files/${adminFile}/url`)).status).toBe(403); + + // Control: the caller's own freshly uploaded file attaches. + const ownFile = await uploadFile(stack, memberATok); + expect((await attach(memberATok, 'att_case', caseAId, ownFile)).status).toBeLessThan(300); + }); + + it('update refuses re-pointing file_id at a file the caller cannot open; re-pointing at the caller own file succeeds (control)', async () => { + const adminFile = await uploadFile(stack, adminTok); + expect((await attach(adminTok, 'att_secret', secretId, adminFile)).status).toBeLessThan(300); + + const ownFile = await uploadFile(stack, memberATok); + expect((await attach(memberATok, 'att_case', caseAId, ownFile)).status).toBeLessThan(300); + const row = await ql.findOne('sys_attachment', { where: { file_id: ownFile }, context: SYS }); + + await expectFileRefusal(await stack.apiAs(memberATok, 'PATCH', `/data/sys_attachment/${row.id}`, { file_id: adminFile })); + expect((await ql.findOne('sys_attachment', { where: { id: row.id }, context: SYS }))?.file_id).toBe(ownFile); + expect((await stack.apiAs(memberATok, 'GET', `/storage/files/${adminFile}/url`)).status).toBe(403); + + // Control: re-pointing at another file the caller uploaded is admitted. + const secondOwn = await uploadFile(stack, memberATok); + const ok = await stack.apiAs(memberATok, 'PATCH', `/data/sys_attachment/${row.id}`, { file_id: secondOwn }); + expect(ok.status, await ok.clone().text()).toBe(200); + expect((await ql.findOne('sys_attachment', { where: { id: row.id }, context: SYS }))?.file_id).toBe(secondOwn); + }); + + it('the owner of the file attaches it to a record they may edit (control)', async () => { + const adminFile = await uploadFile(stack, adminTok); + const res = await attach(adminTok, 'att_case', caseAId, adminFile); + expect(res.status, await res.clone().text()).toBeLessThan(300); + }); + }); + // ── Part 1: sys_file orphan lifecycle, end to end ───────────────────── describe('sys_file orphan lifecycle (ADR-0057 reap guard)', () => { it('tombstones on last-ref delete, keeps shared files alive, un-tombstones on re-attach', async () => { From 6b83a80c4f22c32d43efadb9c0a6ab35ab22f770 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 05:41:24 +0000 Subject: [PATCH 5/7] chore(changeset): sys_attachment file reference verdict Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_017xRBcScm27Q3R5mkYLPWdB --- .changeset/attachment-file-reference-verdict.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/attachment-file-reference-verdict.md diff --git a/.changeset/attachment-file-reference-verdict.md b/.changeset/attachment-file-reference-verdict.md new file mode 100644 index 00000000000..ea3461fdbeb --- /dev/null +++ b/.changeset/attachment-file-reference-verdict.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-storage': patch +--- + +feat(service-storage): `sys_attachment` verifies the caller may open the file a row references + +Clause-②: no +Metadata-protocol: none + +An attachment links an `attachments`-scope file to a parent record, and the download door admits a caller through any parent record the file is attached to. The `sys_attachment` write gate now asks, of every insert and of every update that changes `file_id`, the same question a file-class field asks before it references a file: may this caller open the file it names? + +- **One predicate, two write doors.** The check is the one the file-field door already runs (`findReferenceableFile`, bound by the storage plugin to the download door's own verdict), now shared by both doors from `referenceable-file.ts`, so a field reference and an attachment reference cannot disagree about which files a caller may take. +- **The refusal is the file-field door's.** A file the caller may not open, and an id that names no file the acting organization reaches, are answered alike: `400 VALIDATION_FAILED` with one `invalid_value` entry for `file_id` ("File cannot reference this file: it is not a file you can open. Choose a file you can open, or upload it again."). Nothing is written. +- **What keeps working.** Attaching a file you uploaded, or one you can already open through another record, is admitted as before, as is `attachFileAs`, which attaches the caller's own fresh upload. System-context and context-less writes (seeds, engine self-writes, lifecycle sweeps) are not judged. The parent and row rules still answer first, so a caller they refuse keeps their refusal. A kernel that composes no download gate serves every file, and so every file may be referenced there. From 3dc215b8588f2ac076918d26b604865249d636dd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 05:55:47 +0000 Subject: [PATCH 6/7] test(service-storage): drive the file-gate cases through the suite's existing engine double Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_017xRBcScm27Q3R5mkYLPWdB --- .../src/attachment-access-hooks.test.ts | 82 ++++++++----------- 1 file changed, 34 insertions(+), 48 deletions(-) diff --git a/packages/services/service-storage/src/attachment-access-hooks.test.ts b/packages/services/service-storage/src/attachment-access-hooks.test.ts index 242bffb5659..f897ac7d7d0 100644 --- a/packages/services/service-storage/src/attachment-access-hooks.test.ts +++ b/packages/services/service-storage/src/attachment-access-hooks.test.ts @@ -69,14 +69,21 @@ function install(opts: { /** Parents the CALLER can read through the engine, keyed `object/id`. */ readable?: string[]; messageTranslator?: () => ((key: string, locale: string, params?: Record) => string) | undefined; + /** `sys_file` rows the engine serves; with `authorizeFileRead`, the file half of the gate is installed too. */ + files?: Array>; + authorizeFileRead?: (file: Record, context: any) => Promise; }) { - const hooks = new Map Promise>(); + // Every handler per event, in registration order — the engine's own order + // for same-priority hooks; each event's runner below awaits them in turn. + const hooks = new Map Promise>>(); + const fileReads: any[] = []; const parentReads: Array<{ object: string; options: any }> = []; const parentFind = readableParentFind(opts.readable ?? [], parentReads); - const engine: AttachmentLifecycleEngine = { + const engine: AttachmentLifecycleEngine & { getObject: (name: string) => unknown } = { registerHook: (event, handler) => { - hooks.set(event, handler as any); + hooks.set(event, [...(hooks.get(event) ?? []), handler as any]); }, + getObject: (name) => (name === 'sys_attachment' ? { fields: { file_id: { label: 'File' } } } : undefined), find: async (object, options: any) => { if (object !== 'sys_attachment') return parentFind(object, options); const rows = (opts.attachments ?? []).filter((r) => @@ -85,18 +92,28 @@ function install(opts: { return typeof options?.limit === 'number' ? rows.slice(0, options.limit) : rows; }, findOne: async (_object, options: any) => - { assertEngineFindOnePredicate(_object, options); return (opts.attachments ?? []).find((r) => + { assertEngineFindOnePredicate(_object, options); + if (_object === 'sys_file') { + fileReads.push(options); + return (opts.files ?? []).find((f) => f.id === options.where.id) ?? null; + } + return (opts.attachments ?? []).find((r) => Object.entries(options?.where ?? {}).every(([k, v]) => { if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); return r[k] === v; }), ) ?? null; }, update: async () => ({}), }; const sharing = asTriState(opts.sharing); installAttachmentAccessHooks(engine, () => sharing, silentLogger(), opts.messageTranslator, () => opts.security); + if (opts.authorizeFileRead) installAttachmentFileReferenceGate(engine, opts.authorizeFileRead); + const run = (event: string) => async (ctx: any) => { + for (const handler of hooks.get(event) ?? []) await handler(ctx); + }; return { - beforeInsert: hooks.get('beforeInsert')!, - beforeUpdate: hooks.get('beforeUpdate')!, - beforeDelete: hooks.get('beforeDelete')!, + beforeInsert: run('beforeInsert'), + beforeUpdate: run('beforeUpdate'), + beforeDelete: run('beforeDelete'), parentReads, + fileReads, }; } @@ -1885,53 +1902,22 @@ describe('attachment access — the file a row names must be one the caller may const ROW = { id: 'a1', parent_object: 'task', parent_id: 't1', file_id: 'f-own', uploaded_by: 'u1' }; /** - * The gate with a bound file-read verdict: `openable` lists the file ids the - * caller may open; `fileReads` records every `sys_file` lookup the gate made. + * The gate with the file half installed: `openable` lists the file ids the + * caller may open. `bound: false` installs the access hooks alone. */ function installWithFiles(opts: { openable: string[]; bound?: boolean; canEditParent?: boolean }) { - // Every handler per event, in registration order — the engine's own order - // for same-priority hooks. - const hooks = new Map Promise>>(); - const files = [OWN_FILE, OTHER_FILE]; - const fileReads: any[] = []; const authorizeFileRead = vi.fn(async (file: Record, context: any) => { expect(context.userId).toBe('u1'); return opts.openable.includes(String(file.id)); }); - const engine: AttachmentLifecycleEngine & { getObject: (name: string) => unknown } = { - registerHook: (event, handler) => { - hooks.set(event, [...(hooks.get(event) ?? []), handler as any]); - }, - getObject: (name) => (name === 'sys_attachment' ? { fields: { file_id: { label: 'File' } } } : undefined), - find: async () => [], - findOne: async (object, options: any) => { - assertEngineFindOnePredicate(object, options); - if (object === 'sys_file') { - fileReads.push(options); - return files.find((f) => f.id === options.where.id) ?? null; - } - return object === 'sys_attachment' && options.where.id === ROW.id ? { ...ROW } : null; - }, - update: async () => ({}), - }; - const canEdit = opts.canEditParent ?? true; - installAttachmentAccessHooks( - engine, - () => ({ checkEdit: async () => (canEdit ? ('allow' as const) : ('deny' as const)) }), - silentLogger(), - undefined, - () => null, - ); - if (opts.bound !== false) installAttachmentFileReferenceGate(engine, authorizeFileRead); - const chain = (event: string) => async (ctx: any) => { - for (const handler of hooks.get(event) ?? []) await handler(ctx); - }; - return { - beforeInsert: chain('beforeInsert'), - beforeUpdate: chain('beforeUpdate'), - authorizeFileRead, - fileReads, - }; + const gate = install({ + attachments: [ROW], + files: [OWN_FILE, OTHER_FILE], + sharing: { canEdit: async () => opts.canEditParent ?? true }, + security: null, + authorizeFileRead: opts.bound === false ? undefined : authorizeFileRead, + }); + return { ...gate, authorizeFileRead }; } const attach = (fileId: unknown, session: Record = { userId: 'u1', organizationId: 'org-1' }) => ({ From bc7274ef53fb053cd7ebf5ba6872578ef17a40a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 06:04:39 +0000 Subject: [PATCH 7/7] docs(permissions): the system-context register names the attachment file gate Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_017xRBcScm27Q3R5mkYLPWdB --- content/docs/permissions/system-context.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 54eec363455..4a11e79b1a7 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -173,7 +173,7 @@ One of the largest consumers of the flag; | 41 | **Approval record lock released** — a locked record is writable | plugin-approvals | Get: engine self-writes (the status mirror) pass. Lose: the lock that stops edits while an approval is live. Note there is deliberately **no admin exemption** here — only `isSystem` | `bindApprovalLockHook` | | 42 | Delegation write guard bypassed | plugin-approvals | Get: service / seed / import may write delegation rows naming another delegator | `bindDelegationWriteGuard` | | 43 | Approval actor / submitter / pending-approver checks bypassed (8 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment` | -| 44 | Attachment access hooks return early (insert + update + delete, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentReadVisibility` | +| 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | | 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard` | | 46 | Knowledge search returns hits unfiltered | service-knowledge | Lose: the permission filter over search results | `applyPermissionFilter` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | @@ -648,6 +648,7 @@ and CI refuses one that differs from what the tree produces. | `packages/services/service-print/src/print-service.ts#refuseUnlessHumanCaller` | 1 | 47d | | `packages/services/service-settings/src/settings-read-door.ts#settingsReadDoorMiddleware` | 1 | 18b | | `packages/services/service-storage/src/attachment-access-hooks.ts#installAttachmentAccessHooks` | 3 | 44 | +| `packages/services/service-storage/src/attachment-access-hooks.ts#installAttachmentFileReferenceGate` | 2 | 44 | | `packages/services/service-storage/src/attachment-access-hooks.ts#installAttachmentReadVisibility` | 1 | 44 | | `packages/services/service-storage/src/file-attachment-service.ts#requireUserContext` | 1 | 47e | | `packages/services/service-storage/src/file-reference-lifecycle.ts#referencingCallerOf` | 1 | 47f |