From a1223309c5f8da9eb6f60310da1737edaa718bfd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:22:41 +0000 Subject: [PATCH 1/7] feat(sharing): ISharingService answers the write verdict for a set of record ids checkEditMany / checkDeleteMany on the contract (optional), one implementation in SharingService behind both the by-id and the set form, and plugin-security's predicate write asks the set form where the service serves it. Claude-Session: https://claude.ai/code/session_01Utp6CbdHk3orAeensH6EzS Co-authored-by: Claude --- .../src/security-plugin-authz-middleware.ts | 6 +- .../src/security-plugin-sharing-verdicts.ts | 136 +++++- .../plugin-security/src/security-plugin.ts | 5 +- .../plugin-sharing/src/sharing-service.ts | 394 +++++++++++++----- .../src/contracts/sharing-service.test.ts | 5 +- .../spec/src/contracts/sharing-service.ts | 46 ++ 6 files changed, 478 insertions(+), 114 deletions(-) diff --git a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts index 621050e7b57..3054d45be77 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -605,6 +605,7 @@ export interface AuthzMiddlewareHost { readonly logger: SecurityPlugin['logger']; readonly permissionEvaluator: SecurityPlugin['permissionEvaluator']; readonly ql: SecurityPlugin['ql']; + readonly resolveKernelService: SecurityPlugin['resolveKernelService']; addressedByIdWriteId: SecurityPlugin['addressedByIdWriteId']; addressedPredicateWrite: SecurityPlugin['addressedPredicateWrite']; assertControlledByParentWrite: SecurityPlugin['assertControlledByParentWrite']; @@ -633,12 +634,13 @@ export interface AuthzMiddlewareHost { resolveHopWithheldFields: SecurityPlugin['resolveHopWithheldFields']; resolvePreImageFloorDrop: SecurityPlugin['resolvePreImageFloorDrop']; resolveSharingWriteVerdict: SecurityPlugin['resolveSharingWriteVerdict']; + resolveWriteScopeForSharing: SecurityPlugin['resolveWriteScopeForSharing']; writeCheckFieldOptions: SecurityPlugin['writeCheckFieldOptions']; } /** The authorization middleware registration `SecurityPlugin#start` runs; the comment above its call there is its contract. */ export function registerAuthzMiddleware( - this: Pick, + this: Pick, ctx: PluginContext, ql: IObjectQLEngine, metadata: IMetadataService, @@ -3197,7 +3199,7 @@ export function idsOfReadableScope(scope: Record): (string | nu * readable scope beside this one still binds. */ async function predicateWriteFloorRelief( - this: Pick, + this: Pick, opCtx: any, permissionSets: PermissionSet[], floored: Record, diff --git a/packages/plugins/plugin-security/src/security-plugin-sharing-verdicts.ts b/packages/plugins/plugin-security/src/security-plugin-sharing-verdicts.ts index 5569e873e4a..41ed69f9a32 100644 --- a/packages/plugins/plugin-security/src/security-plugin-sharing-verdicts.ts +++ b/packages/plugins/plugin-security/src/security-plugin-sharing-verdicts.ts @@ -306,34 +306,99 @@ export async function resolvePreImageFloorDrop( /** * How many rows' floor decisions {@link predicateWriteFloorDropIds} asks at - * once. Each decision is one `ISharingService.checkEdit` / `checkDelete` call, - * which reads the store (the row's owner, its shares, the bypass), so the - * batch bounds how many of those reads one write keeps in flight. + * once ON THE PER-ROW PATH, the one it keeps for a sharing service that + * serves no set form. Each decision is one `ISharingService.checkEdit` / + * `checkDelete` call, which reads the store (the row's owner, its shares, the + * bypass), so the batch bounds how many of those reads one write keeps in + * flight. The set form chunks for itself. */ const PREDICATE_WRITE_FLOOR_DECISION_BATCH = 25; /** - * [#35802] The PREDICATE write's floor decision, made per row: the ids among + * [#35934] The SET form of {@link resolveSharingWriteVerdict}: the tri-state + * write verdict for each of `recordIds`, asked of the sharing service's + * `checkEditMany` / `checkDeleteMany` in ONE call, under the context the + * per-row resolution hands `checkEdit` / `checkDelete` (the write depth stash + * and the external OWD grant patch, resolved once for the object). Answers + * `null` when the service serves no set form for this verb, and the caller + * asks per row instead, with the same answers. + * + * Normalised as the per-row form is: any answer that is neither `allow` nor + * `deny` is `abstain`. Fail-closed as the per-row form is: a probe that throws, + * or answers anything but one verdict per record, is a `deny` for every + * record, logged once. + */ +export async function resolveSharingWriteVerdicts( + this: Pick, + rlsOperation: string, + object: string, + recordIds: readonly string[], + context: any, + resolvedSets?: PermissionSet[], +): Promise { + const method = rlsOperation === 'delete' ? 'checkDeleteMany' : 'checkEditMany'; + const sharing = this.resolveKernelService?.('sharing') as + | Record Promise) | undefined> + | undefined; + const probe = sharing?.[method]; + if (typeof probe !== 'function') return null; + if (recordIds.length === 0) return []; + const writeScope = await this.resolveWriteScopeForSharing(object, context, resolvedSets); + const grantPatch = await externalWriteGrantPatch.call(this, rlsOperation, object, context, resolvedSets); + try { + const verdicts = await probe.call(sharing, object, recordIds, { + ...context, + __writeScope: writeScope, + ...grantPatch, + }); + if (!Array.isArray(verdicts) || verdicts.length !== recordIds.length) { + throw new Error( + `${method} answered ${Array.isArray(verdicts) ? `${verdicts.length} verdicts` : 'no list'} for ${recordIds.length} records`, + ); + } + return verdicts.map((verdict): SharingWriteVerdict => (verdict === 'allow' || verdict === 'deny' ? verdict : 'abstain')); + } catch (e) { + this.logger.error?.( + `[security] the row-level write gate could not resolve the sharing (${method}) verdicts ` + + `for ${recordIds.length} '${object}' records (user ${context?.userId ?? 'unknown'}) — keeping ` + + `the platform ownership floor on each (fail-closed: only a resolved sharing allow, from Modify All Data ` + + `or an edit-level share, may replace that floor)`, + e instanceof Error ? e : new Error(String(e)), + ); + return recordIds.map(() => 'deny'); + } +} + +/** + * [#35802] The PREDICATE write's per-row floor decision: the ids among * `candidateIds` whose by-id write would have its platform ownership floor * replaced. * - * The decision for each row is {@link resolvePreImageFloorDrop} itself, asked - * exactly as the by-id write pre-image gate (step 2.7) asks it for that row: - * the same write class, the same sets, the same `delegated` exclusion. So a row - * is in the answer if and only if a by-id write of it would drop the floor — - * the floor in play and an `allow` from the declared write authority — and - * the verb boundary (ADR-0111 D3) comes with it: `delete` asks `checkDelete`, - * which an `edit` share never answers `allow`. + * The decision for each row is {@link resolvePreImageFloorDrop}'s, as the + * by-id write pre-image gate (step 2.7) asks it for that row: the same write + * class, the same sets, the same `delegated` exclusion. So a row is in the + * answer if and only if a by-id write of it would drop the floor — the floor + * in play and an `allow` from the declared write authority — and the verb + * boundary (ADR-0111 D3) comes with it: `delete` asks `checkDelete`, which an + * `edit` share never answers `allow`. + * + * [#35934] Asked as a SET where the sharing service serves one + * ({@link resolveSharingWriteVerdicts}): nothing in the floor test depends on + * the row, so it is made once, and the verdicts for every candidate come from + * one `checkEditMany` / `checkDeleteMany` call, whose reads grow per chunk + * rather than per row. Where the service serves none, each row is asked + * {@link resolvePreImageFloorDrop} itself, in batches of + * {@link PREDICATE_WRITE_FLOOR_DECISION_BATCH}. The answers are the same + * either way; the set form is the per-row verdict for each id. * * `candidateIds` is the caller's to bound. The middleware hands over only the * rows its predicate matches that the caller can read and the floor does not * already admit, so the list is at most `PREDICATE_WRITE_READABLE_ID_CAP` long - * and the write was refused before this ran when the read was longer. Asked in - * batches of {@link PREDICATE_WRITE_FLOOR_DECISION_BATCH}; a row whose verdict - * cannot be resolved is a `deny` there, so it keeps its floor. + * and the write was refused before this ran when the read was longer. A row + * whose verdict cannot be resolved is a `deny`, so it keeps its floor. */ export async function predicateWriteFloorDropIds( - this: Pick, + this: Pick, rlsOperation: string, object: string, candidateIds: readonly (string | number | bigint)[], @@ -342,6 +407,8 @@ export async function predicateWriteFloorDropIds( delegated: boolean, ): Promise<(string | number | bigint)[]> { if (delegated) return []; + const setForm = await predicateWriteFloorDropIdsAsSet.call(this, rlsOperation, object, candidateIds, context, permissionSets); + if (setForm) return setForm; const dropped: (string | number | bigint)[] = []; for (let start = 0; start < candidateIds.length; start += PREDICATE_WRITE_FLOOR_DECISION_BATCH) { const batch = candidateIds.slice(start, start + PREDICATE_WRITE_FLOOR_DECISION_BATCH); @@ -357,6 +424,45 @@ export async function predicateWriteFloorDropIds( return dropped; } +/** + * [#35934] {@link predicateWriteFloorDropIds} through the set form, or `null` + * when the host cannot ask one (a host without the members, or a sharing + * service without `checkEditMany` / `checkDeleteMany`). The floor test is + * {@link resolvePreImageFloorDrop}'s, made once; a row is dropped exactly when + * its verdict is `allow`, as there. + */ +async function predicateWriteFloorDropIdsAsSet( + this: Pick, + rlsOperation: string, + object: string, + candidateIds: readonly (string | number | bigint)[], + context: any, + permissionSets: PermissionSet[], +): Promise<(string | number | bigint)[] | null> { + const method = rlsOperation === 'delete' ? 'checkDeleteMany' : 'checkEditMany'; + const sharing = this.resolveKernelService?.('sharing') as Record | undefined; + if (typeof sharing?.[method] !== 'function') return null; + const host = this; + const floorApplies = host.collectRLSPolicies( + permissionSets, + object, + rlsOperation, + (context?.positions ?? []) as string[], + context, + ).some(isPlatformOwnershipFloorPolicy); + if (!floorApplies) return []; + const verdicts = await resolveSharingWriteVerdicts.call( + host, + rlsOperation, + object, + candidateIds.map(String), + context, + permissionSets, + ); + if (!verdicts) return null; + return candidateIds.filter((_, i) => verdicts[i] === 'allow'); +} + /** The body of `SecurityPlugin#delegatorOwnWriteFloorOptions`; the method's docblock there is its contract. */ export async function delegatorOwnWriteFloorOptions( this: Pick, diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index 49687872878..9ad2c957765 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -2392,7 +2392,8 @@ export class SecurityPlugin implements Plugin { const readLogger = () => this.logger; const readPermissionEvaluator = () => this.permissionEvaluator; const readQl = () => this.ql; - const host: Pick = { + const readResolveKernelService = () => this.resolveKernelService; + const host: Pick = { addressedByIdWriteId: (...a) => this.addressedByIdWriteId(...a), addressedPredicateWrite: (...a) => this.addressedPredicateWrite(...a), assertControlledByParentWrite: (...a) => this.assertControlledByParentWrite(...a), @@ -2426,8 +2427,10 @@ export class SecurityPlugin implements Plugin { resolveOperationPrincipals: (...a) => this.resolveOperationPrincipals(...a), resolvePermissionSetsForContext: (...a) => this.resolvePermissionSetsForContext(...a), resolveHopWithheldFields: (...a) => this.resolveHopWithheldFields(...a), + get resolveKernelService() { return readResolveKernelService(); }, resolvePreImageFloorDrop: (...a) => this.resolvePreImageFloorDrop(...a), resolveSharingWriteVerdict: (...a) => this.resolveSharingWriteVerdict(...a), + resolveWriteScopeForSharing: (...a) => this.resolveWriteScopeForSharing(...a), writeCheckFieldOptions: (...a) => this.writeCheckFieldOptions(...a), }; this.authzMiddleware = registerAuthzMiddleware.call(host, ctx, ql, metadata); diff --git a/packages/plugins/plugin-sharing/src/sharing-service.ts b/packages/plugins/plugin-sharing/src/sharing-service.ts index 9ba121b674b..0bab627cbe7 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.ts @@ -106,6 +106,20 @@ function makeShareId(): string { /** System-elevated context for the plugin's own queries / mutations. */ const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const; +/** + * [#35934] How many records one chunk of a set-form write verdict + * (`SharingService.writeVerdicts`) reads at once: one `id IN (…)` read of + * their rows and, for an update, one `record_id IN (…)` read of the caller's + * write-level shares on them. 1,000 is the largest list every dialect this + * platform reads binds in one predicate: Oracle refuses an IN list over 1,000 + * expressions (ORA-01795), and SQL Server's 2,100 bound parameters leave room + * for the rest of the share read beside it; SQLite, PostgreSQL and MySQL take + * far more. The predicate write that asks these verdicts already binds its + * whole candidate list, up to 10,000 ids, in one list of its own, so a chunk + * never sends a longer list than the write it serves. + */ +const WRITE_VERDICT_CHUNK = 1000; + /** * [#25549] A grant recipient's standing in the record's organization, the one * recipient fact the D7 verdict reads ({@link SharingService} `inertGrantReason`). @@ -989,27 +1003,19 @@ export class SharingService implements ISharingService { } /** - * [ADR-0142 D3] Does `(object, recordId)` sit in a queue the caller belongs - * to? Membership is asked in the record's own organization (the active one - * when the row carries none, and never one the request is not in) — one - * holder check, not the caller's whole queue set. + * [ADR-0142 D3] Does the record `row` (read by {@link writeVerdicts}) sit in + * a queue the caller belongs to? Membership is asked in the record's own + * organization (the active one when the row carries none, and never one the + * request is not in) — one holder check per `(queue, organization)` pair, + * not the caller's whole queue set. `isMember` memoises that check for one + * call of {@link writeVerdicts}, so a chunk of rows in the same queue asks + * once. */ - private async sitsInCallersQueue( - schema: any, - object: string, - recordId: string, + private sitsInCallersQueue( + row: Record | undefined, context: ExecutionContext, - ): Promise { - if (!hasQueueColumn(schema) || !context?.userId || isGuestPrincipal(context)) return false; - const queues = this.ownershipQueues?.(); - if (!queues) return false; - const rows = await this.engine.find(object, { - where: { id: recordId }, - fields: ['id', OWNER_FIELD, QUEUE_FIELD, 'organization_id'], - limit: 1, - context: SYSTEM_CTX, - }); - const row = Array.isArray(rows) ? (rows[0] as Record | undefined) : undefined; + isMember: (queue: string, organizationId: string | null) => Promise, + ): Promise | false { if (!row || (row[OWNER_FIELD] != null && row[OWNER_FIELD] !== '')) return false; const queue = row[QUEUE_FIELD]; if (typeof queue !== 'string' || queue === '') return false; @@ -1018,26 +1024,23 @@ export class SharingService implements ISharingService { const rowOrg = row.organization_id == null || row.organization_id === '' ? null : String(row.organization_id); const activeOrg = context.tenantId ? String(context.tenantId) : null; if (rowOrg && activeOrg && rowOrg !== activeOrg) return false; - return queues.isMember(String(context.userId), queue, rowOrg ?? activeOrg); + return isMember(queue, rowOrg ?? activeOrg); } /** - * Does the caller own `(object, recordId)` within their write DEPTH? The - * shared ownership fast-path behind both {@link canEdit} and - * {@link canDelete}. Returns `false` when the record has no owner value. + * Does the caller own the record `row` (read by {@link writeVerdicts}) + * within their write DEPTH? The shared ownership fast-path behind both + * {@link checkEdit} and {@link checkDelete}. `false` when the record has no + * owner value, or no row was read. `owners` resolves the caller's owner set + * at most once per call of {@link writeVerdicts}, and only when a row with + * an owner reaches it. */ private async matchesOwnerScope( object: string, - recordId: string, + row: Record | undefined, context: ExecutionContext, + owners: () => Promise>, ): Promise { - const own = await this.engine.find(object, { - where: { id: recordId }, - fields: ['id', OWNER_FIELD], - limit: 1, - context: SYSTEM_CTX, - }); - const row = Array.isArray(own) ? (own[0] as Record | undefined) : undefined; const owner = row ? row[OWNER_FIELD] : undefined; if (owner == null) { // [#8418] The refusal is unchanged — `return false` below is the same @@ -1056,8 +1059,7 @@ export class SharingService implements ISharingService { // Middleware-stamped, not a field of the envelope — see buildReadFilter(). const writeScope = (context as any).__writeScope as ('own' | 'own_and_reports' | 'unit' | 'unit_and_below' | 'org' | undefined); if (writeScope === 'org') return true; - const owners = await this.resolveOwnerScopeIds(context, writeScope); - return owners.includes(String(owner)); + return (await owners()).has(String(owner)); } /** @@ -1172,17 +1174,23 @@ export class SharingService implements ISharingService { * confusion that produced #5492's measured fail-open. Logged rather than * swallowed: a silently-denied write is indistinguishable from a legitimate * refusal, which is how a broken engine looks like a permissions problem. + * + * [#35934] A chunk of {@link writeVerdicts} fails as a whole: one line names + * the chunk, and every record in it is a `deny`. */ private writeGateFailClosed( verb: 'update' | 'delete', object: string, - recordId: string, + recordIds: readonly string[], context: ExecutionContext, err: unknown, ): SharingWriteVerdict { + const records = recordIds.length === 1 + ? `record '${recordIds[0]}'` + : `${recordIds.length} records ('${recordIds[0]}' to '${recordIds[recordIds.length - 1]}')`; this.logger?.error?.( - `[sharing] the ${verb} gate could not resolve a verdict for '${object}' record ` - + `'${recordId}' (user ${context?.userId ?? 'unknown'}) — DENYING (fail-closed): ` + `[sharing] the ${verb} gate could not resolve a verdict for '${object}' ${records} ` + + `(user ${context?.userId ?? 'unknown'}) — DENYING (fail-closed): ` + 'a failed lookup is a refusal, never an abstention, because an abstention would hand the row ' + 'to the other write authorities, which may admit it', err instanceof Error ? err : new Error(String(err)), @@ -1217,51 +1225,25 @@ export class SharingService implements ISharingService { recordId: string, context: ExecutionContext, ): Promise { - const bypass = this.bypassVerdict(object, context); - if (bypass) return bypass; - - try { - const schema = this.engine.getSchema?.(object); - if (!schema) return 'abstain'; - // [ADR-0142 D3] A record sitting in a queue the caller belongs to is a - // POSITIVE basis of its own — tested before the public-OWD abstain, so on - // an open OWD too the answer is `allow` (which lifts the platform's - // `created_by` floor for a member), and apart from `matchesOwnerScope`, - // whose fast path `checkDelete` shares: the basis never reaches delete. - if (await this.sitsInCallersQueue(schema, object, recordId, context)) return 'allow'; - // [Ruling of record 6355206139] The EXTERNAL OWD floor (buildReadFilter). - const model = owdForPrincipal(schema, context, object, 'write'); - if (model === 'public') return 'abstain'; - if (!hasOwnerField(schema)) return 'abstain'; - if (!context.userId) return 'deny'; - - // 1) Ownership (write DEPTH widens the owner-set) — fast path. - if (await this.matchesOwnerScope(object, recordId, context)) return 'allow'; - - // 2) Explicit write-level share (`edit`, plus not-yet-normalised `full`), - // [ADR-0155 ② ruled R2] on an object where share grants count: where they - // do not, the read and bulk-write scopes carry no share arm, so this gate - // reads no grant row either, and the three cannot disagree. - const editGrants = this.shareGrantsInertReason(object) !== null ? [] : await this.engine.find('sys_record_share', { - where: { - object_name: object, - record_id: recordId, - recipient_type: 'user', - recipient_id: context.userId, - access_level: { $in: [...WRITE_ACCESS_LEVELS] }, - }, - fields: ['id'], - limit: 1, - context: SYSTEM_CTX, - }); - if (Array.isArray(editGrants) && editGrants.length > 0) return 'allow'; + // [#35934] The N = 1 case of the set form: one implementation, so the + // by-id verdict and the bulk one cannot drift. The reads a single record + // costs are the ones this gate always made (its owner, then its share, + // then the bypass probe), and a queue-sitting check now rides on the + // owner read instead of reading the row a second time. + return (await this.writeVerdicts('update', object, [recordId], context))[0]; + } - // 3) [#4647] Modify All Data — the explicit bypass, asked LAST and - // answered by the same predicate `security/explain` reports. - return (await this.hasModifyAllBypass(object, context)) ? 'allow' : 'deny'; - } catch (err) { - return this.writeGateFailClosed('update', object, recordId, context, err); - } + /** + * [#35934] The set form of {@link checkEdit} (`ISharingService.checkEditMany`): + * `answer[i]` is the verdict {@link checkEdit} answers for `recordIds[i]`. + * See {@link writeVerdicts} for how a list is read. + */ + async checkEditMany( + object: string, + recordIds: readonly string[], + context: ExecutionContext, + ): Promise { + return this.writeVerdicts('update', object, recordIds, context); } /** @@ -1310,26 +1292,248 @@ export class SharingService implements ISharingService { recordId: string, context: ExecutionContext, ): Promise { - const bypass = this.bypassVerdict(object, context); - if (bypass) return bypass; + // [#35934] The N = 1 case of the set form, as {@link checkEdit} is. + return (await this.writeVerdicts('delete', object, [recordId], context))[0]; + } + /** + * [#35934] The set form of {@link checkDelete} (`ISharingService.checkDeleteMany`): + * `answer[i]` is the verdict {@link checkDelete} answers for `recordIds[i]`. + */ + async checkDeleteMany( + object: string, + recordIds: readonly string[], + context: ExecutionContext, + ): Promise { + return this.writeVerdicts('delete', object, recordIds, context); + } + + /** + * [#35934] THE write verdict, for a list of records — the one + * implementation behind {@link checkEdit} / {@link checkDelete} (a list of + * one) and {@link checkEditMany} / {@link checkDeleteMany}. `answer[i]` is + * the verdict for `recordIds[i]`. + * + * Per record, in this order (the order the by-id gates have always had): + * + * 1. system context `allow`; a bypass-listed object `abstain` + * ({@link bypassVerdict}); + * 2. no resolvable schema `abstain`; + * 3. UPDATE only — [ADR-0142 D3] a record sitting in a queue the caller + * belongs to `allow`, tested before the public-OWD abstain, so on an open + * OWD too the answer is `allow` (which lifts the platform's `created_by` + * floor for a member); the basis never reaches delete; + * 4. [Ruling of record 6355206139] the EXTERNAL OWD floor: a write-open + * object `abstain`; an object with no owner field `abstain`; a + * principal-less context `deny`; + * 5. ownership, widened by write DEPTH, `allow` ({@link matchesOwnerScope}); + * 6. UPDATE only — an explicit write-level share (`edit`, plus + * not-yet-normalised `full`) `allow`, [ADR-0155 ② ruled R2] on an object + * where share grants count: where they do not, the read and bulk-write + * scopes carry no share arm, so this gate reads no grant row either, and + * the three cannot disagree. DELETE has no share branch (ADR-0111 D3: + * sharing widens rows, never verbs); + * 7. [#4647] Modify All Data, asked LAST and answered by the same predicate + * `security/explain` reports: `allow`, otherwise `deny`. + * + * What a list changes is only the cost. Steps 1, 2 and 4 do not depend on + * the record, so they are decided once. The records are read in chunks of + * {@link WRITE_VERDICT_CHUNK}: one read of the chunk's rows (owner, and the + * queue columns where step 3 can apply) and, for UPDATE, one read of the + * caller's write-level shares on the chunk's undecided records. The caller's + * owner set (step 5) is resolved at most once per call, a queue membership + * (step 3) once per queue and organization, and the bypass probe (step 7) + * at most once per call. A list of one record reads exactly what the by-id + * gate always read, by the same `where`. + * + * **Fail-closed per chunk** (`ISharingService.checkEditMany`): a chunk whose + * lookup throws answers `deny` for each of its records, never `abstain`, and + * is logged once ({@link writeGateFailClosed}); the other chunks keep their + * answers. A failure before any record is read denies every record. + */ + private async writeVerdicts( + verb: 'update' | 'delete', + object: string, + recordIds: readonly string[], + context: ExecutionContext, + ): Promise { + const count = recordIds.length; + if (count === 0) return []; + const bypass = this.bypassVerdict(object, context); + if (bypass) return recordIds.map(() => bypass); + + // Steps 2 to 4, decided once: nothing in them depends on the record. + let queues: ReturnType> | undefined; + let objectLevel: SharingWriteVerdict | null = null; + // A failure deciding step 4 refuses every record that step 3 does not + // admit — exactly what the per-record gate did, which reached step 4 only + // for those records. + let objectLevelError: { error: unknown } | null = null; try { const schema = this.engine.getSchema?.(object); - if (!schema) return 'abstain'; - // [Ruling of record 6355206139] The EXTERNAL OWD floor (buildReadFilter). - if (owdForPrincipal(schema, context, object, 'write') === 'public') return 'abstain'; - if (!hasOwnerField(schema)) return 'abstain'; - if (!context.userId) return 'deny'; - - // Ownership / write DEPTH only — no share branch. This is the whole - // difference from checkEdit. - if (await this.matchesOwnerScope(object, recordId, context)) return 'allow'; - - // [#4647] Modify All Data — the same explicit bypass checkEdit consults. - return (await this.hasModifyAllBypass(object, context)) ? 'allow' : 'deny'; + if (!schema) return recordIds.map(() => 'abstain'); + if (verb === 'update' && hasQueueColumn(schema) && context?.userId && !isGuestPrincipal(context)) { + queues = this.ownershipQueues?.() ?? undefined; + } + try { + if (owdForPrincipal(schema, context, object, 'write') === 'public') objectLevel = 'abstain'; + else if (!hasOwnerField(schema)) objectLevel = 'abstain'; + else if (!context.userId) objectLevel = 'deny'; + } catch (error) { + objectLevelError = { error }; + } } catch (err) { - return this.writeGateFailClosed('delete', object, recordId, context, err); + const verdict = this.writeGateFailClosed(verb, object, recordIds, context, err); + return recordIds.map(() => verdict); + } + if (!queues) { + if (objectLevel) { + const verdict = objectLevel; + return recordIds.map(() => verdict); + } + if (objectLevelError) { + const verdict = this.writeGateFailClosed(verb, object, recordIds, context, objectLevelError.error); + return recordIds.map(() => verdict); + } + } + + // Step 5's owner set and step 3's memberships, each resolved at most once. + const writeScope = (context as any).__writeScope as ('own' | 'own_and_reports' | 'unit' | 'unit_and_below' | 'org' | undefined); + let ownerSet: Promise> | undefined; + const owners = (): Promise> => + (ownerSet ??= this.resolveOwnerScopeIds(context, writeScope).then((ids) => new Set(ids.map(String)))); + const memberships = new Map>(); + const isMember = (queue: string, organizationId: string | null): Promise => { + const key = JSON.stringify([queue, organizationId]); + let pending = memberships.get(key); + if (!pending) { + pending = queues!.isMember(String(context.userId), queue, organizationId); + memberships.set(key, pending); + } + return pending; + }; + let sharesCount: boolean | undefined; + const shareGrantsCount = (): boolean => + (sharesCount ??= this.shareGrantsInertReason(object) === null); + + const fields = queues ? ['id', OWNER_FIELD, QUEUE_FIELD, 'organization_id'] : ['id', OWNER_FIELD]; + const verdicts: SharingWriteVerdict[] = new Array(count); + const levelRefused: string[] = []; + const awaitingBypass: number[] = []; + for (let start = 0; start < count; start += WRITE_VERDICT_CHUNK) { + const end = Math.min(count, start + WRITE_VERDICT_CHUNK); + const chunkIds = recordIds.slice(start, end); + try { + const rowOf = await this.readWriteVerdictRows(object, chunkIds, fields); + const chunkVerdicts: (SharingWriteVerdict | undefined)[] = new Array(chunkIds.length); + const chunkLevelRefused: string[] = []; + const undecided: number[] = []; + for (let k = 0; k < chunkIds.length; k += 1) { + const row = rowOf(chunkIds[k]); + if (queues && (await this.sitsInCallersQueue(row, context, isMember))) { + chunkVerdicts[k] = 'allow'; + } else if (objectLevelError) { + chunkVerdicts[k] = 'deny'; + chunkLevelRefused.push(chunkIds[k]); + } else if (objectLevel) { + chunkVerdicts[k] = objectLevel; + } else if (await this.matchesOwnerScope(object, row, context, owners)) { + chunkVerdicts[k] = 'allow'; + } else { + undecided.push(k); + } + } + let afterShares = undecided; + if (verb === 'update' && undecided.length > 0 && shareGrantsCount()) { + const shared = await this.readWriteShares(object, undecided.map((k) => chunkIds[k]), String(context.userId)); + afterShares = []; + for (const k of undecided) { + if (shared(chunkIds[k])) chunkVerdicts[k] = 'allow'; + else afterShares.push(k); + } + } + chunkVerdicts.forEach((verdict, k) => { + if (verdict) verdicts[start + k] = verdict; + }); + levelRefused.push(...chunkLevelRefused); + for (const k of afterShares) awaitingBypass.push(start + k); + } catch (err) { + const verdict = this.writeGateFailClosed(verb, object, chunkIds, context, err); + for (let i = start; i < end; i += 1) verdicts[i] = verdict; + } + } + if (levelRefused.length > 0 && objectLevelError) { + this.writeGateFailClosed(verb, object, levelRefused, context, objectLevelError.error); + } + if (awaitingBypass.length > 0) { + // Step 7, once for the whole list: the probe asks about the object and + // the caller, never the record, and fails closed on its own. + const verdict: SharingWriteVerdict = (await this.hasModifyAllBypass(object, context)) ? 'allow' : 'deny'; + for (const i of awaitingBypass) verdicts[i] = verdict; + } + return verdicts; + } + + /** + * [#35934] One read of the rows {@link writeVerdicts} judges in a chunk, as + * a lookup by record id (`undefined` for a record the read did not return). + * A chunk of one reads by the by-id gate's own `where` and takes the row it + * gets, as that gate always did. + */ + private async readWriteVerdictRows( + object: string, + recordIds: readonly string[], + fields: string[], + ): Promise<(recordId: string) => Record | undefined> { + const single = recordIds.length === 1; + const rows = await this.engine.find(object, { + where: single ? { id: recordIds[0] } : { id: { $in: [...recordIds] } }, + fields, + limit: recordIds.length, + context: SYSTEM_CTX, + }); + const list = Array.isArray(rows) ? (rows as Record[]) : []; + if (single) { + const row = list[0]; + return () => row; + } + const byId = new Map>(); + for (const row of list) { + if (row && row.id != null && !byId.has(String(row.id))) byId.set(String(row.id), row); + } + return (recordId) => byId.get(String(recordId)); + } + + /** + * [#35934] One read of the caller's write-level ({@link WRITE_ACCESS_LEVELS}) + * user shares on `recordIds` of `object`, as a membership test. A list of + * one asks the by-id gate's own question (`limit: 1`, any row answers). + */ + private async readWriteShares( + object: string, + recordIds: readonly string[], + userId: string, + ): Promise<(recordId: string) => boolean> { + const single = recordIds.length === 1; + const grants = await this.engine.find('sys_record_share', { + where: { + object_name: object, + record_id: single ? recordIds[0] : { $in: [...recordIds] }, + recipient_type: 'user', + recipient_id: userId, + access_level: { $in: [...WRITE_ACCESS_LEVELS] }, + }, + fields: single ? ['id'] : ['record_id'], + ...(single ? { limit: 1 } : {}), + context: SYSTEM_CTX, + }); + const list = Array.isArray(grants) ? (grants as Record[]) : []; + if (single) { + const shared = list.length > 0; + return () => shared; } + const sharedIds = new Set(list.map((row) => String(row?.record_id))); + return (recordId) => sharedIds.has(String(recordId)); } /** diff --git a/packages/spec/src/contracts/sharing-service.test.ts b/packages/spec/src/contracts/sharing-service.test.ts index d695b0b9b38..2db3e1b9ad1 100644 --- a/packages/spec/src/contracts/sharing-service.test.ts +++ b/packages/spec/src/contracts/sharing-service.test.ts @@ -163,13 +163,16 @@ describe('ISharingService write-gate bypass documentation parity', () => { // added to this interface without deciding whether it documents the // bypass — the loop below is what that decision is written into. 'checkDelete', + // [#35934] The optional set forms of the two tri-state primaries. + 'checkDeleteMany', 'checkEdit', + 'checkEditMany', 'grant', 'listShares', 'revoke', ]); - for (const gate of ['canEdit', 'canDelete', 'canManageShares', 'checkEdit', 'checkDelete'] as const) { + for (const gate of ['canEdit', 'canDelete', 'canManageShares', 'checkEdit', 'checkDelete', 'checkEditMany', 'checkDeleteMany'] as const) { expect(docOf.get(gate), `${gate} must document the modifyAllRecords bypass`) .toContain('modifyAllRecords'); } diff --git a/packages/spec/src/contracts/sharing-service.ts b/packages/spec/src/contracts/sharing-service.ts index 724288c3ef0..80c369430b0 100644 --- a/packages/spec/src/contracts/sharing-service.ts +++ b/packages/spec/src/contracts/sharing-service.ts @@ -34,6 +34,12 @@ * {@link SharingWriteVerdict} for the measured fail-open that * collapsing the two into one `true` produced (#5492 E2). * + * [#35934] The tri-state primaries have an optional SET form, + * `checkEditMany()` / `checkDeleteMany()`: the same verdict for each of + * a list of record ids, answered with reads that grow per chunk rather + * than per row. A caller feature-detects it and asks per record where it + * is absent; the answers are the same either way. + * * 3. **Enforcement runs on the FULL envelope.** Every method on both * interfaces below adjudicates access, so each takes a complete * {@link ExecutionContext} — the whole `resolveAuthzContext` result, @@ -426,6 +432,46 @@ export interface ISharingService { context: ExecutionContext, ): Promise; + /** + * [#35934] The SET form of {@link checkEdit}: the UPDATE verdict for every + * record of `object` that `recordIds` names, in one call. `answer[i]` is the + * verdict for `recordIds[i]`, the answer is exactly as long as `recordIds`, + * and each verdict is the one {@link checkEdit} answers for that id under the + * same `context`: ownership (widened by write DEPTH), a write-level + * ({@link ShareAccessLevel} `edit`) share, a record sitting in a queue the + * caller belongs to, or the `modifyAllRecords` super-user bypass for `allow`; + * the same `abstain` and `deny` rules, the same order. Only the cost differs: + * a list of N records is answered with a number of store reads that grows + * with N divided by the implementation's chunk, never with N itself, so a + * predicate update over many rows asks once rather than once per row. + * + * Optional. A caller feature-detects it (`typeof … === 'function'`) and + * asks {@link checkEdit} once per record where it is absent, with the same + * answers. The implementation owns the chunking. **Fail-closed per chunk**, + * as {@link checkEdit} is per record: a chunk whose lookup throws answers + * `deny` for each of its records, never `abstain`. + */ + checkEditMany?( + object: string, + recordIds: readonly string[], + context: ExecutionContext, + ): Promise; + + /** + * [#35934] The SET form of {@link checkDelete}, on the terms of + * {@link checkEditMany}: `answer[i]` is the DELETE verdict + * {@link checkDelete} answers for `recordIds[i]`. The verb boundary comes + * with it (ADR-0111 D3): `allow` is ownership (widened by write DEPTH), the + * `modifyAllRecords` super-user bypass or system context ONLY, so an `edit` + * share that makes {@link checkEditMany} answer `allow` leaves this one at + * `deny`. Optional and feature-detected; fail-closed per chunk. + */ + checkDeleteMany?( + object: string, + recordIds: readonly string[], + context: ExecutionContext, + ): Promise; + /** * [ADR-0111 D1] May the principal in `context` MANAGE shares (grant / revoke * / list) on `(object, recordId)`? True for system context, the record's From d63fbee1999afe57b31d814d72bc591a0958db34 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:30:58 +0000 Subject: [PATCH 2/7] test(sharing): pin the set-form write verdict against the per-row verdict Equivalence over the record-sharing matrix, counted reads per chunk, fail-closed per chunk, and plugin-security's feature-detect of the set form over the predicate-write matrix. Claude-Session: https://claude.ai/code/session_01Utp6CbdHk3orAeensH6EzS Co-authored-by: Claude --- .../predicate-write-floor-deferral.test.ts | 130 ++++++- .../src/sharing-service.test.ts | 318 +++++++++++++++++- .../plugin-sharing/src/sharing-service.ts | 10 +- 3 files changed, 454 insertions(+), 4 deletions(-) diff --git a/packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts b/packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts index 64d6cd7e940..724219356e4 100644 --- a/packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts +++ b/packages/plugins/plugin-security/src/predicate-write-floor-deferral.test.ts @@ -218,8 +218,10 @@ let securityPlugin: SecurityPlugin; let sharing: SharingService | undefined; let seq = 0; -/** Every write verdict the sharing service was asked, in order. */ +/** Every write verdict the sharing service was asked, in order: per row, or per id of a set-form call. */ const verdictCalls: { verb: 'edit' | 'delete'; object: string; recordId: string }[] = []; +/** [#35934] Every set-form call (`checkEditMany` / `checkDeleteMany`) the sharing service was asked. */ +const setFormCalls: { verb: 'edit' | 'delete'; object: string; count: number }[] = []; /** The `where` each update of a deal reached the driver side of the middleware chain with, while `captureWhere` is on. */ const capturedWheres: unknown[] = []; let captureWhere = false; @@ -356,6 +358,19 @@ beforeAll(async () => { verdictCalls.push({ verb: 'delete', object, recordId }); return checkDelete(object, recordId, context); }; + // [#35934] The set form, recorded per id the same way, and per call. + const checkEditMany = service.checkEditMany.bind(service); + const checkDeleteMany = service.checkDeleteMany.bind(service); + service.checkEditMany = (object: string, recordIds: string[], context: unknown) => { + setFormCalls.push({ verb: 'edit', object, count: recordIds.length }); + for (const recordId of recordIds) verdictCalls.push({ verb: 'edit', object, recordId }); + return checkEditMany(object, recordIds, context); + }; + service.checkDeleteMany = (object: string, recordIds: string[], context: unknown) => { + setFormCalls.push({ verb: 'delete', object, count: recordIds.length }); + for (const recordId of recordIds) verdictCalls.push({ verb: 'delete', object, recordId }); + return checkDeleteMany(object, recordIds, context); + }; engine.registerMiddleware(buildSharingMiddleware(sharing, ctx.logger) as never, { object: '*' }); // Registered last, so it runs after this plugin's and the sharing // middleware's composition: what it records is the predicate the write runs. @@ -725,6 +740,19 @@ describe('[#35802] a predicate write composes the platform ownership floor per r expect(rows.filter((r) => r.name === 'written').map((r) => r.id).sort()).toEqual(ids); }); + it('[#35934] those 60 candidates are asked in ONE set-form call, not one verdict per row', async () => { + const batch = `bulk_set_${++seq}`; + const ids = Array.from({ length: 60 }, (_, i) => `${batch}_${String(i).padStart(2, '0')}`); + await engine.insert(DEAL, ids.map((id) => ({ + id, name: 'as seeded', batch, stage: 'open', region: 'emea', organization_id: ORG, owner_id: BOB, created_by: CAROL, + })), SYS); + const fromSet = setFormCalls.length; + const from = verdictCalls.length; + await predicateWrite(DEAL, 'update', batch, memberOf(BOB, REP_SET.name)); + expect(setFormCalls.slice(fromSet)).toEqual([{ verb: 'edit', object: DEAL, count: 60 }]); + expect(verdictCalls.slice(from).filter((c) => c.object === DEAL)).toHaveLength(60); + }); + it('the tenant wall (Layer 0) is composed back around the relieved Layer 1', async () => { const { batch, ids } = await seedDeals(); capturedWheres.length = 0; @@ -900,6 +928,52 @@ describe('[#35917] beside an authored widener, the by-id write keeps the floor a }); }); +describe('[#35934] a sharing service without the set form keeps the per-row path, with the same answers', () => { + // The set form is optional on `ISharingService`: plugin-security + // feature-detects `checkEditMany` / `checkDeleteMany` and asks + // `checkEdit` / `checkDelete` once per row where they are absent. Each case + // runs the #35802 comparison twice, with and without the set form, and + // holds both to the same rows written and the same rows asked about. + async function withoutSetForm(run: () => Promise): Promise { + const service = sharing as any; + const kept = { checkEditMany: service.checkEditMany, checkDeleteMany: service.checkDeleteMany }; + service.checkEditMany = undefined; + service.checkDeleteMany = undefined; + try { + return await run(); + } finally { + Object.assign(service, kept); + } + } + + const CASES: [string, object, readonly Role[], readonly Role[]][] = [ + ['ALICE, the owner-creator', memberOf(ALICE, REP_SET.name), ['r1', 'r2'], ['r1', 'r2']], + ['BOB, the non-creator owner', memberOf(BOB, REP_SET.name), ['r3', 'r4'], ['r3', 'r4']], + ['CAROL, the creator who owns nothing', memberOf(CAROL, REP_SET.name), [], []], + ['the Modify All manager', memberOf(MANAGER, MANAGER_SET.name), ['r1', 'r2', 'r3', 'r4'], ['r1', 'r2', 'r3', 'r4']], + ['DAVE, the edit-share target', memberOf(DAVE, REP_SET.name), ['r2', 'r3'], []], + ['BOB on behalf of CAROL (delegated)', onBehalfOf(memberOf(BOB, REP_SET.name), CAROL), [], []], + ['ALICE on behalf of ERIN (delegated)', onBehalfOf(memberOf(ALICE, REP_SET.name), ERIN), ['r1', 'r3'], ['r1', 'r3']], + ]; + for (const [name, caller, updates, deletes] of CASES) { + for (const verb of ['update', 'delete'] as const) { + it(`${name}, ${verb}: the same rows, asked about row by row`, async () => { + const expected = verb === 'update' ? updates : deletes; + const fromSet = setFormCalls.length; + const askedWithSet = await expectPredicateMatchesById(verb, caller, expected); + const usedSet = setFormCalls.length > fromSet; + + const fromSetAgain = setFormCalls.length; + const askedPerRow = await withoutSetForm(() => expectPredicateMatchesById(verb, caller, expected)); + expect(setFormCalls.length, 'no set-form call where the service serves none').toBe(fromSetAgain); + expect(askedPerRow, 'the per-row path asks about the rows the set form asked about').toEqual(askedWithSet); + // A predicate write that asks anything at all asks it as one set where it can. + expect(usedSet).toBe(askedWithSet.length > 0); + }); + } + } +}); + describe('[#35802] predicateWriteFloorDropIds: the by-id floor decision, asked per row', () => { // A double of the by-id decision that answers like a write authority with an // `edit` share on every row: the floor is replaced for an update, never for @@ -946,6 +1020,60 @@ describe('[#35802] predicateWriteFloorDropIds: the by-id floor decision, asked p }); }); +describe('[#35934] predicateWriteFloorDropIds through the set form: one call, normalised, fail-closed', () => { + // A host whose floor test is the plugin's own (the platform floor binds an + // ordinary member) and whose kernel `sharing` service is a double. + const hostWith = (sharingDouble: Record, errors: unknown[] = []) => ({ + collectRLSPolicies: (...a: unknown[]) => (securityPlugin as any).collectRLSPolicies(...a), + logger: { error: (...a: unknown[]) => errors.push(a), warn: () => undefined }, + resolveKernelService: (name: string) => (name === 'sharing' ? sharingDouble : undefined), + resolvePermissionSetsForContext: async () => [MEMBER_DEFAULT, REP_SET], + resolveWriteScopeForSharing: async () => 'own', + resolvePreImageFloorDrop: async () => { + throw new Error('the per-row decision is not asked where the set form is served'); + }, + }); + const caller = memberOf(ALICE, REP_SET.name); + const sets = [MEMBER_DEFAULT, REP_SET]; + + it('asks the verb it is handed once, with every id as a string, and drops exactly the allowed rows', async () => { + const asked: unknown[] = []; + const host = hostWith({ + checkEditMany: async (object: string, ids: string[], ctx: any) => { + asked.push(['edit', object, ids, ctx.__writeScope]); + return ids.map((id) => (id === '2' ? 'deny' : id === '3' ? 'abstain' : 'allow')); + }, + checkDeleteMany: async (object: string, ids: string[]) => { + asked.push(['delete', object, ids]); + return ids.map(() => 'deny'); + }, + }); + expect(await predicateWriteFloorDropIds.call(host as never, 'update', DEAL, [1, 2, 3, 4n], caller, sets, false)).toEqual([1, 4n]); + expect(await predicateWriteFloorDropIds.call(host as never, 'delete', DEAL, ['a'], caller, sets, false)).toEqual([]); + expect(asked).toEqual([['edit', DEAL, ['1', '2', '3', '4'], 'own'], ['delete', DEAL, ['a']]]); + }); + + it('an answer that is not a verdict is no allow, and a probe that throws or answers the wrong length denies every row, logged once', async () => { + const strange = hostWith({ checkEditMany: async (_o: string, ids: string[]) => ids.map(() => true) }); + expect(await predicateWriteFloorDropIds.call(strange as never, 'update', DEAL, ['a', 'b'], caller, sets, false)).toEqual([]); + for (const answer of [async () => { throw new Error('sharing store down'); }, async () => ['allow']]) { + const errors: unknown[] = []; + const host = hostWith({ checkEditMany: answer }, errors); + expect(await predicateWriteFloorDropIds.call(host as never, 'update', DEAL, ['a', 'b'], caller, sets, false)).toEqual([]); + expect(errors).toHaveLength(1); + } + }); + + it('a delegated write asks nothing, and a write the floor does not bind asks nothing', async () => { + let asked = 0; + const host = hostWith({ checkEditMany: async (_o: string, ids: string[]) => { asked += 1; return ids.map(() => 'allow'); } }); + expect(await predicateWriteFloorDropIds.call(host as never, 'update', DEAL, ['a'], caller, sets, true)).toEqual([]); + const admin = { ...caller, positions: ['org_admin'] }; + expect(await predicateWriteFloorDropIds.call(host as never, 'update', DEAL, ['a'], admin, sets, false)).toEqual([]); + expect(asked).toBe(0); + }); +}); + // [#35802 · ruling record 7073030861] The other half of the card: its own // repro object, a `controlled_by_parent` detail. // diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index 3f91f9fc83e..c8b94838894 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -11,7 +11,8 @@ import { buildSharingMiddleware } from './sharing-plugin.js'; import { bootRequestContext } from './exec-context-seam.testkit.js'; import { SysRecordShare } from './objects/sys-record-share.object.js'; import { SysSharingRule } from './objects/sys-sharing-rule.object.js'; -import { SharedRecordIds, isSharedRecordIds } from '@objectstack/spec/data'; +import { QUEUE_FIELD_DEF, SharedRecordIds, isSharedRecordIds } from '@objectstack/spec/data'; +import { OWNER_FIELD_DEF } from '@objectstack/metadata-core'; import { WRITE_ACCESS_LEVELS } from './access-level.js'; import { inMembers } from './shared-record-ids.testkit.js'; @@ -2452,3 +2453,318 @@ describe('[ADR-0057] a missing hierarchy-scope resolver is said once per boot', expect(warn).toHaveBeenCalledTimes(1); }); }); + +// ───────────────────────────────────────────────────────────────────── +// [#35934] The set form of the write verdict +// ───────────────────────────────────────────────────────────────────── + +/** + * A double of the engine for the set-form pins: rows indexed by id, so a + * `where` on `id` (a scalar or an `$in` list) is a lookup and 10,000 records + * stay cheap; every other key is an equality or an `$in` list. It counts the + * reads per object and can be told to throw on a read that names a poisoned id. + */ +function makeVerdictEngine(schemas: Record, inert: ReadonlySet) { + const tables: Record>> = {}; + const shares: Record[] = []; + const reads: Record = {}; + const poisoned = new Set(); + const valueMatches = (actual: unknown, wanted: unknown): boolean => { + if (wanted != null && typeof wanted === 'object' && Array.isArray((wanted as any).$in)) { + return (wanted as any).$in.map(String).includes(String(actual)); + } + return actual === wanted; + }; + const rowMatches = (row: Record, where: Record) => + Object.entries(where).every(([key, wanted]) => valueMatches(row[key], wanted)); + return { + reads, + poisoned, + insert(object: string, rows: Record[]) { + if (object === 'sys_record_share') { shares.push(...rows); return; } + const table = (tables[object] ??= new Map()); + for (const row of rows) table.set(String(row.id), row); + }, + getSchema: (object: string) => schemas[object], + getDriverForObject: (object: string) => (inert.has(object) + ? { name: 'mongo-like', supports: {} } + : { name: 'sql', supports: { fixedReadLeaves: ['SharedRecordIds'] } }), + fixedReadLeafClassOf: () => null, + async find(object: string, options: any = {}) { + reads[object] = (reads[object] ?? 0) + 1; + const where = (options.where ?? {}) as Record; + const named = (k: string) => { + const v = where[k]; + return v != null && typeof v === 'object' ? ((v as any).$in as unknown[]).map(String) : v == null ? [] : [String(v)]; + }; + if ([...named('id'), ...named('record_id')].some((id) => poisoned.has(id))) throw new Error('store unavailable'); + let out: Record[]; + if (object === 'sys_record_share') { + out = shares.filter((row) => rowMatches(row, where)); + } else { + const table = tables[object] ?? new Map(); + const { id, ...rest } = where; + const candidates = id === undefined ? [...table.values()] : named('id').map((k) => table.get(k)).filter(Boolean); + out = (candidates as Record[]).filter((row) => rowMatches(row, rest)); + } + return out.slice(0, options.limit ?? Infinity); + }, + async insertOne() { return {}; }, + }; +} + +const VERDICT_ORG = 'org_v'; +const ME = 'u_me'; +const OTHER = 'u_other'; +const MODIFY_ALL = 'u_modify_all'; +/** Owns the bulk rows the caller does not, and is in nobody's hierarchy. */ +const THIRD = 'u_third'; +/** The ids of the record-sharing matrix: every row class one object can hold. */ +const MATRIX_IDS = [ + 'own', 'own_created_by_other', 'created_not_owned', 'edit_shared', 'read_shared', + 'queued_mine', 'queued_not_mine', 'queued_other_org', 'ownerless', 'missing', +] as const; +type MatrixId = (typeof MATRIX_IDS)[number]; +const matrixRows = (object: string): Record[] => [ + { id: `${object}:own`, owner_id: ME, created_by: ME, organization_id: VERDICT_ORG }, + { id: `${object}:own_created_by_other`, owner_id: ME, created_by: OTHER, organization_id: VERDICT_ORG }, + { id: `${object}:created_not_owned`, owner_id: OTHER, created_by: ME, organization_id: VERDICT_ORG }, + { id: `${object}:edit_shared`, owner_id: OTHER, created_by: OTHER, organization_id: VERDICT_ORG }, + { id: `${object}:read_shared`, owner_id: OTHER, created_by: OTHER, organization_id: VERDICT_ORG }, + { id: `${object}:queued_mine`, owner_id: null, queue: 'q_mine', organization_id: VERDICT_ORG }, + { id: `${object}:queued_not_mine`, owner_id: null, queue: 'q_other', organization_id: VERDICT_ORG }, + { id: `${object}:queued_other_org`, owner_id: null, queue: 'q_mine', organization_id: 'org_elsewhere' }, + { id: `${object}:ownerless`, owner_id: null, organization_id: VERDICT_ORG }, +]; +const matrixShares = (object: string) => [ + { object_name: object, record_id: `${object}:edit_shared`, recipient_type: 'user', recipient_id: ME, access_level: 'edit' }, + { object_name: object, record_id: `${object}:read_shared`, recipient_type: 'user', recipient_id: ME, access_level: 'read' }, +]; + +/** Owner-scoped, with the platform's queue column: every basis applies. */ +const V_DEAL = 'v_deal'; +/** The same, write-open (`public_read_write`): abstains, after the queue basis. */ +const V_OPEN = 'v_open'; +/** No owner field: record sharing does not enforce on it. */ +const V_MEMO = 'v_memo'; +/** A federated object whose `owner_id` is the platform's phantom anchor. */ +const V_PHANTOM = 'v_phantom'; +/** Stored by a driver that does not evaluate a share grant: shares do not count (ADR-0155 R2). */ +const V_INERT = 'v_inert'; +/** No registered schema. */ +const V_UNKNOWN = 'v_unknown'; +const VERDICT_SCHEMAS: Record = { + [V_DEAL]: { name: V_DEAL, sharingModel: 'private', fields: { id: {}, owner_id: {}, created_by: {}, queue: { ...QUEUE_FIELD_DEF } } }, + [V_OPEN]: { name: V_OPEN, sharingModel: 'public_read_write', fields: { id: {}, owner_id: {}, queue: { ...QUEUE_FIELD_DEF } } }, + [V_MEMO]: { name: V_MEMO, sharingModel: 'private', fields: { id: {}, created_by: {} } }, + [V_PHANTOM]: { name: V_PHANTOM, sharingModel: 'private', external: { remoteName: 'customers' }, fields: { owner_id: { ...OWNER_FIELD_DEF }, name: { type: 'text' } } }, + [V_INERT]: { name: V_INERT, sharingModel: 'private', fields: { id: {}, owner_id: {}, created_by: {} } }, + sys_record_share: { name: 'sys_record_share' }, +}; +const VERDICT_OBJECTS = [V_DEAL, V_OPEN, V_MEMO, V_PHANTOM, V_INERT, V_UNKNOWN, 'sys_user'] as const; + +/** The callers: each write authority, and each context a by-id gate treats specially. */ +const VERDICT_CALLERS: Record> = { + member: { userId: ME, tenantId: VERDICT_ORG }, + 'member at unit depth': { userId: ME, tenantId: VERDICT_ORG, __writeScope: 'unit' }, + 'Modify All holder': { userId: MODIFY_ALL, tenantId: VERDICT_ORG }, + 'Modify All holder at org depth': { userId: MODIFY_ALL, tenantId: VERDICT_ORG, __writeScope: 'org' }, + 'member on behalf of the Modify All holder (delegated)': { userId: ME, tenantId: VERDICT_ORG, onBehalfOf: { userId: MODIFY_ALL } }, + 'principal-less': { tenantId: VERDICT_ORG }, + guest: { tenantId: VERDICT_ORG, principalKind: 'guest' }, + system: { isSystem: true }, +}; + +function verdictRig(options: { logger?: { error?: (...a: unknown[]) => void; warn?: (...a: unknown[]) => void } } = {}) { + const engine = makeVerdictEngine(VERDICT_SCHEMAS, new Set([V_INERT])); + for (const object of [V_DEAL, V_OPEN, V_MEMO, V_PHANTOM, V_INERT]) { + // The phantom anchor's remote table has no owner column: its rows carry none. + engine.insert(object, object === V_PHANTOM + ? matrixRows(object).map(({ owner_id: _owner, ...row }) => row) + : matrixRows(object)); + engine.insert('sys_record_share', matrixShares(object)); + } + const counters = { bypassProbes: 0, memberships: 0, ownerSets: 0 }; + const svc = new SharingService({ + engine: engine as never, + // The by-id gates' bypass, as plugin-security answers it: Modify All for its + // holder, and never for an on-behalf-of context (ADR-0111 D2, fail-closed). + securityService: () => ({ + hasWriteBypass: async (_object: string, context: any) => { + counters.bypassProbes += 1; + return context?.userId === MODIFY_ALL && !context?.onBehalfOf; + }, + }) as never, + hierarchyResolver: () => ({ + resolveOwnerIds: async (who: { userId: string }) => { + counters.ownerSets += 1; + return [who.userId, OTHER]; + }, + }), + tenancy: () => ({ posture: 'single' }), + ownershipQueues: () => ({ + queuesOf: async () => ['q_mine'], + isMember: async (_user: string, queue: string, organizationId: string | null) => { + counters.memberships += 1; + return queue === 'q_mine' && organizationId === VERDICT_ORG; + }, + }), + logger: { warn: () => undefined, error: () => undefined, ...options.logger } as never, + }); + return { engine, svc, counters }; +} + +const idsOf = (object: string, ids: readonly string[] = MATRIX_IDS) => ids.map((id) => `${object}:${id}`); +/** A verdict list as letters: `a` allow, `d` deny, `-` abstain. */ +const letters = (verdicts: readonly string[]) => + verdicts.map((v) => (v === 'allow' ? 'a' : v === 'deny' ? 'd' : v === 'abstain' ? '-' : '?')).join(' '); + +describe('[#35934] checkEditMany / checkDeleteMany answer, per id, the verdict checkEdit / checkDelete answer', () => { + // Named for V_DEAL, so the comparison below cannot pass by both forms + // drifting together. `a` allow, `d` deny, in MATRIX_IDS order. + const EXPECTED_DEAL: Record = { + // own ownCbO crNotOwn edit read qMine qOther qOrg ownerless missing + member: { update: 'a a d a d a d d d d', delete: 'a a d d d d d d d d' }, + 'member at unit depth': { update: 'a a a a a a d d d d', delete: 'a a a a a d d d d d' }, + 'Modify All holder': { update: 'a a a a a a a a a a', delete: 'a a a a a a a a a a' }, + 'Modify All holder at org depth': { update: 'a a a a a a a a a a', delete: 'a a a a a a a a a a' }, + 'member on behalf of the Modify All holder (delegated)': { update: 'a a d a d a d d d d', delete: 'a a d d d d d d d d' }, + 'principal-less': { update: 'd d d d d d d d d d', delete: 'd d d d d d d d d d' }, + guest: { update: 'd d d d d d d d d d', delete: 'd d d d d d d d d d' }, + system: { update: 'a a a a a a a a a a', delete: 'a a a a a a a a a a' }, + }; + + for (const object of VERDICT_OBJECTS) { + for (const [name, caller] of Object.entries(VERDICT_CALLERS)) { + for (const verb of ['update', 'delete'] as const) { + it(`${object} · ${name} · ${verb}: the set form equals the per-row verdict on every row`, async () => { + const { svc } = verdictRig(); + const ids = idsOf(object); + const perRow: string[] = []; + for (const id of ids) { + perRow.push(verb === 'update' ? await svc.checkEdit(object, id, caller as never) : await svc.checkDelete(object, id, caller as never)); + } + const set = verb === 'update' + ? await svc.checkEditMany(object, ids, caller as never) + : await svc.checkDeleteMany(object, ids, caller as never); + expect(set).toEqual(perRow); + if (object === V_DEAL) expect(letters(set)).toBe(EXPECTED_DEAL[name][verb]); + }); + } + } + } + + it('the named row classes on the other objects: queue before the open-OWD abstain, phantom and inert-share rows', async () => { + const { svc } = verdictRig(); + const member = VERDICT_CALLERS.member as never; + // Open OWD: abstains on every row but the one sitting in the caller's queue. + expect(letters(await svc.checkEditMany(V_OPEN, idsOf(V_OPEN), member))).toBe('- - - - - a - - - -'); + expect(await svc.checkEditMany(V_OPEN, idsOf(V_OPEN, ['own', 'queued_mine']), member)).toEqual(['abstain', 'allow']); + expect(await svc.checkDeleteMany(V_OPEN, idsOf(V_OPEN, ['queued_mine']), member)).toEqual(['abstain']); + // No owner field, no schema, a bypass-listed table: abstain throughout. + expect(new Set(await svc.checkEditMany(V_MEMO, idsOf(V_MEMO), member))).toEqual(new Set(['abstain'])); + expect(new Set(await svc.checkEditMany(V_UNKNOWN, idsOf(V_UNKNOWN), member))).toEqual(new Set(['abstain'])); + expect(new Set(await svc.checkEditMany('sys_user', idsOf('sys_user'), member))).toEqual(new Set(['abstain'])); + // The phantom anchor: no row has a provisioned owner, so ownership admits + // none; the by-id gate still reads the edit share, and so does the set form. + expect(letters(await svc.checkEditMany(V_PHANTOM, idsOf(V_PHANTOM), member))).toBe('d d d a d d d d d d'); + expect(letters(await svc.checkDeleteMany(V_PHANTOM, idsOf(V_PHANTOM), member))).toBe('d d d d d d d d d d'); + // Shares do not count: the edit share admits nothing there. + expect(await svc.checkEditMany(V_INERT, idsOf(V_INERT, ['own', 'edit_shared']), member)).toEqual(['allow', 'deny']); + }); + + it('answers an empty list with an empty list, and keeps the order and length of the ids it was handed, repeats included', async () => { + const { svc } = verdictRig(); + const member = VERDICT_CALLERS.member as never; + expect(await svc.checkEditMany(V_DEAL, [], member)).toEqual([]); + const ids = idsOf(V_DEAL, ['missing', 'own', 'edit_shared', 'own', 'read_shared']); + expect(await svc.checkEditMany(V_DEAL, ids, member)).toEqual(['deny', 'allow', 'allow', 'allow', 'deny']); + }); +}); + +describe('[#35934] the set form reads per chunk, not per row', () => { + const seedBulk = (engine: ReturnType, n: number) => { + const ids = Array.from({ length: n }, (_, i) => `bulk_${i}`); + // Every class the reads must not grow with: owned, edit-shared, other's. + engine.insert(V_DEAL, ids.map((id, i) => ({ + id, owner_id: i % 3 === 0 ? ME : THIRD, organization_id: VERDICT_ORG, + }))); + engine.insert('sys_record_share', ids.filter((_, i) => i % 3 === 1).map((id) => ({ + object_name: V_DEAL, record_id: id, recipient_type: 'user', recipient_id: ME, access_level: 'edit', + }))); + return ids; + }; + + it('10,000 records: two reads per chunk of 1,000, one bypass probe per call, one owner set', async () => { + const { engine, svc, counters } = verdictRig(); + const ids = seedBulk(engine, 10_000); + for (const key of Object.keys(engine.reads)) engine.reads[key] = 0; + const member = { ...VERDICT_CALLERS['member at unit depth'] } as never; + const set = await svc.checkEditMany(V_DEAL, ids, member); + expect(engine.reads[V_DEAL]).toBe(10); + expect(engine.reads.sys_record_share).toBe(10); + expect(counters.bypassProbes).toBe(1); + expect(counters.ownerSets).toBe(1); + // Owned (every third row from the first) and edit-shared rows are allowed; the rest denied by the one probe. + expect(set.filter((v) => v === 'allow')).toHaveLength(6_667); + expect(set.filter((v) => v === 'deny')).toHaveLength(3_333); + + // The delete verb reads no share at all. + engine.reads[V_DEAL] = 0; + engine.reads.sys_record_share = 0; + await svc.checkDeleteMany(V_DEAL, ids, VERDICT_CALLERS.member as never); + expect(engine.reads[V_DEAL]).toBe(10); + expect(engine.reads.sys_record_share ?? 0).toBe(0); + }); + + it('CONTROL: the per-row gate over the same records reads per row', async () => { + const { engine, svc, counters } = verdictRig(); + const ids = seedBulk(engine, 300); + for (const key of Object.keys(engine.reads)) engine.reads[key] = 0; + for (const id of ids) await svc.checkEdit(V_DEAL, id, VERDICT_CALLERS.member as never); + expect(engine.reads[V_DEAL]).toBe(300); + expect(engine.reads.sys_record_share).toBe(200); + expect(counters.bypassProbes).toBe(100); + }); + + it('a queue membership is asked once per queue, not once per record sitting in it', async () => { + const { engine, svc, counters } = verdictRig(); + const ids = Array.from({ length: 2_500 }, (_, i) => `queued_${i}`); + engine.insert(V_DEAL, ids.map((id) => ({ id, owner_id: null, queue: 'q_mine', organization_id: VERDICT_ORG }))); + const set = await svc.checkEditMany(V_DEAL, ids, VERDICT_CALLERS.member as never); + expect(new Set(set)).toEqual(new Set(['allow'])); + expect(counters.memberships).toBe(1); + expect(engine.reads[V_DEAL]).toBe(3); + }); +}); + +describe('[#35934] the set form fails closed per chunk', () => { + it('a chunk whose read throws answers deny for each of its records, logged once; the other chunk keeps its answers', async () => { + const error = vi.fn(); + const { engine, svc } = verdictRig({ logger: { error } }); + const ids = Array.from({ length: 1_500 }, (_, i) => `fc_${i}`); + engine.insert(V_DEAL, ids.map((id) => ({ id, owner_id: ME, organization_id: VERDICT_ORG }))); + engine.poisoned.add('fc_1200'); + const set = await svc.checkEditMany(V_DEAL, ids, VERDICT_CALLERS.member as never); + expect(set).toHaveLength(1_500); + expect(new Set(set.slice(0, 1_000))).toEqual(new Set(['allow'])); + expect(new Set(set.slice(1_000))).toEqual(new Set(['deny'])); + expect(error).toHaveBeenCalledTimes(1); + expect(String(error.mock.calls[0][0])).toContain(`could not resolve a verdict for '${V_DEAL}' 500 records`); + }); + + it('a share read that throws denies its chunk too, owned rows included — never abstain', async () => { + const { engine, svc } = verdictRig(); + const ids = ['fs_owned', 'fs_other']; + engine.insert(V_DEAL, [ + { id: 'fs_owned', owner_id: ME, organization_id: VERDICT_ORG }, + { id: 'fs_other', owner_id: OTHER, organization_id: VERDICT_ORG }, + ]); + const find = engine.find.bind(engine); + engine.find = async (object: string, options: any) => { + if (object === 'sys_record_share') throw new Error('share store unavailable'); + return find(object, options); + }; + expect(await svc.checkEditMany(V_DEAL, ids, VERDICT_CALLERS.member as never)).toEqual(['deny', 'deny']); + }); +}); diff --git a/packages/plugins/plugin-sharing/src/sharing-service.ts b/packages/plugins/plugin-sharing/src/sharing-service.ts index 0bab627cbe7..82010b476dd 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.ts @@ -1467,8 +1467,14 @@ export class SharingService implements ISharingService { } if (awaitingBypass.length > 0) { // Step 7, once for the whole list: the probe asks about the object and - // the caller, never the record, and fails closed on its own. - const verdict: SharingWriteVerdict = (await this.hasModifyAllBypass(object, context)) ? 'allow' : 'deny'; + // the caller, never the record. It fails closed on its own; a lookup of + // the security service that throws is a failed lookup like any other. + let verdict: SharingWriteVerdict; + try { + verdict = (await this.hasModifyAllBypass(object, context)) ? 'allow' : 'deny'; + } catch (err) { + verdict = this.writeGateFailClosed(verb, object, awaitingBypass.map((i) => recordIds[i]), context, err); + } for (const i of awaitingBypass) verdicts[i] = verdict; } return verdicts; From b2a3a51f8a341dd0c4e2c0cb6fc0a22d96dc3569 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:38:55 +0000 Subject: [PATCH 3/7] test(sharing): drop an unused type alias from the set-form pins Claude-Session: https://claude.ai/code/session_01Utp6CbdHk3orAeensH6EzS Co-authored-by: Claude --- packages/plugins/plugin-sharing/src/sharing-service.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index c8b94838894..58db12fa157 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -2524,7 +2524,6 @@ const MATRIX_IDS = [ 'own', 'own_created_by_other', 'created_not_owned', 'edit_shared', 'read_shared', 'queued_mine', 'queued_not_mine', 'queued_other_org', 'ownerless', 'missing', ] as const; -type MatrixId = (typeof MATRIX_IDS)[number]; const matrixRows = (object: string): Record[] => [ { id: `${object}:own`, owner_id: ME, created_by: ME, organization_id: VERDICT_ORG }, { id: `${object}:own_created_by_other`, owner_id: ME, created_by: OTHER, organization_id: VERDICT_ORG }, From 3004ea95dac5ab52374009e17c040627aeb1b0ab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:41:51 +0000 Subject: [PATCH 4/7] chore(changeset): the set form of the sharing write verdict Claude-Session: https://claude.ai/code/session_01Utp6CbdHk3orAeensH6EzS Co-authored-by: Claude --- .../35934-sharing-write-verdict-set-form.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .changeset/35934-sharing-write-verdict-set-form.md diff --git a/.changeset/35934-sharing-write-verdict-set-form.md b/.changeset/35934-sharing-write-verdict-set-form.md new file mode 100644 index 00000000000..34698889e0d --- /dev/null +++ b/.changeset/35934-sharing-write-verdict-set-form.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': patch +'@objectstack/plugin-sharing': patch +'@objectstack/plugin-security': patch +--- + +perf(sharing): a predicate update or delete asks record sharing for the write verdict of all its candidate rows at once, so its store reads no longer grow per row + +Clause-②: yes (widening) +Metadata-protocol: none + +`ISharingService` (`@objectstack/spec/contracts`) gains two optional members, `checkEditMany(object, recordIds, context)` and `checkDeleteMany(object, recordIds, context)`. Each answers, for every id it is handed and in the same order, the tri-state verdict `checkEdit` / `checkDelete` answer for that id (`allow`, `abstain` or `deny`), with the same bases, the same order and the same verb boundary: an `edit` share answers `allow` to `checkEditMany` and `deny` to `checkDeleteMany`. A chunk whose lookup fails answers `deny` for each of its records, as `checkEdit` answers `deny` for a record whose lookup fails. + +`SharingService` (`@objectstack/plugin-sharing`) implements both, and `checkEdit` / `checkDelete` are now the one-record case of the same implementation. A list is read in chunks of 1,000 ids: one read of the chunk's rows and, for an update, one read of the caller's write-level shares on them. The caller's owner set, each queue membership and the Modify All probe are resolved at most once per call. A single record costs the reads it always did, except that an update of a record on an object with an ownership queue column now reads the row once instead of twice. + +`SecurityPlugin` (`@objectstack/plugin-security`) asks the set form on a predicate (`multi: true`) update or delete, for the matched rows the platform ownership floor does not already admit, where the kernel's `sharing` service serves it, and asks `checkEdit` / `checkDelete` per row, 25 at a time as before, where it does not. Which rows are written is unchanged either way. Measured on SQLite over 10,000 rows owned by another user: a member's predicate update went from 20,004 store reads and 6.6 s to 24 reads and 0.27 s, the same delete from 10,003 reads to 13, and a Modify All holder's update of all 10,000 rows from 10,004 reads to 14. + +Nothing to migrate. An `ISharingService` implementation that does not add the two members keeps working: callers ask it per record, with the same answers. From c6f613bef6f9973ec06b5dd2b946fa766adcd45b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:20:53 +0000 Subject: [PATCH 5/7] test(sharing): the set-form pins' engine double applies the caller's bound after its filter check:objectql-double-limit could not drive the double; its find now filters a plain store and slices by limit only when one is given, and the read counting sits outside the store's answer. Claude-Session: https://claude.ai/code/session_01Utp6CbdHk3orAeensH6EzS Co-authored-by: Claude --- .../src/sharing-service.test.ts | 60 ++++++++++++------- 1 file changed, 37 insertions(+), 23 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index 58db12fa157..e5e353b5705 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -2469,15 +2469,34 @@ function makeVerdictEngine(schemas: Record, inert: ReadonlySet[] = []; const reads: Record = {}; const poisoned = new Set(); + /** A scalar as a row key; anything else is no key at all. */ + const keyOf = (value: unknown): string | null => + typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint' ? String(value) : null; + const listOf = (wanted: unknown): string[] => { + const members = wanted != null && typeof wanted === 'object' ? (wanted as { $in?: unknown }).$in : [wanted]; + return Array.isArray(members) ? members.map(keyOf).filter((k): k is string => k !== null) : []; + }; const valueMatches = (actual: unknown, wanted: unknown): boolean => { - if (wanted != null && typeof wanted === 'object' && Array.isArray((wanted as any).$in)) { - return (wanted as any).$in.map(String).includes(String(actual)); + if (wanted != null && typeof wanted === 'object') { + const key = keyOf(actual); + return key !== null && listOf(wanted).includes(key); } return actual === wanted; }; - const rowMatches = (row: Record, where: Record) => - Object.entries(where).every(([key, wanted]) => valueMatches(row[key], wanted)); - return { + /** Counts the read, and fails it when it names a poisoned id. */ + const noteRead = (object: string, where: Record) => { + const seen = reads[object]; + reads[object] = (typeof seen === 'number' ? seen : 0) + 1; + const named = (k: string) => (where[k] === undefined ? [] : listOf(where[k])); + if ([...named('id'), ...named('record_id')].some((id) => poisoned.has(id))) throw new Error('store unavailable'); + }; + /** The object's rows a `where` on `id` can match, by lookup; every row when it names no id. */ + const rowsNamed = (object: string, where: Record): Record[] => { + const table = tables[object] ?? new Map>(); + if (where.id === undefined) return [...table.values()]; + return listOf(where.id).map((k) => table.get(k)).filter((row): row is Record => row !== undefined); + }; + const double = { reads, poisoned, insert(object: string, rows: Record[]) { @@ -2490,27 +2509,22 @@ function makeVerdictEngine(schemas: Record, inert: ReadonlySet null, - async find(object: string, options: any = {}) { - reads[object] = (reads[object] ?? 0) + 1; - const where = (options.where ?? {}) as Record; - const named = (k: string) => { - const v = where[k]; - return v != null && typeof v === 'object' ? ((v as any).$in as unknown[]).map(String) : v == null ? [] : [String(v)]; - }; - if ([...named('id'), ...named('record_id')].some((id) => poisoned.has(id))) throw new Error('store unavailable'); - let out: Record[]; - if (object === 'sys_record_share') { - out = shares.filter((row) => rowMatches(row, where)); - } else { - const table = tables[object] ?? new Map(); - const { id, ...rest } = where; - const candidates = id === undefined ? [...table.values()] : named('id').map((k) => table.get(k)).filter(Boolean); - out = (candidates as Record[]).filter((row) => rowMatches(row, rest)); - } - return out.slice(0, options.limit ?? Infinity); + /** The double's reads, counted and failed where told to — {@link storeFind} answers them. */ + async find(object: string, options?: any) { + noteRead(object, (options?.where ?? {}) as Record); + return storeFind(object, options); }, async insertOne() { return {}; }, }; + return double; + + /** The store's answer: the rows the `where` matches, then the caller's bound, applied only when one is given. */ + async function storeFind(object: string, options?: any) { + const where = (options?.where ?? {}) as Record; + const source = object === 'sys_record_share' ? shares : rowsNamed(object, where); + const out = source.filter((row) => Object.entries(where).every(([key, wanted]) => valueMatches(row[key], wanted))); + return typeof options?.limit === 'number' ? out.slice(0, options.limit) : out; + } } const VERDICT_ORG = 'org_v'; From 14bf9f91364c962a6dc96e3e66272c95ed29e14d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:55:49 +0000 Subject: [PATCH 6/7] test(sharing): the set-form pins' engine double refuses a where combinator Claude-Session: https://claude.ai/code/session_01Utp6CbdHk3orAeensH6EzS Co-authored-by: Claude --- packages/plugins/plugin-sharing/src/sharing-service.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index e5e353b5705..6d66ecf32a0 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -2522,7 +2522,11 @@ function makeVerdictEngine(schemas: Record, inert: ReadonlySet; const source = object === 'sys_record_share' ? shares : rowsNamed(object, where); - const out = source.filter((row) => Object.entries(where).every(([key, wanted]) => valueMatches(row[key], wanted))); + const out = source.filter((row) => Object.entries(where).every(([key, wanted]) => { + // The verdict reads are plain field conjunctions; a combinator is refused, never read as a field name. + if (key.startsWith('$')) throw new Error(`verdict engine double: combinator ${key} is not implemented`); + return valueMatches(row[key], wanted); + })); return typeof options?.limit === 'number' ? out.slice(0, options.limit) : out; } } From bd194d3ffcc734a0c0feb32dc86166ba97a12cd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:37:25 +0000 Subject: [PATCH 7/7] test(sharing): the set-form pins' engine double tests an $in list as a Set The 10,000-record pin spent 709 of its 736 ms in the double, which rebuilt and scanned each $in list once per row; under CI shard load that passed the 5 s test timeout. Each list is now a Set built once, so a read costs the rows it scans plus the ids it names. The counted-read assertions are unchanged. Claude-Session: https://claude.ai/code/session_01Utp6CbdHk3orAeensH6EzS Co-authored-by: Claude --- .../plugin-sharing/src/sharing-service.test.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index 6d66ecf32a0..2b3f086b426 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -2476,10 +2476,20 @@ function makeVerdictEngine(schemas: Record, inert: ReadonlySet k !== null) : []; }; + /** + * Each `$in` list as a Set, built once per list rather than once per row it is tested + * against: a read costs the rows it scans plus the ids it names, never rows x ids. + */ + const inSets = new WeakMap>(); const valueMatches = (actual: unknown, wanted: unknown): boolean => { if (wanted != null && typeof wanted === 'object') { + let members = inSets.get(wanted); + if (members === undefined) { + members = new Set(listOf(wanted)); + inSets.set(wanted, members); + } const key = keyOf(actual); - return key !== null && listOf(wanted).includes(key); + return key !== null && members.has(key); } return actual === wanted; };