diff --git a/.changeset/38419-knowledge-source-save-absent-reference.md b/.changeset/38419-knowledge-source-save-absent-reference.md new file mode 100644 index 00000000000..2ee07815ea4 --- /dev/null +++ b/.changeset/38419-knowledge-source-save-absent-reference.md @@ -0,0 +1,22 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): the knowledge-source save door names an absent object or field as such + +Clause-②: no +Metadata-protocol: none + +Saving a `knowledge_source` whose `source.object` names no object, or whose `source.content` / +`source.metadataFields` names no field of its object, is now refused `400 VALIDATION_ERROR` with the rule +`os validate` reports: `knowledge-source-object-unknown` or `knowledge-source-field-unknown`. The refusal names +the object, and the field. Before, the same save was answered `503 SERVICE_UNAVAILABLE` ("could not be judged ... +try again") for an absent object, `403` "is a system object that does not opt into AI reads" for an absent `sys_` +object, and `403` "you may not query field ... hidden from you" for an absent field. With no security service, it +was admitted. + +The check reads only the object's registered definition. `id` and the system columns the registry injects count +as fields of the object. Every door that asks it admits only a `manage_metadata` holder, and that caller is already +served every object definition whole. So for an object or a field that exists, every refusal stays as it was: a +hidden field, a system object without `enable.aiReadable`, a disabled package, a security service that cannot +answer, and a registry that throws. The fields a `where` reads are not checked for existence, as in `os validate`. diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-source-save-absent-reference.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-save-absent-reference.test.ts new file mode 100644 index 00000000000..f206266b27f --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/knowledge-source-save-absent-reference.test.ts @@ -0,0 +1,258 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161 K4, row 4] The save door's "does not exist" arm: a + * `knowledge_source` whose `source.object` names no object, or whose + * `source.content` / `source.metadataFields` names no field of its object, is + * refused at its save as a permanent reference mistake, by the rule names + * `os validate` reports (`knowledge-source-object-unknown`, + * `knowledge-source-field-unknown`): `400 VALIDATION_ERROR`, never the `503` + * that says "try again" nor a `403` that says "you may not". + * + * The arm is decided from the object's registered definition alone. Every + * door that asks this verdict admits only a `manage_metadata` holder, and that + * caller is served every object definition whole on the metadata plane + * (ADR-0106 D4), so the arm tells the author nothing they could not read. + * Its other half is pinned here byte for byte: for an object or a field that + * EXISTS, every refusal the author was given before is the one given now. + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { KnowledgeService, type KnowledgeLogger } from '../knowledge-service.js'; +import type { KnowledgeFieldSecurity } from '../knowledge-source-admission.js'; + +const MEMBER: ExecutionContext = { userId: 'u_member', positions: ['member'], permissions: [], isSystem: false }; +const MANAGER: ExecutionContext = { userId: 'u_manager', positions: ['manager'], permissions: [], isSystem: false }; +const SYSTEM: ExecutionContext = { positions: [], permissions: [], isSystem: true }; + +interface ObjectDef { + name: string; + enable?: Record; + fields: Record>; +} + +const TICKET: ObjectDef = { + name: 'ticket', + fields: { + title: { type: 'text' }, + body: { type: 'textarea' }, + salary_note: { type: 'textarea' }, + status: { type: 'select' }, + }, +}; +const SYS_CLOSED: ObjectDef = { name: 'sys_closed_note', fields: { title: { type: 'text' }, body: { type: 'textarea' } } }; + +const OBJECT_UNKNOWN = 'knowledge-source-object-unknown'; +const FIELD_UNKNOWN = 'knowledge-source-field-unknown'; + +/** + * A security service shaped like the platform's: an object whose definition it + * cannot resolve gets no answer to either field question (`undefined`), and + * members may not query `salary_note`. + */ +function platformLikeSecurity(objects: ObjectDef[]): KnowledgeFieldSecurity { + const fieldsOf = (object: string) => { + const def = objects.find((o) => o.name === object); + return def ? ['id', ...Object.keys(def.fields)] : undefined; + }; + return { + getQueryableFields: vi.fn(async (object: string, ctx?: ExecutionContext) => { + const all = fieldsOf(object); + return all && ctx?.userId === 'u_member' ? all.filter((f) => f !== 'salary_note') : all; + }), + getReadableFields: vi.fn(async (object: string) => fieldsOf(object)), + }; +} + +function setup(options: { + objects?: ObjectDef[]; + security?: KnowledgeFieldSecurity | 'none'; + disabled?: string[]; + schemaThrows?: boolean; + /** An engine that exposes no schema registry at all. */ + noSchemaRegistry?: boolean; + logger?: KnowledgeLogger; +}) { + const objects = options.objects ?? [TICKET, SYS_CLOSED]; + const byName = new Map(objects.map((o) => [o.name, o])); + const engine = { + find: vi.fn(async () => []), + ...(options.noSchemaRegistry + ? {} + : { + getSchema: (name: string) => { + if (options.schemaThrows) throw new Error('registry unavailable'); + return byName.get(name); + }, + }), + registry: { isObjectPackageDisabled: (name: string) => (options.disabled ?? []).includes(name) }, + } as unknown as IDataEngine; + const security = options.security === 'none' ? undefined : (options.security ?? platformLikeSecurity(objects)); + const svc = new KnowledgeService({ + dataEngine: engine, + logger: options.logger, + resolveSecurity: security ? () => security : undefined, + }); + const adapter: IKnowledgeAdapter = { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] }; + svc.registerAdapter('memory', adapter); + return svc; +} + +const item = (object: string, content: string[], extra: Record = {}) => ({ + name: 'authored', label: 'Authored', adapter: 'memory', source: { kind: 'object', object, content, ...extra }, +}); + +type Refusal = { admitted: false; status: number; code: string; message: string; object: string; field?: string }; + +describe('the save door names an absent object as such, by the rule `os validate` reports', () => { + it.each([ + ['a business object nothing defines', 'tickt'], + ['a `sys_` object nothing defines', 'sys_no_such_note'], + ])('%s is refused VALIDATION_ERROR / 400, naming the object and `knowledge-source-object-unknown`', async (_label, object) => { + for (const security of [undefined, 'none'] as const) { + const svc = setup({ security }); + const verdict = (await svc.admitAuthoredSource(item(object, ['body']), MANAGER)) as Refusal; + expect(verdict, String(security)).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400, object }); + expect(verdict.field).toBeUndefined(); + expect(verdict.message).toContain(`\`${OBJECT_UNKNOWN}\``); + expect(verdict.message).toContain(`names '${object}'`); + expect(verdict.message.startsWith('The knowledge source "authored" was not saved: ')).toBe(true); + // A permanent mistake: never worded as a transient fault or as a refusal of authority. + expect(verdict.message).not.toMatch(/could not be judged|try again|does not opt into AI reads|may not query/); + } + }); + + it('the engine itself is admitted: a package install is judged at validate and publish', async () => { + expect(await setup({}).admitAuthoredSource(item('tickt', ['body']), SYSTEM)).toEqual({ admitted: true }); + }); +}); + +describe('the save door names an absent field as such, by the rule `os validate` reports', () => { + it.each([ + ['`content`', item('ticket', ['body', 'bdy']), 'bdy', 'content'], + ['`metadataFields`', item('ticket', ['body'], { metadataFields: ['stauts'] }), 'stauts', 'metadataFields'], + ['`contentFields` (the retired spelling)', { name: 'authored', label: 'A', adapter: 'memory', source: { kind: 'object', object: 'ticket', contentFields: ['bdy'] } }, 'bdy', 'contentFields'], + ])('a %s member is refused VALIDATION_ERROR / 400, naming the object, the field and `knowledge-source-field-unknown`', async (_label, body, field, key) => { + for (const ctx of [MEMBER, MANAGER]) { + for (const security of [undefined, 'none'] as const) { + const verdict = (await setup({ security }).admitAuthoredSource(body, ctx)) as Refusal; + expect(verdict, `${ctx.userId} ${String(security)}`).toMatchObject({ + admitted: false, code: 'VALIDATION_ERROR', status: 400, object: 'ticket', field, + }); + expect(verdict.message).toContain(`\`${FIELD_UNKNOWN}\``); + expect(verdict.message).toContain(`\`source.${key}\` names field '${field}', which object 'ticket' does not define`); + expect(verdict.message).not.toMatch(/hidden from you|may not query|could not be judged|try again/); + } + } + }); + + it('an absent field is named before a field the author may not query, wherever each is listed', async () => { + const verdict = (await setup({}).admitAuthoredSource(item('ticket', ['salary_note', 'bdy']), MEMBER)) as Refusal; + expect(verdict).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400, field: 'bdy' }); + }); + + it('CONTROL: `id` and the system columns the registry injects are fields of the object, though it does not declare them', async () => { + const svc = setup({ security: 'none' }); + expect(await svc.admitAuthoredSource(item('ticket', ['body', 'id'], { metadataFields: ['created_at', 'owner_id'] }), MANAGER)) + .toEqual({ admitted: true }); + }); + + it('door: duplicate words both arms for the duplicate\'s caller; the status, code, object and field are the save\'s', async () => { + const svc = setup({}); + for (const body of [item('tickt', ['body']), item('ticket', ['bdy'])]) { + const saved = (await svc.admitAuthoredSource(body, MANAGER)) as Refusal; + const duplicated = (await svc.admitAuthoredSource(body, MANAGER, { door: 'duplicate' })) as Refusal; + const { message: _saved, ...savedRest } = saved; + const { message, ...duplicatedRest } = duplicated; + expect(duplicatedRest).toEqual(savedRest); + expect(message).toMatch(/^The knowledge source "authored" cannot be copied: /); + expect(message).toMatch(/, then duplicate the package again\.$/); + expect(message).not.toMatch(/save the source|save it again|was not saved|Nothing was written|nothing was copied|the save /i); + } + }); +}); + +/** + * The arm's other half: what EXISTS keeps the answer it had, byte for byte — + * the sentences below are the ones the door gave before the arm existed. + */ +describe('no permission answer changes for an object or a field that exists', () => { + it('a field that exists but is hidden from the author keeps its PERMISSION_DENIED / 403 sentence', async () => { + const svc = setup({}); + expect(await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), MEMBER)).toEqual({ + admitted: false, + status: 403, + code: 'PERMISSION_DENIED', + object: 'ticket', + field: 'salary_note', + message: + 'The knowledge source "authored" was not saved: you may not query field \'salary_note\' of object \'ticket\' (it is hidden ' + + 'from you, or served to you masked), and the index would hold its text unmasked. Remove the field from `content` ' + + 'and `metadataFields`, or have someone who may query it save the source.', + }); + // The same source, by an author who may query the field. + expect(await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), MANAGER)).toEqual({ admitted: true }); + }); + + it('a `sys_` object that exists without `enable.aiReadable` keeps its PERMISSION_DENIED / 403 sentence', async () => { + expect(await setup({}).admitAuthoredSource(item('sys_closed_note', ['body']), MANAGER)).toEqual({ + admitted: false, + status: 403, + code: 'PERMISSION_DENIED', + object: 'sys_closed_note', + message: + 'The knowledge source "authored" was not saved: \'sys_closed_note\' is a system object that does not opt into AI reads ' + + '(`enable.aiReadable: true`), so its records are not indexed for retrieval.', + }); + }); + + it('an object that exists but whose fields the security service cannot answer keeps its SERVICE_UNAVAILABLE / 503 sentence', async () => { + const mute: KnowledgeFieldSecurity = { getQueryableFields: async () => undefined, getReadableFields: async () => undefined }; + expect(await setup({ security: mute }).admitAuthoredSource(item('ticket', ['body']), MANAGER)).toEqual({ + admitted: false, + status: 503, + code: 'SERVICE_UNAVAILABLE', + object: 'ticket', + message: + 'The knowledge source "authored" was not saved: whether you may search object \'ticket\' could not be judged (the security ' + + "service did not answer which fields of 'ticket' you may read), and an author must be allowed to search what their source " + + 'indexes. Nothing was written; try again.', + }); + }); + + it('an object of a disabled package keeps its PERMISSION_DENIED / 403 sentence, whether or not its definition is served', async () => { + for (const objects of [[TICKET], []]) { + expect(await setup({ objects, security: 'none', disabled: ['ticket'] }).admitAuthoredSource(item('ticket', ['bdy']), MANAGER)) + .toEqual({ + admitted: false, + status: 403, + code: 'PERMISSION_DENIED', + object: 'ticket', + message: + 'The knowledge source "authored" was not saved: its object \'ticket\' belongs to a disabled package, and a disabled ' + + "package's records are not indexed or searched. Enable the package, or index another object.", + }); + } + }); + + it('a registry that throws keeps its SERVICE_UNAVAILABLE / 503 sentence and is reported once', async () => { + const logger = { warn: vi.fn(), error: vi.fn() }; + expect(await setup({ schemaThrows: true, logger }).admitAuthoredSource(item('tickt', ['body']), MANAGER)).toEqual({ + admitted: false, + status: 503, + code: 'SERVICE_UNAVAILABLE', + object: 'tickt', + message: + 'The knowledge source "authored" was not saved: whether you may search object \'tickt\' could not be judged (registry ' + + 'unavailable), and an author must be allowed to search what their source indexes. Nothing was written; try again.', + }); + expect(logger.error).toHaveBeenCalledTimes(1); + }); + + it('an engine with no schema registry draws no "does not exist" verdict: absence of a registry is not absence of the object', async () => { + expect(await setup({ noSchemaRegistry: true, security: 'none' }).admitAuthoredSource(item('tickt', ['bdy']), MANAGER)) + .toEqual({ admitted: true }); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index fc75b128ab2..745ee1e8889 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -27,6 +27,7 @@ import { registryObjectPackageDisabled, } from '@objectstack/core'; import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; +import { resolveInjectedSystemColumns } from '@objectstack/spec/data'; import { createKnowledgeTools, refusal, type KnowledgeTools } from './knowledge-tools.js'; import { resolveSplit, splitDocument, type ResolvedSplit } from './split/index.js'; import { indexExpectation } from './knowledge-index-fingerprint.js'; @@ -3721,7 +3722,12 @@ export class KnowledgeService implements IKnowledgeService { * the protocol's parse refuses it with the schema's own prescription. * * A refusal is coded (ADR-0112) and names the object, and the field for the - * field gate: `403 PERMISSION_DENIED`. A source whose `adapter` names no + * field gate: `403 PERMISSION_DENIED`. Ahead of every gate, a source whose + * object or listed field does not exist is refused `400 VALIDATION_ERROR`, + * naming it and the rule `os validate` reports + * (`knowledge-source-object-unknown`, `knowledge-source-field-unknown`), + * decided from the object's definition alone ({@link absentSourceReference}), + * so no answer about an object or a field that exists changes. A source whose `adapter` names no * adapter this deployment mounts is refused `400 VALIDATION_ERROR`, naming * the source, the adapter and the mounted ones; an omitted `adapter` is not * (it is placed by {@link adapterIdFor}). That check is this door's only: @@ -3797,6 +3803,37 @@ export class KnowledgeService implements IKnowledgeService { const engine = this.options.dataEngine; if (!engine) return unavailable('the knowledge service has no data engine'); + // [ADR-0161 K4, row 4] A reference to nothing is a permanent mistake, named + // by the rule `os validate` reports, ahead of every permission arm. + let absent: AbsentSourceReference | undefined; + try { + absent = absentSourceReference(objSource, listed, engine, this.admissionDeps(engine)); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + if (absent?.kind === 'object') { + return refuse( + 400, + 'VALIDATION_ERROR', + `${named}: \`source.object\` names '${object}', which is not an object of this organization (neither one it ` + + 'authored nor one an installed package registers), so the source indexes nothing ' + + `(\`${KNOWLEDGE_SOURCE_OBJECT_UNKNOWN}\`, the rule \`os validate\` reports). Name an object the organization ` + + `has (check the spelling), or install the package that provides '${object}' first${wording.thenAgain}.`, + ); + } + if (absent?.kind === 'field') { + return refuse( + 400, + 'VALIDATION_ERROR', + `${named}: \`source.${absent.key}\` names field '${absent.field}', which object '${object}' does not define, ` + + 'so the index reads nothing for it on any record ' + + `(\`${KNOWLEDGE_SOURCE_FIELD_UNKNOWN}\`, the rule \`os validate\` reports). Name a field of '${object}' ` + + `(check the spelling), or remove it from \`${absent.key}\`${wording.thenAgain}.`, + absent.field, + ); + } + let admission: ObjectAdmission; try { admission = await admitObject(object, ctx, this.admissionDeps(engine)); @@ -4086,6 +4123,59 @@ const AUTHORED_SOURCE_DOOR_WORDING: Readonly< }, }; +/** The `os validate` rule ids the save door's "does not exist" arm reports (`@objectstack/lint`, `validate-knowledge-source.ts`). */ +const KNOWLEDGE_SOURCE_OBJECT_UNKNOWN = 'knowledge-source-object-unknown'; +const KNOWLEDGE_SOURCE_FIELD_UNKNOWN = 'knowledge-source-field-unknown'; + +/** A saved source's reference to nothing: its object, or a member naming no field of it. */ +type AbsentSourceReference = + | { kind: 'object' } + | { kind: 'field'; field: string; key: 'content' | 'contentFields' | 'metadataFields' }; + +/** + * [ADR-0161 K4, row 4] What a saved source names that does not exist, judged + * as `os validate` judges it (`knowledge-source-object-unknown`, + * `knowledge-source-field-unknown`): its `source.object` is no object the + * registry defines, or a `content` / `contentFields` / `metadataFields` + * member is neither a field the object declares nor `id` or a system column + * the registry injects on it (`resolveInjectedSystemColumns`). The fields a + * `where` reads are not judged here (the CLI rule does not judge them either). + * + * Decided from the object's registered DEFINITION alone, never from a + * permission answer: every door that asks this verdict admits only a + * `manage_metadata` holder, who is served every object definition whole on + * the metadata plane (ADR-0106 D4), so the verdict tells the author nothing + * they could not read. An object or a field that exists is never reported + * here, so every permission answer about it is the one it was. + * + * No verdict where none can be drawn: an engine with no schema registry (no + * registry is not no object), an object of a disabled package (that gate + * answers it, its definition may be withheld), and an object whose fields + * cannot be enumerated. Throws when a lookup throws; the caller refuses `503`. + */ +function absentSourceReference( + objSource: ObjectKnowledgeSource, + listed: { content?: unknown; contentFields?: unknown; metadataFields?: unknown }, + engine: IDataEngine, + deps: KnowledgeAdmissionDeps, +): AbsentSourceReference | undefined { + if (typeof (engine as { getSchema?: unknown }).getSchema !== 'function') return undefined; + const schema = deps.readSchema(objSource.object); + if (deps.isObjectPackageDisabled(objSource.object) === true) return undefined; + if (schema === undefined || schema === null) return { kind: 'object' }; + const declared = declaredFields(schema); + if (!declared) return undefined; + const known = new Set([...declared.map(([name]) => name), ...resolveInjectedSystemColumns(schema).names]); + for (const key of ['content', 'contentFields', 'metadataFields'] as const) { + const members = listed[key]; + if (!Array.isArray(members)) continue; + for (const member of members) { + if (typeof member === 'string' && member !== '' && !known.has(member)) return { kind: 'field', field: member, key }; + } + } + return undefined; +} + function describeName(input: unknown): string { const { name, id } = (input ?? {}) as { name?: unknown; id?: unknown }; const shown = typeof name === 'string' && name !== '' ? name : typeof id === 'string' && id !== '' ? id : undefined;