Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/service-knowledge': patch
'@objectstack/metadata-core': patch
---

fix(service-knowledge): a package duplicate that the knowledge service itself refuses is told the source cannot be copied and to duplicate the package again

Clause-②: yes (widening) — `@objectstack/service-knowledge`'s `KnowledgeService.admitAuthoredSource` takes an optional third input `options: { door?: 'save' | 'duplicate' }`; `@objectstack/metadata-core`'s `KnowledgeSourceSaveAdmitter.admitAuthoredSource` declares the same optional `options` input
Metadata-protocol: none

- **`@objectstack/service-knowledge`.** `admitAuthoredSource(item, ctx, { door: 'duplicate' })` words every verdict for the package duplicate's caller: the source "cannot be copied", a verdict that could not be judged ends "Duplicate the package again.", and a field the caller may not query is fixed by removing it and duplicating the package again, or by someone who may query it duplicating the package. It never says "save the source" or "Nothing was written". The status, code, object and field are the same as at a save. With no `door`, or `door: 'save'`, every sentence is byte-identical to before.
- **`@objectstack/metadata-core`.** `authoredKnowledgeSourceRefusal({ door: 'duplicate' })` hands the door on to the knowledge service's `admitAuthoredSource`, so the package duplicate's refusal says once, in its prefix, that nothing was copied. A save hands on no door: the service is asked with the item and the context alone, as before.
15 changes: 13 additions & 2 deletions packages/metadata-core/src/knowledge-source-save-admission.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,19 @@ describe('authoredKnowledgeSourceRefusal — source admission at save', () => {
for (const refusal of [none, scoped, unresolved]) {
expect(refusal?.message).not.toMatch(/save the source|Nothing was written/);
}
// A verdict of the knowledge service is its own sentence, passed through as before.
expect(await ask(() => serviceAnswering(REFUSED))).toEqual({ status: 403, code: 'PERMISSION_DENIED', message: REFUSED.message });
// A verdict of the knowledge service is its own sentence, passed through
// as it answers: the service is asked with this door, so it words it.
const service = serviceAnswering(REFUSED);
expect(await ask(() => service)).toEqual({ status: 403, code: 'PERMISSION_DENIED', message: REFUSED.message });
expect(service.admitAuthoredSource).toHaveBeenCalledWith(ITEM, AUTHOR, { door: 'duplicate' });
});

it('a save hands the knowledge service no door: it is asked with the item and the context alone', async () => {
for (const door of [undefined, 'save'] as const) {
const service = serviceAnswering({ admitted: true });
await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: () => service, ...(door ? { door } : {}) });
expect(service.admitAuthoredSource.mock.calls, String(door)).toEqual([[ITEM, AUTHOR]]);
}
});

it('`isSystem: false` is not a bypass', async () => {
Expand Down
24 changes: 20 additions & 4 deletions packages/metadata-core/src/knowledge-source-save-admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@
* written). A door that copies sources rather than saves one, the package
* duplicate, asks with `door: 'duplicate'` and gets its caller's remedy
* (duplicate the package again) and no "nothing was written" of its own: that
* door's prefix says once that nothing was copied.
* door's prefix says once that nothing was copied. The door is handed on to
* the knowledge service's own verdict
* ({@link KnowledgeSourceSaveAdmitter.admitAuthoredSource}), which words it
* the same way; a save hands on no door.
*
* ## Fail direction
*
Expand Down Expand Up @@ -129,9 +132,18 @@ function isKnowledgeServiceNotInScope(value: unknown): value is KnowledgeService
return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_IN_SCOPE] === true;
}

/** The member of the `knowledge` service the doors ask, reached duck-typed. */
/**
* The member of the `knowledge` service the doors ask, reached duck-typed.
* `options.door` is passed only by a door other than `save` (the package
* duplicate), so the service words its own verdict for that door's caller; a
* save asks with the item and the context alone, as before.
*/
export interface KnowledgeSourceSaveAdmitter {
admitAuthoredSource(item: unknown, context: unknown): Promise<AuthoredKnowledgeSourceVerdict>;
admitAuthoredSource(
item: unknown,
context: unknown,
options?: { door?: KnowledgeSourceSaveDoor },
): Promise<AuthoredKnowledgeSourceVerdict>;
}

/** The remedy and the no-op each door's caller is told. */
Expand Down Expand Up @@ -237,7 +249,11 @@ export async function authoredKnowledgeSourceRefusal(input: {
if (typeof admit !== 'function') return undefined;
let verdict: AuthoredKnowledgeSourceVerdict;
try {
verdict = await admit.call(service, input.item, input.executionContext);
// The service words its verdict for the door: a duplicate is asked with
// its door, a save as before.
verdict = await (door === 'save'
? admit.call(service, input.item, input.executionContext)
: admit.call(service, input.item, input.executionContext, { door }));
} catch (err) {
return unavailable(err instanceof Error ? err.message : String(err), door);
}
Expand Down
1 change: 1 addition & 0 deletions packages/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"@objectstack/service-analytics": "workspace:*",
"@objectstack/service-datasource": "workspace:*",
"@objectstack/service-job": "workspace:*",
"@objectstack/service-knowledge": "workspace:*",
"@objectstack/service-messaging": "workspace:*",
"@objectstack/service-package": "workspace:*",
"@objectstack/service-record-context": "workspace:*",
Expand Down
167 changes: 152 additions & 15 deletions packages/runtime/src/domains/packages-knowledge-source-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import '@objectstack/metadata';
import { describe, it, expect, vi } from 'vitest';
import { ObjectKernel, ServiceLifecycle } from '@objectstack/core';
import type { Plugin, PluginContext } from '@objectstack/core';
// The platform's knowledge service, for the doors' wording of its own verdict.
import { KnowledgeServicePlugin, type KnowledgeService } from '@objectstack/service-knowledge';
import { HttpDispatcher } from '../http-dispatcher.js';

const ctx = (executionContext: any): any => ({ request: {}, environmentId: 'platform', executionContext });
Expand Down Expand Up @@ -236,8 +239,8 @@ describe('/packages — duplicate admits each knowledge source it copies for the
message: "The knowledge source \"faq\" was not saved: you may not query field 'salary' of object 'article'.",
};
/** A stack whose kernel also serves a knowledge service answering `admit`. */
function withKnowledge(holding: Holding, admit: (item: unknown, ctx: unknown) => unknown) {
const admitAuthoredSource = vi.fn(async (item: unknown, c: unknown) => admit(item, c));
function withKnowledge(holding: Holding, admit: (item: unknown, ctx: unknown, options?: { door?: unknown }) => unknown) {
const admitAuthoredSource = vi.fn(async (item: unknown, c: unknown, options?: { door?: unknown }) => admit(item, c, options));
return { ...make(holding, { admitAuthoredSource }), admitAuthoredSource };
}

Expand All @@ -249,28 +252,35 @@ describe('/packages — duplicate admits each knowledge source it copies for the
expect(r.response?.body?.error?.message).toContain('nothing was copied');
expect(r.response?.body?.error?.message).toContain(REFUSAL.message);
expect(s.protocol.duplicatePackage).not.toHaveBeenCalled();
// Judged as the caller, on the item the package holds.
expect(s.admitAuthoredSource).toHaveBeenCalledWith(SOURCE_ITEM, caller.executionContext);
// Judged as the caller, on the item the package holds, and asked for this door's wording.
expect(s.admitAuthoredSource).toHaveBeenCalledWith(SOURCE_ITEM, caller.executionContext, { door: 'duplicate' });
});

// The save refusal of a source whose `adapter` the deployment does not
// mount is a `400`, where the gates' own are `403`: the door answers the
// predicate's status and sentence, never one of its own.
it('a source naming an adapter the deployment does not mount refuses the duplicate 400 VALIDATION_ERROR with the save\'s sentence, and nothing is copied', async () => {
const UNMOUNTED = {
// The refusal of a source whose `adapter` the deployment does not mount is
// a `400`, where the gates' own are `403`: the door answers the service's
// status and its sentence for this door, worded for the duplicate's caller
// (the service is asked with `door: 'duplicate'`), never one of its own.
it('a source naming an adapter the deployment does not mount refuses the duplicate 400 VALIDATION_ERROR with the service\'s duplicate-door sentence, and nothing is copied', async () => {
const verdictFor = (door: unknown) => ({
admitted: false, status: 400, code: 'VALIDATION_ERROR',
message: "The knowledge source \"faq\" was not saved: it names adapter 'ragflow', which this deployment does not mount (mounted: memory).",
};
message: door === 'duplicate'
? "The knowledge source \"faq\" cannot be copied: it names adapter 'ragflow', which this deployment does not mount (mounted: memory), and a source's `adapter` must name a mounted store. Mount the 'ragflow' store and duplicate the package again."
: "The knowledge source \"faq\" was not saved: it names adapter 'ragflow', which this deployment does not mount (mounted: memory), and a source's `adapter` must name a mounted store. Mount the 'ragflow' store and save it again.",
});
const held = { ...SOURCE_ITEM, adapter: 'ragflow' };
const s = withKnowledge({ items: [held] }, () => UNMOUNTED);
const s = withKnowledge({ items: [held] }, (_item: unknown, _ctx: unknown, options?: { door?: unknown }) => verdictFor(options?.door));
const caller = authed(BOTH);
const r = await call(s, DUPLICATE, caller);
expect(r.response?.status).toBe(400);
expect(r.response?.body?.error?.code).toBe('VALIDATION_ERROR');
expect(r.response?.body?.error?.message).toContain('nothing was copied');
expect(r.response?.body?.error?.message).toContain(UNMOUNTED.message);
const message: string = r.response?.body?.error?.message;
expect(message).toContain(verdictFor('duplicate').message);
expect(message).toContain('cannot be copied');
expect(message).toMatch(/duplicate the package again/i);
expect(message).not.toMatch(/save the source|save it again|Nothing was written|was not saved/);
expect(message.match(/nothing was copied/gi)).toHaveLength(1);
expect(s.protocol.duplicatePackage).not.toHaveBeenCalled();
expect(s.admitAuthoredSource).toHaveBeenCalledWith(held, caller.executionContext);
expect(s.admitAuthoredSource).toHaveBeenCalledWith(held, caller.executionContext, { door: 'duplicate' });
});

it('every source is asked about: the second one refused refuses the duplicate', async () => {
Expand Down Expand Up @@ -435,3 +445,130 @@ describe('/packages — what the gate leaves alone', () => {
expect(s.registry.installPackage).toHaveBeenCalled();
});
});

/**
* The verdict the platform's own knowledge service answers, through both doors
* that ask it: the package duplicate and the `/meta` save. A real kernel runs
* `KnowledgeServicePlugin` over host doubles (the engine, the security
* service, the metadata protocol), so the sentence each door returns is the
* one `admitAuthoredSource` composes for that door, not a double's.
*
* The duplicate's caller copies a package: never told to save a source, and
* told once, by the door's prefix, that nothing was copied. The `/meta`
* save's sentences are the control, pinned byte for byte.
*/
describe('/packages duplicate and /meta save on a real kernel running KnowledgeServicePlugin: each door words the service\'s own verdict', () => {
const ARTICLE = {
name: 'article',
fields: { id: { type: 'text' }, title: { type: 'text' }, body: { type: 'textarea' }, salary: { type: 'textarea' } },
};
const FIELDS = Object.keys(ARTICLE.fields);
type Arm = 'transient' | 'content' | 'where' | 'title';
const sourceFor = (arm: Arm) => ({
name: 'faq', label: 'FAQ', adapter: 'memory',
source: {
kind: 'object', object: 'article', content: arm === 'content' ? ['body', 'salary'] : ['body'],
...(arm === 'where' ? { where: { salary: { $ne: null } } } : {}),
},
});
/** What the save door answers today, byte for byte. */
const SAVE_VERDICT: Record<Arm, { status: number; code: string; message: string }> = {
transient: {
status: 503, code: 'SERVICE_UNAVAILABLE',
message: 'The knowledge source "faq" was not saved: whether you may search object \'article\' could not be judged '
+ '(registry unavailable), and an author must be allowed to search what their source indexes. Nothing was written; try again.',
},
content: {
status: 403, code: 'PERMISSION_DENIED',
message: 'The knowledge source "faq" was not saved: you may not query field \'salary\' of object \'article\' (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.',
},
where: {
status: 403, code: 'PERMISSION_DENIED',
message: 'The knowledge source "faq" was not saved: its `where` reads field \'salary\' of object \'article\', which you may '
+ 'not query (it is hidden from you, or served to you masked), and the source would select its records by that '
+ 'field. Remove the field from `where`, or have someone who may query it save the source.',
},
title: {
status: 403, code: 'PERMISSION_DENIED',
message: 'The knowledge source "faq" was not saved: you may not query field \'title\' of object \'article\' (it is hidden '
+ 'from you, or served to you masked), and the index would hold its text unmasked. The source does not list it: '
+ "it is the object's display field, which every document carries as its title. Have someone who may query it save the source.",
},
};

async function bootPlatformKnowledge(arm: Arm) {
const s = make({ items: [sourceFor(arm)] });
const saveMetaItem = vi.fn(async ({ name }: any) => ({ success: true, name }));
Object.assign(s.protocol, { saveMetaItem });
// The engine the knowledge service reads schemas through; the package registry rides on it.
Object.assign(s.kernelServices.objectql, {
getSchema: (name: string) => {
if (arm === 'transient') throw new Error('registry unavailable');
return name === 'article' ? ARTICLE : undefined;
},
find: vi.fn(async () => []),
});
const hidden = arm === 'title' ? 'title' : arm === 'transient' ? undefined : 'salary';
const security = {
getQueryableFields: vi.fn(async () => FIELDS.filter((f) => f !== hidden)),
getReadableFields: vi.fn(async () => FIELDS),
};
const doubles: Record<string, unknown> = { ...s.kernelServices, security };
const host: Plugin = {
name: 'test.duplicate-door.host',
version: '1.0.0',
type: 'standard',
async init(ctx: PluginContext) {
for (const [name, service] of Object.entries(doubles)) ctx.registerService(name, service);
},
} as Plugin;
const kernel = new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true });
await kernel.use(host);
await kernel.use(new KnowledgeServicePlugin({ enableEventSync: false }));
await kernel.bootstrap();
const knowledge = kernel.getService<KnowledgeService>('knowledge');
knowledge.registerAdapter('memory', { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] });
const dispatcher = new HttpDispatcher(kernel as any);
return {
...s, kernel, saveMetaItem,
duplicate: (caller: any) => dispatcher.handlePackages('/pkg-a/duplicate', 'POST', { targetPackageId: 'pkg-b' }, {}, caller),
save: (caller: any) => dispatcher.handleMetadata('/knowledge_source/faq', caller, 'PUT', JSON.parse(JSON.stringify(sourceFor(arm)))),
};
}

for (const arm of ['transient', 'content', 'where', 'title'] as const) {
it(`${arm}: the duplicate is told nothing was copied once and to duplicate the package, never to save, and nothing is copied`, async () => {
const stack = await bootPlatformKnowledge(arm);
try {
const expected = SAVE_VERDICT[arm];
const r = await stack.duplicate(authed(BOTH));
expect(r.response?.status).toBe(expected.status);
expect(r.response?.body?.error?.code).toBe(expected.code);
const message: string = r.response?.body?.error?.message;
expect(message.startsWith('Duplicating package "pkg-a" is refused, and nothing was copied. The knowledge source "faq" cannot be copied: '), message).toBe(true);
expect(message).not.toMatch(/save the source|save it again|Nothing was written|was not saved|the save /);
expect(message.match(/nothing was copied/gi)).toHaveLength(1);
expect(message).toMatch(arm === 'title' ? /Have someone who may query it duplicate the package\.$/ : /duplicate the package again/i);
expect(stack.protocol.duplicatePackage).not.toHaveBeenCalled();
} finally {
await stack.kernel.shutdown();
}
});

it(`${arm}: CONTROL — the same verdict at the /meta save door is byte for byte what it was, and nothing is saved`, async () => {
const stack = await bootPlatformKnowledge(arm);
try {
const expected = SAVE_VERDICT[arm];
const saved = await stack.save(authed(BOTH));
expect(saved.response?.status).toBe(expected.status);
expect(saved.response?.body?.error?.code).toBe(expected.code);
expect(saved.response?.body?.error?.message).toBe(expected.message);
expect(stack.saveMetaItem).not.toHaveBeenCalled();
} finally {
await stack.kernel.shutdown();
}
});
}
});
9 changes: 9 additions & 0 deletions packages/runtime/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,15 @@ export default defineConfig({
// the #4567 regression (croner rejecting the expression envelope) is
// reproduced by the actual scheduler rather than by a double.
{ find: '@objectstack/service-job', replacement: path.resolve(__dirname, '../services/service-job/src/index.ts') },
// Dev-only: packages-knowledge-source-gate.test.ts drives the package
// duplicate and the `/meta` save over the REAL `KnowledgeServicePlugin`
// (ADR-0161 K4, guard two), so the verdict each door words is the
// service's in the checkout, never a built copy of it. Anchored: the pin
// imports only the root entry.
{
find: /^@objectstack\/service-knowledge$/,
replacement: path.resolve(__dirname, '../services/service-knowledge/src/index.ts'),
},
// Dev-only: src/security/request-execution-context.conformance.test.ts
// drives the REAL settings door (`SettingsServicePlugin`'s context
// resolver) as one row of ruling record 6227928430's conformance test, so
Expand Down
Loading
Loading