Skip to content
14 changes: 14 additions & 0 deletions .changeset/attachment-file-reference-verdict.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
141 changes: 134 additions & 7 deletions packages/services/service-storage/src/attachment-access-hooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -68,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, unknown>) => string) | undefined;
/** `sys_file` rows the engine serves; with `authorizeFileRead`, the file half of the gate is installed too. */
files?: Array<Record<string, unknown>>;
authorizeFileRead?: (file: Record<string, unknown>, context: any) => Promise<boolean>;
}) {
const hooks = new Map<string, (ctx: any) => Promise<void>>();
// 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<string, Array<(ctx: any) => Promise<void>>>();
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) =>
Expand All @@ -84,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,
};
}

Expand Down Expand Up @@ -1877,3 +1895,112 @@ 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 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 }) {
const authorizeFileRead = vi.fn(async (file: Record<string, unknown>, context: any) => {
expect(context.userId).toBe('u1');
return opts.openable.includes(String(file.id));
});
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<string, unknown> = { 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<string, unknown>) => ({
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('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);
});

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();
});
});
Loading
Loading