Skip to content

Commit 4f78f54

Browse files
committed
wip: the vouch is spent on the verb's own write, and attachUploadAs vouches only for an unheld upload
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibvynRbCtMndW8EHNGc
1 parent 53eef2e commit 4f78f54

5 files changed

Lines changed: 99 additions & 7 deletions

File tree

‎packages/core/src/security/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,7 @@ export {
544544
VOUCHED_REFERENCES,
545545
vouchForReference,
546546
isVouchedReference,
547+
withoutVouchedReferences,
547548
type VouchedReference,
548549
} from './vouched-reference.js';
549550

‎packages/core/src/security/vouched-reference.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,18 @@
4646
* string, stored row or flow definition can spell a symbol, so no author can
4747
* set it; it is in no schema; `Symbol.for` keeps it one key across the ESM and
4848
* CJS builds; and, being undeclared, it does not survive
49-
* `ExecutionContextSchema.parse`. It rides a spread of the context as any own
50-
* property does, so a write a hook sets off under the vouched write carries it
51-
* too, and is admitted only for the same object, field and id.
49+
* `ExecutionContextSchema.parse`.
50+
*
51+
* ## It is spent on the verb's own write — no hook inherits it
52+
*
53+
* The mark rides a spread of the context as any own property does, and every
54+
* context a hook writes through is derived from the write that fired it. So
55+
* the engine strips it where it builds a hook's api from the write's context
56+
* (`buildHookApi`, objectql, via {@link withoutVouchedReferences}): a hook —
57+
* app-authored or platform, `runAs: 'user'` or inherited — that writes the same
58+
* object, field and id under the vouched write is judged through its caller's
59+
* read door like any other write. The mark admits the one write the verb
60+
* makes, and no write that write sets off.
5261
*/
5362

5463
/** The context key of the mark. See the module header. */
@@ -98,3 +107,16 @@ export function isVouchedReference(context: unknown, object: unknown, field: unk
98107
&& (r as VouchedReference).id === value,
99108
);
100109
}
110+
111+
/**
112+
* `context` without the mark: the same object when it carries none, else a
113+
* fresh copy with every other own property. The engine calls it where it hands
114+
* a hook the write's context (see the module header), so the vouch is spent
115+
* on the verb's own write.
116+
*/
117+
export function withoutVouchedReferences<T>(context: T): T {
118+
if (context === null || typeof context !== 'object') return context;
119+
if (!Object.prototype.hasOwnProperty.call(context, VOUCHED_REFERENCES)) return context;
120+
const { [VOUCHED_REFERENCES]: _spent, ...rest } = context as T & { [VOUCHED_REFERENCES]?: unknown };
121+
return rest as T;
122+
}

‎packages/objectql/src/engine-defaults-and-autonumbers.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import { isCurrentUserDefaultToken, isNowDefaultToken, missingFieldValues, parseAutonumberFormat, renderAutonumber, resolveAutonumberFormat } from '@objectstack/spec/data';
3838
import type { EngineQueryOptions } from '@objectstack/spec/data';
3939
import type { IDataEngine } from '@objectstack/core';
40+
import { withoutVouchedReferences } from '@objectstack/core';
4041
import { isUniqueViolationError, keysetWalk, uniqueViolationColumn } from '@objectstack/types';
4142
import type { KeysetPageQuery } from '@objectstack/types';
4243
import type { ExecutionContext } from '@objectstack/spec/kernel';
@@ -202,7 +203,11 @@ export class DefaultsAndAutonumbersFacet {
202203
* is supplied (e.g. system-triggered hooks).
203204
*/
204205
static buildHookApi(this: Pick<DefaultsAndAutonumbersHost, 'facade'>, execCtx?: ExecutionContext): ScopedContext {
205-
const safeCtx: ExecutionContext = execCtx ?? ({ isSystem: true } as any);
206+
// A reference a service verb vouched for on the write that fired this hook
207+
// is spent on that write: no context a hook writes through carries it
208+
// (`withoutVouchedReferences`, @objectstack/core). A context with no mark
209+
// is handed through as the same object.
210+
const safeCtx: ExecutionContext = withoutVouchedReferences(execCtx ?? ({ isSystem: true } as any));
206211
return new ScopedContext(safeCtx, this.facade as unknown as IDataEngine);
207212
}
208213

‎packages/objectql/src/engine-unreadable-reference-target.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,55 @@ describe('a reference a service verb vouches for on its own write: that one valu
562562
expect(items()).toEqual([]);
563563
});
564564

565+
describe('the mark is spent on the vouched write: a hook that runs as the user under it is judged as any write is', () => {
566+
/**
567+
* An afterInsert hook on the task that, under the vouched insert, inserts
568+
* a second task naming the SAME vouched id in the SAME field — through the
569+
* api it is handed (the triggering user's context), or through
570+
* `withRunAs('user')`, as an app-authored `runAs: 'user'` hook does. Its
571+
* refusal is captured, and the outer write is left to finish.
572+
*/
573+
const armEchoHook = (via: 'api' | 'runAs-user') => {
574+
const refusals: unknown[] = [];
575+
engine.registerHook('afterInsert', async (ctx: any) => {
576+
if (ctx.input?.data?.title !== 'outer') return;
577+
const api = via === 'api' ? ctx.api : ctx.api.withRunAs('user', { hook: 'echo', object: ITEM, event: 'afterInsert' });
578+
try {
579+
await api.object(ITEM).insert({ title: 'echo', duty: UNREADABLE });
580+
} catch (err) {
581+
refusals.push(err);
582+
}
583+
}, { object: ITEM });
584+
return refusals;
585+
};
586+
587+
for (const via of ['api', 'runAs-user'] as const) {
588+
it(`a hook writing through ${via === 'api' ? 'the api it is handed' : "withRunAs('user')"} that names the vouched id again is refused reference_not_found`, async () => {
589+
const refusals = armEchoHook(via);
590+
await insert(ITEM, { title: 'outer', duty: UNREADABLE }, vouched(UNREADABLE));
591+
expect(refusals).toHaveLength(1);
592+
expect(envelopeOf(refusals[0])).toEqual(notFound('duty'));
593+
// The verb's own write landed; the hook's did not.
594+
expect(items().map((r) => r.title)).toEqual(['outer']);
595+
});
596+
}
597+
598+
it('control: the same hook under an unmarked system write lands its echo (the hook\'s refusal above is the mark being spent, not the hook failing)', async () => {
599+
const refusals: unknown[] = [];
600+
engine.registerHook('afterInsert', async (ctx: any) => {
601+
if (ctx.input?.data?.title !== 'outer') return;
602+
try {
603+
await ctx.api.object(ITEM).insert({ title: 'echo', duty: UNREADABLE });
604+
} catch (err) {
605+
refusals.push(err);
606+
}
607+
}, { object: ITEM });
608+
await engine.insert(ITEM, { title: 'outer', duty: UNREADABLE }, { context: { isSystem: true } });
609+
expect(refusals).toEqual([]);
610+
expect(items().map((r) => r.title).sort()).toEqual(['echo', 'outer']);
611+
});
612+
});
613+
565614
it('control: a caller whose read of the target object is refused outright is admitted for the vouched value only', async () => {
566615
await insert(ITEM, { duty: 't_mine' }, vouched('t_mine', 'duty', ITEM, CAROL));
567616
expect(items().some((r) => r.duty === 't_mine')).toBe(true);

‎packages/services/service-storage/src/file-attachment-service.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ import { StorageMetadataStore, organizationOutOfWriteReach, type StorageWriteCon
1919
// The upload ownership rule, asked of the upload the attach-on-commit verb
2020
// names — the commit door's own rule and its one refusal.
2121
import { isFileUploader, NOT_UPLOADER_CODE, NOT_UPLOADER_MESSAGE, NOT_UPLOADER_STATUS } from './upload-ownership.js';
22+
// The one definition of "is anything holding this file?" — the reap guard's —
23+
// asked so the attach-on-commit verb vouches only for an upload nothing holds.
24+
import { findFileHolder } from './attachment-lifecycle.js';
2225
// The attach rule's one verdict (parent EDIT), asked here before a producer
2326
// spends work on a file it could not attach.
2427
import {
@@ -170,11 +173,15 @@ export interface ICallerFileAttachmentService {
170173
* The file must be the upload the caller is completing: a `sys_file` row
171174
* whose `owner_id` is the caller (the upload doors stamp it from the
172175
* session), still `pending`, in the `attachments` scope, in the caller's
173-
* organization, with its bytes held by the storage backend. Any other id —
176+
* organization, held by nothing yet (no `sys_attachment` names it and no
177+
* record field owns it — `findFileHolder`), with its bytes held by the
178+
* storage backend. That is the whole premise of the vouch: the one file this
179+
* call turns from the caller's unattached upload into an attachment, and
180+
* nothing else. Any other id —
174181
* another user's upload, an id that names no file — is refused with the
175182
* upload ownership rule's one answer (`PERMISSION_DENIED` / `403`, the same
176-
* body for both); a committed file `RESOURCE_CONFLICT` / `409`; another
177-
* scope `INVALID_REQUEST` / `400`.
183+
* body for both); a committed or already-held file `RESOURCE_CONFLICT` /
184+
* `409`; another scope `INVALID_REQUEST` / `400`.
178185
*
179186
* Then the attach authorization, before any write: {@link assertMayAttach}
180187
* (the permission to create an attachment, and the parent-EDIT attach rule),
@@ -316,6 +323,14 @@ export class FileAttachmentService implements IFileAttachmentService, ICallerFil
316323
'switch back to that organization to attach it.',
317324
);
318325
}
326+
if ((await findFileHolder(engine, file.id, file as unknown as Record<string, unknown>)) !== null) {
327+
refuse(
328+
'RESOURCE_CONFLICT',
329+
409,
330+
'This upload is already attached to a record or owned by a record field, so it cannot be attached on ' +
331+
'completion. Start a new upload and complete it with attachTo.',
332+
);
333+
}
319334
const notHeld = await heldBytesRefusal(storage, file);
320335
if (notHeld !== null) refuse('RESOURCE_CONFLICT', 409, notHeld);
321336

0 commit comments

Comments
 (0)