Skip to content

Commit 22af9e6

Browse files
fix(metadata-protocol): search titles a reference-typed nameField by its target's title (#35292)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgRuogP8Tp8XyFXLc92Bxvo6)_ repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me Fixes #34175 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:全局搜索 / ⌘K 面板里,对象的 `nameField` 是引用字段(lookup / master_detail / user / tree)时,命中标题不再显示目标记录的原始 id,而是显示目标记录自己的标题。 - 为什么改:记录页头(`$expand`)和活动时间线早已显示目标名称,只有搜索面板还在显示 id,用户无法分辨命中的是谁。 - 风险与回滚:目标标题按搜索者本人身份读取(对象权限、行级范围、字段级安全全部生效),被拒的读者仍只看到 id;每个被搜对象只多一次批量读取。回滚即 revert 本 PR。 - 先看:`packages/metadata-protocol/src/protocol-record-reads.ts` 的 `readReferenceTitles`(读取身份与拒绝分支),其次同文件 `searchAll` 中 `hitRows` 一段(批量收集 id)。 - 两分钟验证:`pnpm --filter @objectstack/metadata-protocol exec vitest run src/protocol.search-title-lookup.test.ts`,预期 11 个测试全绿。 - 需要你做的:无,席位落地。 ## What changes `searchAll` → `renderTitle` returned `row[nameField]` as stored. When the pointer is a reference field, that value is the target record's id, so the palette titled such a hit by a raw key. Now: - The per-object sweep collects the pointer's ids from the rows it will turn into hits and reads the target's ADR-0079 title pointer (`nameField`, else the deprecated `displayNameField`) in **one** `find(target, { where: { id: { $in } }, fields: ['id', title], limit })` per swept object. No N+1 per hit. - The target is the spec's `referenceTargetOf` answer (the same arbiter the `$expand` gate and engine ask), so `user` resolves to `sys_user` with no `reference` declared, and `tree` follows too. - **The read is the searcher's**: the caller's `context` goes to `find`, so the target's object gate, row scope and FLS apply as they do to `$expand`. A reader refused the target keeps the bare id: - the target's declared exposure does not serve `get` (`canServeApiOperation`) → not read; - `canReadObject(target)` false → not read; - the read throws `PERMISSION_DENIED` → no titles; - a row outside the row scope, or a title column FLS strips → that id keeps its value. - A target read that fails otherwise propagates, the same disposition the sweep gives a failing record read; a target whose table was never provisioned titles nothing (`isMissingTableError`). - The hit's wire shape does not change: `record` still carries the stored id, no `$expand` on the palette `find`. Only `title` changes. - No import from plugin-audit (`resolveLookupTitles`); metadata-protocol sits below it and below objectql. - The exposure decision is its own small function, `servesSearchTitleTarget`, and the new reference-target read is classified as a `decided` read in `packages/core/src/security/second-object-read-exposure.pin.test.ts` (`CALLERS`, plus the pinned list of decision functions). That pin reds any unclassified caller of `referenceTargetOf`. It was red on this PR's earlier head (Test Core 6/10) and is green now. ## Tests New `packages/metadata-protocol/src/protocol.search-title-lookup.test.ts` (11 cases): the title follows `lookup`, `master_detail` and `user`; one target read per swept object, as the searcher, `id` + title only; the wire shape; four refused-reader legs (object refused before the read, refusal thrown by the read, row scope, FLS strip); exposure without `get`; an outage propagates with its envelope (`code` + `status`); a text pointer pays no extra read. ## Acceptance notes - Measured on `main` first, at d6d9645, with the new test file: the PIN answered `{ pm_1: 'per_1', pm_2: 'per_2', pm_3: 'per_1' }`, so each hit was titled by the stored lookup id. 7 of 11 failed on main. The 4 that passed there are the refusal, exposure, wire-shape and control legs, which hold on main because main never follows the reference. - The card's named stock producer, `sys_record_share.recipient_id`, is a **`Field.text`** column (a polymorphic principal id read with `recipient_type`), not a reference field. So this fix does not change that object's palette title. Following it needs the `recipient_type`-keyed directory read the console's `recipient-picker` face does, which is a separate design. Stock objects with a reference `nameField` in this repo are `sys_scim_subject` (`searchable: false`) and `sys_session` (skipped by name prefix), so no stock object reaches the palette through this path. The reach is app objects, for example HotCRM's `crm_project_member` behind #34055. - `referenceNameVisible` (ruling 6574398310) is not served here. A refused reader keeps the bare id, as the dispatch states. Serving a refused reader the target's name needs a system-context read, which is a new disclosure decision and not in this card. - One hop only: a target whose own title column is itself a reference shows that column's stored value. - A multi-valued reference pointer titles each element and joins them with `, `. When nothing resolves, the value is rendered exactly as before. - The `searchAll` method docblock in `protocol.ts` is not edited because it is outside this claim's file surface. The contract text for the new read is on `readReferenceTitles` and at the call site. ## Verification <details><summary>Red leg on main (d6d9645)</summary> ``` × THE PIN — a lookup pointer titles each hit by the target title, not the stored id AssertionError: expected { pm_1: 'per_1', pm_2: 'per_2', …(1) } to deeply equal { pm_1: 'Ada Lovelace', …(2) } Tests 7 failed | 4 passed (11) ``` </details> <details><summary>Green, package suite and typecheck</summary> Run at bc101ad (source identical to the current head; the later commit only adds a module-top import to the new test file, re-run green: `Tests 11 passed (11)` at 7e664c7). ``` pnpm --filter @objectstack/metadata-protocol typecheck -> exit 0 (tsc --listFiles includes the new test file) pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 Test Files 358 passed | 9 skipped (367) Tests 23218 passed | 45 skipped (23263) os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>Ablation (committed fix, then mutated, then restored)</summary> Deleted `if (canReadObject && !(await canReadObject(target))) return titles;` with `scripts/ablation-replace.mjs`: anchor 1 to 0, blob 35ced75 to f92c32c63df5. Result: `× REFUSED — an object-level refusal keeps the bare id, and the target is never read`, `Tests 1 failed | 10 passed (11)`. Restored: blob equals HEAD (35ced75) and `git diff HEAD` is empty. </details> <details><summary>Derived gates and CI</summary> Final head ff64484. `dispatch-gates --commands` derived 69 families. All 69 were run locally and every one exited 0. `dispatch-gates --ran` reported: 69 accounted for, 0 NOT-MEASURED, 0 UNRUN, exit 0. Pre-push `overlap-check` gave VERDICT clean exit 0. Along the way: - `check:test-source-alias` failed on the new test file because it needed a module-top `import '@objectstack/lint'`. Fixed in 7e664c7. - `check:lean-entry-closure` first exited 3 because the objectql dist had not been built. After building objectql it exited 0. - On 7e664c7, CI `Test Core (6/10)` failed on the core `second-object-read-exposure` pin because the new caller was not yet classified. Fixed in ff64484; locally that pin gives `Tests 4 passed (4)`. - CI `Test Core (8/10)` hit a 5000 ms timeout in `plugin-security` `org-admin-assignment-boundary.posture.test.ts`. That file is untouched here. Locally it gives `Tests 104 passed (104)`, and it is green on ff64484. CI check-runs on ff64484: every non-skipped run has `completed/success`. That includes `Lint & Repo Gates`, `TypeScript Type Check`, `Test Core` (10/10 shards), `Build Core`, `Governed Surface Queue Guard`, `Test UI`, `Type Check UI`, `Build & E2E UI`, `Live E2E UI`, `Dogfood Regression Gate` and `Check Changeset`. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent de8d549 commit 22af9e6

4 files changed

Lines changed: 451 additions & 6 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): global search titles a hit by the referenced record's title when the object's `nameField` is a reference field
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`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`).
11+
12+
- The target titles are read in one `id $in` read per searched object, never one per hit, selecting `id` and the title column only.
13+
- 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.
14+
- A target read that fails for any other reason fails the search, as a failing record read in the same sweep already does.
15+
- The hit's shape is unchanged: `record` still carries the stored id, and only `title` changes.

‎packages/core/src/security/second-object-read-exposure.pin.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,14 @@ const CALLERS: Record<string, Classification> = {
187187
wiring: { file: 'packages/plugins/plugin-approvals/src/approval-service.ts', call: 'this.servesPayloadDisplayTarget(' },
188188
pin: 'packages/plugins/plugin-approvals/src/payload-display-target-exposure.test.ts',
189189
},
190+
'packages/metadata-protocol/src/protocol-record-reads.ts': {
191+
kind: 'decided',
192+
read: "global search's hit title for an object whose `nameField` is a reference field (`searchAll` reads the target records' titles as the searcher)",
193+
operation: 'get',
194+
decision: { file: 'packages/metadata-protocol/src/protocol-record-reads.ts', fn: 'servesSearchTitleTarget' },
195+
wiring: { file: 'packages/metadata-protocol/src/protocol-record-reads.ts', call: 'servesSearchTitleTarget(targetObj' },
196+
pin: 'packages/metadata-protocol/src/protocol.search-title-lookup.test.ts',
197+
},
190198
'packages/plugins/plugin-audit/src/audit-writers.ts': {
191199
kind: 'decided',
192200
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
559567
'servesLabelTarget',
560568
'servesPayloadDisplayTarget',
561569
'servesReferenceTarget',
570+
'servesSearchTitleTarget',
562571
'servesSummaryTitleTarget',
563572
'stdioExpandMap',
564573
]);

‎packages/metadata-protocol/src/protocol-record-reads.ts‎

Lines changed: 141 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,10 @@ import { ConcurrentUpdateError, MalformedVersionTokenError, canonicalVersionInst
5555
import { recordNotFoundError, type UserMessageCaller } from '@objectstack/core';
5656
import { collectInternalWriteResponseFields, omitInternalFieldsFromWriteResponse } from './write-response-internal-fields.js';
5757
import { isMissingTableError } from '@objectstack/metadata/errors';
58-
import { canServeApiOperation, resolveSearchFieldResolution } from '@objectstack/spec/data';
58+
import { canServeApiOperation, referenceTargetOf, resolveSearchFieldResolution } from '@objectstack/spec/data';
5959
import type { EngineQueryOptionsParsed } from '@objectstack/spec/data';
6060
import type { ISecurityService } from '@objectstack/spec/contracts';
61+
import type { StandardErrorCode } from '@objectstack/spec/api';
6162
import { resolveI18nLabel } from '@objectstack/spec/ui';
6263
import type { I18nLabel } from '@objectstack/spec/ui';
6364

@@ -270,6 +271,108 @@ export async function readAsCaller(
270271
return this.engine.findOne(object, opts);
271272
}
272273

274+
/**
275+
* The ADR-0112 code of the security layer refusing the CALLER's read — matched
276+
* by the declared code alone, never by message prose, and never by a driver's
277+
* own ACL code (that is the database refusing the platform, not the platform
278+
* refusing a reader). The same reading objectql's `isReadRefusal` makes for the
279+
* `$expand` family; this package sits below objectql and cannot import it.
280+
*/
281+
const READ_REFUSED: StandardErrorCode = 'PERMISSION_DENIED';
282+
283+
/** The ADR-0079 primary-title pointer: `nameField`, else the deprecated `displayNameField` alias. */
284+
function titlePointerOf(obj: { nameField?: unknown; displayNameField?: unknown } | undefined | null): string | undefined {
285+
if (!obj) return undefined;
286+
if (typeof obj.nameField === 'string' && obj.nameField) return obj.nameField;
287+
if (typeof obj.displayNameField === 'string' && obj.displayNameField) return obj.displayNameField;
288+
return undefined;
289+
}
290+
291+
/** A field map in either registered spelling (array of `{ name }` or a keyed record) as a name → definition map. */
292+
function fieldMapOf(fieldsRaw: unknown): Map<string, any> {
293+
if (Array.isArray(fieldsRaw)) return new Map(fieldsRaw.map((f: any) => [f?.name, f]));
294+
if (fieldsRaw && typeof fieldsRaw === 'object') {
295+
return new Map(Object.entries(fieldsRaw).map(([name, f]: [string, any]) => [name, { name, ...(f || {}) }]));
296+
}
297+
return new Map();
298+
}
299+
300+
/**
301+
* May a search hit be titled from this reference TARGET at all? Its declared
302+
* exposure, asked for `get` of the one decision every door judges
303+
* (`canServeApiOperation`, ADR-0049) — the operation a lookup title read is
304+
* judged as wherever one is served (the approvals inbox, the activity
305+
* summaries). A target that does not serve `get` is not read.
306+
*/
307+
function servesSearchTitleTarget(targetObj: { enable?: any }): boolean {
308+
return canServeApiOperation(targetObj.enable, 'get');
309+
}
310+
311+
/**
312+
* The titles of the `ids` records of `target`, read AS THE SEARCHER — the
313+
* second half of `searchAll`'s title for an object whose primary-title pointer
314+
* is a reference field. One read per call, `id $in` over the whole batch, `id`
315+
* and the target's title column only.
316+
*
317+
* The read is the caller's own: `find` with the caller's context, so the
318+
* target's object gate, row scope and field-level security apply exactly as
319+
* they do to a direct read or to `$expand`, which takes the full gate on its
320+
* sub-read. Every refusal leaves an id out of the answer, and an id left out
321+
* keeps its bare value in the title — the answer `$expand` gives a reader it
322+
* refuses the target:
323+
*
324+
* - the target's declared exposure does not serve `get` (ADR-0049, the one
325+
* decision every door judges) → not read, as a lookup title read elsewhere
326+
* asks the same decision;
327+
* - the caller may not read the object (`canReadObject`, asked before any
328+
* read, as the sweep asks it of each swept object) → not read;
329+
* - the read itself answers the typed refusal → no titles;
330+
* - a row outside the caller's row scope is not returned, and a title column
331+
* field-level security strips is absent → that id keeps its value.
332+
*
333+
* Every other failure of the read propagates, the same disposition the sweep
334+
* gives a failing record read (#8896): a title read that could not run must
335+
* not be answered "this record has no title". A target whose table was never
336+
* provisioned holds no rows, so it titles nothing.
337+
*/
338+
async function readReferenceTitles(
339+
engine: RecordReadHost['engine'],
340+
target: string,
341+
ids: string[],
342+
context: unknown,
343+
canReadObject: ((object: string) => Promise<boolean> | boolean) | undefined,
344+
): Promise<Map<string, string>> {
345+
const titles = new Map<string, string>();
346+
const targetObj = engine.registry.getObject(target);
347+
if (!targetObj) return titles;
348+
if (!servesSearchTitleTarget(targetObj)) return titles;
349+
const titleField = titlePointerOf(targetObj);
350+
if (!titleField || !fieldMapOf(targetObj.fields).has(titleField)) return titles;
351+
if (canReadObject && !(await canReadObject(target))) return titles;
352+
let rows: any[];
353+
try {
354+
const opts: EngineQueryOptionsParsed = {
355+
where: { id: { $in: ids } },
356+
fields: ['id', titleField],
357+
limit: ids.length,
358+
};
359+
if (context !== undefined) opts.context = context as EngineQueryOptionsParsed['context'];
360+
rows = (await engine.find(target, opts)) ?? [];
361+
} catch (error) {
362+
if ((error as { code?: unknown } | null)?.code === READ_REFUSED) return titles;
363+
if (isMissingTableError(error, target)) return titles;
364+
throw error;
365+
}
366+
for (const row of rows) {
367+
if (row?.id == null) continue;
368+
const v = row[titleField];
369+
if (v == null || typeof v === 'object') continue;
370+
const title = String(v);
371+
if (title.trim()) titles.set(String(row.id), title);
372+
}
373+
return titles;
374+
}
375+
273376
/** The body of `ObjectStackProtocolImplementation#searchAll`; the method's docblock there is its contract. */
274377
export async function searchAll(
275378
this: Pick<RecordReadHost, 'engine' | 'getMetaItems' | 'getServicesRegistry'>,
@@ -437,10 +540,26 @@ export async function searchAll(
437540
// this function's own search-field resolution below — a fourth
438541
// spelling here would re-split what those merged.
439542
const titlePointer = obj.nameField ?? obj.displayNameField;
440-
const renderTitle = (row: any): string => {
543+
// A pointer that is a REFERENCE field (`lookup` / `master_detail` /
544+
// `user` / `tree`) stores the target record's id, so the title is
545+
// the TARGET's title: read for the whole batch of hits after the
546+
// object's `find`, as the searcher, by `readReferenceTitles` (which
547+
// says whose read it is and what a refused reader keeps — the bare
548+
// id). `referenceTargetOf` is the spec's one answer to "what does
549+
// this field point at", the same the `$expand` gate and engine ask.
550+
// The hit's wire shape does not move: `record` still carries the
551+
// stored id, and only `title` reads through.
552+
const titleTarget = typeof titlePointer === 'string' && hasField(titlePointer)
553+
? referenceTargetOf(fieldByName.get(titlePointer))
554+
: undefined;
555+
const renderTitle = (row: any, referenceTitles?: Map<string, string>): string => {
441556
if (typeof titlePointer === 'string' && hasField(titlePointer)) {
442557
const v = row[titlePointer];
443-
if (v != null && String(v).trim()) return String(v);
558+
if (v != null && String(v).trim()) {
559+
if (!referenceTitles) return String(v);
560+
const titleOf = (id: unknown) => referenceTitles.get(String(id)) ?? String(id);
561+
return Array.isArray(v) ? v.map(titleOf).join(', ') : titleOf(v);
562+
}
444563
}
445564
if (typeof titleFormatSource === 'string') {
446565
let allResolved = true;
@@ -572,9 +691,25 @@ export async function searchAll(
572691
if (request.context !== undefined) opts.context = request.context;
573692

574693
const rows = await this.engine.find(obj.name, opts);
575-
for (const row of rows || []) {
576-
if (hits.length >= overallLimit) break;
577-
const title = renderTitle(row);
694+
// The rows this sweep will turn into hits — so a target read
695+
// never covers a row the `overallLimit` cut drops.
696+
const hitRows = (rows || []).slice(0, Math.max(0, overallLimit - hits.length));
697+
let referenceTitles: Map<string, string> | undefined;
698+
if (titleTarget && typeof titlePointer === 'string') {
699+
const ids = new Set<string>();
700+
for (const row of hitRows) {
701+
const v = row?.[titlePointer];
702+
for (const id of Array.isArray(v) ? v : [v]) {
703+
if (id != null && typeof id !== 'object' && String(id).trim()) ids.add(String(id));
704+
}
705+
}
706+
if (ids.size > 0) {
707+
const read = await readReferenceTitles(this.engine, titleTarget, [...ids], request.context, canReadObject);
708+
if (read.size > 0) referenceTitles = read;
709+
}
710+
}
711+
for (const row of hitRows) {
712+
const title = renderTitle(row, referenceTitles);
578713
// Build snippet from first searchable field that contains a
579714
// term. [#7643] `undefined` is a CORRECT answer here, not a
580715
// miss: a companion (pinyin) hit matches the normalized

0 commit comments

Comments
 (0)