|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// [ADR-0161 K4] A `knowledge_source` whose `adapter` names a store this |
| 4 | +// deployment does not mount is refused at its save, on a REAL booted showcase |
| 5 | +// (the knowledge service and its one store, `memory`): |
| 6 | +// |
| 7 | +// - `PUT /meta/knowledge_source/:name` answers `400 VALIDATION_ERROR`, naming |
| 8 | +// the source, the adapter and the mounted stores; nothing is stored; |
| 9 | +// - the MCP `save_metadata_draft` tool refuses the same save the same way, |
| 10 | +// and no draft is stored. |
| 11 | +// |
| 12 | +// CONTROLS, at both doors: a source naming the mounted store, and one that |
| 13 | +// leaves `adapter` out (the one store holds it), save as before. |
| 14 | +// |
| 15 | +// Before, both saves answered success, and the source was named only by the |
| 16 | +// boot's `error` line and by the `503` its index and search answered. |
| 17 | +// |
| 18 | +// Not judged at these doors: a package install (the engine's own write), a |
| 19 | +// source registered in code and `os validate`. |
| 20 | +// |
| 21 | +// The verify harness mounts no MCP server, so this file mounts one, as |
| 22 | +// `objectstack dev` and `serve` do. The draft door is served only to an OAuth |
| 23 | +// agent granted `metadata:write` whose user holds the authoring capability, |
| 24 | +// and that agent holds its user's system capabilities only under |
| 25 | +// `actions:execute`, so the MCP calls present a REAL access token with both |
| 26 | +// scopes (DCR, authorize with the MCP resource, consent, token). |
| 27 | +// |
| 28 | +// The file is ISOLATED: it writes `/meta`, creates a package and sets |
| 29 | +// `OS_OIDC_PROVIDER_ENABLED` for its boot. |
| 30 | + |
| 31 | +import { createHash, randomBytes } from 'node:crypto'; |
| 32 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 33 | +import { MCPServerPlugin } from '@objectstack/mcp'; |
| 34 | +import { type VerifyStack } from '@objectstack/verify'; |
| 35 | +import { bootShowcase } from './showcase-boot.js'; |
| 36 | + |
| 37 | +const OPERATOR = { email: 'admin@objectos.ai', password: 'admin123' }; |
| 38 | +const AGENT_SCOPE = 'openid profile email offline_access metadata:write actions:execute'; |
| 39 | +const REDIRECT_URI = 'http://127.0.0.1:33421/callback'; |
| 40 | +/** A writable package the drafts are saved into (the showcase's own is read-only). */ |
| 41 | +const DRAFT_PACKAGE = 'com.dogfood.ksadapter'; |
| 42 | + |
| 43 | +/** A source over the showcase's tasks, as the showcase's own `showcase_task_notes`, with the given `adapter`. */ |
| 44 | +const sourceBody = (name: string, adapter?: string) => ({ |
| 45 | + name, |
| 46 | + label: name, |
| 47 | + ...(adapter === undefined ? {} : { adapter }), |
| 48 | + source: { kind: 'object', object: 'showcase_task', content: ['title', 'notes'], metadataFields: ['status', 'priority'] }, |
| 49 | +}); |
| 50 | + |
| 51 | +async function mintAgentToken(stack: VerifyStack): Promise<string> { |
| 52 | + const authSvc: any = await stack.kernel.getServiceAsync('auth'); |
| 53 | + const resource = authSvc.getMcpResourceUrl(); |
| 54 | + const reg = await stack.api('/auth/oauth2/register', { |
| 55 | + method: 'POST', |
| 56 | + headers: { 'content-type': 'application/json' }, |
| 57 | + body: JSON.stringify({ |
| 58 | + client_name: 'knowledge adapter save probe', redirect_uris: [REDIRECT_URI], grant_types: ['authorization_code', 'refresh_token'], |
| 59 | + response_types: ['code'], token_endpoint_auth_method: 'none', application_type: 'native', scope: AGENT_SCOPE, |
| 60 | + }), |
| 61 | + }); |
| 62 | + const regBody: any = await reg.json(); |
| 63 | + expect(reg.status, JSON.stringify(regBody)).toBe(201); |
| 64 | + const signin = await stack.api('/auth/sign-in/email', { |
| 65 | + method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(OPERATOR), |
| 66 | + }); |
| 67 | + expect(signin.status, await signin.clone().text()).toBe(200); |
| 68 | + const cookie = ((signin.headers as any).getSetCookie() as string[]).map((c) => c.split(';')[0]).join('; '); |
| 69 | + const verifier = randomBytes(32).toString('base64url'); |
| 70 | + const challenge = createHash('sha256').update(verifier).digest('base64url'); |
| 71 | + const qs = new URLSearchParams({ |
| 72 | + client_id: regBody.client_id, redirect_uri: REDIRECT_URI, response_type: 'code', scope: AGENT_SCOPE, state: 'st', |
| 73 | + code_challenge: challenge, code_challenge_method: 'S256', resource, |
| 74 | + }); |
| 75 | + const az = await stack.api(`/auth/oauth2/authorize?${qs}`, { headers: { cookie }, redirect: 'manual' }); |
| 76 | + const loc = az.headers.get('location') ?? ''; |
| 77 | + let code = new URL(loc, 'http://localhost:3000').searchParams.get('code'); |
| 78 | + if (!code) { |
| 79 | + const consent = await stack.api('/auth/oauth2/consent', { |
| 80 | + method: 'POST', |
| 81 | + headers: { 'content-type': 'application/json', cookie, origin: 'http://localhost:3000' }, |
| 82 | + body: JSON.stringify({ accept: true, oauth_query: loc.slice(loc.indexOf('?')) }), |
| 83 | + }); |
| 84 | + const cb: any = await consent.json().catch(() => null); |
| 85 | + code = new URL(cb?.redirect_uri ?? cb?.url).searchParams.get('code'); |
| 86 | + } |
| 87 | + const tok = await stack.api('/auth/oauth2/token', { |
| 88 | + method: 'POST', |
| 89 | + headers: { 'content-type': 'application/x-www-form-urlencoded' }, |
| 90 | + body: new URLSearchParams({ |
| 91 | + grant_type: 'authorization_code', code: code!, redirect_uri: REDIRECT_URI, client_id: regBody.client_id, code_verifier: verifier, resource, |
| 92 | + }).toString(), |
| 93 | + }); |
| 94 | + const tj: any = await tok.json(); |
| 95 | + expect(tok.status, JSON.stringify(tj)).toBe(200); |
| 96 | + return String(tj.access_token); |
| 97 | +} |
| 98 | + |
| 99 | +describe('[ADR-0161 K4] a knowledge_source naming an adapter the deployment does not mount is refused at its save', () => { |
| 100 | + let stack: VerifyStack; |
| 101 | + let admin = ''; |
| 102 | + let agent = ''; |
| 103 | + const priorOidc = process.env.OS_OIDC_PROVIDER_ENABLED; |
| 104 | + |
| 105 | + const put = async (name: string, body: unknown) => { |
| 106 | + const res = await stack.apiAs(admin, 'PUT', `/meta/knowledge_source/${name}`, body); |
| 107 | + const json: any = await res.json().catch(() => ({})); |
| 108 | + return { status: res.status, error: json?.error, json }; |
| 109 | + }; |
| 110 | + const saveDraft = async (name: string, item: unknown) => { |
| 111 | + const res = await stack.api('/mcp', { |
| 112 | + method: 'POST', |
| 113 | + headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${agent}` }, |
| 114 | + body: JSON.stringify({ |
| 115 | + jsonrpc: '2.0', id: 1, method: 'tools/call', |
| 116 | + params: { name: 'save_metadata_draft', arguments: { type: 'knowledge_source', name, item, package: DRAFT_PACKAGE } }, |
| 117 | + }), |
| 118 | + }); |
| 119 | + expect(res.status, await res.clone().text()).toBe(200); |
| 120 | + const rpc: any = await res.json(); |
| 121 | + expect(rpc.error, JSON.stringify(rpc.error)).toBeUndefined(); |
| 122 | + const text = String(rpc.result?.content?.[0]?.text ?? ''); |
| 123 | + let payload: any; |
| 124 | + try { payload = JSON.parse(text); } catch { payload = { message: text }; } |
| 125 | + return { isError: rpc.result?.isError === true, payload, text }; |
| 126 | + }; |
| 127 | + const knowledge = async () => stack.kernel.getServiceAsync<any>('knowledge'); |
| 128 | + |
| 129 | + beforeAll(async () => { |
| 130 | + process.env.OS_OIDC_PROVIDER_ENABLED = 'true'; |
| 131 | + stack = await bootShowcase({ extraPlugins: [new MCPServerPlugin()] }); |
| 132 | + admin = await stack.signIn(); |
| 133 | + const created = await stack.apiAs(admin, 'POST', '/packages', { |
| 134 | + manifest: { id: DRAFT_PACKAGE, name: 'Knowledge adapter drafts', version: '0.1.0', type: 'app', namespace: 'ksadapter' }, |
| 135 | + }); |
| 136 | + expect(created.status, await created.clone().text()).toBe(201); |
| 137 | + agent = await mintAgentToken(stack); |
| 138 | + }, 180_000); |
| 139 | + |
| 140 | + afterAll(async () => { |
| 141 | + await stack?.stop(); |
| 142 | + if (priorOidc === undefined) delete process.env.OS_OIDC_PROVIDER_ENABLED; |
| 143 | + else process.env.OS_OIDC_PROVIDER_ENABLED = priorOidc; |
| 144 | + }); |
| 145 | + |
| 146 | + it('the booted deployment mounts one store, memory', async () => { |
| 147 | + expect((await knowledge()).listAdapters()).toEqual(['memory']); |
| 148 | + }); |
| 149 | + |
| 150 | + it('PUT /meta/knowledge_source refuses a retired or mistyped adapter 400 VALIDATION_ERROR, naming the source, the adapter and the mounted stores; nothing is stored', async () => { |
| 151 | + for (const [name, adapter] of [['ks_retired_store', 'ragflow'], ['ks_typo_store', 'memroy']] as const) { |
| 152 | + const saved = await put(name, sourceBody(name, adapter)); |
| 153 | + expect(saved.status, JSON.stringify(saved.json)).toBe(400); |
| 154 | + expect(saved.error, JSON.stringify(saved.json)).toMatchObject({ code: 'VALIDATION_ERROR' }); |
| 155 | + const message = String(saved.error?.message ?? ''); |
| 156 | + expect(message).toContain(name); |
| 157 | + expect(message).toContain(`names adapter '${adapter}', which this deployment does not mount (mounted: memory)`); |
| 158 | + expect((await stack.apiAs(admin, 'GET', `/meta/knowledge_source/${name}`)).status, name).toBe(404); |
| 159 | + expect((await knowledge()).listSources().map((s: { name: string }) => s.name), name).not.toContain(name); |
| 160 | + } |
| 161 | + }); |
| 162 | + |
| 163 | + it('save_metadata_draft refuses the same save 400 VALIDATION_ERROR, and no draft is stored', async () => { |
| 164 | + const refused = await saveDraft('ks_draft_retired_store', sourceBody('ks_draft_retired_store', 'ragflow')); |
| 165 | + expect(refused.isError, refused.text).toBe(true); |
| 166 | + expect(refused.payload.error, refused.text).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); |
| 167 | + expect(String(refused.payload.error?.message)).toContain("names adapter 'ragflow', which this deployment does not mount (mounted: memory)"); |
| 168 | + const draft = await stack.apiAs(admin, 'GET', `/meta/knowledge_source/ks_draft_retired_store?state=draft&package=${DRAFT_PACKAGE}`); |
| 169 | + expect(draft.status, await draft.clone().text()).toBe(404); |
| 170 | + }); |
| 171 | + |
| 172 | + it('CONTROL: a source naming the mounted store, and one leaving `adapter` out, save at both doors', async () => { |
| 173 | + for (const [name, adapter] of [['ks_named_store', 'memory'], ['ks_omitted_store', undefined]] as const) { |
| 174 | + const saved = await put(name, sourceBody(name, adapter)); |
| 175 | + expect(saved.status, JSON.stringify(saved.json)).toBe(200); |
| 176 | + const drafted = await saveDraft(`${name}_draft`, sourceBody(`${name}_draft`, adapter)); |
| 177 | + expect(drafted.isError, drafted.text).toBe(false); |
| 178 | + expect(drafted.payload.saved, drafted.text).toMatchObject({ type: 'knowledge_source', name: `${name}_draft`, package: DRAFT_PACKAGE }); |
| 179 | + } |
| 180 | + }); |
| 181 | +}); |
0 commit comments