diff --git a/.changeset/34175-search-lookup-title.md b/.changeset/34175-search-lookup-title.md new file mode 100644 index 00000000000..f0b07718fda --- /dev/null +++ b/.changeset/34175-search-lookup-title.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): global search titles a hit by the referenced record's title when the object's `nameField` is a reference field + +Clause-②: no +Metadata-protocol: none + +`searchAll` (the ⌘K palette and global search) titled a hit by the stored value of the object's primary-title pointer. When that pointer is a reference field (`lookup`, `master_detail`, `user` or `tree`), the stored value is the target record's id, so the hit was titled by a raw key while the record page header named the target. The title now follows the reference to the target record's own title (its `nameField`). + +- The target titles are read in one `id $in` read per searched object, never one per hit, selecting `id` and the title column only. +- The read runs as the searching user: the target's object permission, row scope and field-level security apply. A reader refused the target object, the row or its title column keeps the bare id, as `$expand` answers that reader on a field that does not declare `referenceNameVisible`. A target whose declared API exposure does not serve `get` is not read. +- A target read that fails for any other reason fails the search, as a failing record read in the same sweep already does. +- The hit's shape is unchanged: `record` still carries the stored id, and only `title` changes. diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index d8ecae0ef8b..70277964c19 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -187,6 +187,14 @@ const CALLERS: Record = { wiring: { file: 'packages/plugins/plugin-approvals/src/approval-service.ts', call: 'this.servesPayloadDisplayTarget(' }, pin: 'packages/plugins/plugin-approvals/src/payload-display-target-exposure.test.ts', }, + 'packages/metadata-protocol/src/protocol-record-reads.ts': { + kind: 'decided', + read: "global search's hit title for an object whose `nameField` is a reference field (`searchAll` reads the target records' titles as the searcher)", + operation: 'get', + decision: { file: 'packages/metadata-protocol/src/protocol-record-reads.ts', fn: 'servesSearchTitleTarget' }, + wiring: { file: 'packages/metadata-protocol/src/protocol-record-reads.ts', call: 'servesSearchTitleTarget(targetObj' }, + pin: 'packages/metadata-protocol/src/protocol.search-title-lookup.test.ts', + }, 'packages/plugins/plugin-audit/src/audit-writers.ts': { kind: 'decided', read: "the activity timeline's tracked-change and milestone summaries (`resolveLookupTitles` writes referenced records' titles at write time)", @@ -559,6 +567,7 @@ describe('[#22661] every read that reaches a second object asks that object its 'servesLabelTarget', 'servesPayloadDisplayTarget', 'servesReferenceTarget', + 'servesSearchTitleTarget', 'servesSummaryTitleTarget', 'stdioExpandMap', ]); diff --git a/packages/metadata-protocol/src/protocol-record-reads.ts b/packages/metadata-protocol/src/protocol-record-reads.ts index a6a6eb636f6..47098bee6c6 100644 --- a/packages/metadata-protocol/src/protocol-record-reads.ts +++ b/packages/metadata-protocol/src/protocol-record-reads.ts @@ -55,9 +55,10 @@ import { ConcurrentUpdateError, MalformedVersionTokenError, canonicalVersionInst import { recordNotFoundError, type UserMessageCaller } from '@objectstack/core'; import { collectInternalWriteResponseFields, omitInternalFieldsFromWriteResponse } from './write-response-internal-fields.js'; import { isMissingTableError } from '@objectstack/metadata/errors'; -import { canServeApiOperation, resolveSearchFieldResolution } from '@objectstack/spec/data'; +import { canServeApiOperation, referenceTargetOf, resolveSearchFieldResolution } from '@objectstack/spec/data'; import type { EngineQueryOptionsParsed } from '@objectstack/spec/data'; import type { ISecurityService } from '@objectstack/spec/contracts'; +import type { StandardErrorCode } from '@objectstack/spec/api'; import { resolveI18nLabel } from '@objectstack/spec/ui'; import type { I18nLabel } from '@objectstack/spec/ui'; @@ -270,6 +271,108 @@ export async function readAsCaller( return this.engine.findOne(object, opts); } +/** + * The ADR-0112 code of the security layer refusing the CALLER's read — matched + * by the declared code alone, never by message prose, and never by a driver's + * own ACL code (that is the database refusing the platform, not the platform + * refusing a reader). The same reading objectql's `isReadRefusal` makes for the + * `$expand` family; this package sits below objectql and cannot import it. + */ +const READ_REFUSED: StandardErrorCode = 'PERMISSION_DENIED'; + +/** The ADR-0079 primary-title pointer: `nameField`, else the deprecated `displayNameField` alias. */ +function titlePointerOf(obj: { nameField?: unknown; displayNameField?: unknown } | undefined | null): string | undefined { + if (!obj) return undefined; + if (typeof obj.nameField === 'string' && obj.nameField) return obj.nameField; + if (typeof obj.displayNameField === 'string' && obj.displayNameField) return obj.displayNameField; + return undefined; +} + +/** A field map in either registered spelling (array of `{ name }` or a keyed record) as a name → definition map. */ +function fieldMapOf(fieldsRaw: unknown): Map { + if (Array.isArray(fieldsRaw)) return new Map(fieldsRaw.map((f: any) => [f?.name, f])); + if (fieldsRaw && typeof fieldsRaw === 'object') { + return new Map(Object.entries(fieldsRaw).map(([name, f]: [string, any]) => [name, { name, ...(f || {}) }])); + } + return new Map(); +} + +/** + * May a search hit be titled from this reference TARGET at all? Its declared + * exposure, asked for `get` of the one decision every door judges + * (`canServeApiOperation`, ADR-0049) — the operation a lookup title read is + * judged as wherever one is served (the approvals inbox, the activity + * summaries). A target that does not serve `get` is not read. + */ +function servesSearchTitleTarget(targetObj: { enable?: any }): boolean { + return canServeApiOperation(targetObj.enable, 'get'); +} + +/** + * The titles of the `ids` records of `target`, read AS THE SEARCHER — the + * second half of `searchAll`'s title for an object whose primary-title pointer + * is a reference field. One read per call, `id $in` over the whole batch, `id` + * and the target's title column only. + * + * The read is the caller's own: `find` with the caller's context, so the + * target's object gate, row scope and field-level security apply exactly as + * they do to a direct read or to `$expand`, which takes the full gate on its + * sub-read. Every refusal leaves an id out of the answer, and an id left out + * keeps its bare value in the title — the answer `$expand` gives a reader it + * refuses the target: + * + * - the target's declared exposure does not serve `get` (ADR-0049, the one + * decision every door judges) → not read, as a lookup title read elsewhere + * asks the same decision; + * - the caller may not read the object (`canReadObject`, asked before any + * read, as the sweep asks it of each swept object) → not read; + * - the read itself answers the typed refusal → no titles; + * - a row outside the caller's row scope is not returned, and a title column + * field-level security strips is absent → that id keeps its value. + * + * Every other failure of the read propagates, the same disposition the sweep + * gives a failing record read (#8896): a title read that could not run must + * not be answered "this record has no title". A target whose table was never + * provisioned holds no rows, so it titles nothing. + */ +async function readReferenceTitles( + engine: RecordReadHost['engine'], + target: string, + ids: string[], + context: unknown, + canReadObject: ((object: string) => Promise | boolean) | undefined, +): Promise> { + const titles = new Map(); + const targetObj = engine.registry.getObject(target); + if (!targetObj) return titles; + if (!servesSearchTitleTarget(targetObj)) return titles; + const titleField = titlePointerOf(targetObj); + if (!titleField || !fieldMapOf(targetObj.fields).has(titleField)) return titles; + if (canReadObject && !(await canReadObject(target))) return titles; + let rows: any[]; + try { + const opts: EngineQueryOptionsParsed = { + where: { id: { $in: ids } }, + fields: ['id', titleField], + limit: ids.length, + }; + if (context !== undefined) opts.context = context as EngineQueryOptionsParsed['context']; + rows = (await engine.find(target, opts)) ?? []; + } catch (error) { + if ((error as { code?: unknown } | null)?.code === READ_REFUSED) return titles; + if (isMissingTableError(error, target)) return titles; + throw error; + } + for (const row of rows) { + if (row?.id == null) continue; + const v = row[titleField]; + if (v == null || typeof v === 'object') continue; + const title = String(v); + if (title.trim()) titles.set(String(row.id), title); + } + return titles; +} + /** The body of `ObjectStackProtocolImplementation#searchAll`; the method's docblock there is its contract. */ export async function searchAll( this: Pick, @@ -437,10 +540,26 @@ export async function searchAll( // this function's own search-field resolution below — a fourth // spelling here would re-split what those merged. const titlePointer = obj.nameField ?? obj.displayNameField; - const renderTitle = (row: any): string => { + // A pointer that is a REFERENCE field (`lookup` / `master_detail` / + // `user` / `tree`) stores the target record's id, so the title is + // the TARGET's title: read for the whole batch of hits after the + // object's `find`, as the searcher, by `readReferenceTitles` (which + // says whose read it is and what a refused reader keeps — the bare + // id). `referenceTargetOf` is the spec's one answer to "what does + // this field point at", the same the `$expand` gate and engine ask. + // The hit's wire shape does not move: `record` still carries the + // stored id, and only `title` reads through. + const titleTarget = typeof titlePointer === 'string' && hasField(titlePointer) + ? referenceTargetOf(fieldByName.get(titlePointer)) + : undefined; + const renderTitle = (row: any, referenceTitles?: Map): string => { if (typeof titlePointer === 'string' && hasField(titlePointer)) { const v = row[titlePointer]; - if (v != null && String(v).trim()) return String(v); + if (v != null && String(v).trim()) { + if (!referenceTitles) return String(v); + const titleOf = (id: unknown) => referenceTitles.get(String(id)) ?? String(id); + return Array.isArray(v) ? v.map(titleOf).join(', ') : titleOf(v); + } } if (typeof titleFormatSource === 'string') { let allResolved = true; @@ -572,9 +691,25 @@ export async function searchAll( if (request.context !== undefined) opts.context = request.context; const rows = await this.engine.find(obj.name, opts); - for (const row of rows || []) { - if (hits.length >= overallLimit) break; - const title = renderTitle(row); + // The rows this sweep will turn into hits — so a target read + // never covers a row the `overallLimit` cut drops. + const hitRows = (rows || []).slice(0, Math.max(0, overallLimit - hits.length)); + let referenceTitles: Map | undefined; + if (titleTarget && typeof titlePointer === 'string') { + const ids = new Set(); + for (const row of hitRows) { + const v = row?.[titlePointer]; + for (const id of Array.isArray(v) ? v : [v]) { + if (id != null && typeof id !== 'object' && String(id).trim()) ids.add(String(id)); + } + } + if (ids.size > 0) { + const read = await readReferenceTitles(this.engine, titleTarget, [...ids], request.context, canReadObject); + if (read.size > 0) referenceTitles = read; + } + } + for (const row of hitRows) { + const title = renderTitle(row, referenceTitles); // Build snippet from first searchable field that contains a // term. [#7643] `undefined` is a CORRECT answer here, not a // miss: a companion (pinyin) hit matches the normalized diff --git a/packages/metadata-protocol/src/protocol.search-title-lookup.test.ts b/packages/metadata-protocol/src/protocol.search-title-lookup.test.ts new file mode 100644 index 00000000000..21e706f71c8 --- /dev/null +++ b/packages/metadata-protocol/src/protocol.search-title-lookup.test.ts @@ -0,0 +1,286 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// `searchAll` titles a hit whose object's primary-title pointer (ADR-0079 +// `nameField`) is a REFERENCE field by the referenced record's own title, not +// by the stored foreign key. +// +// ## The defect +// +// `renderTitle` returned `row[nameField]` as stored. For a reference-typed +// pointer (`lookup` / `master_detail` / `user`) the stored value is the target +// record's id, so the palette and global search titled such a hit by a raw key +// while the record header (`$expand`) and the activity timeline already named +// the target. +// +// ## Whose read it is +// +// The SEARCHER's. The target title is read through the engine's own `find` +// with the caller's context, so the target object's read gate, row scope and +// field-level security apply exactly as they do to a direct read or to +// `$expand`. A reader refused the target — the object, the row or the title +// column — keeps the bare id, the same answer `$expand` gives such a reader. +// +// ## What these pins hold +// +// - the title follows the reference to the target's title (each reference +// type, `user` included, whose target is fixed by the type); +// - one target read per swept object, never one per hit; +// - the hit's wire shape does not move: `record` still carries the stored id; +// - each refusal leg keeps the bare id, and a refused object is never read; +// - a target whose declared exposure does not serve `get` is never read; +// - a target read that FAILS (not a refusal) fails the search, envelope +// intact, as a failing record read already does in this sweep; +// - a non-reference pointer pays no extra read. +// +// The engine double stands in for the middleware: it filters the target read +// by its `id $in` predicate, applies its projection, and throws the typed +// denial for an object the fake security layer refuses. + +import { describe, it, expect, vi } from 'vitest'; +// `protocol.ts` reaches `@objectstack/lint` through a dynamic import; loaded +// here at module scope so the first load lands during collection, not inside a +// clocked window (`pnpm check:test-source-alias`). +import '@objectstack/lint'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +type Row = Record; +type ObjectMeta = Record & { name: string }; + +const text = (name: string) => ({ name, type: 'text' }); + +const MEMBER = { userId: 'usr_member', tenantId: 'org_1' }; + +/** The engine middleware's typed object-level denial, as `PermissionDeniedError` carries it. */ +const readDenied = () => + Object.assign(new Error('You do not have permission to perform this action.'), { + name: 'PermissionDeniedError', + code: 'PERMISSION_DENIED', + status: 403, + statusCode: 403, + }); + +/** A source object titled by a lookup to `person`, scannable through `role`. */ +const projectMember: ObjectMeta = { + name: 'project_member', + nameField: 'member_id', + fields: { + member_id: { name: 'member_id', type: 'lookup', reference: 'person' }, + role: text('role'), + }, + searchableFields: ['role'], +}; + +const person: ObjectMeta = { + name: 'person', + nameField: 'display_name', + fields: { display_name: text('display_name') }, +}; + +const MEMBER_ROWS: Row[] = [ + { id: 'pm_1', member_id: 'per_1', role: 'Lead engineer' }, + { id: 'pm_2', member_id: 'per_2', role: 'Lead designer' }, + { id: 'pm_3', member_id: 'per_1', role: 'Lead reviewer' }, +]; + +const PEOPLE: Row[] = [ + { id: 'per_1', display_name: 'Ada Lovelace' }, + { id: 'per_2', display_name: 'Grace Hopper' }, +]; + +function harness(opts: { + objects?: ObjectMeta[]; + rows?: Record; + /** Objects the fake security layer admits; `'all'` admits every one. */ + readable?: Set | 'all'; + /** Ids of each object the caller's row scope lets through (default: all). */ + rowScope?: Record>; + /** Columns of each object field-level security strips from the caller's read. */ + hiddenColumns?: Record>; + /** Leave the `security` service out, so only `find` itself can refuse. */ + withSecurity?: boolean; + failRead?: { object: string; error: unknown }; +}) { + const objects = opts.objects ?? [projectMember, person]; + const rows = opts.rows ?? { project_member: MEMBER_ROWS, person: PEOPLE }; + const admits = (o: string) => (opts.readable ?? 'all') === 'all' || (opts.readable as Set).has(o); + const reads: Array<[string, Record]> = []; + const engine = { + registry: { + getObject: (n: string) => objects.find((o) => o.name === n), + getAllObjects: () => objects, + listItems: () => [], + }, + find: vi.fn(async (object: string, options: Record) => { + reads.push([object, options]); + if (!admits(object)) throw readDenied(); + if (opts.failRead?.object === object) throw opts.failRead.error; + let out = rows[object] ?? []; + const scope = opts.rowScope?.[object]; + if (scope) out = out.filter((r) => scope.has(String(r.id))); + const ids = options?.where?.id?.$in; + if (Array.isArray(ids)) out = out.filter((r) => ids.includes(r.id)); + const hidden = opts.hiddenColumns?.[object]; + return out.map((r) => { + const projected: Row = {}; + for (const [k, v] of Object.entries(r)) { + if (hidden?.has(k)) continue; + if (Array.isArray(options?.fields) && !options.fields.includes(k)) continue; + projected[k] = v; + } + return projected; + }); + }), + }; + const canReadObject = vi.fn(async (o: string) => admits(o)); + const services = new Map(); + if (opts.withSecurity !== false) services.set('security', { canReadObject }); + const protocol = new ObjectStackProtocolImplementation(engine as never, () => services as Map); + const targetReads = () => reads.filter(([o]) => o !== 'project_member'); + return { protocol, reads, targetReads, canReadObject }; +} + +/** Sweeps the source object only, so every hit is a `project_member` row. */ +const SWEEP = { q: 'lead', objects: ['project_member'], perObject: 5, context: MEMBER }; + +const titles = (hits: Array<{ id: string; title: string }>) => Object.fromEntries(hits.map((h) => [h.id, h.title])); + +describe('searchAll titles a reference-typed nameField by the target record title', () => { + it('THE PIN — a lookup pointer titles each hit by the target title, not the stored id', async () => { + const { protocol } = harness({}); + + const { hits } = await protocol.searchAll(SWEEP); + + expect(titles(hits)).toEqual({ pm_1: 'Ada Lovelace', pm_2: 'Grace Hopper', pm_3: 'Ada Lovelace' }); + }); + + it('reads every target title in ONE read per swept object, as the searcher, id and title only', async () => { + const { protocol, targetReads } = harness({}); + + await protocol.searchAll(SWEEP); + + expect(targetReads()).toHaveLength(1); + const [object, options] = targetReads()[0]; + expect(object).toBe('person'); + expect([...options.where.id.$in].sort()).toEqual(['per_1', 'per_2']); + expect(options.fields).toEqual(['id', 'display_name']); + expect(options.context).toBe(MEMBER); + }); + + it('the hit wire shape does not move: record keeps the stored id and no key is added', async () => { + const { protocol } = harness({}); + + const { hits } = await protocol.searchAll(SWEEP); + + const hit = hits.find((h) => h.id === 'pm_1')!; + expect(Object.keys(hit).sort()).toEqual(['id', 'object', 'record', 'snippet', 'title']); + expect(hit.record).toEqual({ id: 'pm_1', member_id: 'per_1', role: 'Lead engineer' }); + }); + + it('master_detail and user pointers follow too; user reads the sys_user title with no reference declared', async () => { + const task: ObjectMeta = { + name: 'task_line', + nameField: 'parent_id', + fields: { parent_id: { name: 'parent_id', type: 'master_detail', reference: 'person' }, note: text('note') }, + searchableFields: ['note'], + }; + const assignment: ObjectMeta = { + name: 'assignment', + nameField: 'owner', + fields: { owner: { name: 'owner', type: 'user' }, note: text('note') }, + searchableFields: ['note'], + }; + const sysUser: ObjectMeta = { name: 'sys_user', nameField: 'name', fields: { name: text('name') } }; + const { protocol, targetReads } = harness({ + objects: [task, assignment, person, sysUser], + rows: { + task_line: [{ id: 'tl_1', parent_id: 'per_2', note: 'review' }], + assignment: [{ id: 'as_1', owner: 'usr_9', note: 'review' }], + person: PEOPLE, + sys_user: [{ id: 'usr_9', name: 'Katherine Johnson' }], + }, + }); + + const { hits } = await protocol.searchAll({ q: 'review', objects: ['task_line', 'assignment'], context: MEMBER }); + + expect(titles(hits)).toEqual({ tl_1: 'Grace Hopper', as_1: 'Katherine Johnson' }); + expect(targetReads().map(([o]) => o).filter((o) => o !== 'task_line' && o !== 'assignment')).toEqual(['person', 'sys_user']); + }); + + it('REFUSED — an object-level refusal keeps the bare id, and the target is never read', async () => { + const { protocol, targetReads, canReadObject } = harness({ readable: new Set(['project_member']) }); + + const { hits } = await protocol.searchAll(SWEEP); + + expect(titles(hits)).toEqual({ pm_1: 'per_1', pm_2: 'per_2', pm_3: 'per_1' }); + expect(canReadObject).toHaveBeenCalledWith('person', MEMBER); + expect(targetReads()).toEqual([]); + }); + + it('REFUSED — a refusal thrown by the read itself keeps the bare id and the search answers', async () => { + // No security service to ask first: the engine middleware's typed + // denial on the target read is the only refusal there is. + const { protocol, targetReads } = harness({ readable: new Set(['project_member']), withSecurity: false }); + + const { hits } = await protocol.searchAll(SWEEP); + + expect(titles(hits)).toEqual({ pm_1: 'per_1', pm_2: 'per_2', pm_3: 'per_1' }); + expect(targetReads().map(([o]) => o)).toEqual(['person']); + }); + + it('REFUSED — a row outside the caller row scope keeps its bare id; the readable one is titled', async () => { + const { protocol } = harness({ rowScope: { person: new Set(['per_1']) } }); + + const { hits } = await protocol.searchAll(SWEEP); + + expect(titles(hits)).toEqual({ pm_1: 'Ada Lovelace', pm_2: 'per_2', pm_3: 'Ada Lovelace' }); + }); + + it('REFUSED — a title column field-level security strips keeps the bare id', async () => { + const { protocol } = harness({ hiddenColumns: { person: new Set(['display_name']) } }); + + const { hits } = await protocol.searchAll(SWEEP); + + expect(titles(hits)).toEqual({ pm_1: 'per_1', pm_2: 'per_2', pm_3: 'per_1' }); + }); + + it('a target whose declared exposure does not serve get is never read and keeps the bare id', async () => { + const listOnly: ObjectMeta = { ...person, enable: { apiMethods: ['list'] } }; + const { protocol, targetReads } = harness({ objects: [projectMember, listOnly] }); + + const { hits } = await protocol.searchAll(SWEEP); + + expect(titles(hits)).toEqual({ pm_1: 'per_1', pm_2: 'per_2', pm_3: 'per_1' }); + expect(targetReads()).toEqual([]); + }); + + it('a target read that FAILS fails the search with its own envelope', async () => { + const outage = Object.assign(new Error('connection reset'), { code: 'SERVICE_UNAVAILABLE', status: 503 }); + const { protocol } = harness({ failRead: { object: 'person', error: outage } }); + + let caught: any; + try { + await protocol.searchAll(SWEEP); + } catch (e) { + caught = e; + } + expect(caught?.code).toBe('SERVICE_UNAVAILABLE'); + expect(caught?.status).toBe(503); + }); + + it('CONTROL — a text pointer is titled as stored and pays no target read', async () => { + const note: ObjectMeta = { + name: 'project_note', + nameField: 'headline', + fields: { headline: text('headline') }, + }; + const { protocol, reads } = harness({ + objects: [note, person], + rows: { project_note: [{ id: 'pn_1', headline: 'Lead time review' }], person: PEOPLE }, + }); + + const { hits } = await protocol.searchAll({ q: 'lead', objects: ['project_note'], context: MEMBER }); + + expect(titles(hits)).toEqual({ pn_1: 'Lead time review' }); + expect(reads.map(([o]) => o)).toEqual(['project_note']); + }); +});