Repository navigation
fix(service-knowledge): knowledge search asks the object's API exposure and the caller's field-level read rules per source - #36850
Conversation
…nd field-level read rules per source Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
…or restricted callers Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
…owledge-exposure-fls
…he source admission read Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift CheckThis PR changes 1 package(s): 5 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
⛔ 4 release-owned page(s) also name something this change touched. These are read-only:
What this run could not see
Coarse fallback — 4 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin aa4b70fc9a46ef942b8b64f6ff7e65e3fe45b6c6 && git checkout aa4b70fc9a46ef942b8b64f6ff7e65e3fe45b6c6
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 5727092e72f7c8f34964a98ca0aef01103305719 c4abc0caff32cd85d9000d1e6c92444c3969f862 && git checkout -B drift-repro 5727092e72f7c8f34964a98ca0aef01103305719 && git merge --no-ff c4abc0caff32cd85d9000d1e6c92444c3969f862
node scripts/docs-audit/affected-docs.mjs --json 5727092e72f7c8f34964a98ca0aef01103305719
|
|
repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ 席位核对 — L1 REWORK · head
|
…udged object sources and foreign hits are never served Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
… lookup and the dropped hits Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
|
repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ 席位核对 — L1 REWORK (round 2, small) · head
|
…sees; changeset wording Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
…owledge-exposure-fls # Conflicts: # content/docs/permissions/system-context.mdx
… sentences that describe one Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
… check Claude-Session: https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ Co-authored-by: Claude <noreply@anthropic.com>
|
repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ 席位核对 — ACCEPT · L1 · head
|
…a restored record re-enters the index (objectstack-ai#37075) Fixes objectstack-ai#36991 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:挂了知识检索的应用里,知识源只索引符合条件的记录(例如只索引现行版本);记录改成不符合后,旧内容从检索结果里消失;从回收站恢复的记录,符合条件就能重新被搜到。 - 为什么做:知识检索平台化专题第一阶段的「结果要对」——此前记录变更时完全不看索引条件,草稿会进索引,失效内容一直搜得到。 - 出错会怎样:只影响挂了知识检索服务的应用的检索结果,保存记录本身不受影响;改动可直接撤回,撤回后回到旧行为。 - 要你做的:无。 ## What changes `KnowledgeService.handleRecordUpsert` no longer builds the document from the event payload. With a data engine bound, each `object` source bound to the object re-reads the row under the system context, `find(object, { where: { $and: [where, { id }] }, limit: 1 }, { context: system })` (`{ id }` alone when the source has no `where`): - a row comes back: the document is built from the re-read row through the same `recordToDocument(source, objSource, row, this.schemaFor(object))` gate as the reindex walk, so the credential-class / `internal` withholding landed by objectstack-ai#36850 holds on this path too, and the document carries the fields the source lists and the record `title`, never a credential-class or `internal` field; - no row: the document is deleted (idempotent). The plugin's event bridge now routes `data.record.restored` (`RECORD_RESTORED_EVENT` from `@objectstack/spec/data`) through the same path; its comment and the `enableEventSync` option docs name all four per-record events. With no data engine: a source without `where` still builds from the payload; a source with `where` is skipped and reported once per source at `warn`. Syncs of one document (`${source.id}:${recordId}`, upserts and deletes alike) run through an in-process promise chain, dropped when idle, so two opposite events cannot interleave. The system context is one helper now shared with `reindexSource` (same spelling it already used). No adapter-contract member, no spec change, no queue. `content/docs/protocol/knowledge.mdx` section 6 is rewritten to say this, including the measured ordering below; it also drops the claim that a bare `record.*` event is still accepted (the bridge has had no branch for it). ### Item 6: where the event fires relative to the write's transaction (measured on origin/main 8aecf6d) - `data.record.created` is published at `packages/objectql/src/engine-insert.ts:1716`, inside the engine body that `insert` wraps in its own unit when it opens one (`engine-insert.ts:386`, `executeWithMiddleware(opCtx, inOwnUnit(...))`, closing at :1805); `data.record.updated` at `engine-update.ts:2445`, inside `inOwnUnit` opened at `engine-update.ts:529`. So both fire before that unit, or a caller's `engine.transaction(...)`, commits. - `publishDataEvent` awaits `realtimeService.publish` (`engine-realtime-publish.ts:484`), and the in-process adapter awaits each subscriber (`packages/services/service-realtime/src/in-memory-realtime-adapter.ts:98`), so the knowledge handler runs inside the write's async context. A read with no explicit transaction takes the ambient one (`engine-driver-options.ts:304-306`), so the re-read sees the row the write just made. A rolled-back unit leaves the index wrong until the row's next event or a `reindexSource`, in one of two ways: if the uncommitted row matched, the document stays built from a row that never committed (as the payload path did); if it did not match, the document was deleted, so the committed row, which may still match, is missing from the index (new with the re-read). Because the sync is inline, a write's sync can also wait behind an earlier in-flight sync of the same document (on a single-connection pool, up to the acquire timeout); the index still ends consistent. - `data.record.restored` is published at `recycle-bin/restore.ts:470`, after `writeBack` (:451) has run and committed the restore's own unit (`restore.ts:756`). - Bulk `data.records.*` events stay uncovered; the existing warn and doc callout say so. ## Tests `src/__tests__/event-sync-data-events.test.ts` is rewritten (it asserted building from `after`): the bridge cases now cover `data.record.restored`, and the sync cases run the real plugin and service against an engine double whose `find` applies scalar equality and `$and`, refuses any other operator by throwing, and applies `limit` by presence after the filter. One test per acceptance item: enter on match; does not enter when not matching; exit when a record stops matching (and search no longer finds it); no `where`; payload missing a content field; restored and matching is searchable; restored but not matching is not indexed; no engine without `where`; no engine with `where` (skipped, one warn across two events); and three two-event races (match then no match, no match then match, update then delete) each ending consistent with the database. In `knowledge-service.test.ts` the event-path withholding pin now feeds a payload carrying only the id and a re-read row carrying the credential and internal fields, under `'*'` and named explicitly. Ablations, each through `scripts/ablation-replace.mjs` (anchor hit 1 to 0, blob changed, restored to HEAD with `git diff HEAD` empty); the test imports the source by relative path, so no `dist/` leg: | Mutation | Red | |---|---| | re-read `where` reduced to `{ id }` | 5 of 23 (query shape, not matching, stops matching, restored not matching, match-then-no-match race) | | serialization removed from the upsert path | 3 of 23 (all three races) | | `RECORD_RESTORED_EVENT` dropped from the bridge | 2 of 23 (restored routing, restored searchable); a first attempt with the anchor ending in a bare close-paren-brace was refused by the tool before any run (replacement count did not move), and was re-run with a unique anchor | | document built from the payload instead of the re-read row | 3 of 51 across both files (both withholding pins, missing-content-field) | ## Acceptance notes - Under `contentFields: ['*']` the event-path document now carries every string field of the re-read row, exactly what `reindexSource` already sends for the same row; explicit lists send only the listed fields. Retiring `'*'` is the epic's row 3, not this card. - The per-document chain orders syncs in one process only; two processes publishing for one row are not ordered by it (the card scopes item 5 to in-process). - The sync stays inline with the write (as before): a write now also waits for one system-context read per bound source. ## Verification Two minutes: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/event-sync-data-events.test.ts` should print `Tests 23 passed (23)`. Read first, by risk: 1. `packages/services/service-knowledge/src/knowledge-service.ts`: `syncRecord` (the re-read and the miss-means-delete branch) and `serializeRecordSync`. 2. `packages/services/service-knowledge/src/knowledge-service-plugin.ts`: the event-bridge branch now including `RECORD_RESTORED_EVENT`. 3. `content/docs/protocol/knowledge.mdx` section 6: the ordering statement. Container run (head 53f2e69, this worktree; re-run at 4ab8a4f after the text-only patch round: `pnpm --filter @objectstack/service-knowledge test` VERDICT command-exit 0, `Test Files 8 passed (8)`, `Tests 117 passed (117)`): <details><summary>Package tests and typecheck</summary> - `pnpm --filter @objectstack/service-knowledge test`: VERDICT command-exit 0, `Test Files 8 passed (8)`, `Tests 117 passed (117)` (event-sync file 23, knowledge-service file 28). - `pnpm --filter @objectstack/service-knowledge typecheck`: VERDICT command-exit 0; `check:test-typecheck: OK`, 0 files / 0 errors. - Dependency closure built first: `pnpm --workspace-concurrency=2 --filter '@objectstack/service-knowledge^...' build`, VERDICT command-exit 0. </details> <details><summary>Derived gate families (dispatch-gates --commands, 100)</summary> - 98 exit 0, among them `check:system-context-census`, `check:query-options-erasure`, `check:where-matcher`, `check:objectql-double-limit`, `check:engine-double-contract`, `check:doc-authoring`, `check:issue-citations`, `check:nul-bytes`. - 2 NOT MEASURED, exit 3 PREREQUISITE NOT MET (unbuilt packages outside this diff's closure): `pnpm --filter @objectstack/spec run check:skill-examples` (needs `client-react` dist), `pnpm check:dual-build-cjs-loads` (needs every package's dist). Declared to CI. - `dispatch-gates --ran`: 100 derived, 98 run, 2 NOT-MEASURED (derived from the recorded exit 3), 0 UNRUN. - Repo-wide lint, `test:repo` and full dogfood are CI's (no `!`, no narrowing arm). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL)_ <!-- signed: repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
Fixes #36839
Clause-②: no
Metadata-protocol: none
维护者速读
What changes
Option D of the ruling recorded on #36650 (comment 7121194365, quoted in #36839's body): in the knowledge service, at source granularity, fail closed, no new spec key. Governing text: ADR-0090 D10 rule 1, ADR-0049.
KnowledgeService.search(packages/services/service-knowledge/src/knowledge-service.ts) re-checked an object-source hit only with a row read of its id under the caller's context, while the passage it returns is built at index time, under a system context, from everycontentFieldsmember, the recordtitleand the source'smetadataFields.knowledge-source-admission.ts, asked by a new privateadmitSourcesstep before any adapter is searched, for a non-system caller with a data engine bound, once per (caller, object) per search:registryObjectPackageDisabledover the engine's registry (the predicate the data route and the analytics door ask; no injected hook needed, so no new dependency on metadata-protocol);canServeApiOperation(enable, 'search')(@objectstack/spec/data), the decision and operation the cross-object search asks;sys_*objects: served only whenisAiReadExposedanswers true (enable.aiReadable: true), the MCP record tools' posture;contentFields,'*'= every declared field exceptid;metadataFields;title), less the credential-class andinternalfieldsrecordToDocumentnever indexes, must be in thesecurityservice'sgetQueryableFieldsanswer; absent it orundefined,getReadableFieldsless everymaskingRulefield; with nosecurityservice, every field except themaskingRuleones (the contract's fallback,ISecurityService.getQueryableFields).A source failing any gate is not searched for that caller. Queryable rather than readable: a passage carries the unmasked value and the search matches on it.
error,warnas fallback); asecurityservice answering neither field question refuses too. The system context bypasses, as it bypasses the row re-check; the no-context and no-engine paths are unchanged (they already drop every object-source hit).KnowledgeServicePluginpasses a new optionalresolveSecurityoption resolvingsecurityper search (plugin order free). Only a missing answer or the kernel's not-registered refusal (isServiceNotRegisteredError) reads as "no security service"; any other throw from that lookup refuses the object's sources, reported aterroronce per object per search.KnowledgeFieldSecurityis exported as a type.objectsource at all (before, an object-source hit with nosourceRecordIdreached it). An admitted object source's hit with nosourceRecordIdcannot be re-checked and is dropped.KnowledgeService.searchdrops a hit whose reportedsourceIdnames another source than the one searched. Object admissions are asked concurrently, and thesys_*posture also reads the schema's own name.@objectstack/knowledge-ragflow. A RAGFlow-side chunk filter added in review round 1 was removed again under the maintainer's ruling recorded on security(knowledge): search hits skip the API-exposure decision and field-level read rules every other row-serving door applies, now that the MCP door serves search_knowledge #36839 (comment 7134290286, option B): the documented RAGFlow API returns no chunk metadata, so the filter could not act, and the package is retired whole on its own card. This PR changes nothing in that package.row-serving-door-exposure.pin.test.tsnow holds knowledge retrieval BY NAME (HELD_BY_NAME: the door imports its decision site, which asks the exposure decision andgetQueryableFields, and the behaviour pin exists) instead of naming it unconstrained. Themcp-http-identitynote inauthz-conformance.matrix.tsstates the knowledge-service enforcement its "RLS / FLS / tenant apply exactly as on REST /data" claim relies on once a tool serves knowledge search.content/docs/protocol/knowledge.mdx§5 (new "Source admission" subsection), §7.1 and §9 state the gates and the narrowing.content/docs/permissions/system-context.mdxrow 46 now namesadmitSources(its new system-context bypass read), with the generated register regenerated bycheck-system-context-census.mjs --write.Tests
packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts(22), through the realKnowledgeService, refusal and preservation per gate: a member who reads the row but notsalary_notegets no hit from the source naming it and the adapter is never asked to search it, while a manager and the system context get it;titleandmetadataFieldshidden each refuse;'*'refuses on one hidden field and does not ask about credential /internalfields; a masked field via thegetReadableFieldsfallback; no security service ⇒maskingRulefallback; a throwing field answer and an unanswering service fail closed; the answer is asked once per object;apiEnabled: falsedropped for an end-user context and kept for the system context; anapiMethodswhitelist withoutsearchrefused and one withlistadmitted; a disabled package's object dropped and kept for system; asys_*object withoutaiReadabledropped, with it kept; a throwing schema read fails closed; an http source is untouched. Two more driveKnowledgeServicePluginon a realLiteKernelwith a registeredsecurityservice (refusal + preservation) and without one (fallback admits).knowledge-service.tsandknowledge-service-plugin.tsrestored to the basef77d078d(blob match confirmed), the new file ran 14 failed / 2 passed (the 2 are pure preservation legs); restored to HEAD (blob match,git diff HEADempty) it runs 16 / 16.sourceRecordIdis dropped; a hit naming another source is dropped; asecuritylookup throwing anything but the not-registered miss fails closed with oneerrorlog (system preserved); andisServiceNotRegisteredError's discrimination. Red before: with the service and plugin restored to round-1 head774652cd63(the lookup back to swallowing every throw), the file ran 5 failed / 17 passed (the 5 behaviour pins); restores matched HEAD. Three fixtures inknowledge-service.test.tsthat searched an object source with no context now pass the system context or register the http source their hit names.row-serving-door-exposure.pin.test.ts(corerepoproject) 4 / 4; withknowledge-service.tsrestored to base, the new held-by-name test is red (1 failed / 3 passed), restored blob matches HEAD.Local runs on head 5cc0e97 (after merging origin/main at 305fe60)
os-verify-lock, VERDICT command-exit 0:pnpm --filter '@objectstack/service-knowledge^...' --filter '@objectstack/lint...' build, then@objectstack/service-knowledgetest (5 files / 71 tests), typecheck (tsc --noEmit+check:test-typecheckOK) and build (check-dts-emitted2/2); corerepoprojectrow-serving-door-exposure.pin.test.ts4 / 4.node scripts/pm/dispatch-gates.mjs --commandson 5cc0e97: 105 derived; 103 exit 0. NOT MEASURED, PREREQUISITE NOT MET (exit 3; they read dists of packages outside this diff, not built in this worktree):pnpm --filter @objectstack/spec run check:skill-examples,pnpm check:dual-build-cjs-loads.--ranwith exit codes: 105 derived, 103 run, 2 NOT-MEASURED, 0 UNRUN.content/docs/permissions/system-context.mdxrows 45/46 (main changed row 45, this PR row 46); resolved by keeping both changes, andcheck-system-context-census.mjs --writereported the register already current.node scripts/check-platform-checklist.mjs --changed-from origin/main: exit 0, no anchored file in the change set.Acceptance notes
metadataFieldsis gated besidecontentFieldsandtitle: a hit'smetadataserves those values, so leaving them out would keep the same leak; the card's Expected 2 namescontentFieldsandtitle.titleis required only when the object declares atitlefield (or its schema is unknown), becauserecordToDocumentserves the record'stitlewhatever the source names.securityservice whose field answer isundefinedon both methods refuses the source (fail closed) rather than falling to the object's own projection.Verification
Read first, by risk:
packages/services/service-knowledge/src/knowledge-source-admission.ts(admitObject,servedFieldsOf,admitSourceFields), theadmitSourceshunk inknowledge-service.ts, then the plugin'sresolveSecuritywiring.Two-minute check:
pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-source-admission.test.ts— expect 22 passed.Generated by Claude Code