From 54107ea2acac740124c8a5fb2563570cf0ab5353 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:25:24 +0000 Subject: [PATCH 1/6] fix(audit): a search the server widens never names a column the caller may not query The server-chosen search set of an object leaves out every column the object's own query guard would refuse this caller, as it already leaves out a field the caller may not query (#25672). A column the caller names itself is judged by the guard as before. - ObjectQL#registerSearchFieldWithholder: the seam an object's own guard uses to name those columns. - plugin-audit registers one for sys_audit_log and sys_activity, answered by the guard's own rule; the system-context census row owns it. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmRPxhTmqbUbMrqygh4 --- ...audit-search-withholds-snapshot-columns.md | 13 ++ content/docs/permissions/system-context.mdx | 3 +- packages/objectql/src/engine-find.ts | 48 +++++- .../src/engine-middleware-and-context.ts | 11 +- .../engine-search-field-withholder.test.ts | 153 ++++++++++++++++++ packages/objectql/src/engine-top-level.ts | 32 +++- packages/objectql/src/engine.ts | 27 +++- packages/objectql/src/index.ts | 2 +- packages/objectql/src/search-filter.ts | 21 ++- .../src/activity-predicate-guard.test.ts | 25 ++- .../src/audit-log-predicate-guard.test.ts | 40 +++-- .../src/parent-field-query-guard.ts | 126 +++++++++++++-- ...audit-log-audit-capability.dogfood.test.ts | 27 ++++ 13 files changed, 478 insertions(+), 50 deletions(-) create mode 100644 .changeset/34700-audit-search-withholds-snapshot-columns.md create mode 100644 packages/objectql/src/engine-search-field-withholder.test.ts diff --git a/.changeset/34700-audit-search-withholds-snapshot-columns.md b/.changeset/34700-audit-search-withholds-snapshot-columns.md new file mode 100644 index 00000000000..99edd593b3e --- /dev/null +++ b/.changeset/34700-audit-search-withholds-snapshot-columns.md @@ -0,0 +1,13 @@ +--- +'@objectstack/objectql': patch +'@objectstack/plugin-audit': patch +--- + +fix(audit): a search the server widens never names a column the caller may not query (#34700) + +Clause-②: no +Metadata-protocol: none +Skills-docs: none — no skill or docs page teaches this search set. + +- The server-chosen search set of an object now leaves out every column the object's own query guard would refuse this caller, as it already leaves out a field the caller may not query (#25672). A column the caller names in `searchFields` is not left out: the guard judges it as before. +- `ObjectQL#registerSearchFieldWithholder(object, withholder)`: the seam an object's own guard uses to name those columns. plugin-audit registers one for `sys_audit_log` and `sys_activity`, answered by the guard's own rule. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 0ce67742164..97de466cc3c 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -186,7 +186,7 @@ One of the largest consumers of the flag; | 42 | Delegation write guard bypassed | plugin-approvals | Get: service / seed / import may write delegation rows naming another delegator | `bindDelegationWriteGuard` | | 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` | | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | -| 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard` | +| 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` | | 46 | Knowledge search returns hits unfiltered | service-knowledge | Lose: the permission filter over search results | `applyPermissionFilter` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | @@ -590,6 +590,7 @@ and CI refuses one that differs from what the tree produces. | `packages/plugins/plugin-audit/src/comment-access-hooks.ts#installCommentAccessHooks` | 3 | 45 | | `packages/plugins/plugin-audit/src/comment-access-hooks.ts#installCommentReadVisibility` | 1 | 45 | | `packages/plugins/plugin-audit/src/parent-field-query-guard.ts#installParentFieldQueryGuard` | 1 | 45 | +| `packages/plugins/plugin-audit/src/parent-field-query-guard.ts#withheldSearchColumns` | 1 | 45 | | `packages/plugins/plugin-audit/src/read-audit.ts#installReadAuditWriter` | 1 | 16 | | `packages/plugins/plugin-auth/src/api-key-restore-guard.ts#isUserContextWrite` | 1 | 26b | | `packages/plugins/plugin-auth/src/auth-plugin.ts#start` | 1 | 12 | diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index a877ad7b65a..eedc63e5599 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -36,7 +36,7 @@ import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-joi import type { ExecutionContext } from '@objectstack/spec/kernel'; import { isMissingTableError } from '@objectstack/metadata/errors'; import { collectCredentialFields, collectInternalReadFields } from './secret-fields.js'; -import { expandSearchToFilter, normalizeSearch } from './search-filter.js'; +import { expandSearchToFilter, normalizeSearch, resolveSearchFields } from './search-filter.js'; import { FindHookResultNotArrayError } from './find-hook-result-shape.js'; import { FindOneHookResultNotRecordError, isFindOneResultShape } from './verb-hook-result-shape.js'; import { rejectCredentialEvaluation } from './credential-evaluation-guard.js'; @@ -51,7 +51,7 @@ import { resolveWhereFilterTokens, rowsWithoutFormulaWidening, whereResolvedTokenJudge, withFileOwnerKey, withoutFormulaWidening, writeFailureLogMeta, } from './engine-top-level.js'; -import type { EngineReadOptions, OperationContext } from './engine-top-level.js'; +import type { EngineReadOptions, OperationContext, SearchFieldWithholder } from './engine-top-level.js'; import type { ObjectQL } from './engine.js'; /** @@ -92,6 +92,7 @@ export interface FindHost { resolveRelateThenLowerWhere: ObjectQL['resolveRelateThenLowerWhere']; resolveSearchQueryableFields: ObjectQL['resolveSearchQueryableFields']; resolveWhereTokens: ObjectQL['resolveWhereTokens']; + readonly searchFieldWithholders: ObjectQL['searchFieldWithholders']; stripSearchCompanionFromRead: ObjectQL['stripSearchCompanionFromRead']; triggerHooks: ObjectQL['triggerHooks']; } @@ -175,7 +176,7 @@ export class FindFacet { * would hand the driver a key it does not read, which is the same silent drop * one layer down. */ - static async expandSearchOnAst(this: Pick, ast: QueryAST, schema: ServiceObject | undefined, context: ExecutionContext | undefined): Promise { + static async expandSearchOnAst(this: Pick, ast: QueryAST, schema: ServiceObject | undefined, context: ExecutionContext | undefined): Promise { // The `$search`/`$searchFields` OData spellings are NOT read here: the // protocol layer normalizes them to the bare keys before the engine // (protocol.ts findData), and a direct engine call carrying one is an @@ -245,10 +246,19 @@ export class FindFacet { // NAMED in `searchFields` is not withheld, so the guard still refuses it // loudly. The guard itself is unchanged, and still judges every // predicate the caller wrote. - const queryableFields = normalizeSearch(raw).query.trim() + const searching = !!normalizeSearch(raw).query.trim(); + const queryableFields = searching ? await this.resolveSearchQueryableFields(ast.object, context) : undefined; - const searchFilter = expandSearchToFilter(raw, { ...expandOptions, queryableFields }); + // [#34700] …nor a column a guard of the object's own refuses this caller + // (`registerSearchFieldWithholder`): plugin-audit's parent-field query + // guard refused the auditor's whole audit-log search for the snapshot + // columns the server put in the set. Asked with the caller's `where`, the + // one the guard will read its pinned parent from. + const withheldFields = searching + ? await FindFacet.resolveSearchWithheldFields(this.searchFieldWithholders, ast, expandOptions, context) + : undefined; + const searchFilter = expandSearchToFilter(raw, { ...expandOptions, queryableFields, withheldFields }); if (searchFilter) { ast.where = ast.where ? { $and: [ast.where, searchFilter] } : searchFilter; } else if (normalizeSearch(raw).query.trim()) { @@ -266,7 +276,8 @@ export class FindFacet { // it reaches this only then. [#25672] A set the caller's // queryable fields withheld down to nothing gets the same answer: the // declared set expands without the narrowing, so the refusal says so. - const withheld = queryableFields !== undefined && expandSearchToFilter(raw, expandOptions) !== null; + const withheld = (queryableFields !== undefined || !!withheldFields?.size) + && expandSearchToFilter(raw, expandOptions) !== null; throw emptySearchSetError(ast.object, schema, internalFields.length > 0, withheld); } } @@ -274,6 +285,31 @@ export class FindFacet { delete (ast as any).searchFields; } + /** + * [#34700] The fields the search-field withholders registered for + * `ast.object` withhold from this caller's server-resolved search set, or + * `undefined` when none is registered, the read carries no context, or none + * withholds anything. Each is asked with the set the expansion resolves + * before any withholding; their answers are unioned. + */ + static async resolveSearchWithheldFields( + withholders: ReadonlyMap, + ast: QueryAST, + expandOptions: Parameters[0], + context: ExecutionContext | undefined, + ): Promise | undefined> { + const registered = withholders.get(ast.object); + if (!registered?.length || context === undefined) return undefined; + const searchFields = resolveSearchFields(expandOptions); + if (searchFields.length === 0) return undefined; + const withheld = new Set(); + for (const withholder of registered) { + const answer = await withholder({ object: ast.object, where: ast.where, context, searchFields }); + for (const field of answer ?? []) withheld.add(field); + } + return withheld.size > 0 ? withheld : undefined; + } + /** * The aggregate and count verbs' door into {@link expandSearchOnAst} — ⛔ not * a second expander. `QuerySchema.search` (ADR-0061 D1) is declared beside diff --git a/packages/objectql/src/engine-middleware-and-context.ts b/packages/objectql/src/engine-middleware-and-context.ts index cb100e1df1d..5861a9fb8b0 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -44,7 +44,7 @@ import { isMissingTableError } from '@objectstack/metadata/errors'; import { ORGANIZATION_OBJECT, SystemWriteOrganizationRequiredError, carriesOrganization, resolveSystemWriteOrganization, resolveTenantFieldName, type SystemWriteOrganizationDecision } from './tenancy/system-write-organization.js'; import { isFederatedObject } from './federated-object.js'; import { cascadeBatchIdsOf } from './engine-top-level.js'; -import type { EngineMiddleware, OperationContext } from './engine-top-level.js'; +import type { EngineMiddleware, OperationContext, SearchFieldWithholder } from './engine-top-level.js'; import type { ObjectQL } from './engine.js'; /** @@ -64,6 +64,7 @@ export interface MiddlewareAndContextHost { getDriver: ObjectQL['getDriver']; readonly logger: ObjectQL['logger']; readonly middlewares: ObjectQL['middlewares']; + readonly searchFieldWithholders: ObjectQL['searchFieldWithholders']; organizationProbeMemo: ObjectQL['organizationProbeMemo']; probeInstallOrganizations: ObjectQL['probeInstallOrganizations']; resolveEnginePosture: ObjectQL['resolveEnginePosture']; @@ -109,6 +110,14 @@ export class MiddlewareAndContextFacet { this.logger.debug('Registered middleware', { object: options?.object, total: this.middlewares.length }); } + /** The body of `ObjectQL#registerSearchFieldWithholder`; the method's docblock there is its contract. */ + static registerSearchFieldWithholder(this: Pick, object: string, withholder: SearchFieldWithholder): void { + const list = this.searchFieldWithholders.get(object) ?? []; + list.push(withholder); + this.searchFieldWithholders.set(object, list); + this.logger.debug('Registered search-field withholder', { object, total: list.length }); + } + /** The body of `ObjectQL#hasObjectMiddleware`; the method's docblock there is its contract. */ static hasObjectMiddleware(this: Pick, objectName: string): boolean { return this.middlewares.some((m) => !!m.object && m.object !== '*' && m.object === objectName); diff --git a/packages/objectql/src/engine-search-field-withholder.test.ts b/packages/objectql/src/engine-search-field-withholder.test.ts new file mode 100644 index 00000000000..a96dd1f4669 --- /dev/null +++ b/packages/objectql/src/engine-search-field-withholder.test.ts @@ -0,0 +1,153 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34700] A `search` resolves only over fields a guard of the object's own + * lets the caller query (`ObjectQL#registerSearchFieldWithholder`). + * + * plugin-audit's parent-field query guard (#21154) runs as a middleware after + * the expansion and refuses a reader withheld any parent field a predicate over + * the audit log's snapshot columns. The server put those columns in the + * auto-default search set, so the auditor's whole audit-log search answered + * 403. The #25672 narrowing asked only the security service, which does not + * carry that guard. A withholder registered for the object is now asked too, + * and what it names leaves the server-resolved set. + * + * Pinned beside the narrowing, so a fix that over-reaches goes red here too: a + * field the caller NAMES in `searchFields` is never withheld; a context-less + * read and a blank term ask nothing; a withholder of another object is not + * asked; a set withheld down to nothing is the #24284 refusal, not every row; + * and a throw propagates. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { ObjectQL } from './engine.js'; +import type { SearchFieldWithholdingRequest } from './engine.js'; + +type Row = Record; + +const MEMBER = { userId: 'u_member', organizationId: 'org_1' }; + +function makeDriver() { + const seen: Array<{ verb: string; object: string; where: unknown }> = []; + const record = (verb: string) => async (object: string, ast: any) => { + seen.push({ verb, object, where: ast?.where }); + return verb === 'count' ? 0 : verb === 'findOne' ? null : []; + }; + const driver: any = { + name: 'mem', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + find: record('find'), + findOne: record('findOne'), + count: record('count'), + async create(_o: string, d: any) { return d; }, + async update(_o: string, _id: string, d: any) { return d; }, + async delete() { return true; }, + async bulkCreate(_o: string, r: any[]) { return r; }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, seen }; +} + +/** Every field name a filter tree mentions as a key. */ +function fieldsOf(where: unknown, out: Set = new Set()): Set { + if (Array.isArray(where)) { for (const w of where) fieldsOf(w, out); return out; } + if (!where || typeof where !== 'object') return out; + for (const [k, v] of Object.entries(where as Row)) { + if (k.startsWith('$')) fieldsOf(v, out); + else out.add(k); + } + return out; +} + +describe('[#34700] search resolves only over the fields a registered withholder lets the caller query', () => { + let engine: ObjectQL; + let seen: ReturnType['seen']; + let asked: SearchFieldWithholdingRequest[]; + let withhold: string[]; + + beforeEach(async () => { + const made = makeDriver(); + seen = made.seen; + engine = new ObjectQL(); + engine.registerDriver(made.driver, true); + await engine.init(); + const registry = engine.registry as any; + // The audit-log shape: the auto-default set holds the guarded columns. + registry.registerObject({ + name: 'app_ledger', + fields: { action: { type: 'text' }, old_value: { type: 'textarea' }, new_value: { type: 'textarea' }, object_name: { type: 'text' } }, + searchableFields: ['action', 'old_value', 'new_value'], + }, 'test'); + registry.registerObject({ + name: 'app_snapshot_only', + searchableFields: ['old_value'], + fields: { old_value: { type: 'textarea' }, label: { type: 'text' } }, + }, 'test'); + registry.registerObject({ name: 'app_other', fields: { title: { type: 'text' } } }, 'test'); + asked = []; + withhold = ['old_value', 'new_value']; + const withholder = async (request: SearchFieldWithholdingRequest) => { + asked.push(request); + return withhold.filter((f) => request.searchFields.includes(f)); + }; + engine.registerSearchFieldWithholder('app_ledger', withholder); + engine.registerSearchFieldWithholder('app_snapshot_only', withholder); + }); + + const lastWhere = () => seen[seen.length - 1]?.where; + + it.each([ + ['find', (e: ObjectQL) => e.find('app_ledger', { where: { object_name: 'crm_deal' }, search: 'ann', context: MEMBER as any })], + ['findOne', (e: ObjectQL) => e.findOne('app_ledger', { where: { object_name: 'crm_deal' }, search: 'ann', context: MEMBER as any })], + ['count', (e: ObjectQL) => e.count('app_ledger', { where: { object_name: 'crm_deal' }, search: 'ann', context: MEMBER as any })], + ] as const)('%s searches only the fields the withholder leaves, asked with the caller where, context and resolved set', async (_verb, run) => { + await run(engine); + expect([...fieldsOf(lastWhere())].sort()).toEqual(['action', 'object_name']); + expect(asked).toHaveLength(1); + expect(asked[0]).toMatchObject({ + object: 'app_ledger', + where: { object_name: 'crm_deal' }, + context: expect.objectContaining(MEMBER), + searchFields: ['action', 'old_value', 'new_value'], + }); + }); + + it('a field the caller names in searchFields is never withheld', async () => { + await engine.find('app_ledger', { search: 'ann', searchFields: ['action', 'old_value'], context: MEMBER as any }); + expect([...fieldsOf(lastWhere())].sort()).toEqual(['action', 'old_value']); + }); + + it('a withholder that withholds nothing leaves the set whole', async () => { + withhold = []; + await engine.find('app_ledger', { search: 'ann', context: MEMBER as any }); + expect([...fieldsOf(lastWhere())].sort()).toEqual(['action', 'new_value', 'old_value']); + }); + + it('a context-less read and a blank term ask nothing and narrow nothing', async () => { + await engine.find('app_ledger', { search: 'ann' }); + expect([...fieldsOf(lastWhere())].sort()).toEqual(['action', 'new_value', 'old_value']); + await engine.find('app_ledger', { search: ' ', context: MEMBER as any }); + expect(asked).toEqual([]); + }); + + it('a withholder registered for another object is not asked', async () => { + await engine.find('app_other', { search: 'ann', context: MEMBER as any }); + expect(asked).toEqual([]); + expect([...fieldsOf(lastWhere())]).toEqual(['title']); + }); + + it('a set withheld down to nothing is the #24284 refusal, naming the caller, not every row', async () => { + const err: any = await engine.find('app_snapshot_only', { search: 'ann', context: MEMBER as any }).catch((e) => e); + expect(err?.code).toBe('INVALID_FIELD'); + expect(err?.status).toBe(400); + expect(String(err?.message)).toContain('no field this caller may search'); + expect(seen.filter((s) => s.object === 'app_snapshot_only')).toEqual([]); + }); + + it('a throw from a withholder propagates', async () => { + engine.registerSearchFieldWithholder('app_other', async () => { throw new Error('withholder fault'); }); + await expect(engine.find('app_other', { search: 'ann', context: MEMBER as any })).rejects.toThrow('withholder fault'); + }); +}); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index dac2d18b839..d32dfdf6be1 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -2024,13 +2024,15 @@ function assertProjectionHasNoDottedPaths( * one the caller may not query, so the narrowing in `expandSearchOnAst` left * nothing. Same code and status — the search cannot be honoured for this * caller either way — with a message that names the cause, not a declaration - * fault the object does not have. + * fault the object does not have. [#34700] A field a registered search-field + * withholder names counts as one the caller may not query. */ function emptySearchSetError(object: string, schema: any, internalExcluded: boolean, withheld = false): Error { const declared: unknown[] = Array.isArray(schema?.searchableFields) ? schema.searchableFields : []; const err: any = withheld ? new Error( `Object '${object}' has no field this caller may search, so 'search' cannot be honoured on it: ` - + `every field it searches is one field-level security does not let this caller query. ` + + `every field it searches is one field-level security, or a query guard of the object's own, ` + + `does not let this caller query. ` + 'Answering every row instead would read as "everything matched". Grant read access to one of ' + `its searchable fields, or filter on a field this caller can read.`, ) : new Error( @@ -4097,6 +4099,32 @@ export type EngineMiddleware = ( next: () => Promise ) => Promise; +/** + * [#34700] What a search-field withholder is asked, once per read that carries + * a non-blank `search` on its object: the caller's `where` as written (before + * the search is ANDed in and before any middleware adds its own predicate), + * the context the middlewares will see, and the fields the server resolved + * the search over before any withholding. + */ +export interface SearchFieldWithholdingRequest { + readonly object: string; + readonly where: unknown; + readonly context: ExecutionContext; + readonly searchFields: readonly string[]; +} + +/** + * [#34700] A guard of an object's own — a middleware that refuses a query + * naming some of its columns for some callers — tells the search expansion + * which of `searchFields` this caller may not query, so a server-chosen search + * set never names them (`ObjectQL#registerSearchFieldWithholder`). `undefined` + * or `[]` withholds nothing. A throw propagates, as from the security + * service's `getQueryableFields`. + */ +export type SearchFieldWithholder = ( + request: SearchFieldWithholdingRequest, +) => Promise | readonly string[] | undefined; + /** * "Which of these tombstoned `sys_file` rows is something still holding?" * (commit c3c72a4bc). diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 46e72924393..28d8288d76b 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -300,7 +300,8 @@ import type { EngineMiddleware, EngineReadOptions, FieldOwnedFileReadAuthorizer, FormulaFaultSink, FormulaPlanEntry, FormulaRelated, FunctionEntry, FunctionRegistrationOptions, HeldFileResolver, HookEntry, HookHandler, IssuedAutonumber, MigrationFlagRead, OperationContext, PermissionResolution, ReadableIdsChain, ReadableIdsSecurity, - ReadableIdsSecurityResolution, TransactionScope, UnservableControlledByParentMaster, WriteWallVerdict, + ReadableIdsSecurityResolution, SearchFieldWithholder, TransactionScope, UnservableControlledByParentMaster, + WriteWallVerdict, } from './engine-top-level.js'; // [#29986 codemod] Re-exported by name, so every importer of `./engine.js` reads what it read. export { @@ -309,7 +310,8 @@ export { type FieldOwnedFileReadAuthorizer, type FormulaPlanEntry, type FunctionEntry, type FunctionRegistrationOptions, HOOK_EVENT_DISPATCH_VOCABULARY, type HeldFileResolver, type HookEntry, type HookHandler, type MigrationFlagRead, type OperationContext, type PermissionResolution, type PostHookWriteImageCheck, type ReadableIdsChain, - type ReadableIdsSecurity, SECURITY_SERVICE_SOURCE_SLOT, type UnservableControlledByParentMaster, + type ReadableIdsSecurity, SECURITY_SERVICE_SOURCE_SLOT, type SearchFieldWithholder, type SearchFieldWithholdingRequest, + type UnservableControlledByParentMaster, type WriteWallRowVerdict, type WriteWallVerdict, assembledViewItemRefusal, cascadeMemberKey, cascadeSetAdd, cascadeSetHas, collectionItemOwnerStampRefusal, declaredDatetimeLowering, declaredMultiValued, droppedFieldEvents, evaluateFormulaField, foldEngineOptionAliases, hookMatchesObject, insertStaticReadonlySubject, isExpressionDefault, @@ -574,6 +576,9 @@ export class ObjectQL implements IObjectQLEngine { object?: string; }> = []; + // [#34700] Search-field withholders, by object (`registerSearchFieldWithholder`). + private searchFieldWithholders = new Map(); + // Action registry: key = "objectName:actionName" — the UNQUALIFIED slot, what // a call that names no package runs ([ADR-0150 D5, #31697]: two packages // on one key, and a package beside host code or a plugin on the object-less @@ -1890,6 +1895,22 @@ export class ObjectQL implements IObjectQLEngine { return MiddlewareAndContextFacet.registerMiddleware.call(middlewareAndContextHost.of(this), fn, options); } + /** + * [#34700] Register a search-field withholder for `object`: a guard of the + * object's own (a middleware refusing a query that names some of its columns + * for some callers — plugin-audit's parent-field query guard, #21154) names + * the fields a non-blank `search` must not scan for this caller. They leave + * the server-resolved search set before the expansion, beside what the + * security service's `getQueryableFields` withholds (#25672). A field the + * caller names in `searchFields` is never withheld, so the guard still + * refuses it; context-less reads are not asked. The guard stays the + * enforcement (`SearchFieldWithholder`). + */ + registerSearchFieldWithholder(object: string, withholder: SearchFieldWithholder): void { + // [#34700] The body lives in `engine-middleware-and-context.ts` (see `MiddlewareAndContextHost`). + return MiddlewareAndContextFacet.registerSearchFieldWithholder.call(middlewareAndContextHost.of(this), object, withholder); + } + /** * [#21080] Whether a middleware is registered FOR `objectName` — a * {@link registerMiddleware} call whose `object` names it @@ -5913,6 +5934,7 @@ export class ObjectQL implements IObjectQLEngine { resolveRelateThenLowerWhere: (...a) => engine.resolveRelateThenLowerWhere(...a), resolveSearchQueryableFields: (...a) => engine.resolveSearchQueryableFields(...a), resolveWhereTokens: (...a) => engine.resolveWhereTokens(...a), + get searchFieldWithholders() { return engine.searchFieldWithholders; }, stripSearchCompanionFromRead: (...a) => engine.stripSearchCompanionFromRead(...a), triggerHooks: (...a) => engine.triggerHooks(...a), })); @@ -6012,6 +6034,7 @@ export class ObjectQL implements IObjectQLEngine { getDriver: (...a) => engine.getDriver(...a), get logger() { return engine.logger; }, get middlewares() { return engine.middlewares; }, + get searchFieldWithholders() { return engine.searchFieldWithholders; }, get organizationProbeMemo() { return engine.organizationProbeMemo; }, set organizationProbeMemo(v) { engine.organizationProbeMemo = v; }, probeInstallOrganizations: (...a) => engine.probeInstallOrganizations(...a), diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 2d6bbf5d74d..9c50df7c258 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -258,7 +258,7 @@ export type { CompanionFieldMeta, CompanionObjectMeta } from './search-companion // Export Engine export { ObjectQL, ObjectRepository, ScopedContext } from './engine.js'; -export type { HookHandler, HookEntry, OperationContext, EngineMiddleware, HeldFileResolver, FieldOwnedFileReadAuthorizer, WriteWallVerdict, WriteWallRowVerdict } from './engine.js'; +export type { HookHandler, HookEntry, OperationContext, EngineMiddleware, SearchFieldWithholder, SearchFieldWithholdingRequest, HeldFileResolver, FieldOwnedFileReadAuthorizer, WriteWallVerdict, WriteWallRowVerdict } from './engine.js'; export type { AdmittedValueShapeViolationTally } from './engine.js'; // The declarative datasource definition the engine indexes, and the element // type of `ObjectQL.listDatasourceDefs()`. Exported so a consumer sweeping for diff --git a/packages/objectql/src/search-filter.ts b/packages/objectql/src/search-filter.ts index 0c1d38a41cb..064ebea8975 100644 --- a/packages/objectql/src/search-filter.ts +++ b/packages/objectql/src/search-filter.ts @@ -126,6 +126,16 @@ export interface ExpandSearchOptions extends SearchFieldResolutionOptions { * loudly there. Absent = no answer, nothing withheld. */ queryableFields?: ReadonlySet; + /** + * [#34700] Fields a search-field withholder registered for the object + * (`ObjectQL#registerSearchFieldWithholder`) says this caller may not query + * here — a guard of the object's own that the security service's answer + * does not carry. Withheld from the resolved set exactly as a field missing + * from {@link queryableFields}: a field the caller named in + * `requestedFields` is never withheld, so the guard still refuses it. + * Absent or empty = nothing withheld. + */ + withheldFields?: ReadonlySet; } export interface NormalizedSearch { @@ -248,7 +258,8 @@ function companionWithinSearchFields(searchFields: readonly string[], opts: Expa /** * [#25672] Withhold from the resolved search set every field the caller may - * not query, except one the caller named itself. The resolved set is the + * not query, except one the caller named itself. [#34700] A field a + * registered withholder names is withheld the same way. The resolved set is the * server's choice (declared `searchableFields` → auto-default), so a hidden * column in it is the server widening the caller's predicate past what the * caller could write — and the predicate guard refused the WHOLE search for @@ -261,14 +272,15 @@ function withholdUnqueryable( searchFields: string[], requestedFields: string | string[] | undefined, queryable: ReadonlySet | undefined, + withheld: ReadonlySet | undefined, ): string[] { - if (!queryable) return searchFields; + if (!queryable && !withheld?.size) return searchFields; const named = new Set( typeof requestedFields === 'string' ? requestedFields.split(',').map((f) => f.trim()) : requestedFields ?? [], ); - return searchFields.filter((f) => queryable.has(f) || named.has(f)); + return searchFields.filter((f) => named.has(f) || ((!queryable || queryable.has(f)) && !withheld?.has(f))); } /** @@ -284,7 +296,7 @@ function withholdUnqueryable( * would answer the search with every row. This function stays pure and * non-throwing; the judgement lives at the call site every verb reaches. * [#25672] A set that `queryableFields` withheld down to nothing is this - * case too. + * case too, and [#34700] so is one `withheldFields` withheld to nothing. * * [#29394] A NON-empty set whose every field can never hold text is not the * second case: each term's `$or` is emitted with no arm, FALSE, so the search @@ -299,6 +311,7 @@ export function expandSearchToFilter(raw: unknown, opts: ExpandSearchOptions): a resolveSearchFields({ ...opts, requestedFields }), requestedFields, opts.queryableFields, + opts.withheldFields, ); if (searchFields.length === 0) return null; diff --git a/packages/plugins/plugin-audit/src/activity-predicate-guard.test.ts b/packages/plugins/plugin-audit/src/activity-predicate-guard.test.ts index 361986ec82d..4e8d728e522 100644 --- a/packages/plugins/plugin-audit/src/activity-predicate-guard.test.ts +++ b/packages/plugins/plugin-audit/src/activity-predicate-guard.test.ts @@ -278,13 +278,26 @@ describe('[#21154] a query over the activity text by a reader withheld a parent }); } - it('a free-text search reaching the text column is refused, matching or not', async () => { - // The searched set is the object's (its nameField among the textual - // columns), so the words name every value-bearing column it reaches. - const searched = /^\[Security\] Access denied: query on 'sys_activity' references field\(s\) not readable by the caller: summary(, [a-z_]+)*\.$/; + it('[#34700] a server-chosen search leaves the value-bearing columns out: a matching and a non-matching probe both answer no row', async () => { + // Before #34700 the guard refused the whole search. The columns now + // leave the server-resolved set, so a value held only there matches + // nothing, exactly as a value held nowhere: no oracle either way. const c = reader.cases[0]; - await expectRefused(find(reader.ctx, { object_name: c.parent }, { search: c.stored }), searched); - await expectRefused(find(reader.ctx, { object_name: c.parent }, { search: V.none }), searched); + for (const value of [c.stored, V.none]) { + expect(await find(reader.ctx, { object_name: c.parent }, { search: value })).toHaveLength(0); + expect(await find(reader.ctx, {}, { search: value })).toHaveLength(0); + } + }); + + it('[#34700] a search that names a value-bearing column itself is still refused, matching or not', async () => { + for (const c of reader.cases) { + for (const value of [c.stored, V.none]) { + await expectRefused( + find(reader.ctx, { object_name: c.parent }, { search: value, searchFields: [c.column] }), + predicateWords([c.column]), + ); + } + } }); it('the same reader queries the text of a parent it is served in full, as before', async () => { diff --git a/packages/plugins/plugin-audit/src/audit-log-predicate-guard.test.ts b/packages/plugins/plugin-audit/src/audit-log-predicate-guard.test.ts index 1c336a8e268..a7c858a37ff 100644 --- a/packages/plugins/plugin-audit/src/audit-log-predicate-guard.test.ts +++ b/packages/plugins/plugin-audit/src/audit-log-predicate-guard.test.ts @@ -12,6 +12,11 @@ * snapshots as before. The same rule, and the same guard, as the activity * stream's value-bearing columns (`activity-predicate-guard.test.ts`). * + * [#34700] A free-text search the SERVER resolved over those columns is not a + * probe the reader wrote: the columns leave its search set instead, and the + * search answers over the rest. A search naming one in `searchFields` is + * still refused. + * * ## Why a real engine, a real driver and the real plugin * * The rows are written by the real audit writer's CRUD mirror and every probe @@ -213,18 +218,31 @@ describe('[#21154] a query over the ledger snapshots by a reader withheld a pare }); } - it('a free-text search reaching the snapshot columns is refused, matching or not', async () => { - const searched = /^\[Security\] Access denied: query on 'sys_audit_log' references field\(s\) not readable by the caller: old_value, new_value\.$/; + it('[#34700] a server-chosen search leaves the snapshot columns out: a matching and a non-matching probe both answer no row', async () => { + // Before #34700 the guard refused the whole search (the auditor's + // 审计日志 search turned the list into 「无权访问」). The columns now + // leave the server-resolved set, so a value held only there matches + // nothing, exactly as a value held nowhere: no oracle either way. for (const value of [reader.cases[1].stored, V.none]) { - let thrown: any = null; - try { - await find(reader.ctx, { object_name: ITEM }, { search: value }); - } catch (err) { - thrown = err; + expect(await find(reader.ctx, { object_name: ITEM }, { search: value })).toHaveLength(0); + expect(await find(reader.ctx, {}, { search: value })).toHaveLength(0); + expect(await engine.count(LEDGER, { where: { object_name: ITEM }, search: value, context: reader.ctx })).toBe(0); + } + }); + + it('[#34700] the same search still matches on the columns the reader may query', async () => { + expect((await find(reader.ctx, { object_name: ITEM }, { search: ids.item })).length).toBeGreaterThanOrEqual(2); + expect((await find(reader.ctx, {}, { search: ids.item })).length).toBeGreaterThanOrEqual(2); + }); + + it('[#34700] a search that names a snapshot column itself is still refused, matching or not', async () => { + for (const c of reader.cases) { + for (const value of [c.stored, V.none]) { + await expectRefused( + find(reader.ctx, { object_name: ITEM }, { search: value, searchFields: [c.column] }), + predicateWords([c.column]), + ); } - expect(thrown, 'the probe was answered instead of refused').not.toBeNull(); - expect(thrown.code).toBe('PERMISSION_DENIED'); - expect(firstSentence(String(thrown.message))).toMatch(searched); } }); @@ -251,6 +269,8 @@ describe('[#21154] a query over the ledger snapshots by a reader withheld a pare expect(await find(CONTROL, contains('new_value', V.none, null))).toHaveLength(0); expect((await find(CONTROL, {}, { search: V.masked2 })).length).toBeGreaterThan(0); expect(await find(CONTROL, {}, { search: V.none })).toHaveLength(0); + // [#34700] …and nothing is withheld from its server-chosen search set. + expect((await find(CONTROL, { object_name: ITEM }, { search: V.unserved2 })).length).toBeGreaterThan(0); }); it('control: the unrestricted reader filters, groups and sorts by both snapshot columns of a pinned parent, as before', async () => { diff --git a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts index 7d9f238e8ad..a8de20d3280 100644 --- a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts +++ b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts @@ -102,6 +102,14 @@ * objects' searched set. The projection (`fields`) is not a predicate: what it * selects is the redaction's to narrow. * + * [#34700] A search the SERVER resolved over these columns is not refused for + * them: each guard also registers a search-field withholder with the engine + * ({@link withheldSearchColumns}), so the columns this rule would refuse leave + * the server-chosen set before the expansion, as a field the security service + * says the caller may not query does (#25672). The search then answers over + * the columns the caller may query. A search whose `searchFields` names one + * of them is still refused here. + * * ## The refusal * * `PERMISSION_DENIED` / 403 with the engine's words for the same role — the @@ -327,6 +335,21 @@ export async function readerWithholdsParentField( /** The engine slice the declared set is read from: its object registry. */ export interface ParentObjectRegistryEngine extends ActivityMiddlewareEngine { registry?: { getAllObjects?(): ReadonlyArray<{ name?: unknown }> }; + /** + * [#34700] The engine's search-field withholder seam + * (`ObjectQL#registerSearchFieldWithholder`). Optional: an engine without it + * keeps the guard alone, and a server-chosen search over a guarded column + * is refused as before. + */ + registerSearchFieldWithholder?( + object: string, + withholder: (request: { + object: string; + where: unknown; + context: unknown; + searchFields: readonly string[]; + }) => Promise, + ): void; } /** @@ -405,6 +428,86 @@ export function parentFieldQueryRefusal( return err; } +/** + * The guard's verdict on a query over `guard.object` whose `where` is `where` + * and which names `named`: `true` refuses. One question for the middleware + * and the search-field withholder, so the two cannot disagree on a query. + * Fails closed: a security answer that cannot be had refuses. + */ +async function guardRefuses( + engine: ParentObjectRegistryEngine, + guard: ParentFieldQueryGuard, + security: FieldVisibilitySource, + where: unknown, + named: NamedValueBearingColumns, + context: unknown, + logger: FieldRedactionLogger, +): Promise { + const parent = pinnedParentObject(where, guard.object); + const askEveryObject = parent === null || reachesSideCopy(guard.object, parent, named); + try { + if (!askEveryObject && parent !== null) { + return await readerWithholdsParentField(security, parent, context, logger); + } + return await readerWithholdsAnyDeclaredParentField(engine, security, context, logger); + } catch (err) { + logger.warn( + `[audit] ${guard.object} query guard: could not tell whether the caller is served every field of ` + + `${askEveryObject ? 'every registered object' : `'${parent}'`} — refusing the query (fail closed): ` + + `${(err as Error)?.message ?? err}`, + ); + return true; + } +} + +/** + * [#34700] Which of a search's server-resolved fields the guard would refuse + * this caller, so the engine leaves them out of the set + * (`ObjectQL#registerSearchFieldWithholder`) instead of the guard refusing the + * whole search — the auditor's audit-log search answered 403 for the + * `old_value` / `new_value` snapshot columns the server had put in it. A + * column the caller names in `searchFields` is never withheld, so the guard + * still refuses it: the oracle stays closed. + * + * Asked with the guard's own question ({@link guardRefuses}), the search + * naming every guarded column in the set. When that is refused and the query + * pins a parent `side-copy-columns.ts` lists, the carrier columns alone are + * what widen it to every object (`reachesSideCopy`), so the rest is asked + * again without them and kept when the pinned parent admits it. + * + * Costs the guard's question once more per search that resolves a guarded + * column for a caller the guard admits: the middleware still asks it of the + * expanded query. + */ +export async function withheldSearchColumns( + engine: ParentObjectRegistryEngine, + guard: ParentFieldQueryGuard, + security: FieldVisibilitySource | undefined, + request: { where: unknown; context: unknown; searchFields: readonly string[] }, + logger: FieldRedactionLogger, +): Promise { + const context = request.context as { isSystem?: boolean } | undefined; + if (!context || context.isSystem || !security) return undefined; + const inSet = guard.columns.filter((c) => request.searchFields.includes(c)); + if (inSet.length === 0) return undefined; + const asPredicate = (columns: string[]): NamedValueBearingColumns => ({ aggregate: [], predicate: columns }); + if (!(await guardRefuses(engine, guard, security, request.where, asPredicate(inSet), request.context, logger))) { + return undefined; + } + const parent = pinnedParentObject(request.where, guard.object); + if (parent !== null && reachesSideCopy(guard.object, parent, asPredicate(inSet))) { + const carriers = SIDE_COPY_CARRIER_COLUMNS.get(guard.object) ?? []; + const rest = inSet.filter((c) => !carriers.includes(c)); + if ( + rest.length > 0 && + !(await guardRefuses(engine, guard, security, request.where, asPredicate(rest), request.context, logger)) + ) { + return inSet.filter((c) => carriers.includes(c)); + } + } + return inSet; +} + /** Register the query guard for one object. */ function installParentFieldQueryGuard( engine: ParentObjectRegistryEngine, @@ -423,28 +526,17 @@ function installParentFieldQueryGuard( // predicate over it discloses nothing the rows do not. const security = getSecurity(); if (!security) return next(); - const parent = pinnedParentObject(ctx.ast.where, guard.object); - const askEveryObject = parent === null || reachesSideCopy(guard.object, parent, named); - let refuse = true; - try { - if (!askEveryObject && parent !== null) { - refuse = await readerWithholdsParentField(security, parent, ctx.context, logger); - } else { - refuse = await readerWithholdsAnyDeclaredParentField(engine, security, ctx.context, logger); - } - } catch (err) { - logger.warn( - `[audit] ${guard.object} query guard: could not tell whether the caller is served every field of ` + - `${askEveryObject ? 'every registered object' : `'${parent}'`} — refusing the query (fail closed): ` + - `${(err as Error)?.message ?? err}`, - ); - refuse = true; + if (await guardRefuses(engine, guard, security, ctx.ast.where, named, ctx.context, logger)) { + throw parentFieldQueryRefusal(guard, ctx.operation, named); } - if (refuse) throw parentFieldQueryRefusal(guard, ctx.operation, named); return next(); }, { object: guard.object }, ); + // [#34700] …and tell the search expansion which columns it would refuse. + engine.registerSearchFieldWithholder?.(guard.object, (request) => + withheldSearchColumns(engine, guard, getSecurity(), request, logger), + ); } /** diff --git a/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts b/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts index 8dbd24645ed..2754946179e 100644 --- a/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts +++ b/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts @@ -405,6 +405,33 @@ describe('[#21260] the ledger audit capability exempts its holder from the paren expect(await servedById('admin', rowIds.endedSignIn)).toBe(200); expect(await servedTotal('admin', { object_name: OBJ })).toBe(await totalAtRest()); }); + + // [#34700] The ledger list's search box: the server-chosen search set held + // the `old_value` / `new_value` snapshot columns, and plugin-audit's + // parent-field query guard refused the WHOLE search for every caller + // withheld any parent field — the auditor's list turned into 「无权访问」. + // The columns now leave that caller's set; naming one still refuses. + it('[#34700] holder and non-holder: the list search answers over the columns each may query, and a search naming a snapshot column is still refused', async () => { + const search = (who: keyof typeof token, q: string) => + stack.apiAs(token[who], 'GET', `/data/${LEDGER}?search=${encodeURIComponent(q)}&limit=50`); + for (const who of ['holder', 'reader'] as const) { + for (const q of [id.gone, VALUE.withheld]) { + const res = await search(who, q); + expect(res.status, `${who} search: ${await res.clone().text()}`).toBe(200); + } + // A value held only in a snapshot matches nothing for this caller. + expect(rowsOf(await (await search(who, VALUE.withheld)).json())).toHaveLength(0); + const named = await stack.apiAs(token[who], 'GET', `/data/${LEDGER}?search=${VALUE.withheld}&searchFields=old_value&limit=5`); + expect(named.status, `${who} names a snapshot column: ${await named.clone().text()}`).toBe(403); + } + // The holder is served the deleted record's rows, found by the column it may query. + const held = rowsOf(await (await search('holder', id.gone)).json()); + expect(held.length, 'the holder finds the deleted record’s rows by search').toBeGreaterThanOrEqual(2); + // Control: the platform administrator is withheld nothing, so its search still reads the snapshots. + const admin = await search('admin', VALUE.withheld); + expect(admin.status).toBe(200); + expect(rowsOf(await admin.json()).length, 'the administrator’s search matches a snapshot').toBeGreaterThan(0); + }); }); // ── The declared scope, measured: a holder is bounded by its organization ──── From 12455d5accdff81d60481394b1ac51713b68c44f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:21:15 +0000 Subject: [PATCH 2/6] test(dogfood): the activity-stream search pin follows the search-set rule Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmRPxhTmqbUbMrqygh4 --- .../activity-text-predicate.dogfood.test.ts | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/qa/dogfood/test/activity-text-predicate.dogfood.test.ts b/packages/qa/dogfood/test/activity-text-predicate.dogfood.test.ts index 8b5eb87856f..dfdc5663f7f 100644 --- a/packages/qa/dogfood/test/activity-text-predicate.dogfood.test.ts +++ b/packages/qa/dogfood/test/activity-text-predicate.dogfood.test.ts @@ -33,8 +33,10 @@ // - For each class, each value-bearing activity column, each ledger snapshot // column and the approval snapshot column, // a matching and a non-matching filter are both refused with the engine's -// refusal (403, PERMISSION_DENIED, its words); so are a grouping, a search and -// a filter that names no parent object. +// refusal (403, PERMISSION_DENIED, its words); so are a grouping, a search +// naming such a column, and a filter that names no parent object. [#34700] A +// search the server widens leaves those columns out and answers a matching +// and a non-matching probe alike. // - The same reader filters the text of a parent it is served in full, as // before; the control filters every column of a pinned parent, as before. // - The platform admin, granted the fixture's two capabilities and so served @@ -415,12 +417,20 @@ describe('[#21154] a query over activity text or the approval snapshot, by a rea } }); - it('a free-text search over the activity stream of the parent is refused, matching or not', async () => { + // [#34700] A search the server widens leaves the guarded columns out of + // this reader's set: a matching and a non-matching probe answer alike. + // A search that names a guarded column itself is still refused. + it('a free-text search over the activity stream of the parent answers a matching and a non-matching probe alike, and one naming a guarded column is refused', async () => { + const answers: Array<{ status: number; rows: number }> = []; for (const value of [STORED[c][1], NOMATCH]) { const a = await list(c, 'sys_activity', { object_name: OBJ }, `&$search=${encodeURIComponent(value)}`); - expect(a.status, a.text).toBe(403); - expect(a.code).toBe('PERMISSION_DENIED'); + expect(a.status, a.text).toBe(200); + answers.push({ status: a.status, rows: a.rows }); + const named = await list(c, 'sys_activity', { object_name: OBJ }, `&$search=${encodeURIComponent(value)}&$searchFields=summary`); + expect(named.status, named.text).toBe(403); + expect(named.code).toBe('PERMISSION_DENIED'); } + expect(answers[0]).toEqual(answers[1]); }); it('a matching and a non-matching filter on each ledger snapshot column are both refused, and so is a grouping by it', async () => { From 6dcdf177c7f1e13f69ff201aeae9b62f93892e82 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 04:42:55 +0000 Subject: [PATCH 3/6] refactor(objectql, plugin-audit): a guard middleware declares its search-field withholder in its own registration The merge with main put engine.ts over its facade line ceiling (6880 against 6857), and a facade file does not grow. The withholder is no longer a method on the engine: registerMiddleware takes EngineMiddlewareOptions, whose withholdSearchFields the search expansion asks for the reads that middleware runs on (the same object selector). The entry type lives in engine-top-level.ts, so engine.ts ends at 6856. plugin-audit's two guards declare theirs in the registration they already make. Behaviour is unchanged; one pin added for a middleware that runs for every object. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01QSeKYmQuAhLgegkqRcTc38 --- ...audit-search-withholds-snapshot-columns.md | 2 +- packages/objectql/src/engine-find.ts | 30 +++++++----- .../src/engine-middleware-and-context.ts | 16 ++---- .../engine-search-field-withholder.test.ts | 37 ++++++++++---- packages/objectql/src/engine-top-level.ts | 28 +++++++++-- packages/objectql/src/engine.ts | 40 +++------------ packages/objectql/src/index.ts | 4 +- packages/objectql/src/search-filter.ts | 2 +- .../src/parent-field-query-guard.ts | 49 ++++++++++--------- 9 files changed, 113 insertions(+), 95 deletions(-) diff --git a/.changeset/34700-audit-search-withholds-snapshot-columns.md b/.changeset/34700-audit-search-withholds-snapshot-columns.md index 99edd593b3e..f083a0f5951 100644 --- a/.changeset/34700-audit-search-withholds-snapshot-columns.md +++ b/.changeset/34700-audit-search-withholds-snapshot-columns.md @@ -10,4 +10,4 @@ Metadata-protocol: none Skills-docs: none — no skill or docs page teaches this search set. - The server-chosen search set of an object now leaves out every column the object's own query guard would refuse this caller, as it already leaves out a field the caller may not query (#25672). A column the caller names in `searchFields` is not left out: the guard judges it as before. -- `ObjectQL#registerSearchFieldWithholder(object, withholder)`: the seam an object's own guard uses to name those columns. plugin-audit registers one for `sys_audit_log` and `sys_activity`, answered by the guard's own rule. +- `registerMiddleware(fn, { object, withholdSearchFields })`: a guard middleware names those columns in its own registration (`EngineMiddlewareOptions.withholdSearchFields`, asked for the reads the middleware runs on). plugin-audit's guards on `sys_audit_log` and `sys_activity` declare one, answered by the guard's own rule. diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index 03cc3cdc80f..528e8a8464d 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -56,7 +56,7 @@ import { resolveWhereFilterTokens, rowsWithoutFormulaWidening, whereResolvedTokenJudge, withFileOwnerKey, withoutFormulaWidening, writeFailureLogMeta, } from './engine-top-level.js'; -import type { EngineReadOptions, OperationContext, SearchFieldWithholder } from './engine-top-level.js'; +import type { EngineMiddlewareEntry, EngineReadOptions, OperationContext } from './engine-top-level.js'; import type { ObjectQL } from './engine.js'; /** @@ -87,6 +87,7 @@ export interface FindHost { readonly logger: ObjectQL['logger']; lowerRelationConditions: ObjectQL['lowerRelationConditions']; maskSecretFields: ObjectQL['maskSecretFields']; + readonly middlewares: ObjectQL['middlewares']; permissionResolution: ObjectQL['permissionResolution']; readonly relatedSchemaOf: ObjectQL['relatedSchemaOf']; reportFindFailure: ObjectQL['reportFindFailure']; @@ -98,7 +99,6 @@ export interface FindHost { resolveRelateThenLowerWhere: ObjectQL['resolveRelateThenLowerWhere']; resolveSearchQueryableFields: ObjectQL['resolveSearchQueryableFields']; resolveWhereTokens: ObjectQL['resolveWhereTokens']; - readonly searchFieldWithholders: ObjectQL['searchFieldWithholders']; stripSearchCompanionFromRead: ObjectQL['stripSearchCompanionFromRead']; triggerHooks: ObjectQL['triggerHooks']; } @@ -182,7 +182,7 @@ export class FindFacet { * would hand the driver a key it does not read, which is the same silent drop * one layer down. */ - static async expandSearchOnAst(this: Pick, ast: QueryAST, schema: ServiceObject | undefined, context: ExecutionContext | undefined): Promise { + static async expandSearchOnAst(this: Pick, ast: QueryAST, schema: ServiceObject | undefined, context: ExecutionContext | undefined): Promise { // The `$search`/`$searchFields` OData spellings are NOT read here: the // protocol layer normalizes them to the bare keys before the engine // (protocol.ts findData), and a direct engine call carrying one is an @@ -257,12 +257,12 @@ export class FindFacet { ? await this.resolveSearchQueryableFields(ast.object, context) : undefined; // [#34700] …nor a column a guard of the object's own refuses this caller - // (`registerSearchFieldWithholder`): plugin-audit's parent-field query + // (`EngineMiddlewareOptions.withholdSearchFields`): plugin-audit's parent-field query // guard refused the auditor's whole audit-log search for the snapshot // columns the server put in the set. Asked with the caller's `where`, the // one the guard will read its pinned parent from. const withheldFields = searching - ? await FindFacet.resolveSearchWithheldFields(this.searchFieldWithholders, ast, expandOptions, context) + ? await FindFacet.resolveSearchWithheldFields(this.middlewares, ast, expandOptions, context) : undefined; const searchFilter = expandSearchToFilter(raw, { ...expandOptions, queryableFields, withheldFields }); if (searchFilter) { @@ -292,20 +292,24 @@ export class FindFacet { } /** - * [#34700] The fields the search-field withholders registered for - * `ast.object` withhold from this caller's server-resolved search set, or - * `undefined` when none is registered, the read carries no context, or none - * withholds anything. Each is asked with the set the expansion resolves - * before any withholding; their answers are unioned. + * [#34700] The fields the search-field withholders of the middlewares that + * run for `ast.object` (`EngineMiddlewareOptions.withholdSearchFields`, the + * object selector `executeWithMiddleware` applies) withhold from this + * caller's server-resolved search set, or `undefined` when none is + * registered, the read carries no context, or none withholds anything. Each + * is asked with the set the expansion resolves before any withholding; their + * answers are unioned. */ static async resolveSearchWithheldFields( - withholders: ReadonlyMap, + middlewares: readonly EngineMiddlewareEntry[], ast: QueryAST, expandOptions: Parameters[0], context: ExecutionContext | undefined, ): Promise | undefined> { - const registered = withholders.get(ast.object); - if (!registered?.length || context === undefined) return undefined; + const registered = middlewares.flatMap((m) => + m.withholdSearchFields && (!m.object || m.object === '*' || m.object === ast.object) ? [m.withholdSearchFields] : [], + ); + if (registered.length === 0 || context === undefined) return undefined; const searchFields = resolveSearchFields(expandOptions); if (searchFields.length === 0) return undefined; const withheld = new Set(); diff --git a/packages/objectql/src/engine-middleware-and-context.ts b/packages/objectql/src/engine-middleware-and-context.ts index cd73cc0cbcc..9576bac2616 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -46,7 +46,7 @@ import { isMissingTableError } from '@objectstack/metadata/errors'; import { ORGANIZATION_OBJECT, SystemWriteOrganizationRequiredError, carriesOrganization, resolveSystemWriteOrganization, resolveTenantFieldName, type SystemWriteOrganizationDecision } from './tenancy/system-write-organization.js'; import { isFederatedObject } from './federated-object.js'; import { cascadeBatchIdsOf } from './engine-top-level.js'; -import type { EngineMiddleware, OperationContext, SearchFieldWithholder } from './engine-top-level.js'; +import type { EngineMiddleware, EngineMiddlewareOptions, OperationContext } from './engine-top-level.js'; import type { ObjectQL } from './engine.js'; /** @@ -66,7 +66,6 @@ export interface MiddlewareAndContextHost { getDriver: ObjectQL['getDriver']; readonly logger: ObjectQL['logger']; readonly middlewares: ObjectQL['middlewares']; - readonly searchFieldWithholders: ObjectQL['searchFieldWithholders']; organizationProbeMemo: ObjectQL['organizationProbeMemo']; probeInstallOrganizations: ObjectQL['probeInstallOrganizations']; resolveEnginePosture: ObjectQL['resolveEnginePosture']; @@ -107,19 +106,12 @@ export class MiddlewareAndContextFacet { } /** The body of `ObjectQL#registerMiddleware`; the method's docblock there is its contract. */ - static registerMiddleware(this: Pick, fn: EngineMiddleware, options?: { object?: string }): void { - this.middlewares.push({ fn, object: options?.object }); + static registerMiddleware(this: Pick, fn: EngineMiddleware, options?: EngineMiddlewareOptions): void { + const withholdSearchFields = options?.withholdSearchFields; + this.middlewares.push({ fn, object: options?.object, ...(withholdSearchFields ? { withholdSearchFields } : {}) }); this.logger.debug('Registered middleware', { object: options?.object, total: this.middlewares.length }); } - /** The body of `ObjectQL#registerSearchFieldWithholder`; the method's docblock there is its contract. */ - static registerSearchFieldWithholder(this: Pick, object: string, withholder: SearchFieldWithholder): void { - const list = this.searchFieldWithholders.get(object) ?? []; - list.push(withholder); - this.searchFieldWithholders.set(object, list); - this.logger.debug('Registered search-field withholder', { object, total: list.length }); - } - /** The body of `ObjectQL#hasObjectMiddleware`; the method's docblock there is its contract. */ static hasObjectMiddleware(this: Pick, objectName: string): boolean { return this.middlewares.some((m) => !!m.object && m.object !== '*' && m.object === objectName); diff --git a/packages/objectql/src/engine-search-field-withholder.test.ts b/packages/objectql/src/engine-search-field-withholder.test.ts index a96dd1f4669..7c462701e7d 100644 --- a/packages/objectql/src/engine-search-field-withholder.test.ts +++ b/packages/objectql/src/engine-search-field-withholder.test.ts @@ -2,21 +2,22 @@ /** * [#34700] A `search` resolves only over fields a guard of the object's own - * lets the caller query (`ObjectQL#registerSearchFieldWithholder`). + * lets the caller query (`EngineMiddlewareOptions.withholdSearchFields`, the + * withholder a guard middleware declares when it registers). * * plugin-audit's parent-field query guard (#21154) runs as a middleware after * the expansion and refuses a reader withheld any parent field a predicate over * the audit log's snapshot columns. The server put those columns in the * auto-default search set, so the auditor's whole audit-log search answered * 403. The #25672 narrowing asked only the security service, which does not - * carry that guard. A withholder registered for the object is now asked too, - * and what it names leaves the server-resolved set. + * carry that guard. The withholder of a middleware that runs for the object is + * now asked too, and what it names leaves the server-resolved set. * * Pinned beside the narrowing, so a fix that over-reaches goes red here too: a * field the caller NAMES in `searchFields` is never withheld; a context-less - * read and a blank term ask nothing; a withholder of another object is not - * asked; a set withheld down to nothing is the #24284 refusal, not every row; - * and a throw propagates. + * read and a blank term ask nothing; a withholder of a middleware for another + * object is not asked, one for every object is; a set withheld down to nothing + * is the #24284 refusal, not every row; and a throw propagates. */ import { describe, it, expect, beforeEach } from 'vitest'; @@ -92,8 +93,11 @@ describe('[#34700] search resolves only over the fields a registered withholder asked.push(request); return withhold.filter((f) => request.searchFields.includes(f)); }; - engine.registerSearchFieldWithholder('app_ledger', withholder); - engine.registerSearchFieldWithholder('app_snapshot_only', withholder); + const passThrough = async (_ctx: unknown, next: () => Promise) => next(); + engine.registerMiddleware(passThrough, { object: 'app_ledger', withholdSearchFields: withholder }); + engine.registerMiddleware(passThrough, { object: 'app_snapshot_only', withholdSearchFields: withholder }); + // A middleware without a withholder is not asked anything. + engine.registerMiddleware(passThrough, { object: 'app_other' }); }); const lastWhere = () => seen[seen.length - 1]?.where; @@ -138,6 +142,18 @@ describe('[#34700] search resolves only over the fields a registered withholder expect([...fieldsOf(lastWhere())]).toEqual(['title']); }); + it.each([undefined, '*'])('a withholder on a middleware for every object (object %s) is asked for each, as the middleware runs', async (object) => { + const everywhere: string[] = []; + engine.registerMiddleware(async (_ctx, next) => next(), { + ...(object ? { object } : {}), + withholdSearchFields: (request) => { everywhere.push(request.object); return []; }, + }); + await engine.find('app_other', { search: 'ann', context: MEMBER as any }); + await engine.find('app_ledger', { search: 'ann', context: MEMBER as any }); + expect(everywhere).toEqual(['app_other', 'app_ledger']); + expect([...fieldsOf(lastWhere())].sort()).toEqual(['action']); + }); + it('a set withheld down to nothing is the #24284 refusal, naming the caller, not every row', async () => { const err: any = await engine.find('app_snapshot_only', { search: 'ann', context: MEMBER as any }).catch((e) => e); expect(err?.code).toBe('INVALID_FIELD'); @@ -147,7 +163,10 @@ describe('[#34700] search resolves only over the fields a registered withholder }); it('a throw from a withholder propagates', async () => { - engine.registerSearchFieldWithholder('app_other', async () => { throw new Error('withholder fault'); }); + engine.registerMiddleware(async (_ctx, next) => next(), { + object: 'app_other', + withholdSearchFields: async () => { throw new Error('withholder fault'); }, + }); await expect(engine.find('app_other', { search: 'ann', context: MEMBER as any })).rejects.toThrow('withholder fault'); }); }); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index ded4cf81e2c..de84777baf0 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -4347,14 +4347,36 @@ export interface SearchFieldWithholdingRequest { * [#34700] A guard of an object's own — a middleware that refuses a query * naming some of its columns for some callers — tells the search expansion * which of `searchFields` this caller may not query, so a server-chosen search - * set never names them (`ObjectQL#registerSearchFieldWithholder`). `undefined` - * or `[]` withholds nothing. A throw propagates, as from the security - * service's `getQueryableFields`. + * set never names them (`EngineMiddlewareOptions.withholdSearchFields`). + * `undefined` or `[]` withholds nothing. A throw propagates, as from the + * security service's `getQueryableFields`. */ export type SearchFieldWithholder = ( request: SearchFieldWithholdingRequest, ) => Promise | readonly string[] | undefined; +/** The options of `ObjectQL#registerMiddleware`. */ +export interface EngineMiddlewareOptions { + /** The object the middleware runs for; absent or `'*'` = every object. */ + object?: string; + /** + * [#34700] The middleware is a guard of the object's own (plugin-audit's + * parent-field query guard, #21154) and this names the fields a non-blank + * `search` must not scan for the caller, asked for the reads the middleware + * runs on. They leave the server-resolved search set before the expansion, + * beside what the security service's `getQueryableFields` withholds + * (#25672). A field the caller names in `searchFields` is never withheld, so + * the middleware still refuses it; a context-less read is not asked. The + * middleware stays the enforcement. + */ + withholdSearchFields?: SearchFieldWithholder; +} + +/** One registered middleware, as `ObjectQL#registerMiddleware` stores it. */ +export interface EngineMiddlewareEntry extends EngineMiddlewareOptions { + fn: EngineMiddleware; +} + /** * "Which of these tombstoned `sys_file` rows is something still holding?" * (commit c3c72a4bc). diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 28c3893171f..ae39b8a990e 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -298,11 +298,11 @@ import { } from './engine-top-level.js'; import type { AdmittedValueShapeViolationTally, AutonumberReaders, CascadeDeleteSet, CascadeIssuedDelete, DatasourceDef, - EngineMiddleware, EngineReadOptions, FieldOwnedFileReadAuthorizer, FormulaFaultSink, FormulaPlanEntry, + EngineMiddleware, EngineMiddlewareEntry, EngineMiddlewareOptions, EngineReadOptions, FieldOwnedFileReadAuthorizer, + FormulaFaultSink, FormulaPlanEntry, FormulaRelated, FunctionEntry, FunctionRegistrationOptions, HeldFileResolver, HookEntry, HookHandler, IssuedAutonumber, MigrationFlagRead, OperationContext, PermissionResolution, ReadableIdsChain, ReadableIdsSecurity, - ReadableIdsSecurityResolution, SearchFieldWithholder, TransactionScope, UnservableControlledByParentMaster, - WriteWallVerdict, + ReadableIdsSecurityResolution, TransactionScope, UnservableControlledByParentMaster, WriteWallVerdict, } from './engine-top-level.js'; // [#29986 codemod] Re-exported by name, so every importer of `./engine.js` reads what it read. export { @@ -311,8 +311,7 @@ export { type FieldOwnedFileReadAuthorizer, type FormulaPlanEntry, type FunctionEntry, type FunctionRegistrationOptions, HOOK_EVENT_DISPATCH_VOCABULARY, type HeldFileResolver, type HookEntry, type HookHandler, type MigrationFlagRead, type OperationContext, type PermissionResolution, type PostHookWriteImageCheck, type ReadableIdsChain, - type ReadableIdsSecurity, SECURITY_SERVICE_SOURCE_SLOT, type SearchFieldWithholder, type SearchFieldWithholdingRequest, - type UnservableControlledByParentMaster, + type ReadableIdsSecurity, SECURITY_SERVICE_SOURCE_SLOT, type UnservableControlledByParentMaster, type WriteWallRowVerdict, type WriteWallVerdict, assembledViewItemRefusal, cascadeMemberKey, cascadeSetAdd, cascadeSetHas, collectionItemOwnerStampRefusal, declaredDatetimeLowering, declaredMultiValued, droppedFieldEvents, evaluateFormulaField, foldEngineOptionAliases, hookMatchesObject, insertStaticReadonlySubject, isExpressionDefault, @@ -572,13 +571,7 @@ export class ObjectQL implements IObjectQLEngine { ]); // Middleware chain (onion model) - private middlewares: Array<{ - fn: EngineMiddleware; - object?: string; - }> = []; - - // [#34700] Search-field withholders, by object (`registerSearchFieldWithholder`). - private searchFieldWithholders = new Map(); + private middlewares: EngineMiddlewareEntry[] = []; // Action registry: key = "objectName:actionName" — the UNQUALIFIED slot, what // a call that names no package runs ([ADR-0150 D5, #31697]: two packages @@ -1895,29 +1888,13 @@ export class ObjectQL implements IObjectQLEngine { * Register a middleware function * Middlewares execute in onion model around every data operation. * @param fn The middleware function - * @param options Optional: target object filter + * @param options Optional: target object filter; [#34700] the search fields it withholds (`EngineMiddlewareOptions`) */ - registerMiddleware(fn: EngineMiddleware, options?: { object?: string }): void { + registerMiddleware(fn: EngineMiddleware, options?: EngineMiddlewareOptions): void { // [#29986 codemod] The body moved to `engine-middleware-and-context.ts` (see `MiddlewareAndContextHost`). return MiddlewareAndContextFacet.registerMiddleware.call(middlewareAndContextHost.of(this), fn, options); } - /** - * [#34700] Register a search-field withholder for `object`: a guard of the - * object's own (a middleware refusing a query that names some of its columns - * for some callers — plugin-audit's parent-field query guard, #21154) names - * the fields a non-blank `search` must not scan for this caller. They leave - * the server-resolved search set before the expansion, beside what the - * security service's `getQueryableFields` withholds (#25672). A field the - * caller names in `searchFields` is never withheld, so the guard still - * refuses it; context-less reads are not asked. The guard stays the - * enforcement (`SearchFieldWithholder`). - */ - registerSearchFieldWithholder(object: string, withholder: SearchFieldWithholder): void { - // [#34700] The body lives in `engine-middleware-and-context.ts` (see `MiddlewareAndContextHost`). - return MiddlewareAndContextFacet.registerSearchFieldWithholder.call(middlewareAndContextHost.of(this), object, withholder); - } - /** * [#21080] Whether a middleware is registered FOR `objectName` — a * {@link registerMiddleware} call whose `object` names it @@ -5942,6 +5919,7 @@ export class ObjectQL implements IObjectQLEngine { get logger() { return engine.logger; }, lowerRelationConditions: (...a) => engine.lowerRelationConditions(...a), maskSecretFields: (...a) => engine.maskSecretFields(...a), + get middlewares() { return engine.middlewares; }, permissionResolution: (...a) => engine.permissionResolution(...a), get relatedSchemaOf() { return engine.relatedSchemaOf; }, reportFindFailure: (...a) => engine.reportFindFailure(...a), @@ -5953,7 +5931,6 @@ export class ObjectQL implements IObjectQLEngine { resolveRelateThenLowerWhere: (...a) => engine.resolveRelateThenLowerWhere(...a), resolveSearchQueryableFields: (...a) => engine.resolveSearchQueryableFields(...a), resolveWhereTokens: (...a) => engine.resolveWhereTokens(...a), - get searchFieldWithholders() { return engine.searchFieldWithholders; }, stripSearchCompanionFromRead: (...a) => engine.stripSearchCompanionFromRead(...a), triggerHooks: (...a) => engine.triggerHooks(...a), })); @@ -6053,7 +6030,6 @@ export class ObjectQL implements IObjectQLEngine { getDriver: (...a) => engine.getDriver(...a), get logger() { return engine.logger; }, get middlewares() { return engine.middlewares; }, - get searchFieldWithholders() { return engine.searchFieldWithholders; }, get organizationProbeMemo() { return engine.organizationProbeMemo; }, set organizationProbeMemo(v) { engine.organizationProbeMemo = v; }, probeInstallOrganizations: (...a) => engine.probeInstallOrganizations(...a), diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index d10ce476b68..50d07224dbf 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -258,7 +258,9 @@ export type { CompanionFieldMeta, CompanionObjectMeta } from './search-companion // Export Engine export { ObjectQL, ObjectRepository, ScopedContext } from './engine.js'; -export type { HookHandler, HookEntry, OperationContext, EngineMiddleware, SearchFieldWithholder, SearchFieldWithholdingRequest, HeldFileResolver, FieldOwnedFileReadAuthorizer, WriteWallVerdict, WriteWallRowVerdict } from './engine.js'; +export type { HookHandler, HookEntry, OperationContext, EngineMiddleware, HeldFileResolver, FieldOwnedFileReadAuthorizer, WriteWallVerdict, WriteWallRowVerdict } from './engine.js'; +// [#34700] The middleware options, and the search-field withholder a guard middleware declares in them. +export type { EngineMiddlewareOptions, SearchFieldWithholder, SearchFieldWithholdingRequest } from './engine-top-level.js'; export type { AdmittedValueShapeViolationTally } from './engine.js'; // The declarative datasource definition the engine indexes, and the element // type of `ObjectQL.listDatasourceDefs()`. Exported so a consumer sweeping for diff --git a/packages/objectql/src/search-filter.ts b/packages/objectql/src/search-filter.ts index 064ebea8975..45947bb0e17 100644 --- a/packages/objectql/src/search-filter.ts +++ b/packages/objectql/src/search-filter.ts @@ -128,7 +128,7 @@ export interface ExpandSearchOptions extends SearchFieldResolutionOptions { queryableFields?: ReadonlySet; /** * [#34700] Fields a search-field withholder registered for the object - * (`ObjectQL#registerSearchFieldWithholder`) says this caller may not query + * (`EngineMiddlewareOptions.withholdSearchFields`) says this caller may not query * here — a guard of the object's own that the security service's answer * does not carry. Withheld from the resolved set exactly as a field missing * from {@link queryableFields}: a field the caller named in diff --git a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts index 10e6b491075..db144f4085a 100644 --- a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts +++ b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts @@ -103,8 +103,9 @@ * selects is the redaction's to narrow. * * [#34700] A search the SERVER resolved over these columns is not refused for - * them: each guard also registers a search-field withholder with the engine - * ({@link withheldSearchColumns}), so the columns this rule would refuse leave + * them: each guard middleware also declares a search-field withholder in its + * registration (`withholdSearchFields`, answered by + * {@link withheldSearchColumns}), so the columns this rule would refuse leave * the server-chosen set before the expansion, as a field the security service * says the caller may not query does (#25672). The search then answers over * the columns the caller may query. A search whose `searchFields` names one @@ -333,23 +334,25 @@ export async function readerWithholdsParentField( return all.some((field) => !servedSet.has(String(field))); } +/** + * [#34700] The search-field withholder a guard middleware declares in its + * registration options (objectql's `EngineMiddlewareOptions.withholdSearchFields`). + * An engine that does not read the option keeps the guard alone, and a + * server-chosen search over a guarded column is refused as before. + */ +export type GuardSearchFieldWithholder = (request: { + object: string; + where: unknown; + context: unknown; + searchFields: readonly string[]; +}) => Promise; + /** The engine slice the declared set is read from: its object registry. */ -export interface ParentObjectRegistryEngine extends ActivityMiddlewareEngine { +export interface ParentObjectRegistryEngine extends Omit { registry?: { getAllObjects?(): ReadonlyArray<{ name?: unknown }> }; - /** - * [#34700] The engine's search-field withholder seam - * (`ObjectQL#registerSearchFieldWithholder`). Optional: an engine without it - * keeps the guard alone, and a server-chosen search over a guarded column - * is refused as before. - */ - registerSearchFieldWithholder?( - object: string, - withholder: (request: { - object: string; - where: unknown; - context: unknown; - searchFields: readonly string[]; - }) => Promise, + registerMiddleware?( + fn: Parameters>[0], + options?: { object?: string; withholdSearchFields?: GuardSearchFieldWithholder }, ): void; } @@ -468,7 +471,7 @@ async function guardRefuses( /** * [#34700] Which of a search's server-resolved fields the guard would refuse * this caller, so the engine leaves them out of the set - * (`ObjectQL#registerSearchFieldWithholder`) instead of the guard refusing the + * (`EngineMiddlewareOptions.withholdSearchFields`) instead of the guard refusing the * whole search — the auditor's audit-log search answered 403 for the * `old_value` / `new_value` snapshot columns the server had put in it. A * column the caller names in `searchFields` is never withheld, so the guard @@ -536,11 +539,11 @@ function installParentFieldQueryGuard( } return next(); }, - { object: guard.object }, - ); - // [#34700] …and tell the search expansion which columns it would refuse. - engine.registerSearchFieldWithholder?.(guard.object, (request) => - withheldSearchColumns(engine, guard, getSecurity(), request, logger), + { + object: guard.object, + // [#34700] …and tell the search expansion which columns it would refuse. + withholdSearchFields: (request) => withheldSearchColumns(engine, guard, getSecurity(), request, logger), + }, ); } From 18bafcac55f8a5a3ae39dc6022fa4109c952aae6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 04:54:20 +0000 Subject: [PATCH 4/6] test(objectql): the withholder seam's pin imports its request type from where it is declared Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01QSeKYmQuAhLgegkqRcTc38 --- packages/objectql/src/engine-search-field-withholder.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/objectql/src/engine-search-field-withholder.test.ts b/packages/objectql/src/engine-search-field-withholder.test.ts index 7c462701e7d..1d8d29cfef6 100644 --- a/packages/objectql/src/engine-search-field-withholder.test.ts +++ b/packages/objectql/src/engine-search-field-withholder.test.ts @@ -22,7 +22,7 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { ObjectQL } from './engine.js'; -import type { SearchFieldWithholdingRequest } from './engine.js'; +import type { SearchFieldWithholdingRequest } from './engine-top-level.js'; type Row = Record; From 64202f756bce052a14364c7e3130df116c5bc5e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:46:26 +0000 Subject: [PATCH 5/6] test(dogfood): the named-column search refusals assert the ADR-0112 envelope and the refusal words The ledger pin for a search naming old_value now asserts the nested error code PERMISSION_DENIED beside the 403. The activity-stream pin for a search naming summary asserts through the file's own expectRefused, so the refusal's first sentence is pinned too. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01QSeKYmQuAhLgegkqRcTc38 --- .../qa/dogfood/test/activity-text-predicate.dogfood.test.ts | 3 +-- .../qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts | 2 ++ 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/qa/dogfood/test/activity-text-predicate.dogfood.test.ts b/packages/qa/dogfood/test/activity-text-predicate.dogfood.test.ts index dfdc5663f7f..c0b115e255c 100644 --- a/packages/qa/dogfood/test/activity-text-predicate.dogfood.test.ts +++ b/packages/qa/dogfood/test/activity-text-predicate.dogfood.test.ts @@ -427,8 +427,7 @@ describe('[#21154] a query over activity text or the approval snapshot, by a rea expect(a.status, a.text).toBe(200); answers.push({ status: a.status, rows: a.rows }); const named = await list(c, 'sys_activity', { object_name: OBJ }, `&$search=${encodeURIComponent(value)}&$searchFields=summary`); - expect(named.status, named.text).toBe(403); - expect(named.code).toBe('PERMISSION_DENIED'); + expectRefused(named, predicateWords('sys_activity', 'summary')); } expect(answers[0]).toEqual(answers[1]); }); diff --git a/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts b/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts index 2754946179e..8164a84f69a 100644 --- a/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts +++ b/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts @@ -423,6 +423,8 @@ describe('[#21260] the ledger audit capability exempts its holder from the paren expect(rowsOf(await (await search(who, VALUE.withheld)).json())).toHaveLength(0); const named = await stack.apiAs(token[who], 'GET', `/data/${LEDGER}?search=${VALUE.withheld}&searchFields=old_value&limit=5`); expect(named.status, `${who} names a snapshot column: ${await named.clone().text()}`).toBe(403); + // The ADR-0112 envelope: the nested code, not the status alone. + expect(((await named.json()) as any)?.error?.code, `${who} names a snapshot column`).toBe('PERMISSION_DENIED'); } // The holder is served the deleted record's rows, found by the column it may query. const held = rowsOf(await (await search('holder', id.gone)).json()); From 81705ebb1af2e8f1140f30df8d87d467e0f8e6a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:54:53 +0000 Subject: [PATCH 6/6] test(dogfood): the ledger pin reads the refusal code where the list route answers it Measured on the real boot: GET /data/sys_audit_log answers the refusal with the message in error and the code at the top level of the body. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01QSeKYmQuAhLgegkqRcTc38 --- .../dogfood/test/audit-log-audit-capability.dogfood.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts b/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts index 8164a84f69a..c333f719ff6 100644 --- a/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts +++ b/packages/qa/dogfood/test/audit-log-audit-capability.dogfood.test.ts @@ -423,8 +423,8 @@ describe('[#21260] the ledger audit capability exempts its holder from the paren expect(rowsOf(await (await search(who, VALUE.withheld)).json())).toHaveLength(0); const named = await stack.apiAs(token[who], 'GET', `/data/${LEDGER}?search=${VALUE.withheld}&searchFields=old_value&limit=5`); expect(named.status, `${who} names a snapshot column: ${await named.clone().text()}`).toBe(403); - // The ADR-0112 envelope: the nested code, not the status alone. - expect(((await named.json()) as any)?.error?.code, `${who} names a snapshot column`).toBe('PERMISSION_DENIED'); + // The refusal's code, not the status alone (this route answers it at the top level of the body). + expect(((await named.json()) as any)?.code, `${who} names a snapshot column`).toBe('PERMISSION_DENIED'); } // The holder is served the deleted record's rows, found by the column it may query. const held = rowsOf(await (await search('holder', id.gone)).json());