Skip to content
13 changes: 13 additions & 0 deletions .changeset/34700-audit-search-withholds-snapshot-columns.md
Original file line number Diff line number Diff line change
@@ -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.
- `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.
3 changes: 2 additions & 1 deletion content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,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` |
Expand Down Expand Up @@ -595,6 +595,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 |
Expand Down
52 changes: 46 additions & 6 deletions packages/objectql/src/engine-find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import {
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';
Expand All @@ -56,7 +56,7 @@ import {
resolveWhereFilterTokens, rowsWithoutFormulaWidening, whereResolvedTokenJudge, withFileOwnerKey,
withoutFormulaWidening, writeFailureLogMeta,
} from './engine-top-level.js';
import type { EngineReadOptions, OperationContext } from './engine-top-level.js';
import type { EngineMiddlewareEntry, EngineReadOptions, OperationContext } from './engine-top-level.js';
import type { ObjectQL } from './engine.js';

/**
Expand Down Expand Up @@ -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'];
Expand Down Expand Up @@ -181,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<FindHost, 'resolveSearchQueryableFields'>, ast: QueryAST, schema: ServiceObject | undefined, context: ExecutionContext | undefined): Promise<void> {
static async expandSearchOnAst(this: Pick<FindHost, 'middlewares' | 'resolveSearchQueryableFields'>, ast: QueryAST, schema: ServiceObject | undefined, context: ExecutionContext | undefined): Promise<void> {
// 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
Expand Down Expand Up @@ -251,10 +252,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
// (`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.middlewares, 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()) {
Expand All @@ -272,14 +282,44 @@ 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);
}
}
delete (ast as any).search;
delete (ast as any).searchFields;
}

/**
* [#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(
middlewares: readonly EngineMiddlewareEntry[],
ast: QueryAST,
expandOptions: Parameters<typeof resolveSearchFields>[0],
context: ExecutionContext | undefined,
): Promise<ReadonlySet<string> | 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<string>();
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
Expand Down
7 changes: 4 additions & 3 deletions packages/objectql/src/engine-middleware-and-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } from './engine-top-level.js';
import type { EngineMiddleware, EngineMiddlewareOptions, OperationContext } from './engine-top-level.js';
import type { ObjectQL } from './engine.js';

/**
Expand Down Expand Up @@ -106,8 +106,9 @@ export class MiddlewareAndContextFacet {
}

/** The body of `ObjectQL#registerMiddleware`; the method's docblock there is its contract. */
static registerMiddleware(this: Pick<MiddlewareAndContextHost, 'logger' | 'middlewares'>, fn: EngineMiddleware, options?: { object?: string }): void {
this.middlewares.push({ fn, object: options?.object });
static registerMiddleware(this: Pick<MiddlewareAndContextHost, 'logger' | 'middlewares'>, 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 });
}

Expand Down
Loading
Loading