Skip to content

Commit 4464fd0

Browse files
committed
wip: a service verb vouches for the one file reference it created
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibvynRbCtMndW8EHNGc
1 parent e1dac19 commit 4464fd0

5 files changed

Lines changed: 214 additions & 5 deletions

File tree

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,16 @@ export {
537537
keepsFlowWriteReferenceCheck,
538538
} from './flow-write-reference-check.js';
539539

540+
// The mark a service verb's own write carries for one reference to a record
541+
// the same call authorized and created. Set by service-storage's
542+
// file-attachments writer, read by objectql's write-time reference check.
543+
export {
544+
VOUCHED_REFERENCES,
545+
vouchForReference,
546+
isVouchedReference,
547+
type VouchedReference,
548+
} from './vouched-reference.js';
549+
540550
// #30205 — a banned user's open work: the per-object counts, the optional bulk
541551
// hand-over (both read and written as the caller), and the ban-in-force
542552
// predicate objectql's write-time reference check refuses a new assignment by.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The mark a service's own write carries for ONE reference value it vouches
5+
* for: a record the same call has itself authorized and created.
6+
*
7+
* ## The rule it answers to
8+
*
9+
* A write that is not a system write may name, in a `lookup`, `user` or
10+
* `master_detail` field, only a record its caller's own read door returns; a
11+
* record the caller cannot read answers `reference_not_found`
12+
* (`assertReferencesResolve`, objectql). That rule judges a reference the
13+
* CALLER chose. Some service verbs write, as the caller, a row that links to a
14+
* record the verb created a moment earlier in the same call, after asking its
15+
* own authorization question first. The file-attachments verb is the case: it
16+
* asks the attach rule (`assertMayAttach`), stores a new `sys_file` for the
17+
* caller, then inserts the `sys_attachment` naming it AS the caller, so every
18+
* gate on that insert judges the caller. The caller did not choose that file
19+
* id, and a caller who may attach files need not read `sys_file` at all, so
20+
* the read-door question has nothing to judge there; asking it refuses the
21+
* verb outright.
22+
*
23+
* ## What it admits, and what it does not
24+
*
25+
* The mark names one `(object, field, id)`. The reference check reads it for
26+
* exactly that value on a write to that object: the caller's read door is not
27+
* asked for it, and the elevated, tenant-kept existence probe still is, so an
28+
* id that names no row of the caller's organization is refused as before.
29+
* Everything else about the write stays the caller's: every other field and
30+
* every other value in the same field is judged through the caller's read door,
31+
* and nothing about RLS, FLS, the owner and audit stamps, the object's hooks
32+
* or the caller's read of anything changes. It grants no read.
33+
*
34+
* ## Where it is set — and where it is never set
35+
*
36+
* Only by a service verb, on the one write it makes for the record it just
37+
* created, after that verb's own authorization: today the file-attachments
38+
* writer's `sys_attachment` insert (`FileAttachmentService.attachFileAs`,
39+
* service-storage). ⛔ Never on a context a request, an import, a flow, an
40+
* agent tool or any other generic data door hands the engine: a reference such
41+
* a door carries is the caller's choice, and the read-door rule judges it.
42+
*
43+
* ## Why a symbol, and why it is not an `ExecutionContext` field
44+
*
45+
* The same reasons as `FLOW_WRITE_REFERENCE_CHECK`: no request body, query
46+
* string, stored row or flow definition can spell a symbol, so no author can
47+
* set it; it is in no schema; `Symbol.for` keeps it one key across the ESM and
48+
* 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.
52+
*/
53+
54+
/** The context key of the mark. See the module header. */
55+
export const VOUCHED_REFERENCES: unique symbol = Symbol.for('objectstack.core.vouchedReferences');
56+
57+
/** One reference value a service vouches for: `field` of a write to `object`, naming `id`. */
58+
export interface VouchedReference {
59+
readonly object: string;
60+
readonly field: string;
61+
readonly id: string;
62+
}
63+
64+
/**
65+
* `context` with `reference` added to the references it vouches for — a fresh
66+
* object; `context` is not changed. Called only by a service verb, for a
67+
* record the same call created (see the module header).
68+
*/
69+
export function vouchForReference<T extends object>(
70+
context: T,
71+
reference: VouchedReference,
72+
): T & { [VOUCHED_REFERENCES]: ReadonlyArray<VouchedReference> } {
73+
const held = (context as { [VOUCHED_REFERENCES]?: unknown })[VOUCHED_REFERENCES];
74+
const prior = Array.isArray(held) ? (held as ReadonlyArray<VouchedReference>) : [];
75+
const entry: VouchedReference = Object.freeze({
76+
object: String(reference.object),
77+
field: String(reference.field),
78+
id: String(reference.id),
79+
});
80+
return { ...context, [VOUCHED_REFERENCES]: Object.freeze([...prior, entry]) };
81+
}
82+
83+
/**
84+
* Does `context` vouch for `id` in `field` of a write to `object`? `false` for
85+
* every other value, field, object and context.
86+
*/
87+
export function isVouchedReference(context: unknown, object: unknown, field: unknown, id: unknown): boolean {
88+
if (context === null || typeof context !== 'object') return false;
89+
if (typeof object !== 'string' || typeof field !== 'string') return false;
90+
if (typeof id !== 'string' && typeof id !== 'number') return false;
91+
const held = (context as { [VOUCHED_REFERENCES]?: unknown })[VOUCHED_REFERENCES];
92+
if (!Array.isArray(held)) return false;
93+
const value = String(id);
94+
return held.some(
95+
(r) => r !== null && typeof r === 'object'
96+
&& (r as VouchedReference).object === object
97+
&& (r as VouchedReference).field === field
98+
&& (r as VouchedReference).id === value,
99+
);
100+
}

‎packages/objectql/src/engine-referential-integrity.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252

5353
import { referenceTargetOf, type EngineQueryOptions } from '@objectstack/spec/data';
5454
import type { ExecutionContext } from '@objectstack/spec/kernel';
55-
import { isUserBanInForce, keepsFlowWriteReferenceCheck, USER_BAN_FIELDS } from '@objectstack/core';
55+
import { isUserBanInForce, isVouchedReference, keepsFlowWriteReferenceCheck, USER_BAN_FIELDS } from '@objectstack/core';
5656
import { ValidationError, buildFieldError } from './validation/record-validator.js';
5757
import { servedAsStored } from './engine-top-level.js';
5858
import type { ObjectQL } from './engine.js';
@@ -219,6 +219,16 @@ export function referencesCheckedBeforeRules(context: unknown): boolean {
219219
* and a value the row already stores is not judged again (#29062). `tree`
220220
* keeps the elevated probe alone.
221221
*
222+
* One value is not the caller's choice: a reference a service verb vouches for
223+
* on its own write (`vouchForReference`, `@objectstack/core`), naming a record
224+
* the same call authorized and created — the file-attachments writer's
225+
* `sys_attachment.file_id`, inserted as the caller after its own attach check.
226+
* For exactly that object, field and id the caller's read door is not asked;
227+
* the elevated, tenant-kept existence probe still is. Every other value, field
228+
* and object on the write is judged as above, and the mark comes from no
229+
* request: it is a symbol-keyed context property no body, query or stored row
230+
* can spell.
231+
*
222232
* Fails OPEN when the target cannot be checked (unregistered object, no
223233
* driver, a probe that throws): an integrity check that cannot run must not
224234
* invent a rejection, and the alternative — refusing every write to an object
@@ -301,8 +311,12 @@ export async function assertReferencesResolve(
301311
if (v === null || v === undefined || v === '') continue;
302312
if (typeof v === 'object') continue;
303313
// [#22519, #29029] A master-detail header, a lookup target and a user
304-
// must also be one the caller can read.
305-
const callerReads = CALLER_READ_REFERENCE_TYPES.has(def?.type);
314+
// must also be one the caller can read — except the one value a service
315+
// verb vouches for on its own write: a record the same call authorized
316+
// and created (`vouchForReference`, @objectstack/core). Its existence is
317+
// still probed; nothing else on the write is admitted by it.
318+
const callerReads = CALLER_READ_REFERENCE_TYPES.has(def?.type)
319+
&& !isVouchedReference(context, schema?.name, name, v);
306320
if (def?.type !== 'master_detail' && target === BAN_CHECKED_USER_OBJECT) {
307321
// [#30205] One probe answers both: the row's existence and its ban.
308322
// [#29029] The caller's read door comes first: a user it does not

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

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131

3232
import { describe, it, expect, beforeEach } from 'vitest';
3333
import { resolveThrownHttpError } from '@objectstack/types';
34-
import { markFlowWriteReferenceCheck } from '@objectstack/core';
34+
import { markFlowWriteReferenceCheck, vouchForReference, VOUCHED_REFERENCES } from '@objectstack/core';
3535
import { ObjectQL } from './engine.js';
3636
import { ValidationError } from './validation/record-validator.js';
3737

@@ -498,3 +498,74 @@ describe('[#29029] the update\'s reference forgiveness compares only stored valu
498498
});
499499
});
500500
});
501+
502+
describe('a reference a service verb vouches for on its own write: that one value skips the caller\'s read door, nothing else does', () => {
503+
let engine: ObjectQL;
504+
let targetReads: TargetRead[];
505+
let storeFor: (o: string) => Map<string, Record<string, any>>;
506+
507+
beforeEach(() => {
508+
({ engine, targetReads, storeFor } = makeEngine());
509+
});
510+
511+
/** Alice's context, vouching for `id` in `field` of a write to `object`. */
512+
const vouched = (id: string, field = 'duty', object = ITEM, base: Record<string, unknown> = ALICE) =>
513+
vouchForReference({ ...base }, { object, field, id });
514+
const insert = (object: string, payload: Record<string, unknown>, context: Record<string, unknown>) =>
515+
engine.insert(object, { title: 'new', ...payload }, { context } as any);
516+
const items = (object = ITEM) => [...storeFor(object).values()];
517+
518+
it('the vouched value lands although the caller cannot read it; its existence is still probed, elevated', async () => {
519+
await insert(ITEM, { duty: UNREADABLE }, vouched(UNREADABLE));
520+
expect(items().some((r) => r.duty === UNREADABLE)).toBe(true);
521+
// No read door asked for it; the existence probe ran.
522+
expect(targetReads.map(({ operation, elevated }) => ({ operation, elevated }))).toEqual([
523+
{ operation: 'findOne', elevated: true },
524+
]);
525+
});
526+
527+
it('a vouched id that names no row is still refused reference_not_found', async () => {
528+
expect(envelopeOf(await refusalOf(() => insert(ITEM, { duty: NOWHERE }, vouched(NOWHERE))))).toEqual(notFound('duty'));
529+
expect(items()).toEqual([]);
530+
});
531+
532+
it('control: another unreadable id in the vouched field is refused as before', async () => {
533+
const err = await refusalOf(() => insert(ITEM, { duty: 't_flagged_other' }, vouched(UNREADABLE)));
534+
expect(envelopeOf(err)).toEqual(notFound('duty'));
535+
expect(items()).toEqual([]);
536+
});
537+
538+
it('control: the vouched id in another field of the same write is refused as before', async () => {
539+
const err = await refusalOf(() => insert(ITEM, { duty: UNREADABLE, assignee: UNREADABLE }, vouched(UNREADABLE)));
540+
expect(envelopeOf(err)).toEqual(notFound('assignee'));
541+
expect(items()).toEqual([]);
542+
});
543+
544+
it('control: the vouched id on a write to another object is refused as before', async () => {
545+
const err = await refusalOf(() => insert(RULED, { duty: UNREADABLE }, vouched(UNREADABLE)));
546+
expect(envelopeOf(err)).toEqual(notFound('duty'));
547+
expect(items(RULED)).toEqual([]);
548+
});
549+
550+
it('control: a multi-valued field admits the vouched member only, and refuses another unreadable one beside it', async () => {
551+
const err = await refusalOf(() => insert(ITEM, { duties: [UNREADABLE, 't_flagged_other'] }, vouched(UNREADABLE, 'duties')));
552+
expect(envelopeOf(err)).toEqual(notFound('duties'));
553+
await insert(ITEM, { duties: [UNREADABLE, 't_mine'] }, vouched(UNREADABLE, 'duties'));
554+
expect(items().some((r) => Array.isArray(r.duties) && r.duties.includes(UNREADABLE))).toBe(true);
555+
});
556+
557+
it('control: the same value without the mark is refused, and a string key of the same name is no mark', async () => {
558+
expect(envelopeOf(await refusalOf(() => insert(ITEM, { duty: UNREADABLE }, { ...ALICE })))).toEqual(notFound('duty'));
559+
// What a JSON body or a stored row could spell: the symbol's description as a plain key.
560+
const spelled = { ...ALICE, [String(VOUCHED_REFERENCES.description)]: [{ object: ITEM, field: 'duty', id: UNREADABLE }] };
561+
expect(envelopeOf(await refusalOf(() => insert(ITEM, { duty: UNREADABLE }, spelled)))).toEqual(notFound('duty'));
562+
expect(items()).toEqual([]);
563+
});
564+
565+
it('control: a caller whose read of the target object is refused outright is admitted for the vouched value only', async () => {
566+
await insert(ITEM, { duty: 't_mine' }, vouched('t_mine', 'duty', ITEM, CAROL));
567+
expect(items().some((r) => r.duty === 't_mine')).toBe(true);
568+
const err = await refusalOf(() => insert(ITEM, { duty: 't_mine_2' }, vouched('t_mine', 'duty', ITEM, CAROL)));
569+
expect(envelopeOf(err)).toEqual(notFound('duty'));
570+
});
571+
});

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ import type {
1212
IStorageService,
1313
} from '@objectstack/spec/contracts';
1414
import type { ExecutionContext } from '@objectstack/spec/kernel';
15+
// The one reference this verb's caller-scoped insert vouches for: the file it
16+
// created in the same call (see step ⑤).
17+
import { vouchForReference } from '@objectstack/core';
1518
import { StorageMetadataStore, type StorageWriteContext } from './metadata-store.js';
1619
// The attach rule's one verdict (parent EDIT), asked here before a producer
1720
// spends work on a file it could not attach.
@@ -343,7 +346,18 @@ export class FileAttachmentService implements IFileAttachmentService, ICallerFil
343346
mime_type: request.mimeType,
344347
size,
345348
},
346-
{ context },
349+
// As the caller, this insert names the one file this call created
350+
// in ③ for the caller, after reading the parent as the caller: the
351+
// call vouches for that file id and for no other value
352+
// (`vouchForReference`, @objectstack/core). The write-time reference
353+
// check then does not ask the caller's read door for it — a caller
354+
// who may attach need not read `sys_file` — and still probes that it
355+
// exists. Every other gate on the insert judges the caller as
356+
// before: the object permission to create an attachment, the attach
357+
// rule (parent EDIT), `enable.files`, the file-reference gate, RLS,
358+
// FLS and the `uploaded_by` stamp. The system context is exempt from
359+
// the read-door question already, so it carries no mark.
360+
{ context: caller ? vouchForReference(context, { object: 'sys_attachment', field: 'file_id', id: fileId }) : context },
347361
)) as { id?: unknown } | null | undefined;
348362
if (row?.id === undefined || row.id === null || row.id === '') {
349363
throw new Error('attachFile: the sys_attachment insert answered no row id, so the attachment cannot be named');

0 commit comments

Comments
 (0)