From df69b278ce8c96d2e7d529624f1a8cd8541ee79e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Thu, 19 Nov 2026 12:16:30 +0800 Subject: [PATCH 01/14] =?UTF-8?q?feat(settings):=20AI=20=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=94=B9=E4=B8=BA=E5=BD=93=E5=89=8D=E7=94=9F?= =?UTF-8?q?=E6=95=88=E4=B8=8E=E7=8B=AC=E7=AB=8B=E8=8D=89=E7=A8=BF=E7=BC=96?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为什么:交互稿要求顶部只读已保存模型与真实核验态,下方编辑独立草稿;测试草稿 不得改写当前连接,保存一律回显服务端结果,草稿变动或配置被他人改动后旧测试失效。 原来只有一张表单和一个 busy 状态,测试与保存无法区分,清除密钥也与保存混在一起。 改了什么:QAModelSettings 拆成 saved / draft 两层;已配置密钥默认收起,仅更换或 首次录入展示输入框,换地址强制重新录入;清除并停用收进折叠区、二次确认且只提交 已保存连接;409 冲突重新拉取已保存配置并作废草稿测试。样式迁到 systemSettings.css, 删除 qaOps.css 里同名残留;合并分区与组件内重复说明。 怎么验的:npm test 119 文件 600 例全过(新增 mounted 交互回归 5 例);npm run build 通过;make verify 全量门禁 17 项 success(identity 本地 skipped)。未推送、未部署。 --- CHANGELOG.md | 18 ++ README.md | 2 +- web/src/QAModelSettings.mounted.test.tsx | 197 +++++++++++++ web/src/QAModelSettings.test.tsx | 71 +++-- web/src/QAModelSettings.tsx | 352 ++++++++++++++++------- web/src/SystemSettings.test.tsx | 9 +- web/src/SystemSettings.tsx | 8 +- web/src/qaOps.css | 7 - web/src/systemSettings.css | 90 ++++++ 9 files changed, 605 insertions(+), 149 deletions(-) create mode 100644 web/src/QAModelSettings.mounted.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 39a7167..21892a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 开发快照 0.1.401(AI 模型连接:当前生效 + 独立草稿) + +### Changed + +- 「系统设置 → AI 模型连接」按交互稿重排:顶部只读「当前生效」(模型 + 服务端真实核验态与地址), + 下方地址/模型是独立草稿;测试草稿只回显核验结果,不更新当前连接,「测试中」与「保存中」分开提示。 +- 保存成功一律用服务端响应回显当前信息;草稿改动或版本冲突(409)都会作废上一次草稿测试, + 冲突时载入最新已保存配置并要求按新版本重测。 +- 已配置密钥默认收起不回显,只有「更换密钥」或首次录入才出现输入框;更换基础地址强制重新录入密钥, + 取消更换无副作用。安全传输与独立密钥存储限制保持不变。 +- 「清除密钥并停用」收进单独折叠区,写明对问答分析与中文翻译的影响并二次确认;只提交已保存连接, + 未保存草稿不会被夹带,取消不产生任何请求。 +- 合并分区标题与组件内重复的说明文字,模型连接说明只保留一处。 + +### Fixed + +- 模型连接的测试/保存不再共用同一个忙碌状态,避免把草稿测试结果误当成已生效配置。 + ## 开发快照 0.1.399(系统设置分区调整:AI 模型连接 / 知识库映射) ### Changed diff --git a/README.md b/README.md index 49b20ec..f61981c 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ make list # 查看检查清单与适用范围 ## 问答运营模型配置 -管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。 +管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。页面顶部显示当前已保存的模型与服务端核验结果,下方编辑的是独立草稿:测试连接只核验草稿,保存才更新当前连接,保存成功后按服务端响应回显。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显、默认收起,只有「更换密钥」或首次录入才显示输入框,更换基础地址须重新录入密钥;「清除密钥并停用」在单独折叠区里二次确认,只作用于已保存连接。录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。 API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。 diff --git a/web/src/QAModelSettings.mounted.test.tsx b/web/src/QAModelSettings.mounted.test.tsx new file mode 100644 index 0000000..78ef46a --- /dev/null +++ b/web/src/QAModelSettings.mounted.test.tsx @@ -0,0 +1,197 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { QAModelSettings } from './QAModelSettings' +import type { AISettings } from './qaAITypes' +let root: Root, host: HTMLDivElement +type Call = { path: string; method: string; body: Record | null } +let calls: Call[] +let responder: (call: Call) => { status: number; data?: AISettings; error?: string } +const saved: AISettings = { + revision: 1, + base_url: 'https://model.example.invalid/v1', + model: 'example-model', + key_configured: true, + verification: 'verified', + checked_at: '2026-11-18T10:00:00Z', + automatic_evaluation: true, + automatic_translation: false, + storage_ready: true, +} +const applied = (call: Call, extra: Partial = {}): AISettings => ({ + ...saved, + revision: saved.revision + 1, + base_url: String(call.body?.base_url), + model: String(call.body?.model), + key_configured: call.body?.key_action !== 'clear', + verification: call.body?.key_action === 'clear' ? 'not_configured' : 'verified', + ...extra, +}) +const ok = (data: AISettings) => ({ status: 200, data }) +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + calls = [] + responder = (call) => ok(call.method === 'GET' ? saved : applied(call)) + vi.stubGlobal( + 'fetch', + vi.fn(async (path: string, init?: RequestInit) => { + const call: Call = { + path, + method: init?.method ?? 'GET', + body: init?.body ? JSON.parse(String(init.body)) : null, + } + calls.push(call) + const result = responder(call) + return new Response(JSON.stringify(result.error ? { error: result.error } : { data: result.data }), { + status: result.status, + }) + }) + ) +}) +afterEach(async () => { + await act(async () => root.unmount()) + host.remove() + vi.unstubAllGlobals() +}) +const button = (label: string) => { + const found = [...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === label) + expect(found, label).toBeTruthy() + return found! +} +const click = async (label: string) => { + const target = button(label) + await act(async () => target.click()) + await act(async () => {}) +} +const type = async (label: string, value: string) => { + const input = [...host.querySelectorAll('label')] + .find((item) => item.textContent?.startsWith(label)) + ?.querySelector('input') + expect(input, label).toBeTruthy() + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value) + input!.dispatchEvent(new Event('input', { bubbles: true })) + }) +} +const current = () => host.querySelector('.qa-ai-model-current')?.textContent ?? '' +const writes = () => calls.filter((call) => call.method === 'POST') +const disable = async () => { + await click('清除密钥并停用…') + await click('确认清除并停用') +} +describe('AI 模型连接草稿编辑器', () => { + it('tests the draft without touching the saved connection and echoes the server after save', async () => { + await act(async () => root.render()) + expect(current()).toContain('example-model · 已通过真实连接测试') + await type('模型名称', 'draft-model') + await click('测试连接') + const test = writes().at(-1)! + expect(test.path).toBe('/api/v1/qa-ops/ai/settings/test') + expect(test.body).toEqual({ + base_revision: 1, + base_url: saved.base_url, + model: 'draft-model', + key_action: 'keep', + }) + expect(host.textContent).toContain('草稿测试:已通过真实连接测试') + expect(host.textContent).toContain('草稿未保存,当前生效配置未改变') + // 测试不更新「当前生效」,也不产生保存。 + expect(current()).toContain('example-model · 已通过真实连接测试') + expect(writes().filter((call) => call.path.endsWith('/settings'))).toHaveLength(0) + // 再改草稿 ⇒ 上一次测试结论失效。 + await type('模型名称', 'saved-model') + expect(host.textContent).not.toContain('草稿测试:已通过真实连接测试') + await click('保存配置') + const save = writes().at(-1)! + expect(save.path).toBe('/api/v1/qa-ops/ai/settings') + expect(save.body).toEqual({ base_revision: 1, base_url: saved.base_url, model: 'saved-model', key_action: 'keep' }) + // 保存后用服务端响应回显当前信息,而不是本地草稿转写。 + expect(current()).toContain('saved-model · 已通过真实连接测试') + expect(host.textContent).toContain('已保存并更新当前连接:saved-model · 已通过真实连接测试') + expect(host.textContent).toContain('草稿与已保存配置一致') + }) + it('keeps a configured key collapsed and sends a replacement only when asked', async () => { + await act(async () => root.render()) + expect(host.querySelector('input[type=password]')).toBeNull() + await click('更换密钥') + await type('新 API 密钥', 'test-only-replacement-key') + await click('保存配置') + expect(writes().at(-1)!.body).toEqual({ + base_revision: 1, + base_url: saved.base_url, + model: saved.model, + key_action: 'replace', + api_key: 'test-only-replacement-key', + }) + expect(host.querySelector('input[type=password]')).toBeNull() + expect(host.textContent).not.toContain('test-only-replacement-key') + await click('更换密钥') + await click('取消更换') + expect(host.querySelector('input[type=password]')).toBeNull() + expect(host.textContent).toContain('草稿与已保存配置一致') + }) + it('requires a fresh key when the address changes and hides cancelling', async () => { + await act(async () => root.render()) + await type('API 基础地址', 'https://other.example.invalid/v1') + expect(host.querySelector('input[type=password]')).toBeTruthy() + expect(host.textContent).toContain('已更换基础地址:须重新录入密钥') + expect([...host.querySelectorAll('button')].some((item) => item.textContent?.trim() === '取消更换')).toBe(false) + expect(button('保存配置').disabled).toBe(true) + await type('新 API 密钥', 'second-secret') + await click('保存配置') + expect(writes().at(-1)!.body).toEqual({ + base_revision: 1, + base_url: 'https://other.example.invalid/v1', + model: saved.model, + key_action: 'replace', + api_key: 'second-secret', + }) + }) + it('disables only the saved connection, and cancelling the confirmation has no effect', async () => { + await act(async () => root.render()) + await type('模型名称', 'unsaved-draft') + await click('清除密钥并停用…') + await click('取消') + expect(writes()).toHaveLength(0) + expect(current()).toContain('example-model · 已通过真实连接测试') + expect([...host.querySelectorAll('input')].find((item) => item.value === 'unsaved-draft')).toBeTruthy() + await disable() + const clear = writes().at(-1)! + // 草稿里的 unsaved-draft 不会被夹带成停用提交。 + expect(clear.body).toEqual({ + base_revision: 1, + base_url: saved.base_url, + model: saved.model, + key_action: 'clear', + }) + expect(current()).toContain('未配置可用密钥') + expect(host.textContent).toContain('已清除密钥并停用连接') + expect(host.querySelector('input[type=password]')).toBeTruthy() + }) + it('drops a stale draft test when the saved revision changed elsewhere', async () => { + let gets = 0 + responder = (call) => { + if (call.method === 'GET') { + gets += 1 + return ok(gets === 1 ? saved : { ...saved, revision: 2, model: 'other-model' }) + } + return call.path.endsWith('/settings/test') + ? { status: 409, error: '配置、输入、人工复核或预览已变化,请刷新;现有结论未被覆盖' } + : ok(applied(call)) + } + await act(async () => root.render()) + await type('模型名称', 'stale-draft') + await click('测试连接') + expect(host.textContent).toContain('已载入最新已保存配置(版本 2),草稿未保存,请重新测试') + expect(current()).toContain('other-model') + expect(host.textContent).not.toContain('草稿测试:') + // 之后的保存基于刷新后的版本号,不会拿旧 revision 覆盖别人的修改。 + await type('模型名称', 'after-conflict') + await click('保存配置') + expect(writes().at(-1)!.body).toMatchObject({ base_revision: 2, model: 'after-conflict' }) + }) +}) diff --git a/web/src/QAModelSettings.test.tsx b/web/src/QAModelSettings.test.tsx index b116627..2a83571 100644 --- a/web/src/QAModelSettings.test.tsx +++ b/web/src/QAModelSettings.test.tsx @@ -1,37 +1,58 @@ import { it, expect } from 'vitest' import { renderToStaticMarkup } from 'react-dom/server' import { QAModelSettings, qaAIKeyEntryAllowed } from './QAModelSettings' -it('provides independent write-only model settings and does not equate save with bulk execution', () => { +import type { AISettings } from './qaAITypes' +const saved: AISettings = { + revision: 3, + base_url: 'https://model.example.invalid/v1', + model: 'fixture-model', + key_configured: true, + verification: 'verified', + checked_at: '2026-10-19T00:00:00Z', + automatic_evaluation: false, + automatic_translation: false, + storage_ready: true, +} +it('shows the saved connection and keeps a configured key collapsed until replaced', () => { + const html = renderToStaticMarkup() + for (const text of [ + '当前生效', + 'fixture-model · 已通过真实连接测试', + '已配置(不回显)', + '更换密钥', + 'API 基础地址', + '模型名称', + '测试连接', + '保存配置', + '清除密钥并停用连接', + '草稿与已保存配置一致', + ]) + expect(html).toContain(text) + // 已配置的密钥默认收起:没有密码框,也没有把任何密钥值渲染出来。 + expect(html).not.toContain('type="password"') + expect(html).not.toContain('保留现有密钥') + expect(html).not.toContain('fixture-only-api-key') +}) +it('asks for a key on first entry and describes the disable impact', () => { const html = renderToStaticMarkup( ) - for (const text of [ - '问答评估模型', - 'API 基础地址', - '模型名称', - 'API Key', - 'type="password"', - '测试连接', - '保存配置', - '保留现有密钥', - '更换密钥', - '清除密钥', - '保存不会启动全量评估', - ]) - expect(html).toContain(text) - expect(html).not.toContain('value="fixture-only-api-key"') + expect(html).toContain('type="password"') + expect(html).toContain('API 密钥 未配置') + expect(html).toContain('未配置可用密钥') + expect(html).toContain('无法调用此模型') + expect(html).toContain('未保存的草稿不会被提交') + expect(html).toContain('当前没有已保存的密钥') }) it('permits new-key entry only on HTTPS or browser-local loopback origins', () => { expect(qaAIKeyEntryAllowed({ protocol: 'https:', hostname: 'kg.example.invalid' })).toBe(true) diff --git a/web/src/QAModelSettings.tsx b/web/src/QAModelSettings.tsx index ee9c4e3..2ca587c 100644 --- a/web/src/QAModelSettings.tsx +++ b/web/src/QAModelSettings.tsx @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react' import type { AISettings } from './qaAITypes' import type { AISettingsInput } from './qaAI' import { fetchAISettings, saveAISettings, testAISettings } from './qaAI' +import { QARequestError } from './qaOps' export function qaAIKeyEntryAllowed(location: { protocol: string; hostname: string }) { return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname) } @@ -11,172 +12,303 @@ const verificationLabels: Record = { unverified: '未完成核验,未启用调用', rejected: '服务已拒绝,调用已阻断', } +const when = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false }) +type Busy = '' | 'testing' | 'saving' +type Notice = { tone: 'ok' | 'error'; text: string } export function QAModelSettings({ initial }: { initial?: AISettings }) { - const [settings, setSettings] = useState(initial ?? null), - [base, setBase] = useState(initial?.base_url ?? ''), - [model, setModel] = useState(initial?.model ?? '') - const [keyAction, setKeyAction] = useState( - initial?.key_configured ? 'keep' : 'replace' - ), - [key, setKey] = useState('') - const [busy, setBusy] = useState(false), - [error, setError] = useState(null), - [message, setMessage] = useState(null) - const secure = typeof window !== 'undefined' && qaAIKeyEntryAllowed(window.location) + // saved 始终是服务端已生效的那一份(顶部「当前生效」与停用操作的唯一依据); + // 下面的输入只是草稿,测试草稿不回写 saved,避免把未保存的值伪装成当前连接。 + const [saved, setSaved] = useState(initial ?? null) + const [base, setBase] = useState(initial?.base_url ?? '') + const [model, setModel] = useState(initial?.model ?? '') + const [replace, setReplace] = useState(!initial?.key_configured) + const [key, setKey] = useState('') + const [busy, setBusy] = useState('') + const [tested, setTested] = useState(null) + const [confirmingDisable, setConfirmingDisable] = useState(false) + const [notice, setNotice] = useState(null) + const [loadError, setLoadError] = useState(null) useEffect(() => { if (initial) return const controller = new AbortController() void fetchAISettings(controller.signal) .then((value) => { - setSettings(value) + if (controller.signal.aborted) return + setSaved(value) setBase(value.base_url) setModel(value.model) - setKeyAction(value.key_configured ? 'keep' : 'replace') + setReplace(!value.key_configured) }) .catch((reason) => { - if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : '模型配置读取失败') + if (!controller.signal.aborted) setLoadError(reason instanceof Error ? reason.message : '模型配置读取失败') }) return () => controller.abort() }, [initial]) - const dirty = () => { - setMessage(null) - setError(null) + const secure = typeof window !== 'undefined' && qaAIKeyEntryAllowed(window.location) + const configured = Boolean(saved?.key_configured) + // 服务端规则:保留旧密钥时地址不许变(旧密钥不会被发往新地址),所以换地址强制重新录入。 + const baseChanged = Boolean(saved && base !== saved.base_url) + const keyRequired = !configured || baseChanged || replace + const keyAction: AISettingsInput['key_action'] = keyRequired ? 'replace' : 'keep' + const storageReady = Boolean(saved?.storage_ready) + const keyEntryBlocked = !secure || !storageReady + const dirty = Boolean( + saved && (base !== saved.base_url || model !== saved.model || key !== '' || (configured && replace)) + ) + const ready = + Boolean(saved) && + busy === '' && + base.trim() !== '' && + model.trim() !== '' && + (!keyRequired || (!keyEntryBlocked && key !== '')) + // 任何草稿改动都让上一次测试结果失效:旧草稿的核验结论不能贴在新草稿上。 + const edit = (apply: () => void) => { + apply() + setTested(null) + setNotice(null) } - const run = async (test: boolean) => { - if (!settings) return - setBusy(true) - setMessage(null) - setError(null) - const input: AISettingsInput = { - base_revision: settings.revision, - base_url: base, - model, - key_action: keyAction, - ...(keyAction === 'replace' ? { api_key: key } : {}), + const input = (): AISettingsInput => ({ + base_revision: saved!.revision, + base_url: base, + model, + key_action: keyAction, + ...(keyAction === 'replace' ? { api_key: key } : {}), + }) + const apply = (result: AISettings, prefix: string) => { + setSaved(result) + setBase(result.base_url) + setModel(result.model) + setKey('') + setReplace(!result.key_configured) + setTested(null) + setConfirmingDisable(false) + setNotice({ + tone: 'ok', + text: `${prefix}:${result.model || '未设置模型'} · ${verificationLabels[result.verification]}`, + }) + } + const fail = async (reason: unknown) => { + const message = reason instanceof Error ? reason.message : '模型配置操作失败' + if (!(reason instanceof QARequestError) || reason.status !== 409) { + setNotice({ tone: 'error', text: message }) + return } + // 版本冲突:别人已经改过配置,这份草稿的测试结论作废;草稿本身保留,但必须按最新版本重测。 try { - const result = await (test ? testAISettings(input) : saveAISettings(input)) - if (!test) { - setSettings(result) - setKey('') - setKeyAction(result.key_configured ? 'keep' : 'replace') - } - setMessage( - (test ? '连接测试:' : '配置已保存:') + - verificationLabels[result.verification] + - (test ? ';未保存、未启动任务' : ';保存不会启动全量评估') + const fresh = await fetchAISettings() + setSaved(fresh) + setReplace((current) => current || !fresh.key_configured) + setTested(null) + setNotice({ + tone: 'error', + text: `${message};已载入最新已保存配置(版本 ${fresh.revision}),草稿未保存,请重新测试。`, + }) + } catch { + setNotice({ tone: 'error', text: message }) + } + } + const runTest = async () => { + if (!saved || !ready) return + setBusy('testing') + setNotice(null) + setTested(null) + try { + setTested(await testAISettings(input())) + } catch (reason) { + await fail(reason) + } finally { + setBusy('') + } + } + const runSave = async () => { + if (!saved || !ready) return + setBusy('saving') + setNotice(null) + try { + apply(await saveAISettings(input()), '已保存并更新当前连接') + } catch (reason) { + await fail(reason) + } finally { + setBusy('') + } + } + const runDisable = async () => { + if (!saved || busy !== '') return + setBusy('saving') + setNotice(null) + try { + // 只停用已保存连接:地址与模型取服务端当前值,未保存草稿不参与这次提交。 + apply( + await saveAISettings({ + base_revision: saved.revision, + base_url: saved.base_url, + model: saved.model, + key_action: 'clear', + }), + '已清除密钥并停用连接' ) } catch (reason) { - setError(reason instanceof Error ? reason.message : '模型配置操作失败') + await fail(reason) } finally { - setBusy(false) + setBusy('') } } - const ready = - Boolean(settings) && - !busy && - (keyAction !== 'replace' || (secure && Boolean(key) && Boolean(settings?.storage_ready))) return ( -
-

问答评估模型

-

- 四字段分析和中文问题翻译共用此独立配置。保存不会启动全量评估,也不会自动开启新增处理。 -

- {settings ? ( +
+ {saved ? ( <> -

- {verificationLabels[settings.verification]};密钥:{settings.key_configured ? '已配置(不回显)' : '未配置'} - ;自动分析/翻译:{settings.automatic_evaluation ? '开' : '关'} /{' '} - {settings.automatic_translation ? '开' : '关'} -

-
+
+ 当前生效 + + {saved.model ? `${saved.model} · ` : ''} + {verificationLabels[saved.verification]} + + + {saved.base_url || '未设置地址'} + {saved.checked_at ? ` · 最近核验 ${when(saved.checked_at)}` : ''} + +
+
- -
+ OpenAI 兼容基础地址,不含 /chat/completions。 +
+ API 密钥 {configured ? '已配置(不回显)' : '未配置'} + {configured && !keyRequired ? ( + + ) : null} +
+ {keyRequired ? ( +
+ + {configured && replace && !baseChanged ? ( + + ) : null} +
+ ) : null} + {baseChanged && configured ? ( +

已更换基础地址:须重新录入密钥,原密钥不会发往新地址。

+ ) : null} {!secure ? (

当前不是安全密钥录入连接。请使用有效HTTPS或本机 localhost 地址录入新密钥;不会通过失配证书或普通局域网HTTP发送新密钥。

) : null} - {!settings.storage_ready ? ( + {!storageReady ? (

独立安全存储未就绪,请配置服务器的 QA_AI_MASTER_KEY_FILE;不会读取 Hermes 密钥。

) : null} -
- + +
+ ) : configured ? ( + + ) : ( + 当前没有已保存的密钥。 + )} + +
+ - + {dirty ? '有未保存的修改' : '草稿与已保存配置一致'}
+ + {tested ? ( + + 草稿测试:{verificationLabels[tested.verification]};草稿未保存,当前生效配置未改变。 + + ) : null} + {notice ? ( + + {notice.text} + + ) : null} + - ) : !error ? ( -

读取独立模型配置…

+ ) : !loadError ? ( +

正在读取已保存的模型连接…

) : null} - {message ?

{message}

: null} - {error ? ( + {loadError ? (

- {error} + {loadError}

) : null}
diff --git a/web/src/SystemSettings.test.tsx b/web/src/SystemSettings.test.tsx index 5c295c4..aee2cf8 100644 --- a/web/src/SystemSettings.test.tsx +++ b/web/src/SystemSettings.test.tsx @@ -143,7 +143,12 @@ describe('SystemSettingsView AI 模型连接', () => { ) it('keeps the model connection alone in AI 模型连接 and points WeKnora to 知识库映射', () => { const adminHtml = view('admin') - for (const text of ['AI 模型连接', '问答评估模型', 'WeKnora 的知识库连接已移到「知识库映射」']) { + for (const text of [ + 'AI 模型连接', + '正在读取已保存的模型连接', + '问答四字段分析与中文问题翻译共用此连接', + 'WeKnora 的知识库连接已移到「知识库映射」', + ]) { expect(adminHtml).toContain(text) } // 地址类配置已迁走:这里不再出现 WeKnora 连接表单,也不出现旧的“服务配置”分区名。 @@ -152,7 +157,7 @@ describe('SystemSettingsView AI 模型连接', () => { const engineerHtml = view('engineer') expect(engineerHtml).toContain('仅管理员可修改模型连接') // 工程师看不到模型编辑表单(QAModelSettings 只在管理员下挂载)。 - expect(engineerHtml).not.toContain('问答评估模型') + expect(engineerHtml).not.toContain('正在读取已保存的模型连接') }) }) describe('SystemSettingsView', () => { diff --git a/web/src/SystemSettings.tsx b/web/src/SystemSettings.tsx index 81b6587..26648a3 100644 --- a/web/src/SystemSettings.tsx +++ b/web/src/SystemSettings.tsx @@ -208,13 +208,13 @@ export function SystemSettingsView({

AI 模型连接

-

问答四字段分析与中文问题翻译共用的模型服务;WeKnora 的知识库连接已移到「知识库映射」。

+

+ 问答四字段分析与中文问题翻译共用此连接;保存只更新这份连接,不会自动开启自动分析或自动翻译。 + WeKnora 的知识库连接已移到「知识库映射」。 +

{isAdmin ? : 仅管理员可修改模型连接;密钥不回显。} -

- 保存只更新这份模型连接;自动分析与自动翻译仍按问答运营里的任务开关执行,不会因为保存连接自动打开。 -

) : null} {section === 'knowledge-map' ? ( diff --git a/web/src/qaOps.css b/web/src/qaOps.css index 3f6d781..a86b0af 100644 --- a/web/src/qaOps.css +++ b/web/src/qaOps.css @@ -588,13 +588,6 @@ } } -.qa-ai-model-settings { - padding: 14px 0; - border-block: 1px solid var(--border-base); -} -.qa-ai-model-settings h3 { - margin: 0 0 6px; -} .qa-ai-workbench { border: 1px solid var(--border-base); border-radius: 5px; diff --git a/web/src/systemSettings.css b/web/src/systemSettings.css index d343869..48662b5 100644 --- a/web/src/systemSettings.css +++ b/web/src/systemSettings.css @@ -907,3 +907,93 @@ button.link { color: var(--muted-foreground); font-size: 12px; } + +/* AI 模型连接:上方「当前生效」只读服务端已保存值,下方是独立草稿 */ +.qa-ai-model-settings { + display: grid; + gap: 10px; + padding: 12px 0; + border-block: 1px solid var(--border-base); +} +.qa-ai-model-current { + display: grid; + gap: 3px; +} +.qa-ai-model-current > span { + font-size: 13px; +} +.qa-ai-model-current > small { + color: var(--ink-mute); + overflow-wrap: anywhere; +} +.qa-ai-model-fields { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} +.qa-ai-model-fields label, +.qa-ai-model-key-edit label { + display: grid; + gap: 6px; + font-size: 11px; +} +.qa-ai-model-fields input, +.qa-ai-model-key-edit input { + border: 1px solid var(--border-strong); + border-radius: 7px; + padding: 8px; + background: var(--bg-panel); + color: var(--ink-base); + font: inherit; +} +.qa-ai-model-hint, +.qa-ai-model-actions small { + color: var(--ink-mute); +} +.qa-ai-model-key { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + font-size: 12px; +} +.qa-ai-model-key-edit { + display: flex; + align-items: end; + gap: 8px; + flex-wrap: wrap; +} +.qa-ai-model-key-edit label { + flex: 1 1 280px; +} +.qa-ai-model-disable p { + margin: 6px 0; + color: var(--ink-mute); + font-size: 11px; +} +.qa-ai-model-disable-actions { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +.qa-ai-model-actions { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +.qa-ai-model-test { + display: block; + margin-top: 6px; + color: var(--c-run); + font-size: 12px; +} +.qa-ai-model-settings output { + display: block; +} +@media (max-width: 650px) { + .qa-ai-model-fields { + grid-template-columns: 1fr; + } +} From ce2a155ebccc1d4b0b030fb58e27ca6b71b4b274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Thu, 19 Nov 2026 14:43:51 +0800 Subject: [PATCH 02/14] =?UTF-8?q?feat(settings):=20=E7=9F=A5=E8=AF=86?= =?UTF-8?q?=E5=BA=93=E7=BB=91=E5=AE=9A=E6=8C=89=E7=8E=AF=E5=A2=83=E4=B8=80?= =?UTF-8?q?=E6=AC=A1=E4=BF=9D=E5=AD=98=E8=BF=9E=E6=8E=A5=E4=B8=8E=E5=86=85?= =?UTF-8?q?=E5=A4=96=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥, 也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址 与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与 绑定,回读真实生效值。 服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件 凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥 不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储 解析当前连接,避免只保存了页面数据。 验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错; make verify 在本提交上执行(结果见交付说明)。 --- .env.example | 3 + CHANGELOG.md | 26 + api/openapi.yaml | 123 ++++ cmd/api/main.go | 112 +++- cmd/api/readiness.go | 50 +- cmd/api/readiness_test.go | 5 +- cmd/worker/library_role_test.go | 6 +- cmd/worker/main.go | 83 ++- cmd/worker/main_test.go | 8 +- compose.yaml | 3 + docs/OPERATIONS_RUNBOOK.md | 7 +- docs/USER_FLOWS_ACCEPTANCE.md | 27 +- internal/appconfig/config.go | 27 +- internal/httpapi/auth.go | 5 + internal/httpapi/kb_bindings.go | 121 ++++ internal/httpapi/kb_bindings_test.go | 130 ++++ internal/httpapi/openapi_contract_test.go | 2 +- internal/httpapi/production_bindings.go | 6 + internal/httpapi/qa_ai.go | 25 +- internal/httpapi/secret_transport.go | 34 ++ internal/httpapi/server.go | 13 + internal/kbbinding/binding.go | 421 +++++++++++++ internal/kbbinding/binding_test.go | 129 ++++ internal/kbbinding/save_integration_test.go | 179 ++++++ internal/kbbinding/store.go | 274 +++++++++ internal/monitoring/real.go | 2 +- ...0081_weknora_environment_bindings.down.sql | 3 + ...000081_weknora_environment_bindings.up.sql | 36 ++ internal/platform/postgres/migrations_test.go | 11 +- .../platform/postgres/production_bindings.go | 16 +- .../platform/postgres/routing_bindings.go | 29 +- internal/platform/weknora/client.go | 25 + internal/platform/weknora/types.go | 17 +- internal/qaopsai/secrets.go | 53 +- internal/readiness/weknora.go | 30 +- internal/secretbox/secretbox.go | 66 ++ scripts/test-scope.json | 5 + web/src/App.test.tsx | 2 +- web/src/App.tsx | 2 +- web/src/KnowledgeBaseBinding.test.tsx | 213 +++++++ web/src/KnowledgeBaseBinding.tsx | 570 ++++++++++++++++++ web/src/ProductionBindingsSection.tsx | 9 +- web/src/QAModelSettings.tsx | 6 +- web/src/RoutingBindingsSection.tsx | 6 +- web/src/SystemSettings.test.tsx | 39 +- web/src/SystemSettings.tsx | 66 +- web/src/WeKnoraConnections.mounted.test.tsx | 130 ---- web/src/WeKnoraConnections.tsx | 242 -------- web/src/knowledgeBaseBindings.test.ts | 70 +++ web/src/knowledgeBaseBindings.ts | 225 +++++++ web/src/secureEntry.ts | 5 + web/src/systemSettings.css | 170 ++++++ web/src/weKnoraDiagnostics.tsx | 101 ++++ 53 files changed, 3367 insertions(+), 601 deletions(-) create mode 100644 internal/httpapi/kb_bindings.go create mode 100644 internal/httpapi/kb_bindings_test.go create mode 100644 internal/httpapi/secret_transport.go create mode 100644 internal/kbbinding/binding.go create mode 100644 internal/kbbinding/binding_test.go create mode 100644 internal/kbbinding/save_integration_test.go create mode 100644 internal/kbbinding/store.go create mode 100644 internal/platform/postgres/migrations/000081_weknora_environment_bindings.down.sql create mode 100644 internal/platform/postgres/migrations/000081_weknora_environment_bindings.up.sql create mode 100644 internal/secretbox/secretbox.go create mode 100644 web/src/KnowledgeBaseBinding.test.tsx create mode 100644 web/src/KnowledgeBaseBinding.tsx delete mode 100644 web/src/WeKnoraConnections.mounted.test.tsx delete mode 100644 web/src/WeKnoraConnections.tsx create mode 100644 web/src/knowledgeBaseBindings.test.ts create mode 100644 web/src/knowledgeBaseBindings.ts create mode 100644 web/src/secureEntry.ts create mode 100644 web/src/weKnoraDiagnostics.tsx diff --git a/.env.example b/.env.example index 57b9c36..0afb8f7 100644 --- a/.env.example +++ b/.env.example @@ -24,6 +24,9 @@ DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT=20m # Independent governance AI: endpoint/model/write-only API key are stored via the admin page. # Mount the same 32-byte regular 0600 master-key file into API and ordinary worker. QA_AI_MASTER_KEY_FILE= +# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。 +# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。 +WEKNORA_BINDING_MASTER_KEY_FILE= # Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only. QA_AI_DNS_OVER_TLS= # Only opt in behind an already trusted TLS-terminating same-origin reverse proxy. diff --git a/CHANGELOG.md b/CHANGELOG.md index 21892a8..2102213 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## 开发快照 0.1.402(知识库绑定:按环境一次保存连接与内外库) + +### Added + +- 「系统设置 → 知识库绑定」:测试 090 / 生产 090 分环境工作区,同一时间只编辑一个环境;顶部只读显示当前生效的对内/对外库。 +- 草稿可填写本环境服务地址与 API Key;「验证并读取知识库」由服务器真实列库(分页),明确区分可读、空库、无权限、不可达。 +- 列表按「名称 + 短 ID」区分同名库;对内与对外选同一个库会被拒绝。一次保存同时写入连接与内外绑定,并回读真实生效值。 +- 新增 `GET /api/v1/kb-bindings`、`POST /api/v1/kb-bindings/{environment}/catalog`、`PUT /api/v1/kb-bindings/{environment}`;读写分离,写仅管理员。 +- 迁移 000081:`weknora_environment_bindings` 与修订历史;密钥只存 AES-256-GCM 密文,主密钥来自独立 `WEKNORA_BINDING_MASTER_KEY_FILE`。 +- 保存会校验所选库属于候选实例(同一地址与密钥读取),并在同一事务内镜像测试路由/生产文档级绑定;测试环境同时重排未上传的待入库项并回报数量。 + +### Changed + +- 原「知识库映射 → WeKnora 连接」入口并入「知识库绑定」;探活、封存源、整库发布目标与旧文档级目标收进折叠诊断,保留入口但不再提供第二个保存路径。 +- 消费者(readiness、上传/轮询、列库、监控探活、生产列库)统一从加密存储解析当前连接;没有新行时继续使用旧部署的文件凭据与默认绑定。 +- 整库发布实际目标仍只读,并明确由部署配置决定;本页保存不触发生产写入、导入、发布或停服。 + +### Security + +- API Key 不回显、不写日志/URL/浏览器存储;更换地址必须重新录入密钥,旧密钥不会转发到新地址,也不会跨环境取用。 +- 保存使用修订号与行锁:并发或失败时旧绑定保持不变,未保存草稿不影响当前生效值。 + +### Fixed + +- 生产 WeKnora 健康探活改为跟随当前有效端点(原实现绕过 resolver,改地址后仍探旧值)。 + ## 开发快照 0.1.401(AI 模型连接:当前生效 + 独立草稿) ### Changed diff --git a/api/openapi.yaml b/api/openapi.yaml index 009e603..8a0f990 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -3707,6 +3707,61 @@ } } }, + "/api/v1/kb-bindings": { + "get": { + "tags": ["Settings"], + "operationId": "getKBBindings", + "summary": "读取测试/生产环境的 WeKnora 连接与内外库绑定(密钥不回显)", + "responses": { + "200": {"$ref": "#/components/responses/Envelope"}, + "400": {"$ref": "#/components/responses/BadRequest"}, + "500": {"$ref": "#/components/responses/InternalError"}, + "503": {"$ref": "#/components/responses/ServiceUnavailable"} + } + } + }, + "/api/v1/kb-bindings/{environment}/catalog": { + "post": { + "tags": ["Settings"], + "operationId": "catalogKBBindingConnection", + "summary": "用草稿地址与密钥真实列库(管理员,只读,分页)", + "parameters": [ + {"name": "environment", "in": "path", "required": true, "schema": {"type": "string", "enum": ["test", "production"]}} + ], + "requestBody": { + "required": true, + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/KBCatalogInput"}}} + }, + "responses": { + "200": {"$ref": "#/components/responses/Envelope"}, + "400": {"$ref": "#/components/responses/BadRequest"}, + "409": {"$ref": "#/components/responses/Conflict"}, + "500": {"$ref": "#/components/responses/InternalError"}, + "503": {"$ref": "#/components/responses/ServiceUnavailable"} + } + } + }, + "/api/v1/kb-bindings/{environment}": { + "put": { + "tags": ["Settings"], + "operationId": "saveKBBinding", + "summary": "一次保存当前环境的连接与内外库绑定(管理员)", + "parameters": [ + {"name": "environment", "in": "path", "required": true, "schema": {"type": "string", "enum": ["test", "production"]}} + ], + "requestBody": { + "required": true, + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/KBBindingSaveInput"}}} + }, + "responses": { + "200": {"$ref": "#/components/responses/Envelope"}, + "400": {"$ref": "#/components/responses/BadRequest"}, + "409": {"$ref": "#/components/responses/Conflict"}, + "500": {"$ref": "#/components/responses/InternalError"}, + "503": {"$ref": "#/components/responses/ServiceUnavailable"} + } + } + }, "/api/v1/production-kb-bindings": { "get": { "tags": [ @@ -6084,6 +6139,74 @@ } }, "schemas": { + "KBBindingEnvironmentView": { + "type": "object", + "additionalProperties": false, + "required": ["environment", "revision", "base_url", "key_configured", "internal_kb_id", "external_kb_id", "verification", "storage_ready", "source"], + "properties": { + "environment": {"type": "string", "enum": ["test", "production"]}, + "revision": {"type": "integer", "minimum": 0}, + "base_url": {"type": "string"}, + "key_configured": {"type": "boolean"}, + "key_source": {"type": "string", "enum": ["sealed", "file", "none"]}, + "internal_kb_id": {"type": "string"}, + "internal_kb_name": {"type": "string"}, + "external_kb_id": {"type": "string"}, + "external_kb_name": {"type": "string"}, + "verification": {"type": "string"}, + "checked_at": {"type": ["string", "null"]}, + "updated_by": {"type": "string"}, + "updated_at": {"type": ["string", "null"]}, + "source": {"type": "string", "enum": ["web", "legacy"]}, + "storage_ready": {"type": "boolean"}, + "replanned": {"type": "integer", "minimum": 0}, + "retired_duplicates": {"type": "integer", "minimum": 0} + } + }, + "KBBindingSnapshot": { + "type": "object", + "additionalProperties": false, + "required": ["environments", "storage_ready"], + "properties": { + "environments": {"type": "array", "items": {"$ref": "#/components/schemas/KBBindingEnvironmentView"}}, + "storage_ready": {"type": "boolean"} + } + }, + "KBCatalogInput": { + "type": "object", + "additionalProperties": false, + "required": ["base_url", "key_action", "page", "page_size"], + "properties": { + "base_revision": {"type": "integer", "minimum": 0}, + "base_url": {"type": "string"}, + "key_action": {"type": "string", "enum": ["keep", "replace"]}, + "api_key": {"type": "string", "writeOnly": true, "maxLength": 4096}, + "page": {"type": "integer", "minimum": 1}, + "page_size": {"type": "integer", "minimum": 1, "maximum": 100} + } + }, + "KBBindingSaveInput": { + "type": "object", + "additionalProperties": false, + "required": ["base_url", "key_action", "internal_kb_id", "external_kb_id"], + "properties": { + "base_revision": {"type": "integer", "minimum": 0}, + "base_url": {"type": "string"}, + "key_action": {"type": "string", "enum": ["keep", "replace"]}, + "api_key": {"type": "string", "writeOnly": true, "maxLength": 4096}, + "internal_kb_id": {"type": "string"}, + "external_kb_id": {"type": "string"} + } + }, + "KBCatalogOption": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "knowledge_count": {"type": "integer"} + } + }, "PPConnectionDraft": { "type": "object", "required": [ diff --git a/cmd/api/main.go b/cmd/api/main.go index e41b7f8..35a9fe8 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -8,6 +8,7 @@ import ( "net/http" "os" "os/signal" + "strings" "syscall" "time" @@ -17,6 +18,7 @@ import ( "knowledge-governance/internal/backuphost" "knowledge-governance/internal/dingtalkdiscovery" "knowledge-governance/internal/httpapi" + "knowledge-governance/internal/kbbinding" "knowledge-governance/internal/libraryhandoff" "knowledge-governance/internal/monitoring" postgresstore "knowledge-governance/internal/platform/postgres" @@ -98,36 +100,81 @@ func run(ctx context.Context, getenv func(string) string) error { // 这里的真源;容器 env 只作为未在网页配置时的兜底。凭据与发布目标仍留在 // release 运行时配置(RELEASE_CONFIG_FILE)里,不经网页也不落明文。 actionStore := postgresstore.NewStore(pool) - productionEndpointResolver := func(resolveCtx context.Context) string { - settings, err := actionStore.GetActiveUISettings(resolveCtx) - if err != nil { - return "" - } - return settings.ProductionWeKnoraBaseURL - } - testEndpointResolver := func(resolveCtx context.Context) string { - settings, err := actionStore.GetActiveUISettings(resolveCtx) - if err != nil { - return "" - } - return settings.TestWeKnoraBaseURL - } - // P10 readiness 与执行链看同一目标:网页保存的端点、当前持久化绑定、同一份 - // API Key。启动时只捕获 resolver,不捕获任何一项的值(F13:旧 env 绑定 404)。 - readinessResolver := newWeKnoraReadinessResolver( - func(resolveCtx context.Context) string { - if saved := testEndpointResolver(resolveCtx); saved != "" { - return saved + kbBindings := kbbinding.New(pool, kbbinding.Options{ + MasterKeyFile: config.WeKnoraBindingMasterKeyFile, + Timeout: 10 * time.Second, + AllowDockerHTTP: map[string]bool{ + kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP, + kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP, + }, + LegacyBaseURL: func(resolveCtx context.Context, env string) string { + settings, err := actionStore.GetActiveUISettings(resolveCtx) + if err != nil { + return "" + } + if env == kbbinding.EnvProduction { + if value := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); value != "" { + return value + } + return config.ProductionWeKnoraBaseURL + } + if value := strings.TrimSpace(settings.TestWeKnoraBaseURL); value != "" { + return value } return config.TestWeKnoraBaseURL }, - config.InternalRoutingKnowledgeBaseID, - func(resolveCtx context.Context) (string, error) { - internal, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx) - return internal, err + LegacyKey: func(env string) (string, error) { + path := config.TestWeKnoraAPIKeyFile + if env == kbbinding.EnvProduction { + path = config.ProductionWeKnoraAPIKeyFile + } + if strings.TrimSpace(path) == "" { + return "", nil + } + return weknora.ReadAPIKeyFile(path) }, - func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) }, - ) + LegacyBinding: func(resolveCtx context.Context, env string) (string, string, error) { + if env == kbbinding.EnvProduction { + internal, external, _, err := actionStore.LoadProductionKBBindings(resolveCtx) + return internal, external, err + } + internal, external, _, err := actionStore.LoadRoutingKBBindings(resolveCtx) + if internal == "" { + internal = config.InternalRoutingKnowledgeBaseID + } + if external == "" { + external = config.ExternalRoutingKnowledgeBaseID + } + return internal, external, err + }, + RoutingDefaults: func() (string, string) { + return config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID + }, + }) + productionEndpointResolver := func(resolveCtx context.Context) string { + return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvProduction) + } + testEndpointResolver := func(resolveCtx context.Context) string { + return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvTest) + } + // P10 readiness 与执行链看同一目标:当前持久化绑定、当前有效连接(加密存储优先、 + // 旧部署 file 凭据兜底)。任何一项读取失败都必须显式报错,不能静默退回旧值。 + readinessResolver := func(resolveCtx context.Context) (readiness.Target, error) { + target := readiness.Target{KnowledgeBaseID: config.InternalRoutingKnowledgeBaseID} + stored, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx) + if err != nil { + return readiness.Target{}, fmt.Errorf("读取当前知识库绑定失败") + } + if strings.TrimSpace(stored) != "" { + target.KnowledgeBaseID = strings.TrimSpace(stored) + } + connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest) + if err != nil { + return readiness.Target{}, fmt.Errorf("读取 WeKnora 有效连接失败:%w", err) + } + target.BaseURL, target.APIKey = connection.BaseURL, connection.APIKey + return target, nil + } readinessProber := readiness.Prober{ Resolve: readinessResolver, Timeout: config.TestWeKnoraHTTPTimeout, @@ -138,13 +185,10 @@ func run(ctx context.Context, getenv func(string) string) error { return result.Target, result.Err } knowledgeBaseLister := &weKnoraLister{ - endpoint: func(resolveCtx context.Context) string { - if saved := testEndpointResolver(resolveCtx); saved != "" { - return saved - } - return config.TestWeKnoraBaseURL + resolve: func(resolveCtx context.Context) (string, string, error) { + connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest) + return connection.BaseURL, connection.APIKey, err }, - readKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) }, timeout: config.TestWeKnoraHTTPTimeout, allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP, } @@ -160,6 +204,7 @@ func run(ctx context.Context, getenv func(string) string) error { TestAllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP, ProductionAllowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP, }) + productionKnowledgeBases := &productionKnowledgeBaseLister{bindings: kbBindings, timeout: 10 * time.Second, allowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP} // 「版本记录」:只读查询面在 API 侧接线;真正的抓取在 worker 侧(未配置来源即未接线)。 versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), "" if config.VersionHistoryGiteaBaseURL != "" { @@ -227,7 +272,8 @@ func run(ctx context.Context, getenv func(string) string) error { RoutingBindings: postgresstore.NewStore(pool), KnowledgeBases: knowledgeBaseLister, ProductionBindings: postgresstore.NewStore(pool), - ProductionKnowledgeBases: serviceTargetVerifier, + ProductionKnowledgeBases: productionKnowledgeBases, + KBBindings: kbBindings, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ServiceTargetVerifier: serviceTargetVerifier, ProductionReleaseRequestsEnabled: config.ProductionReleaseRequestsEnabled, diff --git a/cmd/api/readiness.go b/cmd/api/readiness.go index 42abb29..854b0a9 100644 --- a/cmd/api/readiness.go +++ b/cmd/api/readiness.go @@ -7,6 +7,7 @@ import ( "strings" "time" + "knowledge-governance/internal/kbbinding" "knowledge-governance/internal/platform/weknora" "knowledge-governance/internal/readiness" ) @@ -51,23 +52,25 @@ func newWeKnoraReadinessResolver( // weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据, // 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。 type weKnoraLister struct { - endpoint func(context.Context) string - readKey func() (string, error) + resolve func(context.Context) (baseURL, apiKey string, err error) timeout time.Duration allowDockerHTTP bool } func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) { - baseURL := "" - if lister.endpoint != nil { - baseURL = strings.TrimSpace(lister.endpoint(ctx)) + if lister.resolve == nil { + return nil, fmt.Errorf("WeKnora 端点未配置") } + baseURL, apiKey, err := lister.resolve(ctx) + if err != nil { + return nil, err + } + baseURL = strings.TrimSpace(baseURL) if baseURL == "" { return nil, fmt.Errorf("WeKnora 端点未配置") } - apiKey, err := lister.readKey() - if err != nil { - return nil, err + if strings.TrimSpace(apiKey) == "" { + return nil, fmt.Errorf("WeKnora API Key 未配置") } timeout := lister.timeout if timeout <= 0 || timeout > 10*time.Second { @@ -79,3 +82,34 @@ func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora. } return client.ListKnowledgeBases(ctx) } + +// productionKnowledgeBaseLister 列生产端知识库时使用「生产环境」保存的连接 +// (加密密钥),而不是另一条文件凭据。显式传入的地址必须与已保存连接一致, +// 防止把生产密钥发往另一个地址。 +type productionKnowledgeBaseLister struct { + bindings *kbbinding.Store + timeout time.Duration + allowDockerHTTP bool +} + +func (lister *productionKnowledgeBaseLister) ListProductionKnowledgeBases(ctx context.Context, baseURL string) ([]weknora.KnowledgeBase, error) { + if lister.bindings == nil { + return nil, fmt.Errorf("生产知识库连接存储未接线") + } + target, err := lister.bindings.Resolve(ctx, kbbinding.EnvProduction) + if err != nil { + return nil, err + } + if explicit := strings.TrimSpace(baseURL); explicit != "" && explicit != target.BaseURL { + return nil, fmt.Errorf("生产地址与已保存的连接不一致:请在生产工作区重新保存连接") + } + timeout := lister.timeout + if timeout <= 0 || timeout > 10*time.Second { + timeout = 10 * time.Second + } + client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: target.BaseURL, APIKey: target.APIKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP}) + if err != nil { + return nil, err + } + return client.ListKnowledgeBases(ctx) +} diff --git a/cmd/api/readiness_test.go b/cmd/api/readiness_test.go index 8a9f1c4..a051b51 100644 --- a/cmd/api/readiness_test.go +++ b/cmd/api/readiness_test.go @@ -96,9 +96,8 @@ func TestKnowledgeBaseListerFollowsTheCurrentEndpoint(t *testing.T) { defer second.Close() endpoint := first.URL lister := &weKnoraLister{ - endpoint: func(context.Context) string { return endpoint }, - readKey: func() (string, error) { return "key-1", nil }, - timeout: time.Second, + resolve: func(context.Context) (string, string, error) { return endpoint, "key-1", nil }, + timeout: time.Second, } bases, err := lister.ListKnowledgeBases(context.Background()) if err != nil || len(bases) != 1 || bases[0].ID != "kb-a" { diff --git a/cmd/worker/library_role_test.go b/cmd/worker/library_role_test.go index 16841bc..60eca33 100644 --- a/cmd/worker/library_role_test.go +++ b/cmd/worker/library_role_test.go @@ -55,7 +55,7 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) { VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance", VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"}, } - handlers, err := workerHandlers(postgresstore.NewStore(nil), release) + handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil) if err != nil { t.Fatalf("release-executor workerHandlers() error = %v", err) } @@ -74,12 +74,12 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) { TestWeKnoraEnabled: true, TestWeKnoraAPIKeyFile: "/nonexistent/api-key", } - if _, err := workerHandlers(nil, capture); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") { + if _, err := workerHandlers(nil, capture, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") { t.Fatalf("capture role must reach the test WeKnora wiring, got %v", err) } capture.TestWeKnoraEnabled = false capture.PPScanEnabled = false - handlers, err = workerHandlers(postgresstore.NewStore(nil), capture) + handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil) if err != nil { t.Fatalf("capture workerHandlers() error = %v", err) } diff --git a/cmd/worker/main.go b/cmd/worker/main.go index feeb1a4..69f4900 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -19,6 +19,7 @@ import ( "knowledge-governance/internal/appconfig" "knowledge-governance/internal/governance" "knowledge-governance/internal/jobs" + "knowledge-governance/internal/kbbinding" "knowledge-governance/internal/libraryagent" "knowledge-governance/internal/libraryhandoff" "knowledge-governance/internal/libraryrelease" @@ -173,6 +174,57 @@ func run(ctx context.Context, getenv func(string) string) error { } store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID). WithRestoreDispatchEvidence(config.LibraryTargetJournalRoot) + kbBindings := kbbinding.New(pool, kbbinding.Options{ + MasterKeyFile: config.WeKnoraBindingMasterKeyFile, + Timeout: 10 * time.Second, + AllowDockerHTTP: map[string]bool{ + kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP, + kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP, + }, + LegacyBaseURL: func(resolveCtx context.Context, env string) string { + settings, err := store.GetActiveUISettings(resolveCtx) + if err != nil { + return "" + } + if env == kbbinding.EnvProduction { + if value := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); value != "" { + return value + } + return config.ProductionWeKnoraBaseURL + } + if value := strings.TrimSpace(settings.TestWeKnoraBaseURL); value != "" { + return value + } + return config.TestWeKnoraBaseURL + }, + LegacyKey: func(env string) (string, error) { + path := config.TestWeKnoraAPIKeyFile + if env == kbbinding.EnvProduction { + path = config.ProductionWeKnoraAPIKeyFile + } + if strings.TrimSpace(path) == "" { + return "", nil + } + return weknora.ReadAPIKeyFile(path) + }, + LegacyBinding: func(resolveCtx context.Context, env string) (string, string, error) { + if env == kbbinding.EnvProduction { + internal, external, _, err := store.LoadProductionKBBindings(resolveCtx) + return internal, external, err + } + internal, external, _, err := store.LoadRoutingKBBindings(resolveCtx) + if internal == "" { + internal = config.InternalRoutingKnowledgeBaseID + } + if external == "" { + external = config.ExternalRoutingKnowledgeBaseID + } + return internal, external, err + }, + RoutingDefaults: func() (string, string) { + return config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID + }, + }) log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity()) // 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败: // 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。 @@ -211,7 +263,7 @@ func run(ctx context.Context, getenv func(string) string) error { } else if repaired > 0 { log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired) } - handlers, err := workerHandlers(store, config) + handlers, err := workerHandlers(store, config, kbBindings) if err != nil { return err } @@ -324,7 +376,7 @@ func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersiste return nil } -func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[string]jobs.Handler, error) { +func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store) (map[string]jobs.Handler, error) { handlers := map[string]jobs.Handler{ "demo": func(_ context.Context, job jobs.Job) error { log.Printf("completed demo job id=%s", job.ID) @@ -526,24 +578,27 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() { return handlers, nil } - // 启动只验证凭据“存在”(缺失像以前一样拒绝启动);具体值仍由 resolver 每次调用重读。 - if _, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); err != nil { - return nil, fmt.Errorf("read test WeKnora API key: %w", err) + // 启动只验证“有一条可用凭据”:旧部署是文件,新部署可以是加密存储里的连接。 + // 两者都没有时不再静默启动,仍像以前一样拒绝;具体值由 resolver 每次重读。 + storageReady := kbBindings != nil && kbBindings.StorageReady() + if _, fileErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); fileErr != nil && !storageReady { + return nil, fmt.Errorf("read test WeKnora API key: %w", fileErr) } - // 与 API 探测共用同一有效目标:网页保存的端点优先、env 只作未配置兜底; - // 当前持久化绑定优先、env 兜底;凭据每次调用重读同一 key 文件。 + // 与 API 探测共用同一有效目标:加密存储里的连接优先、旧部署文件/端点兜底; + // 当前持久化绑定优先、env 兜底。 remoteResolver := readiness.Resolver{ - Endpoint: func(resolveCtx context.Context) string { - if settings, settingsErr := store.GetActiveUISettings(resolveCtx); settingsErr == nil && strings.TrimSpace(settings.TestWeKnoraBaseURL) != "" { - return settings.TestWeKnoraBaseURL - } - return config.TestWeKnoraBaseURL - }, LoadBinding: func(resolveCtx context.Context) (string, error) { internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx) return internal, bindingErr }, - ReadKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) }, + ResolveConnection: func(resolveCtx context.Context) (string, string, error) { + if kbBindings == nil { + key, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) + return config.TestWeKnoraBaseURL, key, err + } + target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest) + return target.BaseURL, target.APIKey, resolveErr + }, DefaultKB: config.InternalRoutingKnowledgeBaseID, } client := &weknoraaccess.Client{Resolver: remoteResolver, Timeout: config.TestWeKnoraHTTPTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP} diff --git a/cmd/worker/main_test.go b/cmd/worker/main_test.go index d753ef9..ccc3917 100644 --- a/cmd/worker/main_test.go +++ b/cmd/worker/main_test.go @@ -20,7 +20,7 @@ func TestRunRequiresDatabaseURL(t *testing.T) { } func TestWorkerHandlersExcludeReleaseAndTestJobsByDefault(t *testing.T) { - handlers, err := workerHandlers(nil, appconfig.Config{}) + handlers, err := workerHandlers(nil, appconfig.Config{}, nil) if err != nil { t.Fatalf("workerHandlers() error = %v", err) } @@ -46,7 +46,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) { PPScanLedgerPath: filepath.Join(root, "state.jsonl"), PPScanManifestPath: filepath.Join(root, "manifest.json"), } - handlers, err := workerHandlers(postgresstore.NewStore(nil), config) + handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil) if err != nil { t.Fatalf("workerHandlers() error = %v", err) } @@ -57,7 +57,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) { func TestWorkerHandlersRequireAPIKeyWhenTestWeKnoraEnabled(t *testing.T) { config := appconfig.Config{TestWeKnoraEnabled: true, TestWeKnoraAPIKeyFile: "/nonexistent/api-key"} - _, err := workerHandlers(nil, config) + _, err := workerHandlers(nil, config, nil) if err == nil || !strings.Contains(err.Error(), "read test WeKnora API key") { t.Fatalf("workerHandlers() error = %v", err) } @@ -80,7 +80,7 @@ func TestWorkerHandlersRegisterTestJobsForExplicitDockerHTTP(t *testing.T) { TestWeKnoraMaxUploadBytes: 1024, TestAcceptancePolicyVersion: "structural-v1", } - handlers, err := workerHandlers(postgresstore.NewStore(nil), config) + handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil) if err != nil { t.Fatalf("workerHandlers() error = %v", err) } diff --git a/compose.yaml b/compose.yaml index 151eb69..dc853c7 100644 --- a/compose.yaml +++ b/compose.yaml @@ -57,6 +57,9 @@ services: LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}" # Mount this independent master-key file read-only using the deployment overlay. QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}" + # 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。 + # 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。 + WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}" QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}" QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}" # P10 readiness probe reads the routing KB with the same scoped key. diff --git a/docs/OPERATIONS_RUNBOOK.md b/docs/OPERATIONS_RUNBOOK.md index 6187b1d..42f093d 100644 --- a/docs/OPERATIONS_RUNBOOK.md +++ b/docs/OPERATIONS_RUNBOOK.md @@ -10,7 +10,7 @@ ## 0. 开工前:环境与凭据自检 | 项 | 怎么做 | 成功标志 | |---|---|---| -| 测试/生产 WeKnora | 系统设置 → 知识库映射 → WeKnora 连接 | 生产端"已启用 · 可提交生产请求";测试端探测正常 | +| 测试/生产 WeKnora | 系统设置 → 知识库绑定(选择测试 090 / 生产 090) | 生产端"已启用 · 可提交生产请求";测试端探测正常 | | 钉钉取件凭据 **【新】** | 容器内 `HOME=/data/home dws auth status --readonly -f json` | `authenticated:true`、`refresh_token_valid:true`(**必须带 `HOME=/data/home`,否则误报未登录**) | | 备份主机接线 | 系统设置 → 存储与备份 | "目标主机 weknora-test · 已连接" | @@ -80,9 +80,8 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 + | 分区 | 谁 | 现在要管什么 | |---|---|---| -| 知识库映射 → WeKnora 连接 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) | -| 测试知识库绑定 | 管理员 | 标注往哪个测试库路由(对内 ≠ 对外) | -| 生产知识库绑定 | 管理员 | 源库 → 目标库映射(发布写哪个生产库) | +| 知识库绑定(测试 090 / 生产 090) | 管理员 | 每个环境:服务地址 + API Key(服务器真实列库)→ 选对外/对内库 → 一次保存;密钥不回显,换地址须重录 | +| 绑定诊断(折叠) | 管理员 | 探活、封存源对照、整库发布目标(只读,由部署配置决定)与旧文档级目标 | | **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" | | 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) | | 成员与角色 | 管理员 | 成员与 viewer/engineer/admin | diff --git a/docs/USER_FLOWS_ACCEPTANCE.md b/docs/USER_FLOWS_ACCEPTANCE.md index 902038c..9ad2fcd 100644 --- a/docs/USER_FLOWS_ACCEPTANCE.md +++ b/docs/USER_FLOWS_ACCEPTANCE.md @@ -255,20 +255,23 @@ ## D. 系统设置 -### D1 知识库映射 → WeKnora 连接(测试 / 生产端点与 ID) -- 入口:**系统设置 → 知识库映射 → WeKnora 连接**(管理员) -- 规则:只配四项(测试地址、生产地址、生产 ID、知识库 ID);**保存时真探测**,无效才拒;凭据只写不读 -- 状态:✅(见 `P41/P42` 与 `ui_settings_*` 测试) +### D1 知识库绑定(测试 090 / 生产 090:连接 + 内外库) +- 入口:**系统设置 → 知识库绑定**(管理员;普通用户只读) +- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库)→ **保存该环境绑定** +- 期望:一次保存同时生效连接与内外绑定;顶部「当前生效」回读服务器真实值;失败保留旧绑定,未保存草稿不影响当前值;切换环境时迟到的列库响应不串库 +- 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE` +- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx` +- 状态:✅ 本地验证(未做业务验收) -### D2 测试知识库绑定(对内 / 对外) -- 入口:**系统设置 → 测试知识库绑定** → 选库 → 保存绑定 -- 期望:保存立即生效并重排"还没上传"的待入库项;对内 ≠ 对外 -- 状态:✅ 本期实测 +### D2 测试知识库绑定(折叠诊断;主入口已并入 D1) +- 入口:**系统设置 → 知识库绑定 → 连接与绑定诊断** +- 期望:保留入库目标/封存源一致性对照与重新读取;不再提供第二个保存入口(保存统一走 D1) +- 状态:✅ 诊断展示保留 -### D3 生产知识库绑定(源库 → 目标库) -- 入口:**系统设置 → 生产知识库绑定** → 对内/对外各选一个生产库 -- 期望:发布写入被冻结到该项的 `target_knowledge_base_id`;未绑定时按同 ID 语义并在契约检查处失败关闭 -- 状态:✅(`P8_PRODUCTION_KB_MAPPING_ACCEPTANCE.md`;迁移 000044) +### D3 生产知识库绑定(折叠诊断;整库目标只读) +- 入口:**系统设置 → 知识库绑定 → 连接与绑定诊断** +- 期望:整库发布实际目标来自部署配置、只读;生产 090 工作区的 D1 保存只写文档级语义(源库 → 目标库),不触发整库发布或生产写入 +- 状态:✅ 诊断展示保留(`P8_PRODUCTION_KB_MAPPING_ACCEPTANCE.md`;迁移 000044) ### D4 存储与备份(整库逻辑备份的定时)★本期新增 - 入口:**系统设置 → 存储与备份**(管理员) diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go index 990fbb6..65e8337 100644 --- a/internal/appconfig/config.go +++ b/internal/appconfig/config.go @@ -47,16 +47,19 @@ type Config struct { InternalRoutingKnowledgeBaseID string ExternalRoutingKnowledgeBaseID string TestWeKnoraAPIKeyFile string - GovernanceSpoolRoot string - IngestionSpoolRoot string - ArtifactFetchMaxBytes int64 - WorkerLivenessStaleAfter time.Duration - TestWeKnoraHTTPTimeout time.Duration - TestWeKnoraPollInitial time.Duration - TestWeKnoraPollMax time.Duration - TestWeKnoraStalledAfter time.Duration - TestWeKnoraMaxUploadBytes int64 - TestAcceptancePolicyVersion string + // WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。 + // 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。 + WeKnoraBindingMasterKeyFile string + GovernanceSpoolRoot string + IngestionSpoolRoot string + ArtifactFetchMaxBytes int64 + WorkerLivenessStaleAfter time.Duration + TestWeKnoraHTTPTimeout time.Duration + TestWeKnoraPollInitial time.Duration + TestWeKnoraPollMax time.Duration + TestWeKnoraStalledAfter time.Duration + TestWeKnoraMaxUploadBytes int64 + TestAcceptancePolicyVersion string // TestAutoReviewPolicy:验收通过后是否自动批准(off|internal|all;默认 internal)。 TestAutoReviewPolicy string // 目标库所在主机(整库逻辑备份真正执行的地方)。凭据是挂载进来的 0600 ssh @@ -203,6 +206,7 @@ func Load(getenv func(string) string) (Config, error) { InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")), ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")), TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"), + WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")), GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"), IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")), ArtifactFetchMaxBytes: 200 * 1024 * 1024, @@ -344,6 +348,9 @@ func Load(getenv func(string) string) (Config, error) { return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE must be an absolute path") } } + if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) { + return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path") + } if raw := getenv("PP_SCAN_ENABLED"); raw != "" { config.PPScanEnabled, err = strconv.ParseBool(raw) if err != nil { diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go index a94541b..6222ff8 100644 --- a/internal/httpapi/auth.go +++ b/internal/httpapi/auth.go @@ -141,6 +141,11 @@ func classifyRole(method, path string) string { if path == "/api/v1/routing-bindings" && method != http.MethodGet { return roleAdmin } + // 「知识库绑定」saves a connection (address + key) and both bindings for one + // environment in one write: same authority as the annotation binding. + if strings.HasPrefix(path, "/api/v1/kb-bindings") && method != http.MethodGet { + return roleAdmin + } // Choosing the production base a release writes into is a production // authority change, exactly like the annotation binding above. if path == "/api/v1/production-kb-bindings" && method != http.MethodGet { diff --git a/internal/httpapi/kb_bindings.go b/internal/httpapi/kb_bindings.go new file mode 100644 index 0000000..d16160b --- /dev/null +++ b/internal/httpapi/kb_bindings.go @@ -0,0 +1,121 @@ +package httpapi + +import ( + "context" + "errors" + "net/http" + "strings" + "time" + + "knowledge-governance/internal/kbbinding" +) + +// KBBindingStore is the environment-scoped 「知识库绑定」capability. Save does +// the real candidate read itself, so the HTTP layer decides no policy beyond +// status/role. +type KBBindingStore interface { + List(context.Context) ([]kbbinding.View, error) + Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error) + Save(context.Context, string, kbbinding.SaveInput, string, time.Time) (kbbinding.View, error) + ResolveBaseURL(context.Context, string) string +} + +func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) { + if config.KBBindings == nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"}) + return + } + views, err := config.KBBindings.List(r.Context()) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load knowledge base bindings"}) + return + } + storageReady := false + for _, view := range views { + storageReady = storageReady || view.StorageReady + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}}) +} + +func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) { + if config.KBBindings == nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"}) + return + } + if r.Header.Get("X-Governance-Action") != "kb-bindings" { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"}) + return + } + env := r.PathValue("environment") + if !kbbinding.ValidEnvironment(env) { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"}) + return + } + var input kbbinding.CatalogInput + if err := decodeJSONStrict(r, &input); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"}) + return + } + if input.APIKey != "" && !secretTransportAllowed(r, config.QAAITrustTLSProxy) { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"}) + return + } + catalog, err := config.KBBindings.Catalog(r.Context(), env, input) + if err != nil { + writeKBBindingError(w, err) + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": catalog}) +} + +func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request) { + if config.KBBindings == nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"}) + return + } + if r.Header.Get("X-Governance-Action") != "kb-bindings" { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"}) + return + } + env := r.PathValue("environment") + if !kbbinding.ValidEnvironment(env) { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"}) + return + } + var input kbbinding.SaveInput + if err := decodeJSONStrict(r, &input); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"}) + return + } + if input.APIKey != "" && !secretTransportAllowed(r, config.QAAITrustTLSProxy) { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"}) + return + } + view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC()) + if err != nil { + writeKBBindingError(w, err) + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": view, "operation": "saved"}) +} + +func writeKBBindingError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, kbbinding.ErrInvalid): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "绑定参数不合法:请检查地址、密钥与内外库选择"}) + case errors.Is(err, kbbinding.ErrConflict): + writeJSON(w, http.StatusConflict, map[string]string{"error": "该环境的绑定已被其他保存更新;草稿未写入,旧绑定保持不变,请重新读取后再试"}) + case errors.Is(err, kbbinding.ErrKeyForwarding): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址"}) + case errors.Is(err, kbbinding.ErrNotConfigured): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "这个地址还没有可用 API Key:请输入密钥或先选择已配置的连接"}) + case errors.Is(err, kbbinding.ErrStorage): + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "独立安全存储未就绪(WEKNORA_BINDING_MASTER_KEY_FILE);未写入任何绑定"}) + case errors.Is(err, kbbinding.ErrRejected): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrRejected.Error()+":")}) + case errors.Is(err, kbbinding.ErrUnreachable): + writeJSON(w, http.StatusBadGateway, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrUnreachable.Error()+":")}) + default: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"}) + } +} diff --git a/internal/httpapi/kb_bindings_test.go b/internal/httpapi/kb_bindings_test.go new file mode 100644 index 0000000..262d0ae --- /dev/null +++ b/internal/httpapi/kb_bindings_test.go @@ -0,0 +1,130 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "knowledge-governance/internal/kbbinding" +) + +type fakeKBBindings struct { + views []kbbinding.View + catalog kbbinding.Catalog + saveErr error + catalogErr error + lastSave kbbinding.SaveInput + lastActor string +} + +func (fake *fakeKBBindings) List(context.Context) ([]kbbinding.View, error) { + return fake.views, nil +} +func (fake *fakeKBBindings) Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error) { + return fake.catalog, fake.catalogErr +} +func (fake *fakeKBBindings) Save(_ context.Context, _ string, input kbbinding.SaveInput, actor string, _ time.Time) (kbbinding.View, error) { + fake.lastSave = input + fake.lastActor = actor + if fake.saveErr != nil { + return kbbinding.View{}, fake.saveErr + } + return fake.views[0], nil +} +func (fake *fakeKBBindings) ResolveBaseURL(context.Context, string) string { return "" } + +func kbBindingHandler(t *testing.T, store KBBindingStore) *Config { + t.Helper() + config := &Config{KBBindings: store, Now: func() time.Time { return time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) }} + return config +} + +func TestKBBindingsReadNeverEchoesSecretsAndWriteRequiresIntent(t *testing.T) { + store := &fakeKBBindings{views: []kbbinding.View{{ + Environment: kbbinding.EnvTest, Revision: 2, BaseURL: "https://weknora.test.example", + KeyConfigured: true, KeySource: "sealed", InternalKBID: "kb-in", InternalKBName: "内部", + ExternalKBID: "kb-out", ExternalKBName: "对外", Source: "web", StorageReady: true, + }}} + config := kbBindingHandler(t, store) + response := httptest.NewRecorder() + config.handleKBBindings(response, httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)) + if response.Code != http.StatusOK { + t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String()) + } + body := response.Body.String() + for _, forbidden := range []string{"api_key", "key_ciphertext", "sealed-key-value"} { + if strings.Contains(body, forbidden) { + t.Fatalf("read response exposes %q: %s", forbidden, body) + } + } + + request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`)) + request.SetPathValue("environment", "test") + response = httptest.NewRecorder() + config.handleKBBindingSave(response, request) + if response.Code != http.StatusForbidden { + t.Fatalf("save without intent status = %d", response.Code) + } +} + +func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) { + store := &fakeKBBindings{ + views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}}, + saveErr: kbbinding.ErrConflict, + } + config := kbBindingHandler(t, store) + request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`)) + request.SetPathValue("environment", "test") + request.Header.Set("X-Governance-Action", "kb-bindings") + response := httptest.NewRecorder() + config.handleKBBindingSave(response, request) + if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "旧绑定保持不变") { + t.Fatalf("conflict status=%d body=%s", response.Code, response.Body.String()) + } +} + +func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) { + store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}} + config := kbBindingHandler(t, store) + body := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}` + request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body)) + request.SetPathValue("environment", "test") + request.Header.Set("X-Governance-Action", "kb-bindings") + response := httptest.NewRecorder() + config.handleKBBindingCatalog(response, request) + if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "HTTPS") { + t.Fatalf("plain HTTP key entry status=%d body=%s", response.Code, response.Body.String()) + } + + request = httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body)) + request.SetPathValue("environment", "test") + request.Header.Set("X-Governance-Action", "kb-bindings") + response = httptest.NewRecorder() + config.handleKBBindingCatalog(response, request) + if response.Code != http.StatusOK { + t.Fatalf("loopback catalog status=%d body=%s", response.Code, response.Body.String()) + } + var payload map[string]any + if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if strings.Contains(response.Body.String(), "typed-key") { + t.Fatal("catalog response echoed the typed key") + } +} + +func TestKBBindingWritesAreAdminOnly(t *testing.T) { + for _, path := range []string{"/api/v1/kb-bindings/test", "/api/v1/kb-bindings/test/catalog"} { + if role := classifyRole(http.MethodPut, path); role != roleAdmin { + t.Fatalf("PUT %s role = %s, want admin", path, role) + } + if role := classifyRole(http.MethodGet, "/api/v1/kb-bindings"); role != roleViewer { + t.Fatalf("GET bindings role = %s, want viewer", role) + } + } +} diff --git a/internal/httpapi/openapi_contract_test.go b/internal/httpapi/openapi_contract_test.go index 15e4b08..b1660b1 100644 --- a/internal/httpapi/openapi_contract_test.go +++ b/internal/httpapi/openapi_contract_test.go @@ -52,7 +52,7 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) { switch value := node.(type) { case map[string]any: for key, child := range value { - if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" { + if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" && path != "components.schemas.KBBindingEnvironmentView.properties" && path != "components.schemas.KBCatalogInput.properties" && path != "components.schemas.KBBindingSaveInput.properties" { t.Fatalf("unapproved endpoint exposure at %s", path) } next := key diff --git a/internal/httpapi/production_bindings.go b/internal/httpapi/production_bindings.go index 43756c7..7d746ba 100644 --- a/internal/httpapi/production_bindings.go +++ b/internal/httpapi/production_bindings.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "knowledge-governance/internal/kbbinding" "knowledge-governance/internal/pgdsn" "knowledge-governance/internal/platform/weknora" ) @@ -88,6 +89,11 @@ func (config Config) libraryPublishTarget() libraryPublishTargetView { // productionTargetBaseURL is the production endpoint the picker reads from: the // operator-managed 「服务配置 · 生产地址」 first, the deployment default second. func (config Config) productionTargetBaseURL(ctx context.Context) string { + if config.KBBindings != nil { + if resolved := strings.TrimSpace(config.KBBindings.ResolveBaseURL(ctx, kbbinding.EnvProduction)); resolved != "" { + return resolved + } + } if settings, err := config.Store.GetActiveUISettings(ctx); err == nil { if resolved := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); resolved != "" { return resolved diff --git a/internal/httpapi/qa_ai.go b/internal/httpapi/qa_ai.go index 4edfa66..6d5cea7 100644 --- a/internal/httpapi/qa_ai.go +++ b/internal/httpapi/qa_ai.go @@ -2,11 +2,9 @@ package httpapi import ( "errors" - "knowledge-governance/internal/qaopsai" - "net" "net/http" - "net/url" - "strings" + + "knowledge-governance/internal/qaopsai" ) func qaAIError(w http.ResponseWriter, err error) { @@ -42,24 +40,7 @@ func qaAIReady(w http.ResponseWriter, r *http.Request, c Config) bool { return true } func qaAISecretTransport(r *http.Request, c Config) bool { - if r.TLS != nil { - return true - } - host := r.Host - if parsed, _, err := net.SplitHostPort(host); err == nil { - host = parsed - } - if strings.EqualFold(host, "localhost") { - return true - } - if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { - return true - } - if c.QAAITrustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" { - origin, err := url.Parse(r.Header.Get("Origin")) - return err == nil && origin.Scheme == "https" - } - return false + return secretTransportAllowed(r, c.QAAITrustTLSProxy) } func registerQAAIRoutes(mux *http.ServeMux, c Config) { mux.HandleFunc("GET /api/v1/qa-ops/ai/settings", func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/httpapi/secret_transport.go b/internal/httpapi/secret_transport.go new file mode 100644 index 0000000..4c92e3d --- /dev/null +++ b/internal/httpapi/secret_transport.go @@ -0,0 +1,34 @@ +package httpapi + +import ( + "net" + "net/http" + "net/url" + "strings" +) + +// secretTransportAllowed is the single rule for typing a secret into the +// console: a real TLS connection, a loopback request, or a same-origin HTTPS +// request that a trusted reverse proxy forwarded. The browser's origin scheme +// must agree, so a plain-HTTP page behind a misconfigured proxy cannot submit +// a key even if it spoofs X-Forwarded-Proto. +func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool { + if r.TLS != nil { + return true + } + host := r.Host + if parsedHost, _, err := net.SplitHostPort(host); err == nil { + host = parsedHost + } + if strings.EqualFold(host, "localhost") { + return true + } + if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { + return true + } + if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" { + origin, err := url.Parse(r.Header.Get("Origin")) + return err == nil && origin.Scheme == "https" + } + return false +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 052e4ce..13443b6 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -137,6 +137,10 @@ type Config struct { ExternalRoutingKnowledgeBaseID string RoutingBindings RoutingBindingStore KnowledgeBases KnowledgeBaseLister + // KBBindings is the environment-scoped 「知识库绑定」store: connection + + // internal/external bindings saved together. Nil keeps the page read-only + // and reports unavailable, never a fake success. + KBBindings KBBindingStore // ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases // enumerates the production-side bases the operator can bind. // BackupSchedule 是「系统设置 → 存储与备份」的计划存储;BackupHost 负责在目标库 @@ -404,6 +408,15 @@ func NewHandler(config Config) (http.Handler, error) { } config.handleSaveRoutingBindings(w, r) }) + mux.HandleFunc("GET /api/v1/kb-bindings", func(w http.ResponseWriter, r *http.Request) { + config.handleKBBindings(w, r) + }) + mux.HandleFunc("POST /api/v1/kb-bindings/{environment}/catalog", func(w http.ResponseWriter, r *http.Request) { + config.handleKBBindingCatalog(w, r) + }) + mux.HandleFunc("PUT /api/v1/kb-bindings/{environment}", func(w http.ResponseWriter, r *http.Request) { + config.handleKBBindingSave(w, r) + }) mux.HandleFunc("GET /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) { if config.BackupSchedule == nil { writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"}) diff --git a/internal/kbbinding/binding.go b/internal/kbbinding/binding.go new file mode 100644 index 0000000..1bd73bb --- /dev/null +++ b/internal/kbbinding/binding.go @@ -0,0 +1,421 @@ +// Package kbbinding 是「知识库绑定」的唯一服务端入口:按环境保存连接 +// (地址 + 加密后的 API Key)和对内/对外知识库绑定,并提供候选人列库、 +// 选库归属校验与消费者解析。旧的部署文件凭据/默认绑定在没有任何新行时 +// 继续生效,所以升级不需要回填数据。 +package kbbinding + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/platform/weknora" + "knowledge-governance/internal/secretbox" +) + +const ( + EnvTest = "test" + EnvProduction = "production" +) + +func Environments() []string { return []string{EnvTest, EnvProduction} } + +func ValidEnvironment(value string) bool { + return value == EnvTest || value == EnvProduction +} + +func EnvironmentLabel(value string) string { + if value == EnvProduction { + return "生产 090" + } + return "测试 090" +} + +var ( + ErrInvalid = errors.New("invalid knowledge base binding") + ErrConflict = errors.New("knowledge base binding revision conflict") + ErrKeyForwarding = errors.New("old key must not follow a new address") + ErrNotConfigured = errors.New("weknora connection is not configured") + ErrStorage = errors.New("secure binding storage is not ready") + ErrRejected = errors.New("weknora rejected the candidate connection") + ErrUnreachable = errors.New("weknora candidate connection is unreachable") +) + +// View is the public projection. It never carries a key, ciphertext or any +// value derived from the key beyond "configured or not". +type View struct { + Environment string `json:"environment"` + Revision int64 `json:"revision"` + BaseURL string `json:"base_url"` + KeyConfigured bool `json:"key_configured"` + KeySource string `json:"key_source"` + InternalKBID string `json:"internal_kb_id"` + InternalKBName string `json:"internal_kb_name"` + ExternalKBID string `json:"external_kb_id"` + ExternalKBName string `json:"external_kb_name"` + Verification string `json:"verification"` + CheckedAt *time.Time `json:"checked_at"` + UpdatedBy string `json:"updated_by"` + UpdatedAt *time.Time `json:"updated_at"` + // Source says where this effective configuration comes from: a row saved on + // this page, or the pre-existing deployment file/default binding. + Source string `json:"source"` + StorageReady bool `json:"storage_ready"` + // Replanned / RetiredDuplicates only report what a save just did to 待入库 + // rows that had never been uploaded; a plain read reports zeros. + Replanned int `json:"replanned"` + RetiredDuplicates int `json:"retired_duplicates"` +} + +type Option struct { + ID string `json:"id"` + Name string `json:"name"` + KnowledgeCount int64 `json:"knowledge_count"` +} + +type Catalog struct { + Status string `json:"status"` + Message string `json:"message"` + Page int `json:"page"` + PageSize int `json:"page_size"` + Total int64 `json:"total"` + Options []Option `json:"options"` +} + +type CatalogInput struct { + BaseRevision int64 `json:"base_revision"` + BaseURL string `json:"base_url"` + KeyAction string `json:"key_action"` + APIKey string `json:"api_key"` + Page int `json:"page"` + PageSize int `json:"page_size"` +} + +type SaveInput struct { + BaseRevision int64 `json:"base_revision"` + BaseURL string `json:"base_url"` + KeyAction string `json:"key_action"` + APIKey string `json:"api_key"` + InternalKBID string `json:"internal_kb_id"` + ExternalKBID string `json:"external_kb_id"` +} + +// Target is what consumers (readiness, upload, listing, monitoring) need to +// reach the effective instance. It never leaves the server. +type Target struct { + BaseURL string + APIKey string + Revision int64 + Source string +} + +type Options struct { + MasterKeyFile string + Timeout time.Duration + // AllowDockerHTTP mirrors the per-environment client policy (a single-label + // docker host may be reached over plain HTTP in the internal network). + AllowDockerHTTP map[string]bool + // LegacyBaseURL resolves the pre-existing endpoint (web setting first, then + // the deployment env value). It is only consulted when no row exists. + LegacyBaseURL func(context.Context, string) string + // LegacyKey reads the deployment credential file. It is only consulted when + // no row exists, or when a keep action targets exactly that legacy address. + LegacyKey func(string) (string, error) + // LegacyBinding resolves the pre-existing internal/external binding ids. + LegacyBinding func(context.Context, string) (string, string, error) + // RoutingDefaults are the deployment bootstrap ids used to replan pending + // publications when a saved side is empty. + RoutingDefaults func() (string, string) + Now func() time.Time +} + +type DB interface { + QueryRow(ctx context.Context, sql string, args ...any) pgx.Row + Begin(ctx context.Context) (pgx.Tx, error) +} + +type Store struct { + db DB + options Options +} + +func New(db DB, options Options) *Store { + if options.Timeout <= 0 { + options.Timeout = 10 * time.Second + } + if options.Now == nil { + options.Now = time.Now + } + return &Store{db: db, options: options} +} + +type stored struct { + Environment string + Revision int64 + BaseURL string + KeyCiphertext []byte + InternalKBID string + ExternalKBID string + InternalKBName string + ExternalKBName string + Verification string + CheckedAt *time.Time + UpdatedBy string + UpdatedAt *time.Time +} + +const bindingColumns = `environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at` + +func scanStored(row pgx.Row) (stored, bool, error) { + var value stored + err := row.Scan(&value.Environment, &value.Revision, &value.BaseURL, &value.KeyCiphertext, + &value.InternalKBID, &value.ExternalKBID, &value.InternalKBName, &value.ExternalKBName, + &value.Verification, &value.CheckedAt, &value.UpdatedBy, &value.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return stored{}, false, nil + } + if err != nil { + return stored{}, false, err + } + return value, true, nil +} + +func (s *Store) load(ctx context.Context, env string) (stored, bool, error) { + if !ValidEnvironment(env) { + return stored{}, false, ErrInvalid + } + return scanStored(s.db.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1`, env)) +} + +func (s *Store) StorageReady() bool { + return s.loadBox() != nil +} + +func (s *Store) loadBox() *secretbox.Box { + box, err := secretbox.Load(s.options.MasterKeyFile) + if err != nil { + return nil + } + return box +} + +func (s *Store) legacyBaseURL(ctx context.Context, env string) string { + if s.options.LegacyBaseURL == nil { + return "" + } + return strings.TrimSpace(s.options.LegacyBaseURL(ctx, env)) +} + +func (s *Store) legacyKey(env string) (string, error) { + if s.options.LegacyKey == nil { + return "", nil + } + value, err := s.options.LegacyKey(env) + if err != nil { + return "", err + } + return strings.TrimSpace(value), nil +} + +// List returns both environments' effective views for the page header and the +// environment switch. Names are best-effort: an unreachable instance yields +// short ids instead of hiding the binding. +func (s *Store) List(ctx context.Context) ([]View, error) { + views := make([]View, 0, 2) + for _, env := range Environments() { + view, err := s.Get(ctx, env) + if err != nil { + return nil, err + } + views = append(views, view) + } + return views, nil +} + +func (s *Store) Get(ctx context.Context, env string) (View, error) { + saved, found, err := s.load(ctx, env) + if err != nil { + return View{}, err + } + view := View{Environment: env, StorageReady: s.StorageReady(), Source: "legacy"} + if found { + view.Revision = saved.Revision + view.BaseURL = saved.BaseURL + view.KeyConfigured = len(saved.KeyCiphertext) > 0 + view.KeySource = keySource(view.KeyConfigured) + view.InternalKBID = saved.InternalKBID + view.InternalKBName = saved.InternalKBName + view.ExternalKBID = saved.ExternalKBID + view.ExternalKBName = saved.ExternalKBName + view.Verification = saved.Verification + view.CheckedAt = saved.CheckedAt + view.UpdatedBy = saved.UpdatedBy + view.UpdatedAt = saved.UpdatedAt + view.Source = "web" + return view, nil + } + // Legacy fallback: exactly what the consumers use before any page save. + view.BaseURL = s.legacyBaseURL(ctx, env) + if key, keyErr := s.legacyKey(env); keyErr == nil && key != "" { + view.KeyConfigured = true + view.KeySource = "file" + } + if s.options.LegacyBinding != nil { + internal, external, bindErr := s.options.LegacyBinding(ctx, env) + if bindErr != nil { + return View{}, bindErr + } + view.InternalKBID = internal + view.ExternalKBID = external + } + view.Verification = "legacy" + s.fillNames(ctx, &view) + return view, nil +} + +func keySource(configured bool) string { + if configured { + return "sealed" + } + return "none" +} + +// fillNames reads names from the effective instance for the legacy view. A +// failure leaves names empty; ids still identify the binding. +func (s *Store) fillNames(ctx context.Context, view *View) { + if view.BaseURL == "" || (view.InternalKBID == "" && view.ExternalKBID == "") { + return + } + // 只是把 ID 换成名字:不能让一次不可达的旧实例拖住整个页面读取。 + namesCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + key, err := s.legacyKey(view.Environment) + if err != nil || key == "" { + return + } + client, err := s.client(view.BaseURL, key, view.Environment) + if err != nil { + return + } + names := map[string]string{} + page := 1 + for page <= 20 { + result, err := client.ListKnowledgeBasesPage(namesCtx, page, 100) + if err != nil { + break + } + for _, base := range result.Items { + names[base.ID] = base.Name + } + if result.Total <= int64(page*100) || len(result.Items) < 100 { + break + } + page++ + } + view.InternalKBName = names[view.InternalKBID] + view.ExternalKBName = names[view.ExternalKBID] +} + +// Resolve returns the effective connection consumers must use. A saved row is +// authoritative: if its key cannot be opened we fail closed instead of falling +// back to the file credential (that would send the old key to a new address). +func (s *Store) Resolve(ctx context.Context, env string) (Target, error) { + saved, found, err := s.load(ctx, env) + if err != nil { + return Target{}, err + } + if found { + if saved.BaseURL == "" { + return Target{}, ErrNotConfigured + } + if len(saved.KeyCiphertext) == 0 { + return Target{}, ErrNotConfigured + } + box := s.loadBox() + if box == nil { + return Target{}, ErrStorage + } + raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision)) + if err != nil { + return Target{}, ErrStorage + } + return Target{BaseURL: saved.BaseURL, APIKey: string(raw), Revision: saved.Revision, Source: "web"}, nil + } + baseURL := s.legacyBaseURL(ctx, env) + key, err := s.legacyKey(env) + if err != nil { + return Target{}, err + } + if baseURL == "" || key == "" { + return Target{}, ErrNotConfigured + } + return Target{BaseURL: baseURL, APIKey: key, Source: "legacy"}, nil +} + +// ResolveBaseURL is for health probes that only need the endpoint (no key). +func (s *Store) ResolveBaseURL(ctx context.Context, env string) string { + if saved, found, err := s.load(ctx, env); err == nil && found && saved.BaseURL != "" { + return saved.BaseURL + } + return s.legacyBaseURL(ctx, env) +} + +func (s *Store) keyFor(ctx context.Context, env string, action, baseURL, apiKey string, saved stored, found bool) (string, error) { + switch action { + case "keep": + if apiKey != "" { + return "", ErrInvalid + } + if found { + if saved.BaseURL != baseURL { + return "", ErrKeyForwarding + } + if len(saved.KeyCiphertext) == 0 { + return "", ErrNotConfigured + } + box := s.loadBox() + if box == nil { + return "", ErrStorage + } + raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision)) + if err != nil { + return "", ErrStorage + } + return string(raw), nil + } + // First save on an upgraded deployment: keeping the deployment file key + // is allowed only for exactly that legacy address. + if s.legacyBaseURL(ctx, env) != baseURL { + return "", ErrKeyForwarding + } + return s.legacyKey(env) + case "replace": + if !validAPIKey(apiKey) { + return "", ErrInvalid + } + return apiKey, nil + default: + return "", ErrInvalid + } +} + +func validAPIKey(value string) bool { + return value != "" && len(value) <= 4096 && strings.TrimSpace(value) == value && !strings.ContainsAny(value, "\r\n\x00") +} + +func (s *Store) client(baseURL, apiKey, env string) (*weknora.Client, error) { + return weknora.NewClient(weknora.ClientConfig{ + BaseURL: baseURL, + APIKey: apiKey, + Timeout: s.options.Timeout, + AllowDockerHTTP: s.options.AllowDockerHTTP[env], + }) +} + +func keyAAD(env string, revision int64) string { + return "weknora-binding:" + env + ":" + strconv.FormatInt(revision, 10) +} diff --git a/internal/kbbinding/binding_test.go b/internal/kbbinding/binding_test.go new file mode 100644 index 0000000..a35579c --- /dev/null +++ b/internal/kbbinding/binding_test.go @@ -0,0 +1,129 @@ +package kbbinding + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" +) + +type emptyDB struct{} + +func (emptyDB) QueryRow(context.Context, string, ...any) pgx.Row { return emptyRow{} } +func (emptyDB) Begin(context.Context) (pgx.Tx, error) { + return nil, errors.New("no transaction in unit test") +} + +type emptyRow struct{} + +func (emptyRow) Scan(...any) error { return pgx.ErrNoRows } + +// fakeWeKnora serves the two reads the candidate validation makes: one page of +// knowledge bases and a single base by id. +func fakeWeKnora(t *testing.T, wantKey string, bases []struct{ id, name string }, total int64) *httptest.Server { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("X-API-Key"); got != wantKey { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.URL.Path == "/api/v1/knowledge-bases" { + items := make([]string, 0, len(bases)) + for _, base := range bases { + items = append(items, `{"id":"`+base.id+`","name":"`+base.name+`","knowledge_count":2}`) + } + _, _ = w.Write([]byte(`{"success":true,"data":[` + strings.Join(items, ",") + `],"total":` + strconv.FormatInt(total, 10) + `}`)) + return + } + if strings.HasPrefix(r.URL.Path, "/api/v1/knowledge-bases/") { + id := strings.TrimPrefix(r.URL.Path, "/api/v1/knowledge-bases/") + for _, base := range bases { + if base.id == id { + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"` + base.id + `","name":"` + base.name + `"}}`)) + return + } + } + w.WriteHeader(http.StatusNotFound) + return + } + w.WriteHeader(http.StatusNotFound) + })) + t.Cleanup(server.Close) + return server +} + +func TestCatalogDistinguishesEmptyFromPermissionFromUnreachable(t *testing.T) { + ctx := context.Background() + store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}}) + + empty := fakeWeKnora(t, "key-1", nil, 0) + catalog, err := store.Catalog(ctx, EnvTest, CatalogInput{ + BaseURL: empty.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20, + }) + if err != nil || catalog.Status != statusEmpty || catalog.Total != 0 { + t.Fatalf("empty catalog = %#v, %v", catalog, err) + } + + denied := fakeWeKnora(t, "another-key", nil, 0) + catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{ + BaseURL: denied.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20, + }) + if err != nil || catalog.Status != statusUnauthorized { + t.Fatalf("denied catalog = %#v, %v", catalog, err) + } + + down := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + downURL := down.URL + down.Close() + catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{ + BaseURL: downURL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20, + }) + if err != nil || catalog.Status != statusUnreachable { + t.Fatalf("unreachable catalog = %#v, %v", catalog, err) + } +} + +func TestCatalogPaginatesAndReturnsNamesWithShortIDsAreStable(t *testing.T) { + server := fakeWeKnora(t, "key-1", []struct{ id, name string }{{"kb-1", "技术资料"}}, 1) + store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}}) + catalog, err := store.Catalog(context.Background(), EnvTest, CatalogInput{ + BaseURL: server.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20, + }) + if err != nil || catalog.Status != statusOK || len(catalog.Options) != 1 || catalog.Options[0].Name != "技术资料" { + t.Fatalf("catalog = %#v, %v", catalog, err) + } +} + +func TestKeyActionRulesRejectForwardingAndInvalidInput(t *testing.T) { + store := New(emptyDB{}, Options{}) + saved := stored{Environment: EnvTest, Revision: 1, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")} + if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://new.example", "", saved, true); !errors.Is(err, ErrKeyForwarding) { + t.Fatalf("keep with a new address = %v, want ErrKeyForwarding", err) + } + if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) { + t.Fatalf("keep with a typed key = %v, want ErrInvalid", err) + } + if _, err := store.keyFor(context.Background(), EnvTest, "replace", "https://new.example", " ", saved, true); !errors.Is(err, ErrInvalid) { + t.Fatalf("replace with blank key = %v, want ErrInvalid", err) + } +} + +func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) { + now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) + store := New(emptyDB{}, Options{Now: func() time.Time { return now }}) + for _, input := range []SaveInput{ + {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"}, + {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"}, + {BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"}, + } { + if _, err := store.Save(context.Background(), EnvTest, input, "admin", now); !errors.Is(err, ErrInvalid) { + t.Fatalf("input %#v error = %v, want ErrInvalid", input, err) + } + } +} diff --git a/internal/kbbinding/save_integration_test.go b/internal/kbbinding/save_integration_test.go new file mode 100644 index 0000000..172a2bb --- /dev/null +++ b/internal/kbbinding/save_integration_test.go @@ -0,0 +1,179 @@ +package kbbinding_test + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/kbbinding" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/platform/postgres/pgtest" +) + +// testSecret() 在运行时拼出测试夹具密钥,避免把任何字面量误当成真实凭据入库。 +func testSecret() string { return "fixture-" + strings.Repeat("k", 24) } + +func fakeCandidate(t *testing.T) *httptest.Server { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-API-Key") != testSecret() { + w.WriteHeader(http.StatusUnauthorized) + return + } + switch { + case r.URL.Path == "/api/v1/knowledge-bases": + _, _ = w.Write([]byte(`{"success":true,"total":2,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4}]}`)) + case r.URL.Path == "/api/v1/knowledge-bases/kb-in": + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料"}}`)) + case r.URL.Path == "/api/v1/knowledge-bases/kb-out": + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册"}}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(server.Close) + return server +} + +func masterKey(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "binding-master.key") + if err := os.WriteFile(path, []byte(strings.Repeat("k", 32)), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction(t *testing.T) { + databaseURL := pgtest.IsolatedDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if databaseURL == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, databaseURL) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, ` +INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-kbb','manual','KBB',true); +INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,title,item_type,revision,visibility,visibility_origin) VALUES + ('item-kbb','conn-kbb','n-kbb',repeat('c',64),'docs/kbb.docx','kbb.docx','document','locator:r1','internal','configured_scope'); +INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES + ('version-kbb','item-kbb','locator:r1',NULL,'unknown'); +INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES + ('pub-kbb','version-kbb','kb-old','planned','pending','internal'); +`); err != nil { + t.Fatal(err) + } + server := fakeCandidate(t) + store := kbbinding.New(pool, kbbinding.Options{ + MasterKeyFile: masterKey(t), + Timeout: 2 * time.Second, + AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true}, + RoutingDefaults: func() (string, string) { return "env-in", "env-out" }, + }) + now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) + view, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{ + BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(), + InternalKBID: "kb-in", ExternalKBID: "kb-out", + }, "admin", now) + if err != nil { + t.Fatalf("Save() error = %v", err) + } + if view.Revision != 1 || !view.KeyConfigured || view.InternalKBName != "内部技术资料" || view.ExternalKBName != "客户使用手册" { + t.Fatalf("view = %#v", view) + } + if view.Replanned != 1 { + t.Fatalf("replanned = %d, want 1", view.Replanned) + } + target, err := store.Resolve(ctx, kbbinding.EnvTest) + if err != nil || target.BaseURL != server.URL || target.APIKey != testSecret() || target.Revision != 1 { + t.Fatalf("Resolve() = %#v, %v", target, err) + } + var routingInternal, routingExternal string + if err := pool.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal, &routingExternal); err != nil { + t.Fatal(err) + } + if routingInternal != "kb-in" || routingExternal != "kb-out" { + t.Fatalf("routing binding = %s/%s", routingInternal, routingExternal) + } + var pendingKB string + if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-kbb'`).Scan(&pendingKB); err != nil { + t.Fatal(err) + } + if pendingKB != "kb-in" { + t.Fatalf("pending publication target = %s, want kb-in", pendingKB) + } + + // A stale revision must not overwrite the saved connection or re-point work. + _, err = store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{ + BaseRevision: 0, BaseURL: server.URL, KeyAction: "keep", + InternalKBID: "kb-out", ExternalKBID: "kb-in", + }, "admin", now.Add(time.Minute)) + if !errors.Is(err, kbbinding.ErrConflict) { + t.Fatalf("stale save error = %v, want ErrConflict", err) + } + unchanged, err := store.Resolve(ctx, kbbinding.EnvTest) + if err != nil || unchanged.APIKey != testSecret() { + t.Fatalf("connection changed after conflict: %#v, %v", unchanged, err) + } + if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal); err != nil { + t.Fatal(err) + } + if routingInternal != "kb-in" { + t.Fatalf("routing binding changed after conflict: %s", routingInternal) + } + + // A base from another instance (404 here) must be refused and leave no row + // for a different environment. + if _, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{ + BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(), + InternalKBID: "not-there", ExternalKBID: "kb-out", + }, "admin", now); !errors.Is(err, kbbinding.ErrRejected) { + t.Fatalf("unknown base error = %v, want ErrRejected", err) + } + var count int + if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM weknora_environment_bindings WHERE environment='production'`).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 0 { + t.Fatalf("failed production save wrote %d rows", count) + } + + // The old key must never be forwarded: keep is only legal for the saved URL. + if _, err := store.Catalog(ctx, kbbinding.EnvTest, kbbinding.CatalogInput{ + BaseURL: "https://another.example", KeyAction: "keep", Page: 1, PageSize: 20, + }); !errors.Is(err, kbbinding.ErrKeyForwarding) { + t.Fatalf("keep with another address = %v, want ErrKeyForwarding", err) + } + + prodView, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{ + BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(), + InternalKBID: "kb-in", ExternalKBID: "kb-out", + }, "admin", now) + if err != nil { + t.Fatalf("production Save() error = %v", err) + } + if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 { + t.Fatalf("production view = %#v", prodView) + } + var productionInternal string + if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal); err != nil { + t.Fatal(err) + } + if productionInternal != "kb-in" { + t.Fatalf("production binding = %s", productionInternal) + } +} diff --git a/internal/kbbinding/store.go b/internal/kbbinding/store.go new file mode 100644 index 0000000..d3d8f42 --- /dev/null +++ b/internal/kbbinding/store.go @@ -0,0 +1,274 @@ +package kbbinding + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "time" + + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/platform/weknora" +) + +const ( + statusOK = "ok" + statusEmpty = "empty" + statusUnauthorized = "unauthorized" + statusUnreachable = "unreachable" + statusUnsupported = "unsupported" +) + +// Catalog validates a draft connection for real and returns one page of the +// knowledge bases that key can read. It never writes anything and never echoes +// the key. +func (s *Store) Catalog(ctx context.Context, env string, input CatalogInput) (Catalog, error) { + if !ValidEnvironment(env) { + return Catalog{}, ErrInvalid + } + baseURL := strings.TrimSpace(input.BaseURL) + if baseURL == "" || baseURL != input.BaseURL || len(baseURL) > 300 { + return Catalog{}, ErrInvalid + } + page, pageSize := input.Page, input.PageSize + if page <= 0 { + page = 1 + } + if pageSize <= 0 { + pageSize = 20 + } + if pageSize > 100 { + pageSize = 100 + } + saved, found, err := s.load(ctx, env) + if err != nil { + return Catalog{}, err + } + key, err := s.keyFor(ctx, env, input.KeyAction, baseURL, input.APIKey, saved, found) + if err != nil { + return Catalog{}, err + } + client, err := s.client(baseURL, key, env) + if err != nil { + return Catalog{}, ErrInvalid + } + result, err := client.ListKnowledgeBasesPage(ctx, page, pageSize) + if err != nil { + return catalogFailure(err), nil + } + options := make([]Option, 0, len(result.Items)) + for _, base := range result.Items { + options = append(options, Option{ID: base.ID, Name: base.Name, KnowledgeCount: base.KnowledgeCount}) + } + status := statusOK + message := fmt.Sprintf("已读取 %d 个知识库", result.Total) + if result.Total == 0 { + status = statusEmpty + message = "连接可用,但这个实例还没有可读的知识库" + } + return Catalog{Status: status, Message: message, Page: page, PageSize: pageSize, Total: result.Total, Options: options}, nil +} + +// catalogFailure turns a transport/permission failure into a distinguishable +// answer: "empty" must never be shown for "could not ask". +func catalogFailure(err error) Catalog { + var httpErr *weknora.HTTPError + if errors.As(err, &httpErr) { + switch httpErr.StatusCode { + case http.StatusUnauthorized, http.StatusForbidden: + return Catalog{Status: statusUnauthorized, Message: "密钥被实例拒绝(HTTP 401/403):检查 API Key 与该实例权限"} + case http.StatusNotFound: + return Catalog{Status: statusUnsupported, Message: "该地址没有知识库列表接口(HTTP 404):确认填的是 WeKnora 服务地址"} + default: + return Catalog{Status: statusUnreachable, Message: fmt.Sprintf("实例返回 HTTP %d,无法确认连接", httpErr.StatusCode)} + } + } + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { + return Catalog{Status: statusUnreachable, Message: "连接超时:检查地址、网络与防火墙"} + } + return Catalog{Status: statusUnreachable, Message: "服务不可达:检查地址、网络与证书"} +} + +// Save writes the environment's connection and both bindings in ONE +// transaction. The candidate instance is asked first; nothing is written when +// either selected base does not belong to it. A stale base_revision returns +// ErrConflict and leaves the previous binding untouched. +func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor string, now time.Time) (View, error) { + if !ValidEnvironment(env) || strings.TrimSpace(actor) == "" || now.IsZero() { + return View{}, ErrInvalid + } + baseURL := strings.TrimSpace(input.BaseURL) + internal := strings.TrimSpace(input.InternalKBID) + external := strings.TrimSpace(input.ExternalKBID) + if baseURL == "" || baseURL != input.BaseURL || len(baseURL) > 300 || + internal != input.InternalKBID || external != input.ExternalKBID || + len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) { + return View{}, ErrInvalid + } + if internal != "" && internal == external { + return View{}, ErrInvalid + } + saved, found, err := s.load(ctx, env) + if err != nil { + return View{}, err + } + key, err := s.keyFor(ctx, env, input.KeyAction, baseURL, input.APIKey, saved, found) + if err != nil { + return View{}, err + } + client, err := s.client(baseURL, key, env) + if err != nil { + return View{}, ErrInvalid + } + names, err := s.verifySelection(ctx, client, internal, external) + if err != nil { + return View{}, err + } + revision := saved.Revision + 1 + if !found { + revision = 1 + } + box := s.loadBox() + if box == nil { + return View{}, ErrStorage + } + sealed, err := box.Seal([]byte(key), keyAAD(env, revision)) + if err != nil { + return View{}, ErrStorage + } + verification := "verified" + + tx, err := s.db.Begin(ctx) + if err != nil { + return View{}, ErrStorage + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,42))`, "weknora-binding:"+env); err != nil { + return View{}, ErrStorage + } + locked, lockedFound, err := scanStored(tx.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1 FOR UPDATE`, env)) + if err != nil { + return View{}, ErrStorage + } + lockedRevision := int64(0) + if lockedFound { + lockedRevision = locked.Revision + } + if lockedRevision != input.BaseRevision { + return View{}, ErrConflict + } + if _, err := tx.Exec(ctx, ` +INSERT INTO weknora_environment_bindings( + environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id, + internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at) +VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$10) +ON CONFLICT(environment) DO UPDATE SET + revision=EXCLUDED.revision,base_url=EXCLUDED.base_url,key_ciphertext=EXCLUDED.key_ciphertext, + internal_kb_id=EXCLUDED.internal_kb_id,external_kb_id=EXCLUDED.external_kb_id, + internal_kb_name=EXCLUDED.internal_kb_name,external_kb_name=EXCLUDED.external_kb_name, + verification=EXCLUDED.verification,checked_at=EXCLUDED.checked_at, + updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`, + env, revision, baseURL, sealed, internal, external, names[internal], names[external], verification, now.UTC(), actor); err != nil { + return View{}, ErrStorage + } + if _, err := tx.Exec(ctx, ` +INSERT INTO weknora_environment_binding_history( + environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at) +VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, + env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC()); err != nil { + return View{}, ErrStorage + } + replan := postgresstore.RoutingBindingReplanResult{} + if env == EnvTest { + if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil { + return View{}, ErrStorage + } + effectiveInternal, effectiveExternal := internal, external + if s.options.RoutingDefaults != nil { + defaultInternal, defaultExternal := s.options.RoutingDefaults() + if effectiveInternal == "" { + effectiveInternal = defaultInternal + } + if effectiveExternal == "" { + effectiveExternal = defaultExternal + } + } + replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now.UTC()) + if err != nil { + return View{}, ErrStorage + } + } else { + // 生产页这里沿用「文档级发布」语义;整库发布目标由部署配置决定,本保存不写它。 + if err := postgresstore.SaveProductionKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil { + return View{}, ErrStorage + } + } + if err := tx.Commit(ctx); err != nil { + return View{}, ErrStorage + } + view, err := s.Get(ctx, env) + if err != nil { + return View{}, err + } + view.Replanned = replan.Replanned + view.RetiredDuplicates = replan.RetiredDuplicates + return view, nil +} + +// verifySelection proves both chosen bases belong to THIS candidate instance by +// reading them with the draft credential. An empty selection still probes the +// list endpoint, so a save cannot store a connection nobody verified. +func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]string, error) { + names := map[string]string{} + if internal == "" && external == "" { + if _, err := client.ListKnowledgeBasesPage(ctx, 1, 1); err != nil { + return nil, selectionError(err, "无法确认候选连接") + } + return names, nil + } + for _, id := range []string{internal, external} { + if id == "" { + continue + } + base, err := client.GetKnowledgeBase(ctx, id) + if err != nil { + return nil, selectionError(err, fmt.Sprintf("知识库 %s 不属于该连接实例或不可读", shortID(id))) + } + if base.ID != id { + return nil, ErrInvalid + } + names[id] = base.Name + } + return names, nil +} + +func selectionError(err error, message string) error { + var httpErr *weknora.HTTPError + if errors.As(err, &httpErr) { + if httpErr.StatusCode == http.StatusUnauthorized || httpErr.StatusCode == http.StatusForbidden { + return fmt.Errorf("%w:密钥被实例拒绝(HTTP %d)", ErrRejected, httpErr.StatusCode) + } + } + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { + return fmt.Errorf("%w:连接超时", ErrUnreachable) + } + if _, ok := err.(*weknora.HTTPError); ok { + return fmt.Errorf("%w:%s", ErrRejected, message) + } + if errors.Is(err, ErrInvalid) || errors.Is(err, ErrRejected) || errors.Is(err, ErrUnreachable) { + return err + } + return fmt.Errorf("%w:%s", ErrUnreachable, message) +} + +func validBaseID(value string) bool { + return !strings.ContainsAny(value, "\x00\r\n\t /?#\\") +} + +func shortID(value string) string { + if len(value) > 8 { + return value[:8] + } + return value +} diff --git a/internal/monitoring/real.go b/internal/monitoring/real.go index 49776f9..efa942e 100644 --- a/internal/monitoring/real.go +++ b/internal/monitoring/real.go @@ -114,7 +114,7 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO overview.Health = provider.Services(ctx) overview.Services = append(overview.Services, provider.httpHealth(ctx, "weknora", "WeKnora API", provider.resolveTestWeKnoraBaseURL(ctx), now), - provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.productionWeKnoraBaseURL, now), + provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.resolveProductionWeKnoraBaseURL(ctx), now), governance.MonitorService{Key: "embedding", Name: "Embedding模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now}, governance.MonitorService{Key: "llm", Name: "LLM模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now}, provider.httpHealth(ctx, "mineru", "MinerU", provider.minerUBaseURL, now), diff --git a/internal/platform/postgres/migrations/000081_weknora_environment_bindings.down.sql b/internal/platform/postgres/migrations/000081_weknora_environment_bindings.down.sql new file mode 100644 index 0000000..aa3d2f6 --- /dev/null +++ b/internal/platform/postgres/migrations/000081_weknora_environment_bindings.down.sql @@ -0,0 +1,3 @@ +-- 回滚只删本迁移新增的审计与配置表;旧部署的 file 凭据/绑定表不受影响。 +DROP TABLE IF EXISTS weknora_environment_binding_history; +DROP TABLE IF EXISTS weknora_environment_bindings; \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000081_weknora_environment_bindings.up.sql b/internal/platform/postgres/migrations/000081_weknora_environment_bindings.up.sql new file mode 100644 index 0000000..3c9bc1f --- /dev/null +++ b/internal/platform/postgres/migrations/000081_weknora_environment_bindings.up.sql @@ -0,0 +1,36 @@ +-- 「知识库绑定」按环境保存一组连接与内外库绑定:测试与生产各自一行, +-- 一次保存同时写连接(地址 + 加密密钥)与对内/对外目标。没有行时消费者 +-- 继续使用旧部署的文件凭据/默认绑定,所以升级不需要回填。 +-- +-- key_ciphertext 只存密文;主密钥在独立文件里(WEKNORA_BINDING_MASTER_KEY_FILE), +-- 不进库、不进备份、不经页面回显。verification 记录最近一次真实列库/选库核验。 +CREATE TABLE weknora_environment_bindings ( + environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')), + revision BIGINT NOT NULL CHECK (revision > 0), + base_url TEXT NOT NULL DEFAULT '', + key_ciphertext BYTEA NOT NULL DEFAULT ''::bytea, + internal_kb_id VARCHAR(128) NOT NULL DEFAULT '', + external_kb_id VARCHAR(128) NOT NULL DEFAULT '', + internal_kb_name TEXT NOT NULL DEFAULT '', + external_kb_name TEXT NOT NULL DEFAULT '', + verification TEXT NOT NULL DEFAULT 'not_configured' + CHECK (verification IN ('not_configured','verified','empty','unreachable','rejected')), + checked_at TIMESTAMPTZ, + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +-- 修订历史只记录“是否配置了密钥”,绝不复制密文或明文,供审计回答谁在何时 +-- 把哪个环境指向了哪里。 +CREATE TABLE weknora_environment_binding_history ( + environment VARCHAR(16) NOT NULL, + revision BIGINT NOT NULL, + base_url TEXT NOT NULL, + key_configured BOOLEAN NOT NULL, + internal_kb_id VARCHAR(128) NOT NULL, + external_kb_id VARCHAR(128) NOT NULL, + verification TEXT NOT NULL, + actor TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (environment, revision) +); \ No newline at end of file diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index e3e11ec..292bfb1 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -11,8 +11,15 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) { if err != nil { t.Fatalf("loadMigrations() error = %v", err) } - if len(migrations) != 80 { - t.Fatalf("migration count = %d, want 80", len(migrations)) + if len(migrations) != 81 { + t.Fatalf("migration count = %d, want 81", len(migrations)) + } + // 81 是环境级「知识库绑定」:连接密文与内外库同表同事务,历史只记是否配置密钥。 + if binding := migrations[80]; binding.Version != 81 || + !strings.Contains(binding.UpSQL, "weknora_environment_bindings") || + !strings.Contains(binding.UpSQL, "key_ciphertext") || + !strings.Contains(binding.DownSQL, "DROP TABLE IF EXISTS weknora_environment_bindings") { + t.Fatalf("migration 81 = %#v", binding) } // 79 是恢复验证:verify 成为独立业务作业并与写作业共用互斥, // 证据按 target_id 落库(换目标旧证据自动失效)。 diff --git a/internal/platform/postgres/production_bindings.go b/internal/platform/postgres/production_bindings.go index b31b786..f3a2a7a 100644 --- a/internal/platform/postgres/production_bindings.go +++ b/internal/platform/postgres/production_bindings.go @@ -39,14 +39,26 @@ func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, extern if now.IsZero() { return errors.New("production binding save requires a timestamp") } - if _, err := s.db.Exec(ctx, ` + if _, err := s.db.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil { + return errors.New("save production kb bindings") + } + return nil +} + +const productionBindingUpsertSQL = ` INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at) VALUES('active',$1,$2,$3,$4) ON CONFLICT(id) DO UPDATE SET internal_kb_id=EXCLUDED.internal_kb_id, external_kb_id=EXCLUDED.external_kb_id, updated_by=EXCLUDED.updated_by, - updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil { + updated_at=EXCLUDED.updated_at` + +// SaveProductionKBBindingsTx lets the environment-scoped 「知识库绑定」save +// update the same row inside its own transaction, so connection and bindings +// cannot be half-written. +func SaveProductionKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error { + if _, err := tx.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil { return errors.New("save production kb bindings") } return nil diff --git a/internal/platform/postgres/routing_bindings.go b/internal/platform/postgres/routing_bindings.go index fba7bfb..7a23e97 100644 --- a/internal/platform/postgres/routing_bindings.go +++ b/internal/platform/postgres/routing_bindings.go @@ -121,6 +121,22 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, return result, fmt.Errorf("begin routing binding save: %w", err) } defer func() { _ = tx.Rollback(ctx) }() + if err := SaveRoutingKBBindingsTx(ctx, tx, internalID, externalID, updatedBy, now); err != nil { + return result, err + } + result, err = ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now) + if err != nil { + return RoutingBindingReplanResult{}, err + } + if err := tx.Commit(ctx); err != nil { + return result, fmt.Errorf("commit routing binding save: %w", err) + } + return result, nil +} + +// SaveRoutingKBBindingsTx is the binding upsert, shared by the settings page and +// the environment-scoped 「知识库绑定」save so the two entries cannot drift. +func SaveRoutingKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error { if _, err := tx.Exec(ctx, ` INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at) VALUES('active',$1,$2,$3,$4) @@ -129,8 +145,16 @@ ON CONFLICT(id) DO UPDATE SET external_kb_id=EXCLUDED.external_kb_id, updated_by=EXCLUDED.updated_by, updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil { - return result, errors.New("save routing kb bindings") + return errors.New("save routing kb bindings") } + return nil +} + +// ReplanPendingPublicationsTx re-points untouched 待入库 rows at the new targets +// inside the caller's transaction. It only moves rows that were never uploaded +// anywhere; anything already in flight keeps its frozen target. +func ReplanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, effectiveInternal, effectiveExternal string, now time.Time) (RoutingBindingReplanResult, error) { + var result RoutingBindingReplanResult for _, scope := range []struct{ name, kbID string }{ {"internal", effectiveInternal}, {"external", effectiveExternal}, @@ -149,8 +173,5 @@ ON CONFLICT(id) DO UPDATE SET result.RetiredDuplicates += int(retired.RowsAffected()) result.Replanned += int(moved.RowsAffected()) } - if err := tx.Commit(ctx); err != nil { - return result, fmt.Errorf("commit routing binding save: %w", err) - } return result, nil } diff --git a/internal/platform/weknora/client.go b/internal/platform/weknora/client.go index 3cb78df..3db2282 100644 --- a/internal/platform/weknora/client.go +++ b/internal/platform/weknora/client.go @@ -234,6 +234,31 @@ func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error return response.Data, nil } +// ListKnowledgeBasesPage reads one page. The console must show every readable +// base without pretending the first page is the whole set, so the total is +// carried through whenever the instance reports one. +func (c *Client) ListKnowledgeBasesPage(ctx context.Context, page, pageSize int) (KnowledgeBasePage, error) { + if !validPage(page, pageSize) { + return KnowledgeBasePage{}, errors.New("invalid knowledge base list request") + } + query := url.Values{} + query.Set("page", fmt.Sprint(page)) + query.Set("page_size", fmt.Sprint(pageSize)) + var response knowledgeBaseListResponse + if err := c.doJSONQuery(ctx, http.MethodGet, "/api/v1/knowledge-bases", query, nil, &response); err != nil { + return KnowledgeBasePage{}, err + } + if !response.Success { + return KnowledgeBasePage{}, errors.New("WeKnora returned an unsuccessful knowledge base list") + } + total := response.Total + totalKnown := total > 0 || (len(response.Data) == 0 && response.Page > 0) + if !totalKnown { + total = int64(len(response.Data)) + } + return KnowledgeBasePage{Items: response.Data, Total: total, Page: page, PageSize: pageSize, TotalKnown: totalKnown}, nil +} + // GetKnowledgeBase reads a single knowledge base by id. A knowledge base that is // not there surfaces as *HTTPError with status 404, so a caller can tell // "definitely absent" from "could not ask". diff --git a/internal/platform/weknora/types.go b/internal/platform/weknora/types.go index 222e6f4..71e5374 100644 --- a/internal/platform/weknora/types.go +++ b/internal/platform/weknora/types.go @@ -76,8 +76,21 @@ type KnowledgeBase struct { } type knowledgeBaseListResponse struct { - Success bool `json:"success"` - Data []KnowledgeBase `json:"data"` + Success bool `json:"success"` + Data []KnowledgeBase `json:"data"` + Total int64 `json:"total"` + Page int `json:"page"` + PageSize int `json:"page_size"` +} + +// KnowledgeBasePage is one page of the readable knowledge bases. TotalKnown is +// false when the instance did not report a total; callers must not invent one. +type KnowledgeBasePage struct { + Items []KnowledgeBase + Total int64 + Page int + PageSize int + TotalKnown bool } type knowledgeBaseResponse struct { diff --git a/internal/qaopsai/secrets.go b/internal/qaopsai/secrets.go index 4c30d53..18caf7f 100644 --- a/internal/qaopsai/secrets.go +++ b/internal/qaopsai/secrets.go @@ -1,53 +1,42 @@ package qaopsai import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" "fmt" - "os" + + "knowledge-governance/internal/secretbox" ) // The independently provisioned master key never lives in source, settings JSON or database backups. +func (s *Store) box() (*secretbox.Box, error) { + box, err := secretbox.Load(s.options.KeyFile) + if err != nil { + return nil, ErrUnavailable + } + return box, nil +} + +// masterKey 保留给调用方判断“存储是否就绪”;实际加解密统一走 secretbox。 func (s *Store) masterKey() ([]byte, error) { - info, err := os.Lstat(s.options.KeyFile) - if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 { - return nil, ErrUnavailable - } - raw, err := os.ReadFile(s.options.KeyFile) - if err != nil || len(raw) != 32 { - return nil, ErrUnavailable - } - return raw, nil -} -func (s *Store) aead() (cipher.AEAD, error) { - key, err := s.masterKey() - if err != nil { + if _, err := s.box(); err != nil { return nil, err } - block, err := aes.NewCipher(key) - if err != nil { - return nil, ErrUnavailable - } - return cipher.NewGCM(block) + return []byte{1}, nil } + func (s *Store) seal(secret string, revision int64) ([]byte, error) { - aead, err := s.aead() + box, err := s.box() if err != nil { return nil, err } - nonce := make([]byte, aead.NonceSize()) - if _, err = rand.Read(nonce); err != nil { - return nil, ErrUnavailable - } - return aead.Seal(nonce, nonce, []byte(secret), []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))), nil + return box.Seal([]byte(secret), fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision)) } + func (s *Store) unseal(sealed []byte, revision int64) (string, error) { - aead, err := s.aead() - if err != nil || len(sealed) < aead.NonceSize() { - return "", ErrUnavailable + box, err := s.box() + if err != nil { + return "", err } - raw, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))) + raw, err := box.Open(sealed, fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision)) if err != nil { return "", ErrUnavailable } diff --git a/internal/readiness/weknora.go b/internal/readiness/weknora.go index 6e30105..57bd966 100644 --- a/internal/readiness/weknora.go +++ b/internal/readiness/weknora.go @@ -45,6 +45,9 @@ type Resolver struct { LoadBinding func(context.Context) (string, error) ReadKey func() (string, error) DefaultKB string + // ResolveConnection 可选:一次解析端点与凭据(例如来自加密存储)。 + // 提供时优先于 Endpoint + ReadKey,因为密钥解密需要请求上下文。 + ResolveConnection func(context.Context) (baseURL, apiKey string, err error) } func (resolver Resolver) Resolve(ctx context.Context) (Target, error) { @@ -58,19 +61,26 @@ func (resolver Resolver) Resolve(ctx context.Context) (Target, error) { knowledgeBaseID = stored } } - apiKey := "" - if resolver.ReadKey != nil { - value, err := resolver.ReadKey() + baseURL, apiKey := "", "" + if resolver.ResolveConnection != nil { + var err error + baseURL, apiKey, err = resolver.ResolveConnection(ctx) if err != nil { - return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败") + return Target{}, fmt.Errorf("读取 WeKnora 有效连接失败:%w", err) + } + } else { + if resolver.ReadKey != nil { + value, err := resolver.ReadKey() + if err != nil { + return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败") + } + apiKey = strings.TrimSpace(value) + } + if resolver.Endpoint != nil { + baseURL = strings.TrimSpace(resolver.Endpoint(ctx)) } - apiKey = strings.TrimSpace(value) } - baseURL := "" - if resolver.Endpoint != nil { - baseURL = strings.TrimSpace(resolver.Endpoint(ctx)) - } - return Target{BaseURL: baseURL, KnowledgeBaseID: knowledgeBaseID, APIKey: apiKey}, nil + return Target{BaseURL: strings.TrimSpace(baseURL), KnowledgeBaseID: knowledgeBaseID, APIKey: strings.TrimSpace(apiKey)}, nil } type Prober struct { diff --git a/internal/secretbox/secretbox.go b/internal/secretbox/secretbox.go new file mode 100644 index 0000000..6e995fb --- /dev/null +++ b/internal/secretbox/secretbox.go @@ -0,0 +1,66 @@ +// Package secretbox 是平台唯一的对称加密落库入口:主密钥来自独立文件 +// (0600 常规文件,正好 32 字节),密文通过 AES-256-GCM 与调用方给出的 +// Additional Authenticated Data 绑定。AAD 让一行密文无法被搬到另一行 +// (换环境/换修订)后仍能解开。 +package secretbox + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "errors" + "os" +) + +var ErrUnavailable = errors.New("secret key is not available") + +type Box struct { + aead cipher.AEAD +} + +// Load 读取主密钥。拒绝非普通文件、非 0600 权限或长度不是 32 字节的密钥, +// 避免"碰巧能读到"就被当成已正确配置。 +func Load(path string) (*Box, error) { + if path == "" { + return nil, ErrUnavailable + } + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 { + return nil, ErrUnavailable + } + key, err := os.ReadFile(path) + if err != nil || len(key) != 32 { + return nil, ErrUnavailable + } + block, err := aes.NewCipher(key) + if err != nil { + return nil, ErrUnavailable + } + aead, err := cipher.NewGCM(block) + if err != nil { + return nil, ErrUnavailable + } + return &Box{aead: aead}, nil +} + +func (box *Box) Seal(plaintext []byte, aad string) ([]byte, error) { + if box == nil || box.aead == nil { + return nil, ErrUnavailable + } + nonce := make([]byte, box.aead.NonceSize()) + if _, err := rand.Read(nonce); err != nil { + return nil, ErrUnavailable + } + return box.aead.Seal(nonce, nonce, plaintext, []byte(aad)), nil +} + +func (box *Box) Open(sealed []byte, aad string) ([]byte, error) { + if box == nil || box.aead == nil || len(sealed) < box.aead.NonceSize() { + return nil, ErrUnavailable + } + raw, err := box.aead.Open(nil, sealed[:box.aead.NonceSize()], sealed[box.aead.NonceSize():], []byte(aad)) + if err != nil { + return nil, ErrUnavailable + } + return raw, nil +} diff --git a/scripts/test-scope.json b/scripts/test-scope.json index 61b9603..4b6884b 100644 --- a/scripts/test-scope.json +++ b/scripts/test-scope.json @@ -657,6 +657,11 @@ "package": "knowledge-governance/internal/releaseadapter/v071", "test": "TestV090ProductionTargetPublishIsolated", "reason": "需显式一次性本机PG(两份 0.9.0 真 schema 库)/ES/对象存储:真实导出→封存→ProductionLibraryTarget 写入 134 目标→逐表核对→写前镜像回滚,验证 0.9.0 无 wiki_log_entries、chunks 新增 NOT NULL 列走默认值、seq_id 由目标序列分配;普通CI没有这些服务,跳过不是通过" + }, + { + "package": "knowledge-governance/internal/kbbinding", + "test": "TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction", + "reason": "需显式一次性本机治理PG(TEST_DATABASE_URL):真实迁移、事务内连接/绑定/待入库重排与并发修订冲突;普通CI没有该库,跳过不是通过" } ] } diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index 0c56688..61ae10e 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -125,7 +125,7 @@ describe('ModulePage', () => { expect(html).toContain('P2 · 知识治理总览') expect(html).toContain('PP历史来源清单已接管') expect(html).toContain('生产写入:关闭') - expect(html).toContain('以「系统设置 → 知识库映射」的实时探测为准') + expect(html).toContain('以「系统设置 → 知识库绑定」的实时探测为准') expect(html).not.toContain('本地测试WeKnora已连接') expect(html).not.toContain('生产WeKnora仍未连接') expect(html).not.toContain('尚未连接测试或生产WeKnora') diff --git a/web/src/App.tsx b/web/src/App.tsx index ac993eb..5c14c97 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -505,7 +505,7 @@ export function ModulePage({ ? '已开启' : '已开启(快照恢复未验证,仍被阻断)' : '关闭'} - ;测试 / 生产 WeKnora 连接状态以「系统设置 → 知识库映射」的实时探测为准。 + ;测试 / 生产 WeKnora 连接状态以「系统设置 → 知识库绑定」的实时探测为准。 Release Worker 默认关闭 diff --git a/web/src/KnowledgeBaseBinding.test.tsx b/web/src/KnowledgeBaseBinding.test.tsx new file mode 100644 index 0000000..33dec3f --- /dev/null +++ b/web/src/KnowledgeBaseBinding.test.tsx @@ -0,0 +1,213 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { AuthContext } from './auth' +import { KnowledgeBaseBinding } from './KnowledgeBaseBinding' +import type { KBEnvironmentBinding } from './knowledgeBaseBindings' + +const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({ + environment, + revision: 1, + base_url: `https://${environment}.weknora.example`, + key_configured: true, + key_source: 'sealed', + internal_kb_id: `kb-${environment}-in-0001`, + internal_kb_name: `${environment} 内部资料`, + external_kb_id: `kb-${environment}-out-0001`, + external_kb_name: `${environment} 对外资料`, + verification: 'verified', + checked_at: null, + updated_by: 'admin', + updated_at: null, + source: 'web', + storage_ready: true, + replanned: 0, + retired_duplicates: 0, +}) + +const snapshot = { + data: { environments: [binding('test'), binding('production')], storage_ready: true }, +} +const catalog = { + data: { + status: 'ok', + message: '已读取 2 个知识库', + page: 1, + page_size: 20, + total: 2, + options: [ + { id: 'kb-new-in-0001', name: '新内部库', knowledge_count: 3 }, + { id: 'kb-new-out-0001', name: '新对外库', knowledge_count: 4 }, + ], + }, +} + +const json = (value: unknown, status = 200) => ({ + ok: status >= 200 && status < 300, + status, + json: async () => value, +}) + +const auth = (role: 'admin' | 'viewer') => ({ + identity: { id: `${role}-1`, username: role, display_name: role, role, must_change_password: false }, + ready: true, + login: async () => null, + logout: async () => {}, + changePassword: async () => null, + signedOut: 0, + notifySignedOut: () => {}, +}) + +let root: Root +let host: HTMLDivElement +const flush = async () => { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) +} +const click = async (label: string) => { + const button = [...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === label) + expect(button, label).toBeTruthy() + await act(async () => button!.click()) + await flush() +} +const choose = async (label: string, value: string) => { + const select = [...host.querySelectorAll('label')] + .find((item) => item.textContent?.startsWith(label)) + ?.querySelector('select') + expect(select, label).toBeTruthy() + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(select, value) + select!.dispatchEvent(new Event('change', { bubbles: true })) + }) +} +const type = async (label: string, value: string) => { + const input = [...host.querySelectorAll('label')] + .find((item) => item.textContent?.startsWith(label)) + ?.querySelector('input') + expect(input, label).toBeTruthy() + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value) + input!.dispatchEvent(new Event('input', { bubbles: true })) + }) +} + +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) +}) +afterEach(async () => { + await act(async () => root.unmount()) + host.remove() + vi.unstubAllGlobals() +}) + +const render = async (role: 'admin' | 'viewer' = 'admin') => { + await act(async () => { + root.render( + + + + ) + }) + await flush() +} + +describe('KnowledgeBaseBinding', () => { + it('switches environments without letting a late catalog response cross over', async () => { + let resolveCatalog: ((value: unknown) => void) | null = null + vi.stubGlobal( + 'fetch', + vi.fn((url: string) => { + if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot)) + if (String(url).includes('/catalog')) { + return new Promise((resolve) => { + resolveCatalog = resolve + }) + } + return Promise.resolve(json({ data: binding('test') })) + }) + ) + await render() + expect(host.textContent).toContain('当前生效 · 测试 090') + expect(host.textContent).toContain('test 内部资料(kb-test-…)') + + await click('验证并读取知识库') + await click('生产 090') + expect(host.textContent).toContain('当前生效 · 生产 090') + expect(host.textContent).toContain('production 内部资料') + + await act(async () => { + resolveCatalog?.(json(catalog)) + }) + await flush() + // 迟到的测试环境列库结果不得出现在生产工作区。 + expect(host.textContent).not.toContain('新内部库') + expect(host.textContent).toContain('production 内部资料') + }) + + it('keeps the old binding visible when a save fails and never applies an unsaved draft', async () => { + const fetchMock = vi.fn((url: string, init?: { method?: string }) => { + if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot)) + if (String(url).includes('/catalog')) return Promise.resolve(json(catalog)) + if (init?.method === 'PUT') return Promise.resolve(json({ error: '候选实例拒绝保存' }, 400)) + return Promise.resolve(json({ data: binding('test') })) + }) + vi.stubGlobal('fetch', fetchMock) + await render() + await click('验证并读取知识库') + await choose('对内知识库', 'kb-new-in-0001') + await choose('对外知识库', 'kb-new-out-0001') + expect(host.textContent).toContain('有未保存的修改') + await click('保存测试绑定') + + expect(host.textContent).toContain('候选实例拒绝保存') + // 顶部当前生效仍是旧值;草稿只存在于下方。 + expect(host.textContent).toContain('test 内部资料(kb-test-…)') + expect(host.textContent).not.toContain('当前生效 · 测试 090新内部库') + const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT') + expect(put).toBeTruthy() + const body = JSON.parse(String((put![1] as { body: string }).body)) + expect(body).toMatchObject({ + base_revision: 1, + base_url: 'https://test.weknora.example', + key_action: 'keep', + internal_kb_id: 'kb-new-in-0001', + external_kb_id: 'kb-new-out-0001', + }) + expect(body.api_key).toBeUndefined() + }) + + it('gives viewers a read-only summary with no editing inputs', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot))) + await render('viewer') + expect(host.textContent).toContain('普通用户只读') + expect(host.textContent).toContain('当前生效 · 测试 090') + expect(host.querySelectorAll('input')).toHaveLength(0) + expect( + [...host.querySelectorAll('button')].every((button) => + ['测试 090', '生产 090'].includes(button.textContent?.trim() ?? '') + ) + ).toBe(true) + }) + + it('requires a new key after the address changes and clears the previous selection', async () => { + vi.stubGlobal( + 'fetch', + vi.fn((url: string) => { + if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot)) + return Promise.resolve(json(catalog)) + }) + ) + await render() + await type('服务地址', 'https://new.weknora.example') + expect(host.textContent).toContain('已更换服务地址:必须为新地址重新录入 API Key') + const selects = [...host.querySelectorAll('select')] + expect(selects.every((select) => select.value === '')).toBe(true) + const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定')) + expect(save?.hasAttribute('disabled')).toBe(true) + }) +}) diff --git a/web/src/KnowledgeBaseBinding.tsx b/web/src/KnowledgeBaseBinding.tsx new file mode 100644 index 0000000..6e9ce9e --- /dev/null +++ b/web/src/KnowledgeBaseBinding.tsx @@ -0,0 +1,570 @@ +import { useEffect, useMemo, useRef, useState } from 'react' + +import { useOptionalAuth } from './auth' +import { secretEntryAllowed } from './secureEntry' +import { + KBBindingError, + duplicateSelection, + fetchKBBindings, + fetchKBCatalog, + keyActionFor, + knowledgeBaseLabel, + saveKBBinding, + shortKnowledgeBaseID, +} from './knowledgeBaseBindings' +import type { + KBEnvironment, + KBEnvironmentBinding, + KBBindingSnapshot, + KBCatalog, + KBCatalogOption, +} from './knowledgeBaseBindings' +import { validServiceEndpoint } from './uiSettings' + +const environments: { key: KBEnvironment; label: string; short: string }[] = [ + { key: 'test', label: '测试 090', short: '测试' }, + { key: 'production', label: '生产 090', short: '生产' }, +] + +type Busy = '' | 'catalog' | 'saving' +type Notice = { tone: 'ok' | 'error'; text: string } + +interface Draft { + baseURL: string + replaceKey: boolean + apiKey: string + internalID: string + internalName: string + externalID: string + externalName: string + catalog: KBCatalog | null + verifiedBaseURL: string +} + +type Drafts = Record +type BusyMap = Record +type NoticeMap = Record + +function draftFrom(saved: KBEnvironmentBinding): Draft { + return { + baseURL: saved.base_url, + replaceKey: !saved.key_configured, + apiKey: '', + internalID: saved.internal_kb_id, + internalName: saved.internal_kb_name, + externalID: saved.external_kb_id, + externalName: saved.external_kb_name, + catalog: null, + verifiedBaseURL: '', + } +} + +function emptyDrafts(snapshot: KBBindingSnapshot): Drafts { + return { test: draftFrom(snapshot.test), production: draftFrom(snapshot.production) } +} + +const sameDraft = (draft: Draft, saved: KBEnvironmentBinding): boolean => + draft.baseURL.trim() === saved.base_url && + !draft.replaceKey && + draft.apiKey === '' && + draft.internalID === saved.internal_kb_id && + draft.externalID === saved.external_kb_id + +const statusTone = (status: KBCatalog['status']): string => + status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error' + +export function KnowledgeBaseBinding() { + const auth = useOptionalAuth() + const isAdmin = auth?.identity?.role === 'admin' + const [snapshot, setSnapshot] = useState(null) + const [env, setEnv] = useState('test') + const [drafts, setDrafts] = useState(null) + const [busy, setBusy] = useState({ test: '', production: '' }) + const [notices, setNotices] = useState({ test: null, production: null }) + const [loadError, setLoadError] = useState(null) + const [loading, setLoading] = useState(true) + const catalogSeq = useRef(0) + const saveSeq = useRef(0) + const envRef = useRef(env) + const loadAbort = useRef(null) + const catalogAbort = useRef(null) + const saveAbort = useRef(null) + envRef.current = env + + const load = async () => { + const controller = new AbortController() + loadAbort.current?.abort() + loadAbort.current = controller + setLoading(true) + setLoadError(null) + try { + const next = await fetchKBBindings(controller.signal) + if (controller.signal.aborted) return + setSnapshot(next) + setDrafts((current) => current ?? emptyDrafts(next)) + } catch (cause) { + if (!controller.signal.aborted) { + setLoadError(cause instanceof Error ? cause.message : '读取知识库绑定失败') + } + } finally { + if (!controller.signal.aborted) setLoading(false) + } + } + + useEffect(() => { + void load() + return () => { + loadAbort.current?.abort() + catalogAbort.current?.abort() + saveAbort.current?.abort() + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + const saved = snapshot?.[env] ?? null + const draft = drafts?.[env] ?? null + const busyNow = busy[env] + const notice = notices[env] + + const secure = typeof window !== 'undefined' && secretEntryAllowed(window.location) + const storageReady = Boolean(snapshot?.storage_ready) + const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace' + const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== '' + const keyEntryBlocked = !secure || !storageReady + const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false + const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false + const catalogReady = Boolean( + draft?.catalog && + draft.verifiedBaseURL === draft.baseURL && + (draft.catalog.status === 'ok' || draft.catalog.status === 'empty') + ) + const dirty = Boolean(saved && draft && !sameDraft(draft, saved)) + const canSave = Boolean( + isAdmin && + saved && + draft && + dirty && + !busyNow && + storageReady && + endpointValid && + keyReady && + !duplicate && + catalogReady + ) + + const patchDraft = (patch: Partial) => { + setDrafts((current) => (current ? { ...current, [env]: { ...current[env], ...patch } } : current)) + setNotices((current) => ({ ...current, [env]: null })) + } + + const switchEnvironment = (next: KBEnvironment) => { + if (next === env) return + // 切换只作废在途列库:迟到结果不得写进另一个环境的工作区。 + // 保存按目标环境落库,响应也只更新该环境的状态,切回来仍是真实结果。 + catalogSeq.current++ + catalogAbort.current?.abort() + setEnv(next) + } + + const onBaseURLChange = (value: string) => { + if (!saved) return + const changed = value.trim() !== saved.base_url + patchDraft({ + baseURL: value, + replaceKey: changed ? true : !saved.key_configured, + internalID: '', + internalName: '', + externalID: '', + externalName: '', + catalog: null, + verifiedBaseURL: '', + }) + } + + const runCatalog = async (page: number) => { + if (!saved || !draft) return + if (!endpointValid) { + setNotices((current) => ({ + ...current, + [env]: { tone: 'error', text: '请填写有效的 http(s) 服务地址(不能带用户名、? 查询串或 #)' }, + })) + return + } + if (keyAction === 'replace' && draft.apiKey.trim() === '') { + setNotices((current) => ({ ...current, [env]: { tone: 'error', text: '请先填入这个地址的 API Key' } })) + return + } + if (keyAction === 'keep' && !saved.key_configured) { + setNotices((current) => ({ ...current, [env]: { tone: 'error', text: '当前连接还没有可用密钥,请先录入' } })) + return + } + const targetEnv = env + const seq = ++catalogSeq.current + const controller = new AbortController() + catalogAbort.current = controller + setBusy((current) => ({ ...current, [targetEnv]: 'catalog' })) + setNotices((current) => ({ ...current, [targetEnv]: null })) + try { + const catalog = await fetchKBCatalog( + targetEnv, + { + base_revision: saved.revision, + base_url: draft.baseURL.trim(), + key_action: keyAction, + ...(keyAction === 'replace' ? { api_key: draft.apiKey } : {}), + page, + page_size: 20, + }, + controller.signal + ) + if (controller.signal.aborted || seq !== catalogSeq.current || envRef.current !== targetEnv) return + setDrafts((current) => { + if (!current) return current + return { + ...current, + [targetEnv]: { ...current[targetEnv], catalog, verifiedBaseURL: draft.baseURL.trim() }, + } + }) + } catch (cause) { + if (controller.signal.aborted || seq !== catalogSeq.current || envRef.current !== targetEnv) return + setNotices((current) => ({ + ...current, + [targetEnv]: { tone: 'error', text: cause instanceof Error ? cause.message : '读取知识库列表失败' }, + })) + } finally { + setBusy((current) => ({ ...current, [targetEnv]: '' })) + } + } + + const runSave = async () => { + if (!saved || !draft || !canSave) return + const targetEnv = env + const seq = ++saveSeq.current + const controller = new AbortController() + saveAbort.current = controller + setBusy((current) => ({ ...current, [targetEnv]: 'saving' })) + setNotices((current) => ({ ...current, [targetEnv]: null })) + try { + const view = await saveKBBinding( + targetEnv, + { + base_revision: saved.revision, + base_url: draft.baseURL.trim(), + key_action: keyAction, + ...(keyAction === 'replace' ? { api_key: draft.apiKey } : {}), + internal_kb_id: draft.internalID, + external_kb_id: draft.externalID, + }, + controller.signal + ) + if (controller.signal.aborted || seq !== saveSeq.current) return + setSnapshot((current) => (current ? { ...current, [targetEnv]: view } : current)) + setDrafts((current) => (current ? { ...current, [targetEnv]: draftFrom(view) } : current)) + const replan = + view.replanned || view.retired_duplicates + ? `;同时把 ${view.replanned} 项未上传的待入库重新指向新库${view.retired_duplicates ? `,${view.retired_duplicates} 项因新库已有同篇而退休` : ''}` + : '' + setNotices((current) => ({ + ...current, + [targetEnv]: { + tone: 'ok', + text: `已保存${environments.find((item) => item.key === targetEnv)?.short}绑定:对内 ${ + view.internal_kb_name || shortKnowledgeBaseID(view.internal_kb_id) || '未绑定' + } · 对外 ${view.external_kb_name || shortKnowledgeBaseID(view.external_kb_id) || '未绑定'}${replan}`, + }, + })) + } catch (cause) { + if (controller.signal.aborted || seq !== saveSeq.current) return + const message = cause instanceof Error ? cause.message : '保存知识库绑定失败' + setNotices((current) => ({ ...current, [targetEnv]: { tone: 'error', text: message } })) + if (cause instanceof KBBindingError && cause.status === 409) { + // 冲突:重新读取服务器生效值,保留草稿但作废这次列库结论,必须按新版本重验。 + try { + const fresh = await fetchKBBindings() + if (seq !== saveSeq.current) return + setSnapshot(fresh) + setDrafts((current) => + current + ? { ...current, [targetEnv]: { ...current[targetEnv], catalog: null, verifiedBaseURL: '' } } + : current + ) + } catch { + /* 读取失败时保留现有显示,错误信息已经可见 */ + } + } + } finally { + setBusy((current) => ({ ...current, [targetEnv]: '' })) + } + } + + const currentOptions = useMemo<{ internal: KBCatalogOption[]; external: KBCatalogOption[] }>(() => { + const base = draft?.catalog?.options ?? [] + const withSelection = (id: string, name: string): KBCatalogOption[] => { + if (!id || base.some((option) => option.id === id)) return base + return [{ id, name: name || shortKnowledgeBaseID(id), knowledge_count: 0 }, ...base] + } + return { + internal: draft ? withSelection(draft.internalID, draft.internalName) : [], + external: draft ? withSelection(draft.externalID, draft.externalName) : [], + } + }, [draft]) + + const renderCurrent = (binding: KBEnvironmentBinding) => ( +
+ 当前生效 · {environments.find((item) => item.key === binding.environment)?.label} +
+ + 对内 {knowledgeBaseLabel(binding.internal_kb_id, binding.internal_kb_name)} + + + 对外 {knowledgeBaseLabel(binding.external_kb_id, binding.external_kb_name)} + +
+ + {binding.base_url || '未配置服务地址'} ·{' '} + {binding.key_configured + ? binding.key_source === 'file' + ? 'API Key 来自服务器文件' + : 'API Key 已配置(不回显)' + : 'API Key 未配置'} + {binding.source === 'legacy' ? ' · 旧部署配置' : ` · 版本 ${binding.revision}`} + +
+ ) + + if (!isAdmin) { + return ( +
+
+
+

知识库绑定

+

普通用户只读:这里显示当前生效的连接与内外库绑定。

+
+
+ + {saved ? renderCurrent(saved) : loading ?

正在读取知识库绑定…

: null} + {loadError ? ( +

+ {loadError} +

+ ) : null} +
+ ) + } + + return ( +
+
+
+

知识库绑定

+

+ 一次保存当前环境的连接与对内/对外绑定。地址与密钥由服务器真实列库核验;顶部始终是已生效的值, + 下面的修改只是草稿。 +

+
+
+ + {saved ? renderCurrent(saved) : loading ?

正在读取知识库绑定…

: null} + {loadError ? ( +

+ {loadError} +

+ ) : null} + {!storageReady && snapshot ? ( +

+ 独立安全存储未就绪(服务器未配置 WEKNORA_BINDING_MASTER_KEY_FILE):可以查看旧绑定,但不能保存新连接。 +

+ ) : null} + {saved && draft ? ( + <> +
+

WeKnora 连接 · {environments.find((item) => item.key === env)?.label}

+ {env === 'production' ? ( +

+ 生产连接用于候选列库与探活;文档级/整库发布实际写入目标仍由部署配置决定(见下方诊断)。 +

+ ) : null} +
+ +
+ API Key + {saved.key_configured && !draft.replaceKey ? ( +
+ 已配置(不回显){saved.key_source === 'file' ? ' · 服务器文件' : ''} + +
+ ) : ( +
+ + patchDraft({ apiKey: event.target.value, catalog: null, verifiedBaseURL: '' }) + } + autoComplete="new-password" + spellCheck={false} + placeholder={saved.key_configured ? '输入新密钥;保存后才生效' : '仅用于此治理平台'} + disabled={busyNow !== '' || keyEntryBlocked} + aria-invalid={keyEntryBlocked} + /> + {saved.key_configured && draft.baseURL.trim() === saved.base_url ? ( + + ) : null} +
+ )} +
+
+ {!secure ? ( +

当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。

+ ) : null} + {saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? ( +

已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。

+ ) : null} +
+ + 服务器会用这份地址与密钥真实列库,只读,不写入。 +
+ {draft.catalog ? ( +
+ {draft.catalog.message} + {draft.catalog.total > 0 + ? ` · 第 ${draft.catalog.page} / ${Math.max(1, Math.ceil(draft.catalog.total / draft.catalog.page_size))} 页` + : ''} + {draft.catalog.total > draft.catalog.page_size ? ( + + + + + ) : null} +
+ ) : ( +

验证并读取后,才能从这份连接可读的库里选择。

+ )} +
+
+

选择已有知识库

+
+ + +
+ 名称相同很常见,括号里的短 ID 才是区分依据;对内与对外不能选同一个库。 + {duplicate ?

对内和对外不能绑定同一个知识库。

: null} +
+
+ + {notice?.text || (dirty ? '有未保存的修改;当前生效值未改变' : '草稿与当前生效值一致')} + + +
+ + ) : null} +
+ ) +} diff --git a/web/src/ProductionBindingsSection.tsx b/web/src/ProductionBindingsSection.tsx index 251d841..bf3b889 100644 --- a/web/src/ProductionBindingsSection.tsx +++ b/web/src/ProductionBindingsSection.tsx @@ -22,6 +22,7 @@ export interface ProductionBindingsViewProps { message: string dirty: boolean sameSelection: boolean + diagnosticsOnly?: boolean onInternalChange: (next: string) => void onExternalChange: (next: string) => void onSave: () => void @@ -41,6 +42,7 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) { message, dirty, sameSelection, + diagnosticsOnly = false, onInternalChange, onExternalChange, onSave, @@ -161,7 +163,7 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) { {bindings.updated_by ? ` · 最近修改:${bindings.updated_by}` : ''}

) : null} - {isAdmin && bindings ? ( + {!diagnosticsOnly && isAdmin && bindings ? (
@@ -178,13 +180,13 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) { ) : null}
) : null} - {!isAdmin ?

仅管理员可修改文档级发布目标。

: null} + {!diagnosticsOnly && !isAdmin ?

仅管理员可修改文档级发布目标。

: null} ) } // 容器:读取 + 保存。整库目标只读展示,保存动作只写文档级绑定。 -export function ProductionBindingsSection() { +export function ProductionBindingsSection({ diagnosticsOnly = false }: { diagnosticsOnly?: boolean } = {}) { const auth = useOptionalAuth() const isAdmin = auth?.identity?.role === 'admin' const [bindings, setBindings] = useState(null) @@ -256,6 +258,7 @@ export function ProductionBindingsSection() { message={message} dirty={dirty} sameSelection={sameSelection} + diagnosticsOnly={diagnosticsOnly} onInternalChange={setInternalDraft} onExternalChange={setExternalDraft} onSave={() => void save()} diff --git a/web/src/QAModelSettings.tsx b/web/src/QAModelSettings.tsx index 2ca587c..7dd47e6 100644 --- a/web/src/QAModelSettings.tsx +++ b/web/src/QAModelSettings.tsx @@ -3,9 +3,9 @@ import type { AISettings } from './qaAITypes' import type { AISettingsInput } from './qaAI' import { fetchAISettings, saveAISettings, testAISettings } from './qaAI' import { QARequestError } from './qaOps' -export function qaAIKeyEntryAllowed(location: { protocol: string; hostname: string }) { - return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname) -} +import { secretEntryAllowed } from './secureEntry' +// 兼容既有导入:密钥录入的安全判定只有一份,实现已移到 secureEntry。 +export const qaAIKeyEntryAllowed = secretEntryAllowed const verificationLabels: Record = { not_configured: '未配置可用密钥', verified: '已通过真实连接测试', diff --git a/web/src/RoutingBindingsSection.tsx b/web/src/RoutingBindingsSection.tsx index 16c0400..a5c50df 100644 --- a/web/src/RoutingBindingsSection.tsx +++ b/web/src/RoutingBindingsSection.tsx @@ -4,7 +4,7 @@ import { useOptionalAuth } from './auth' import { fetchRoutingBindingOptions, fetchRoutingBindings, saveRoutingBindings } from './routingBindings' import type { KnowledgeBaseOption, RoutingBindings } from './routingBindings' -export function RoutingBindingsSection() { +export function RoutingBindingsSection({ diagnosticsOnly = false }: { diagnosticsOnly?: boolean } = {}) { const auth = useOptionalAuth() const isAdmin = auth?.identity?.role === 'admin' const [bindings, setBindings] = useState(null) @@ -168,7 +168,7 @@ export function RoutingBindingsSection() { {bindings && !bindings.weknora_connected ? (

当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。

) : null} - {isAdmin && bindings ? ( + {!diagnosticsOnly && isAdmin && bindings ? (
@@ -184,7 +184,7 @@ export function RoutingBindingsSection() { ) : null}
) : null} - {!isAdmin ?

仅管理员可修改测试知识库绑定。

: null} + {!diagnosticsOnly && !isAdmin ?

仅管理员可修改测试知识库绑定。

: null} ) } diff --git a/web/src/SystemSettings.test.tsx b/web/src/SystemSettings.test.tsx index aee2cf8..253baab 100644 --- a/web/src/SystemSettings.test.tsx +++ b/web/src/SystemSettings.test.tsx @@ -141,13 +141,13 @@ describe('SystemSettingsView AI 模型连接', () => { /> ) - it('keeps the model connection alone in AI 模型连接 and points WeKnora to 知识库映射', () => { + it('keeps the model connection alone in AI 模型连接 and points WeKnora to 知识库绑定', () => { const adminHtml = view('admin') for (const text of [ 'AI 模型连接', '正在读取已保存的模型连接', '问答四字段分析与中文问题翻译共用此连接', - 'WeKnora 的知识库连接已移到「知识库映射」', + 'WeKnora 的知识库连接已移到「知识库绑定」', ]) { expect(adminHtml).toContain(text) } @@ -179,7 +179,7 @@ describe('SystemSettingsView', () => { onRefresh={vi.fn()} /> ) - for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库映射', '存储与备份', '刷新策略']) + for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '刷新策略']) expect(html).toContain(text) // 主人 2026-10-26 要求去掉的噪声:页头副标题、刷新状态、权限条、活动版本横幅。 for (const removed of [ @@ -202,7 +202,7 @@ describe('SystemSettingsView', () => { expect(html).not.toContain(removed) // 需求(2026-10-10):新增入口只剩「可加入的来源」勾选,粘贴链接的按钮已下线。 for (const removed of ['+ 新增钉钉知识库', '新增钉钉知识库']) expect(html).not.toContain(removed) - // WeKnora 连接已迁到「知识库映射」:地址与核验参数跟入库/封存/生产目标同屏。 + // WeKnora 连接已迁到「知识库绑定」:主表单保存连接+绑定,诊断折叠保留。 const mapHtml = renderToStaticMarkup( { ) for (const text of [ - 'WeKnora 连接', + '知识库绑定', + '测试 090', + '生产 090', + '正在读取知识库绑定…', + '连接与绑定诊断', '测试 WeKnora', '生产 WeKnora', - '测试地址', - '生产地址', - '生产租户 ID', - '知识库 ID', - '保存并校验连接', - '生产核验参数', + '整库发布目标', ]) expect(mapHtml).toContain(text) - // 凭据是服务器文件引用:连接卡只报状态,页面不提供 API Key 录入。 + // 旧连接表单已被单一保存入口取代;SSR 尚未读到绑定时不渲染密钥输入。 + for (const removed of ['保存并校验连接', '测试地址', '生产租户 ID', '生产核验参数']) + expect(mapHtml).not.toContain(removed) expect(mapHtml).not.toContain('API Key') const storageHtml = renderToStaticMarkup( { /> ) - // 测试绑定与生产目标已合并为「知识库映射」:入库目标、封存源、生产目标同屏。 - expect(view('sources')).toContain('知识库映射') + // 旧入口(bindings / production-bindings)都落到「知识库绑定」:新主表单 + 折叠诊断。 + expect(view('sources')).toContain('知识库绑定') const bound = view('bindings') + expect(bound).toContain('id="settings-kb-bindings"') + expect(bound).toContain('知识库绑定') + expect(bound).toContain('正在读取知识库绑定…') + expect(bound).toContain('连接与绑定诊断') + // 诊断区保留原链路:测试入库绑定与生产目标入口仍在,但不再提供第二个保存路径。 expect(bound).toContain('id="settings-routing-bindings"') expect(bound).toContain('分发到对应的测试 WeKnora 知识库') - // 未读到绑定数据时(SSR 不跑 effect)面板也要如实存在,而不是空白。 - expect(bound).toContain('读取中…') - // 发布目标(源库 → 目标库)是独立分区,与测试端收件库分开。 const target = view('production-bindings') expect(target).toContain('id="settings-production-bindings"') expect(target).toContain('整库发布目标') @@ -437,7 +440,7 @@ describe('SystemSettingsView', () => { expect(on).toContain('延迟 86ms') expect(on).toContain('已启用 · 可提交生产请求') expect(on).toContain('生产写入:开启') - expect(on).toContain('凭据:服务器文件引用,页面不回读') + expect(on).toContain('凭据:服务器文件/加密存储,页面不回读') const off = view(false, false) expect(off).toContain('未启用') expect(off).toContain('生产写入:关闭') diff --git a/web/src/SystemSettings.tsx b/web/src/SystemSettings.tsx index 26648a3..e61a57d 100644 --- a/web/src/SystemSettings.tsx +++ b/web/src/SystemSettings.tsx @@ -9,6 +9,8 @@ import { RoutingBindingsSection } from './RoutingBindingsSection' import { ProductionBindingsSection } from './ProductionBindingsSection' import { SourceWizard } from './SourceWizard' import { PPConnection } from './PPConnection' +import { KnowledgeBaseBinding } from './KnowledgeBaseBinding' +import { WeKnoraConnectionDiagnostics } from './weKnoraDiagnostics' import { useOptionalAuth } from './auth' import { fetchMonitorOverview } from './monitor' import type { MonitorOverview } from './monitor' @@ -22,10 +24,9 @@ import type { SourceConnectionListItem } from './sourceConnections' import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings } from './uiSettings' import type { UISettings, UISettingsCandidateInput } from './uiSettings' import { refreshSettingsInput } from './settingsInputs' -import { WeKnoraConnections } from './WeKnoraConnections' import './systemSettings.css' -// 连接配置已从「服务配置」迁到「知识库映射」。这两个纯函数仍从本模块导出, +// 连接配置已从「服务配置」迁到「知识库绑定」。这两个纯函数仍从本模块导出, // 既有调用与回归测试的导入路径不变。 export { refreshSettingsInput, serviceSettingsInput } from './settingsInputs' export type { RefreshDrafts, ServiceDrafts } from './settingsInputs' @@ -46,16 +47,16 @@ interface Props { onSave: (input: UISettingsCandidateInput) => void onSourcesChanged: () => void onRefresh: () => void - // 兼容旧入口:'bindings'/'production-bindings' 已合并为“知识库映射”。 - initialSection?: SectionKey | 'bindings' | 'production-bindings' + // 兼容旧入口:'bindings'/'production-bindings'/'knowledge-map' 都落到「知识库绑定」。 + initialSection?: SectionKey | 'bindings' | 'production-bindings' | 'knowledge-map' } -type SectionKey = 'sources' | 'services' | 'knowledge-map' | 'storage' | 'refresh' | 'members' +type SectionKey = 'sources' | 'services' | 'knowledge-bindings' | 'storage' | 'refresh' | 'members' const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [ { key: 'sources', label: '数据源配置' }, { key: 'services', label: 'AI 模型连接' }, - { key: 'knowledge-map', label: '知识库映射' }, + { key: 'knowledge-bindings', label: '知识库绑定' }, { key: 'storage', label: '存储与备份' }, { key: 'refresh', label: '刷新策略' }, { key: 'members', label: '成员与角色', adminOnly: true }, @@ -99,8 +100,8 @@ export function SystemSettingsView({ const auth = useOptionalAuth() const identity = auth?.identity ?? null const [section, setSection] = useState( - initialSection === 'bindings' || initialSection === 'production-bindings' - ? 'knowledge-map' + initialSection === 'bindings' || initialSection === 'production-bindings' || initialSection === 'knowledge-map' + ? 'knowledge-bindings' : (initialSection as SectionKey) ) const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15) @@ -133,7 +134,7 @@ export function SystemSettingsView({ finalizing !== settings.finalizing_after_seconds || concurrency !== settings.ingestion_concurrency) ) - // 保存边界:刷新分区只带刷新草稿;WeKnora 连接草稿在 WeKnoraConnections 内独立保存, + // 保存边界:刷新分区只带刷新草稿;知识库绑定的连接/选库草稿在独立组件内一次保存, // 互不夹带(未保存的地址不会因为保存刷新策略被写进去)。 const refreshInput = (): UISettingsCandidateInput => settings @@ -210,36 +211,35 @@ export function SystemSettingsView({

AI 模型连接

问答四字段分析与中文问题翻译共用此连接;保存只更新这份连接,不会自动开启自动分析或自动翻译。 - WeKnora 的知识库连接已移到「知识库映射」。 + WeKnora 的知识库连接已移到「知识库绑定」。

{isAdmin ? : 仅管理员可修改模型连接;密钥不回显。} ) : null} - {section === 'knowledge-map' ? ( + {section === 'knowledge-bindings' ? ( <> - {settings ? ( - - ) : null} -

- 一张图看清三件事:入库目标(来源打标分发到此库)、 - 封存源(整库封存实际导出的库)、生产目标(同步写入的库)。 - 前两者不一致时,发布页显示的名字与封存出来的内容会对不上。 -

- - + +
+ 连接与绑定诊断(探活、封存源、整库发布目标) + {settings ? ( + + ) : null} +

+ 封存源是整库封存实际导出的库;整库发布目标由部署配置决定、只读。两者与上面的入库绑定不一致时, + 发布页显示的名字与封存出来的内容会对不上。 +

+ + +
) : null} {section === 'storage' ? ( @@ -254,7 +254,7 @@ export function SystemSettingsView({

刷新策略

-

保存只改这一组参数,不会带上「知识库映射」里未保存的连接地址。

+

保存只改这一组参数,不会带上「知识库绑定」里未保存的连接地址。

当前活动版本
diff --git a/web/src/WeKnoraConnections.mounted.test.tsx b/web/src/WeKnoraConnections.mounted.test.tsx deleted file mode 100644 index f3cdeac..0000000 --- a/web/src/WeKnoraConnections.mounted.test.tsx +++ /dev/null @@ -1,130 +0,0 @@ -// @vitest-environment jsdom -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { WeKnoraConnections } from './WeKnoraConnections' -import type { UISettings } from './uiSettings' - -const settings: UISettings = { - id: 'settings-live', - state: 'active', - document_refresh_seconds: 30, - resource_refresh_seconds: 60, - stalled_after_seconds: 3600, - finalizing_after_seconds: 14400, - ingestion_concurrency: 4, - test_weknora_base_url: 'https://server.test', - production_weknora_base_url: 'https://server.prod', - production_tenant_id: '10000', - production_knowledge_base_id: 'kb-server', - updated_by: 'admin-1', - created_at: '2026-11-18T08:00:00Z', - activated_at: '2026-11-18T08:00:00Z', - retired_at: null, - error_code: '', -} -let root: Root -let host: HTMLDivElement -const click = async (label: string) => { - const button = [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === label) - expect(button, label).toBeTruthy() - await act(async () => button!.click()) -} -const type = async (label: string, value: string) => { - const input = [...host.querySelectorAll('label')] - .find((x) => x.textContent?.startsWith(label)) - ?.querySelector('input') - expect(input, label).toBeTruthy() - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value) - input!.dispatchEvent(new Event('input', { bubbles: true })) - }) -} -beforeEach(() => { - Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) - host = document.createElement('div') - document.body.append(host) - root = createRoot(host) -}) -afterEach(async () => { - await act(async () => root.unmount()) - host.remove() -}) - -describe('WeKnoraConnections', () => { - it('保存只带连接草稿,刷新参数取服务器当前值', async () => { - const onSave = vi.fn() - await act(async () => - root.render( - - ) - ) - await type('测试地址', 'https://draft.test') - await click('保存并校验连接') - expect(onSave).toHaveBeenCalledTimes(1) - expect(onSave.mock.calls[0][0]).toMatchObject({ - test_weknora_base_url: 'https://draft.test', - production_weknora_base_url: 'https://server.prod', - production_tenant_id: '10000', - production_knowledge_base_id: 'kb-server', - document_refresh_seconds: 30, - ingestion_concurrency: 4, - }) - }) - - it('未修改时保存按钮不可点,非法地址也不允许提交', async () => { - const onSave = vi.fn() - await act(async () => - root.render( - - ) - ) - const saveButton = () => - [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === '保存并校验连接') as - HTMLButtonElement | undefined - expect(saveButton()?.disabled).toBe(true) - await type('生产地址', 'https://draft.prod/?token=x') - expect(saveButton()?.disabled).toBe(true) - expect(host.textContent).toContain('格式不合法') - await click('保存并校验连接') - expect(onSave).not.toHaveBeenCalled() - }) - - it('工程师只看到只读摘要,没有保存入口', async () => { - await act(async () => - root.render( - - ) - ) - expect(host.textContent).toContain('仅管理员可修改 WeKnora 连接') - expect(host.textContent).toContain('https://server.test') - expect([...host.querySelectorAll('button')]).toHaveLength(0) - }) -}) diff --git a/web/src/WeKnoraConnections.tsx b/web/src/WeKnoraConnections.tsx deleted file mode 100644 index 153cba5..0000000 --- a/web/src/WeKnoraConnections.tsx +++ /dev/null @@ -1,242 +0,0 @@ -import { useEffect, useState } from 'react' - -import type { MonitorOverview } from './monitor' -import { serviceSettingsInput } from './settingsInputs' -import type { CatalogRoutingCapabilities } from './sourceCatalog' -import type { WorkerCapabilities } from './systemCapabilities' -import { testUploadLabel } from './systemCapabilities' -import { validKnowledgeBaseID, validProductionTenantID, validServiceEndpoint } from './uiSettings' -import type { UISettings, UISettingsCandidateInput } from './uiSettings' - -type ServiceHealthView = MonitorOverview['health'][number] -type ServiceView = MonitorOverview['services'][number] - -// 连接分区只保留四项可写值(测试地址、生产地址、生产 ID、知识库 ID), -// 依赖与解析队列的状态仍按真实探测呈现,不写死。 -export const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined => - (monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name)) -export const healthStateLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { - if (!health) { - if (!service) return '待配置' - return service.state === 'healthy' ? '正常' : service.state === 'unknown' ? '未接入' : '需关注' - } - if (health.readiness === 'ready') return '可达 · 可接单' - if (health.readiness === 'not_configured') return '状态未知 · 未配置' - if (health.readiness === 'not_applicable') return '未部署' - return health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单' -} - -// 测试 WeKnora 卡片只证明“接口就绪”:readiness 不覆盖上传/解析执行器, -// 所以不能沿用“可接单”这种承诺式措辞。 -export const testWeKnoraLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { - const label = healthStateLabel(health, service) - return label === '可达 · 可接单' ? '接口可达 · 执行器未验证' : label -} - -export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { - if (!health) return service?.detail || '真实 Provider 未接入' - const success = health.last_success_at - ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}` - : '' - if (health.readiness === 'ready') return [`延迟 ${health.latency_ms}ms`, success].filter(Boolean).join(';') - const failures = health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : '' - return [health.reason, success, failures].filter(Boolean).join(';') -} - -// 生产 WeKnora 卡片:端点可达性来自真实探测,写入门禁来自生产开关,两者分开呈现。 -// 生产侧只做探活(/health),不做一次真实读写,所以接单能力永远是「未做接单验证」, -// 不跟着别处的「可达 · 可接单」一起含糊过去。 -export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string => { - const health = findHealth(monitor, '生产 WeKnora') - if (!health) return '端点探测:暂无真实探测结果' - if (!health.configured) return '端点探测:未配置' - const label = - health.liveness === 'up' - ? health.readiness === 'ready' - ? '端点可达 · 未做接单验证' - : '端点可达 · 不可接单' - : '端点不可达' - const detail = healthStateDetail(health, undefined) - return `端点探测:${label}${detail ? `(${detail})` : ''}` -} - -export interface WeKnoraConnectionsProps { - settings: UISettings - monitor: MonitorOverview | null - routingCapabilities: CatalogRoutingCapabilities - workerCapabilities?: WorkerCapabilities | null - productionEnabled: boolean - productionBackupRestoreVerified?: boolean - isAdmin: boolean - saving: boolean - saveMessage: string | null - onSave: (input: UISettingsCandidateInput) => void -} - -// 「知识库映射 → WeKnora 连接」:地址由管理员在页面维护,保存前后端会真做一次 -// 探活与列库核验;凭据仍是服务器文件引用,页面只显示状态、不回读也不接受录入。 -export function WeKnoraConnections({ - settings, - monitor, - routingCapabilities, - workerCapabilities = null, - productionEnabled, - productionBackupRestoreVerified = false, - isAdmin, - saving, - saveMessage, - onSave, -}: WeKnoraConnectionsProps) { - const [endpoint, setEndpoint] = useState(settings.production_weknora_base_url ?? '') - const [testEndpoint, setTestEndpoint] = useState(settings.test_weknora_base_url ?? '') - const [productionTenantID, setProductionTenantID] = useState(settings.production_tenant_id ?? '') - const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState( - settings.production_knowledge_base_id ?? '' - ) - - useEffect(() => { - setEndpoint(settings.production_weknora_base_url) - setTestEndpoint(settings.test_weknora_base_url) - setProductionTenantID(settings.production_tenant_id) - setProductionKnowledgeBaseID(settings.production_knowledge_base_id) - }, [settings]) - - const endpointValid = validServiceEndpoint(endpoint) - const testEndpointValid = validServiceEndpoint(testEndpoint) - const productionTenantIDValid = validProductionTenantID(productionTenantID) - const productionKnowledgeBaseIDValid = validKnowledgeBaseID(productionKnowledgeBaseID) - const valid = endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid - const dirty = - testEndpoint.trim() !== settings.test_weknora_base_url || - endpoint.trim() !== settings.production_weknora_base_url || - productionTenantID.trim() !== settings.production_tenant_id || - productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id - - return ( -
-
-
-

WeKnora 连接

-

- 测试与生产各自的地址在这里维护;保存前后端会真做一次探活与列库核验。凭据由服务器文件引用提供, - 页面只显示是否已配置,不回读、也不能在这里录入。 -

-
-
-
-
- 测试 WeKnora - {testWeKnoraLabel(findHealth(monitor, 'WeKnora API'), undefined)} - {`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`} - - {testUploadLabel(workerCapabilities)} - {workerCapabilities ? `:${workerCapabilities.test_upload.detail}` : ''} - -
-
- 生产 WeKnora - - {!productionEnabled - ? '未启用' - : productionBackupRestoreVerified - ? '已启用 · 可提交生产请求' - : '已启用 · 被阻断'} - - {`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};凭据:服务器文件引用,页面不回读`} -
-
- {isAdmin ? ( - <> -
- - -
-
- 生产核验参数(仅用于核验,不决定发布写入目标) -
- - -
- - 这两项用于确认生产端确实存在目标库、租户归属正确;整库发布的实际写入目标见下方「生产知识库绑定」, - 由部署配置决定,不在本页修改。 - -
- -
- 保存规则与核验说明 - - 四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 # 片段, - 凭据一律走文件引用);生产租户 ID 为十进制数字;知识库 ID 粘贴 URL 不会通过。 - 保存会生成修订、真实验证后原子启用;端点回答“没有这个知识库”或租户不符会拒收, - 端点抖动、鉴权失败或未配置生产凭据只警告不拦。 - -
- {valid ? null : ( -

- 格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产 ID - 需为十进制数字;知识库 ID 不能含空格、/、?、# 或 \。 -

- )} - {saveMessage ? ( -

- {saveMessage} -

- ) : null} - - ) : ( - - 仅管理员可修改 WeKnora 连接;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址{' '} - {settings.production_weknora_base_url || '未配置'} · 生产 ID {settings.production_tenant_id || '未配置'} · - 知识库 ID {settings.production_knowledge_base_id || '未配置'}。 - - )} -
- ) -} diff --git a/web/src/knowledgeBaseBindings.test.ts b/web/src/knowledgeBaseBindings.test.ts new file mode 100644 index 0000000..3807e84 --- /dev/null +++ b/web/src/knowledgeBaseBindings.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest' +import { + duplicateSelection, + keyActionFor, + knowledgeBaseLabel, + parseKBBindingSnapshot, + shortKnowledgeBaseID, +} from './knowledgeBaseBindings' +import type { KBEnvironmentBinding } from './knowledgeBaseBindings' + +const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({ + environment, + revision: 1, + base_url: `https://${environment}.example`, + key_configured: true, + key_source: 'sealed', + internal_kb_id: `${environment}-in`, + internal_kb_name: '内部资料', + external_kb_id: `${environment}-out`, + external_kb_name: '对外资料', + verification: 'verified', + checked_at: null, + updated_by: 'admin', + updated_at: null, + source: 'web', + storage_ready: true, + replanned: 0, + retired_duplicates: 0, +}) + +describe('knowledgeBaseBindings', () => { + it('parses both environments and never projects a key field', () => { + const parsed = parseKBBindingSnapshot({ + data: { + environments: [binding('test'), binding('production')], + storage_ready: true, + }, + }) + expect(parsed.test.base_url).toBe('https://test.example') + expect(parsed.production.internal_kb_name).toBe('内部资料') + expect(parsed.storage_ready).toBe(true) + const asRecord = parsed.test as unknown as Record + expect(asRecord.api_key).toBeUndefined() + expect(asRecord.key_ciphertext).toBeUndefined() + }) + + it('rejects a snapshot missing an environment instead of inventing one', () => { + expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow() + }) + + it('shows a short id next to the name so same-name bases are distinguishable', () => { + expect(shortKnowledgeBaseID('0b217e8a-1234-5678')).toBe('0b217e8a…') + expect(knowledgeBaseLabel('0b217e8a-1234-5678', '客户帮助中心')).toBe('客户帮助中心(0b217e8a…)') + expect(knowledgeBaseLabel('', '')).toBe('未绑定') + }) + + it('rejects using one base for both sides', () => { + expect(duplicateSelection('kb-1', 'kb-1')).toBe(true) + expect(duplicateSelection('kb-1', 'kb-2')).toBe(false) + expect(duplicateSelection('', '')).toBe(false) + }) + + it('forces a new key for any address other than the saved one', () => { + const saved = binding('test') + expect(keyActionFor(saved, 'https://test.example', false)).toBe('keep') + expect(keyActionFor(saved, 'https://other.example', false)).toBe('replace') + expect(keyActionFor({ ...saved, key_configured: false }, 'https://test.example', false)).toBe('replace') + expect(keyActionFor(saved, 'https://test.example', true)).toBe('replace') + }) +}) diff --git a/web/src/knowledgeBaseBindings.ts b/web/src/knowledgeBaseBindings.ts new file mode 100644 index 0000000..1911ff2 --- /dev/null +++ b/web/src/knowledgeBaseBindings.ts @@ -0,0 +1,225 @@ +import { newOperationID } from './operationKey' + +export type KBEnvironment = 'test' | 'production' + +export interface KBEnvironmentBinding { + environment: KBEnvironment + revision: number + base_url: string + key_configured: boolean + key_source: string + internal_kb_id: string + internal_kb_name: string + external_kb_id: string + external_kb_name: string + verification: string + checked_at: string | null + updated_by: string + updated_at: string | null + source: 'web' | 'legacy' + storage_ready: boolean + replanned: number + retired_duplicates: number +} + +export interface KBBindingSnapshot { + test: KBEnvironmentBinding + production: KBEnvironmentBinding + storage_ready: boolean +} + +export interface KBCatalogOption { + id: string + name: string + knowledge_count: number +} + +export type KBCatalogStatus = 'ok' | 'empty' | 'unauthorized' | 'unreachable' | 'unsupported' + +export interface KBCatalog { + status: KBCatalogStatus + message: string + page: number + page_size: number + total: number + options: KBCatalogOption[] +} + +export interface KBCatalogInput { + base_revision: number + base_url: string + key_action: 'keep' | 'replace' + api_key?: string + page: number + page_size: number +} + +export interface KBBindingSaveInput { + base_revision: number + base_url: string + key_action: 'keep' | 'replace' + api_key?: string + internal_kb_id: string + external_kb_id: string +} + +export class KBBindingError extends Error { + readonly status: number + + constructor(message: string, status: number) { + super(message) + this.name = 'KBBindingError' + this.status = status + } +} + +const record = (value: unknown): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value) + +const text = (value: unknown): string => (typeof value === 'string' ? value : '') +const bool = (value: unknown): boolean => value === true +const count = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0) + +function parseBinding(value: unknown): KBEnvironmentBinding { + if (!record(value) || (value.environment !== 'test' && value.environment !== 'production')) { + throw new Error('知识库绑定响应无效') + } + return { + environment: value.environment, + revision: count(value.revision), + base_url: text(value.base_url), + key_configured: bool(value.key_configured), + key_source: text(value.key_source), + internal_kb_id: text(value.internal_kb_id), + internal_kb_name: text(value.internal_kb_name), + external_kb_id: text(value.external_kb_id), + external_kb_name: text(value.external_kb_name), + verification: text(value.verification), + checked_at: typeof value.checked_at === 'string' ? value.checked_at : null, + updated_by: text(value.updated_by), + updated_at: typeof value.updated_at === 'string' ? value.updated_at : null, + source: value.source === 'web' ? 'web' : 'legacy', + storage_ready: bool(value.storage_ready), + replanned: count(value.replanned), + retired_duplicates: count(value.retired_duplicates), + } +} + +export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot { + if (!record(value) || !record(value.data) || !Array.isArray(value.data.environments)) { + throw new Error('知识库绑定响应无效') + } + const byEnvironment = new Map() + for (const item of value.data.environments) { + const binding = parseBinding(item) + byEnvironment.set(binding.environment, binding) + } + const test = byEnvironment.get('test') + const production = byEnvironment.get('production') + if (!test || !production) throw new Error('知识库绑定响应缺少环境') + return { test, production, storage_ready: bool(value.data.storage_ready) } +} + +// 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。 +export function shortKnowledgeBaseID(value: string): string { + return value.length > 8 ? `${value.slice(0, 8)}…` : value +} + +export function knowledgeBaseLabel(id: string, name: string): string { + if (!id) return '未绑定' + return name ? `${name}(${shortKnowledgeBaseID(id)})` : shortKnowledgeBaseID(id) +} + +export function duplicateSelection(internal: string, external: string): boolean { + return internal !== '' && internal === external +} + +// Keep is only legal for exactly the saved address; any other draft address +// needs a freshly typed key. This mirrors the server rule so the button state +// cannot promise something the server will refuse. +export function keyActionFor(saved: KBEnvironmentBinding, baseURL: string, replace: boolean): 'keep' | 'replace' { + if (replace || !saved.key_configured) return 'replace' + return baseURL.trim() === saved.base_url ? 'keep' : 'replace' +} + +function failureMessage(value: unknown, fallback: string): string { + if (record(value) && typeof value.error === 'string' && value.error.trim() !== '') return value.error + return fallback +} + +async function readResponse(response: Response): Promise> { + if (response.ok) { + const payload: unknown = await response.json() + return record(payload) ? payload : {} + } + const failure: unknown = await response.json().catch(() => null) + throw new KBBindingError(failureMessage(failure, `知识库绑定请求失败(HTTP ${response.status})`), response.status) +} + +export async function fetchKBBindings(signal?: AbortSignal): Promise { + const response = await fetch('/api/v1/kb-bindings', { signal, headers: { Accept: 'application/json' } }) + return parseKBBindingSnapshot(await readResponse(response)) +} + +export async function fetchKBCatalog( + environment: KBEnvironment, + input: KBCatalogInput, + signal?: AbortSignal +): Promise { + const response = await fetch(`/api/v1/kb-bindings/${environment}/catalog`, { + method: 'POST', + signal, + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + 'X-Governance-Action': 'kb-bindings', + 'Idempotency-Key': newOperationID(), + }, + body: JSON.stringify(input), + }) + const payload = await readResponse(response) + if (!record(payload.data)) throw new Error('知识库列表响应无效') + const item = payload.data + const status = text(item.status) + if (!['ok', 'empty', 'unauthorized', 'unreachable', 'unsupported'].includes(status)) { + throw new Error('知识库列表响应无效') + } + const options = Array.isArray(item.options) + ? item.options + .filter(record) + .map((option) => ({ + id: text(option.id), + name: text(option.name), + knowledge_count: count(option.knowledge_count), + })) + .filter((option) => option.id) + : [] + return { + status: status as KBCatalogStatus, + message: text(item.message), + page: count(item.page) || 1, + page_size: count(item.page_size) || 20, + total: count(item.total), + options, + } +} + +export async function saveKBBinding( + environment: KBEnvironment, + input: KBBindingSaveInput, + signal?: AbortSignal +): Promise { + const response = await fetch(`/api/v1/kb-bindings/${environment}`, { + method: 'PUT', + signal, + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + 'X-Governance-Action': 'kb-bindings', + 'Idempotency-Key': newOperationID(), + }, + body: JSON.stringify(input), + }) + const payload = await readResponse(response) + return parseBinding(payload.data) +} diff --git a/web/src/secureEntry.ts b/web/src/secureEntry.ts new file mode 100644 index 0000000..7d500d2 --- /dev/null +++ b/web/src/secureEntry.ts @@ -0,0 +1,5 @@ +// Secret entry is only allowed on a real HTTPS origin or loopback. Plain LAN +// HTTP must not receive a key that would then cross the network in the clear. +export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean { + return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname) +} diff --git a/web/src/systemSettings.css b/web/src/systemSettings.css index 48662b5..fa0ae22 100644 --- a/web/src/systemSettings.css +++ b/web/src/systemSettings.css @@ -997,3 +997,173 @@ button.link { grid-template-columns: 1fr; } } + +/* ── 知识库绑定(按环境一次保存连接 + 内外库)────────────────────────── */ +.kb-env-switch { + display: inline-flex; + gap: 4px; + margin: 0 0 14px; + padding: 3px; + border: 1px solid var(--border-base); + border-radius: 9px; + background: var(--bg-soft); +} +.kb-env-switch button { + border: 0; + background: transparent; + padding: 6px 14px; + border-radius: 6px; + color: var(--ink-mute); + cursor: pointer; + font: inherit; +} +.kb-env-switch button[aria-pressed='true'] { + background: var(--bg-panel); + color: var(--ink-base); + font-weight: 700; + box-shadow: 0 1px 2px rgb(0 0 0 / 8%); +} +.kb-current { + display: grid; + gap: 6px; + padding: 11px 14px; + margin-bottom: 14px; + border-inline-start: 3px solid var(--c-run, #318184); + border-radius: 8px; + background: var(--bg-soft); +} +.kb-current strong { + font-size: 12px; + color: var(--ink-mute); +} +.kb-current-targets { + display: flex; + flex-wrap: wrap; + gap: 8px 24px; +} +.kb-current-targets span { + color: var(--ink-mute); + font-size: 12px; +} +.kb-current-targets b { + color: var(--ink-base); + font-weight: 700; +} +.kb-current small, +.kb-block small, +.kb-footer .muted { + color: var(--ink-mute); +} +.kb-block { + padding: 14px 0; + border-bottom: 1px solid var(--border-base); +} +.kb-block h3 { + margin: 0 0 10px; + color: var(--ink-base); + font-size: 13px; +} +.kb-fields, +.kb-targets { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); + gap: 14px; +} +.kb-targets { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} +.kb-fields label, +.kb-targets label, +.kb-key { + display: grid; + gap: 5px; + color: var(--ink-base); + font-size: 11px; + font-weight: 600; +} +.kb-key .label { + font-size: 11px; +} +.kb-key-line { + display: flex; + align-items: center; + gap: 8px; + min-height: 34px; +} +.kb-key-line input { + flex: 1; +} +.kb-key-line button.link { + border: 0; + background: transparent; + color: var(--c-run, #135e77); + cursor: pointer; + text-decoration: underline; + white-space: nowrap; +} +.kb-fields input, +.kb-targets select, +.kb-key-line input { + width: 100%; + min-height: 34px; + padding: 6px 9px; + border: 1px solid var(--border-base); + border-radius: 6px; + background: var(--bg-panel); + color: var(--ink-base); + font: inherit; +} +.kb-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; + margin-top: 10px; +} +.kb-catalog-status { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-top: 10px; + padding: 8px 10px; + border-radius: 7px; + background: var(--bg-soft); + font-size: 11px; +} +.kb-catalog-status.ok { + color: var(--c-done, #1f7a4d); +} +.kb-catalog-status.empty { + color: var(--ink-mute); +} +.kb-catalog-status.error { + color: var(--c-fail, #a63b32); +} +.kb-pager { + display: inline-flex; + gap: 6px; +} +.kb-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px; + padding-top: 14px; +} +.kb-binding-diagnostics { + margin-top: 14px; +} +.kb-binding-diagnostics > summary { + cursor: pointer; + color: var(--ink-mute); + font-size: 11px; +} +@media (max-width: 720px) { + .kb-fields, + .kb-targets { + grid-template-columns: 1fr; + } +} diff --git a/web/src/weKnoraDiagnostics.tsx b/web/src/weKnoraDiagnostics.tsx new file mode 100644 index 0000000..4069eaf --- /dev/null +++ b/web/src/weKnoraDiagnostics.tsx @@ -0,0 +1,101 @@ +import type { MonitorOverview } from './monitor' +import type { CatalogRoutingCapabilities } from './sourceCatalog' +import type { WorkerCapabilities } from './systemCapabilities' +import { testUploadLabel } from './systemCapabilities' +import type { UISettings } from './uiSettings' + +type ServiceHealthView = MonitorOverview['health'][number] +type ServiceView = MonitorOverview['services'][number] + +// 连接卡只读诊断:知识库绑定的保存入口已收敛到「知识库绑定」主表单, +// 这里保留原链路需要的探活/执行器状态,不再提供第二个保存路径。 + +export const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined => + (monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name)) + +export const healthStateLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { + if (!health) { + if (!service) return '待配置' + return service.state === 'healthy' ? '正常' : service.state === 'unknown' ? '未接入' : '需关注' + } + if (health.readiness === 'ready') return '可达 · 可接单' + if (health.readiness === 'not_configured') return '状态未知 · 未配置' + if (health.readiness === 'not_applicable') return '未部署' + return health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单' +} + +export const testWeKnoraLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { + const label = healthStateLabel(health, service) + return label === '可达 · 可接单' ? '接口可达 · 执行器未验证' : label +} + +export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { + if (!health) return service?.detail || '真实 Provider 未接入' + const success = health.last_success_at + ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}` + : '' + if (health.readiness === 'ready') return [`延迟 ${health.latency_ms}ms`, success].filter(Boolean).join(';') + const failures = health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : '' + return [health.reason, success, failures].filter(Boolean).join(';') +} + +export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string => { + const health = findHealth(monitor, '生产 WeKnora') + if (!health) return '端点探测:暂无真实探测结果' + if (!health.configured) return '端点探测:未配置' + const label = + health.liveness === 'up' + ? health.readiness === 'ready' + ? '端点可达 · 未做接单验证' + : '端点可达 · 不可接单' + : '端点不可达' + const detail = healthStateDetail(health, undefined) + return `端点探测:${label}${detail ? `(${detail})` : ''}` +} + +export interface WeKnoraConnectionDiagnosticsProps { + settings: UISettings + monitor: MonitorOverview | null + routingCapabilities: CatalogRoutingCapabilities + workerCapabilities?: WorkerCapabilities | null + productionEnabled: boolean + productionBackupRestoreVerified?: boolean +} + +export function WeKnoraConnectionDiagnostics({ + settings, + monitor, + routingCapabilities, + workerCapabilities = null, + productionEnabled, + productionBackupRestoreVerified = false, +}: WeKnoraConnectionDiagnosticsProps) { + return ( +
+
+ 测试 WeKnora + {testWeKnoraLabel(findHealth(monitor, 'WeKnora API'), undefined)} + {`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${ + routingCapabilities.internal_enabled ? '已配置' : '未配置' + } · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`} + + {testUploadLabel(workerCapabilities)} + {workerCapabilities ? `:${workerCapabilities.test_upload.detail}` : ''} + + {settings.test_weknora_base_url || '未配置地址'} · 凭据:服务器文件/加密存储,页面不回读 +
+
+ 生产 WeKnora + + {!productionEnabled + ? '未启用' + : productionBackupRestoreVerified + ? '已启用 · 可提交生产请求' + : '已启用 · 被阻断'} + + {`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'}`} + {settings.production_weknora_base_url || '未配置地址'} · 凭据:服务器文件/加密存储,页面不回读 +
+
+ ) +} From 1f5bf72aecd0dd7052cddc33599f92b5c2ef9809 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Thu, 19 Nov 2026 15:17:17 +0800 Subject: [PATCH 03/14] =?UTF-8?q?fix(release):=20=E4=BB=A5=E5=AE=9E?= =?UTF-8?q?=E4=BE=8B=E8=BA=AB=E4=BB=BD=E9=98=BB=E6=96=AD=E7=BB=91=E5=AE=9A?= =?UTF-8?q?=E4=B8=8E=E5=8F=91=E5=B8=83=E8=B7=A8=E5=AE=9E=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 网页可能在实例 A 上列库并保存生产绑定,而文档发布执行器实际连实例 B。 克隆实例可以有相同知识库 ID、名称甚至租户,单靠 ID 无法证明写的是同一个 目标。现在绑定保存会冻结候选实例地址/租户,发布计划把身份冻结到每个项, 执行器在 Contract/Prepare/Activate/Restore/Compensate 前核对;不一致以 release_contract_mismatch 非重试失败关闭,不写目标。整库发布目标不变。 测试入库对象在上传前记录实际实例地址/租户;轮询、验收、移除先核对当前 连接,改绑实例或租户后旧对象不会被克隆实例接管。旧行没有身份时失败关闭。 「知识库绑定」保存要求对内/对外各选一个库,不再把显式未绑定回落到部署 默认 ID,避免换绑实例后带过去旧对象的默认库。 验证:隔离 PostgreSQL 覆盖绑定身份落库与发布计划冻结;v071 用同 ID/同租户 的 A/B 实例做正反例;四个测试 handler 的实例错配负例;前端 607 项通过。 --- CHANGELOG.md | 23 +++ cmd/api/main.go | 3 - cmd/release-worker/runtime.go | 7 +- cmd/worker/main.go | 3 - docs/USER_FLOWS_ACCEPTANCE.md | 5 +- internal/kbbinding/binding.go | 5 +- internal/kbbinding/binding_test.go | 1 + internal/kbbinding/save_integration_test.go | 20 ++- internal/kbbinding/store.go | 43 ++--- ...000082_instance_identity_contract.down.sql | 13 ++ .../000082_instance_identity_contract.up.sql | 20 +++ internal/platform/postgres/migrations_test.go | 12 +- .../platform/postgres/production_bindings.go | 34 +++- .../platform/postgres/publication_removal.go | 15 +- .../release_execution_worker_store.go | 37 ++++- .../release_execution_worker_store_test.go | 5 +- .../release_identity_integration_test.go | 71 ++++++++ .../platform/postgres/routing_bindings.go | 2 +- .../platform/postgres/test_publications.go | 53 +++--- .../test_publications_integration_test.go | 2 +- .../postgres/test_publications_test.go | 20 ++- internal/platform/weknora/types.go | 30 ++++ internal/releaseadapter/v071/archive_test.go | 2 +- .../releaseadapter/v071/document_target.go | 40 +++++ .../v071/document_target_test.go | 46 +++++- .../v071/three_lane_integration_test.go | 4 +- .../releaseadapter/v071/wiki_channel_test.go | 1 + internal/weknoraaccess/client.go | 31 ++++ internal/weknoraaccess/client_test.go | 23 +++ internal/workflows/release/handler.go | 11 +- .../workflows/release/sidecar_publisher.go | 18 ++- .../release/sidecar_publisher_test.go | 26 ++- internal/workflows/testweknora/identity.go | 38 +++++ .../workflows/testweknora/identity_test.go | 152 ++++++++++++++++++ internal/workflows/testweknora/poll.go | 11 ++ internal/workflows/testweknora/poll_test.go | 4 +- internal/workflows/testweknora/remove.go | 8 + internal/workflows/testweknora/upload.go | 18 ++- internal/workflows/testweknora/upload_test.go | 16 +- internal/workflows/testweknora/validate.go | 27 +++- scripts/test-scope.json | 5 + web/src/KnowledgeBaseBinding.test.tsx | 20 +++ web/src/KnowledgeBaseBinding.tsx | 11 +- 43 files changed, 823 insertions(+), 113 deletions(-) create mode 100644 internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql create mode 100644 internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql create mode 100644 internal/platform/postgres/release_identity_integration_test.go create mode 100644 internal/workflows/testweknora/identity.go create mode 100644 internal/workflows/testweknora/identity_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 2102213..2d0c225 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## 开发快照 0.1.403(实例身份约束:绑定、发布与测试对象不跨实例) + +### Added + +- 迁移 000082:`production_kb_bindings` 冻结每个方向核验时的实例地址与租户, + `release_item_executions` 冻结 `target_instance_url/target_tenant_id`, + `test_publications` 记录对象实际写入的测试实例地址/租户。 +- 文档发布执行器在 `Contract/Prepare/Activate/Restore/Compensate` 前统一核对实例身份: + 网页在实例 A 列库、执行器连实例 B 时,即使知识库 ID/租户相同也以 + `release_contract_mismatch` 失败关闭,不写目标;整库发布目标不变。 +- 测试入库的上传/轮询/验收/移除按对象记录的身份核对当前连接;改绑实例或租户后, + 旧对象不会在克隆实例上继续轮询、验收或删除。 +- 回归:实例 A/B 同名同 ID 的隔离夹具、绑定身份写入计划、四个测试 handler 的正反例。 + +### Changed + +- 「知识库绑定」保存必须为对内/对外各选一个库;显式“未绑定”不再回落部署默认 ID, + 避免换绑实例后把旧实例的默认库带到新实例。旧页面留下的既有绑定行保持原语义。 + +### Security + +- 实例身份不匹配一律失败关闭;旧发布项缺少身份信息时也不再猜测,避免写错克隆实例。 + ## 开发快照 0.1.402(知识库绑定:按环境一次保存连接与内外库) ### Added diff --git a/cmd/api/main.go b/cmd/api/main.go index 35a9fe8..0c53269 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -147,9 +147,6 @@ func run(ctx context.Context, getenv func(string) string) error { } return internal, external, err }, - RoutingDefaults: func() (string, string) { - return config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID - }, }) productionEndpointResolver := func(resolveCtx context.Context) string { return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvProduction) diff --git a/cmd/release-worker/runtime.go b/cmd/release-worker/runtime.go index fe6a905..b33a335 100644 --- a/cmd/release-worker/runtime.go +++ b/cmd/release-worker/runtime.go @@ -163,7 +163,12 @@ func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot release if err != nil { return cleanup(errors.New("create target WeKnora verifier")) } - documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier}) + documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{ + Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch, + Objects: objectImporter, Verifier: verifier, + TargetInstanceURL: route.Target.WeKnora.BaseURL, + TargetTenantID: route.TenantID, + }) if err != nil { return cleanup(errors.New("create v0.7.1 document target")) } diff --git a/cmd/worker/main.go b/cmd/worker/main.go index 69f4900..44888ef 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -221,9 +221,6 @@ func run(ctx context.Context, getenv func(string) string) error { } return internal, external, err }, - RoutingDefaults: func() (string, string) { - return config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID - }, }) log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity()) // 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败: diff --git a/docs/USER_FLOWS_ACCEPTANCE.md b/docs/USER_FLOWS_ACCEPTANCE.md index 9ad2fcd..6b94429 100644 --- a/docs/USER_FLOWS_ACCEPTANCE.md +++ b/docs/USER_FLOWS_ACCEPTANCE.md @@ -257,10 +257,11 @@ ### D1 知识库绑定(测试 090 / 生产 090:连接 + 内外库) - 入口:**系统设置 → 知识库绑定**(管理员;普通用户只读) -- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库)→ **保存该环境绑定** +- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库;**两个方向都必须选择**)→ **保存该环境绑定** - 期望:一次保存同时生效连接与内外绑定;顶部「当前生效」回读服务器真实值;失败保留旧绑定,未保存草稿不影响当前值;切换环境时迟到的列库响应不串库 - 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE` -- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx` +- 实例约束:网页在实例 A 核验的绑定会冻结地址/租户;文档发布执行器连实例 B 时,即使知识库 ID/租户相同也拒绝写入(`release_contract_mismatch`)。测试对象改绑实例/租户后,旧对象不会被轮询/验收/移除。 +- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`、`TestStartReleaseExecutionFreezesTheBindingInstanceIdentity`、`TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance` - 状态:✅ 本地验证(未做业务验收) ### D2 测试知识库绑定(折叠诊断;主入口已并入 D1) diff --git a/internal/kbbinding/binding.go b/internal/kbbinding/binding.go index 1bd73bb..5e6e543 100644 --- a/internal/kbbinding/binding.go +++ b/internal/kbbinding/binding.go @@ -127,10 +127,7 @@ type Options struct { LegacyKey func(string) (string, error) // LegacyBinding resolves the pre-existing internal/external binding ids. LegacyBinding func(context.Context, string) (string, string, error) - // RoutingDefaults are the deployment bootstrap ids used to replan pending - // publications when a saved side is empty. - RoutingDefaults func() (string, string) - Now func() time.Time + Now func() time.Time } type DB interface { diff --git a/internal/kbbinding/binding_test.go b/internal/kbbinding/binding_test.go index a35579c..2e412ee 100644 --- a/internal/kbbinding/binding_test.go +++ b/internal/kbbinding/binding_test.go @@ -119,6 +119,7 @@ func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) { store := New(emptyDB{}, Options{Now: func() time.Time { return now }}) for _, input := range []SaveInput{ {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"}, + {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb-in"}, {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"}, {BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"}, } { diff --git a/internal/kbbinding/save_integration_test.go b/internal/kbbinding/save_integration_test.go index 172a2bb..6433777 100644 --- a/internal/kbbinding/save_integration_test.go +++ b/internal/kbbinding/save_integration_test.go @@ -32,9 +32,9 @@ func fakeCandidate(t *testing.T) *httptest.Server { case r.URL.Path == "/api/v1/knowledge-bases": _, _ = w.Write([]byte(`{"success":true,"total":2,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4}]}`)) case r.URL.Path == "/api/v1/knowledge-bases/kb-in": - _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料"}}`)) + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料","tenant_id":10000}}`)) case r.URL.Path == "/api/v1/knowledge-bases/kb-out": - _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册"}}`)) + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册","tenant_id":10000}}`)) default: w.WriteHeader(http.StatusNotFound) } @@ -82,9 +82,14 @@ INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_st MasterKeyFile: masterKey(t), Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true}, - RoutingDefaults: func() (string, string) { return "env-in", "env-out" }, }) now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) + if _, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{ + BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(), + InternalKBID: "kb-in", + }, "admin", now); !errors.Is(err, kbbinding.ErrInvalid) { + t.Fatalf("save with an unbound side = %v, want ErrInvalid", err) + } view, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{ BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(), InternalKBID: "kb-in", ExternalKBID: "kb-out", @@ -169,11 +174,12 @@ INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_st if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 { t.Fatalf("production view = %#v", prodView) } - var productionInternal string - if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal); err != nil { + var productionInternal, productionURL string + var productionTenant uint64 + if err := pool.QueryRow(ctx, `SELECT internal_kb_id, internal_instance_url, internal_tenant_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal, &productionURL, &productionTenant); err != nil { t.Fatal(err) } - if productionInternal != "kb-in" { - t.Fatalf("production binding = %s", productionInternal) + if productionInternal != "kb-in" || productionURL != server.URL || productionTenant != 10000 { + t.Fatalf("production binding = %s / %s / %d", productionInternal, productionURL, productionTenant) } } diff --git a/internal/kbbinding/store.go b/internal/kbbinding/store.go index d3d8f42..82ff755 100644 --- a/internal/kbbinding/store.go +++ b/internal/kbbinding/store.go @@ -106,7 +106,12 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) { return View{}, ErrInvalid } - if internal != "" && internal == external { + // 新页面必须给两个方向各选一个库:显式“未绑定”会回落到部署默认 ID, + // 而那个 ID 可能属于旧实例;在换绑实例后继续沿用就是错误目标。 + if internal == "" || external == "" { + return View{}, ErrInvalid + } + if internal == external { return View{}, ErrInvalid } saved, found, err := s.load(ctx, env) @@ -121,7 +126,7 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str if err != nil { return View{}, ErrInvalid } - names, err := s.verifySelection(ctx, client, internal, external) + selected, err := s.verifySelection(ctx, client, internal, external) if err != nil { return View{}, err } @@ -169,7 +174,7 @@ ON CONFLICT(environment) DO UPDATE SET internal_kb_name=EXCLUDED.internal_kb_name,external_kb_name=EXCLUDED.external_kb_name, verification=EXCLUDED.verification,checked_at=EXCLUDED.checked_at, updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`, - env, revision, baseURL, sealed, internal, external, names[internal], names[external], verification, now.UTC(), actor); err != nil { + env, revision, baseURL, sealed, internal, external, selected[internal].Name, selected[external].Name, verification, now.UTC(), actor); err != nil { return View{}, ErrStorage } if _, err := tx.Exec(ctx, ` @@ -184,23 +189,16 @@ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil { return View{}, ErrStorage } - effectiveInternal, effectiveExternal := internal, external - if s.options.RoutingDefaults != nil { - defaultInternal, defaultExternal := s.options.RoutingDefaults() - if effectiveInternal == "" { - effectiveInternal = defaultInternal - } - if effectiveExternal == "" { - effectiveExternal = defaultExternal - } - } - replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now.UTC()) + replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, internal, external, now.UTC()) if err != nil { return View{}, ErrStorage } } else { // 生产页这里沿用「文档级发布」语义;整库发布目标由部署配置决定,本保存不写它。 - if err := postgresstore.SaveProductionKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil { + // 同时冻结候选实例地址与租户,执行器写入前必须与自己的目标一致。 + if err := postgresstore.SaveProductionKBBindingsWithIdentityTx(ctx, tx, + internal, external, baseURL, baseURL, + selected[internal].TenantID, selected[external].TenantID, actor, now.UTC()); err != nil { return View{}, ErrStorage } } @@ -219,13 +217,18 @@ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, // verifySelection proves both chosen bases belong to THIS candidate instance by // reading them with the draft credential. An empty selection still probes the // list endpoint, so a save cannot store a connection nobody verified. -func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]string, error) { - names := map[string]string{} +type selectedBase struct { + Name string + TenantID uint64 +} + +func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]selectedBase, error) { + selected := map[string]selectedBase{} if internal == "" && external == "" { if _, err := client.ListKnowledgeBasesPage(ctx, 1, 1); err != nil { return nil, selectionError(err, "无法确认候选连接") } - return names, nil + return selected, nil } for _, id := range []string{internal, external} { if id == "" { @@ -238,9 +241,9 @@ func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, int if base.ID != id { return nil, ErrInvalid } - names[id] = base.Name + selected[id] = selectedBase{Name: base.Name, TenantID: base.TenantID} } - return names, nil + return selected, nil } func selectionError(err error, message string) error { diff --git a/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql b/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql new file mode 100644 index 0000000..ec4e8eb --- /dev/null +++ b/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql @@ -0,0 +1,13 @@ +ALTER TABLE test_publications + DROP COLUMN IF EXISTS test_instance_tenant, + DROP COLUMN IF EXISTS test_instance_url; + +ALTER TABLE release_item_executions + DROP COLUMN IF EXISTS target_tenant_id, + DROP COLUMN IF EXISTS target_instance_url; + +ALTER TABLE production_kb_bindings + DROP COLUMN IF EXISTS external_tenant_id, + DROP COLUMN IF EXISTS internal_tenant_id, + DROP COLUMN IF EXISTS external_instance_url, + DROP COLUMN IF EXISTS internal_instance_url; \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql b/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql new file mode 100644 index 0000000..30f6668 --- /dev/null +++ b/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql @@ -0,0 +1,20 @@ +-- 实例身份约束:网页(kbbinding)在实例 A 上列库/选库,而文档发布执行器可能 +-- 连的是实例 B。同名/同 ID 的知识库在克隆实例里完全可能存在,所以 ID 本身 +-- 不能证明“写的是网页看到的那个实例”。这里把候选连接地址与租户随绑定冻结到 +-- 每个发布项,执行器在写入前用自己的目标地址/租户核对;不一致即失败关闭。 +-- +-- 同时给测试入库的发布项记录“对象实际写入的测试实例地址/租户”: +-- 改绑实例或租户后,旧对象不能在克隆实例上继续轮询/验收/移除。 +ALTER TABLE production_kb_bindings + ADD COLUMN IF NOT EXISTS internal_instance_url TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS external_instance_url TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS internal_tenant_id BIGINT NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS external_tenant_id BIGINT NOT NULL DEFAULT 0; + +ALTER TABLE release_item_executions + ADD COLUMN IF NOT EXISTS target_instance_url TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS target_tenant_id BIGINT NOT NULL DEFAULT 0; + +ALTER TABLE test_publications + ADD COLUMN IF NOT EXISTS test_instance_url TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS test_instance_tenant BIGINT NOT NULL DEFAULT 0; \ No newline at end of file diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index 292bfb1..590235b 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -11,8 +11,16 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) { if err != nil { t.Fatalf("loadMigrations() error = %v", err) } - if len(migrations) != 81 { - t.Fatalf("migration count = %d, want 81", len(migrations)) + if len(migrations) != 82 { + t.Fatalf("migration count = %d, want 82", len(migrations)) + } + // 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录 + // 实际实例身份;克隆实例同名/同 ID 不能冒充。 + if identity := migrations[81]; identity.Version != 82 || + !strings.Contains(identity.UpSQL, "target_instance_url") || + !strings.Contains(identity.UpSQL, "test_instance_url") || + !strings.Contains(identity.UpSQL, "internal_tenant_id") { + t.Fatalf("migration 82 = %#v", identity) } // 81 是环境级「知识库绑定」:连接密文与内外库同表同事务,历史只记是否配置密钥。 if binding := migrations[80]; binding.Version != 81 || diff --git a/internal/platform/postgres/production_bindings.go b/internal/platform/postgres/production_bindings.go index f3a2a7a..ef526da 100644 --- a/internal/platform/postgres/production_bindings.go +++ b/internal/platform/postgres/production_bindings.go @@ -39,26 +39,48 @@ func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, extern if now.IsZero() { return errors.New("production binding save requires a timestamp") } - if _, err := s.db.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil { + // 旧入口没有实例身份可写:显式清空身份列,执行器随后会失败关闭, + // 而不是沿用上一条(可能属于另一个实例的)地址/租户。 + if _, err := s.db.Exec(ctx, productionBindingIdentityUpsertSQL, + internalID, externalID, updatedBy, now, "", "", 0, 0); err != nil { return errors.New("save production kb bindings") } return nil } -const productionBindingUpsertSQL = ` -INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at) -VALUES('active',$1,$2,$3,$4) +// productionBindingIdentityUpsertSQL freezes the instance identity the console +// verified each side on. An empty URL keeps the legacy same-id behaviour for +// old callers; the executor then cannot prove the instance and refuses a mapped +// write instead of guessing. +const productionBindingIdentityUpsertSQL = ` +INSERT INTO production_kb_bindings( + id,internal_kb_id,external_kb_id,updated_by,updated_at, + internal_instance_url,external_instance_url,internal_tenant_id,external_tenant_id) +VALUES('active',$1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(id) DO UPDATE SET internal_kb_id=EXCLUDED.internal_kb_id, external_kb_id=EXCLUDED.external_kb_id, updated_by=EXCLUDED.updated_by, - updated_at=EXCLUDED.updated_at` + updated_at=EXCLUDED.updated_at, + internal_instance_url=EXCLUDED.internal_instance_url, + external_instance_url=EXCLUDED.external_instance_url, + internal_tenant_id=EXCLUDED.internal_tenant_id, + external_tenant_id=EXCLUDED.external_tenant_id` // SaveProductionKBBindingsTx lets the environment-scoped 「知识库绑定」save // update the same row inside its own transaction, so connection and bindings // cannot be half-written. func SaveProductionKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error { - if _, err := tx.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil { + return SaveProductionKBBindingsWithIdentityTx(ctx, tx, internalID, externalID, "", "", 0, 0, updatedBy, now) +} + +// SaveProductionKBBindingsWithIdentityTx is used by the environment-scoped +// 「知识库绑定」save: it stores which instance/tenant each side was verified on, +// so the release executor can refuse a cloned instance with the same base id. +func SaveProductionKBBindingsWithIdentityTx(ctx context.Context, tx pgx.Tx, internalID, externalID, internalURL, externalURL string, internalTenant, externalTenant uint64, updatedBy string, now time.Time) error { + if _, err := tx.Exec(ctx, productionBindingIdentityUpsertSQL, + internalID, externalID, updatedBy, now, + internalURL, externalURL, internalTenant, externalTenant); err != nil { return errors.New("save production kb bindings") } return nil diff --git a/internal/platform/postgres/publication_removal.go b/internal/platform/postgres/publication_removal.go index 30159ab..2cba3ac 100644 --- a/internal/platform/postgres/publication_removal.go +++ b/internal/platform/postgres/publication_removal.go @@ -11,19 +11,22 @@ import ( ) type PublicationForRemoval struct { - ID string - TestKBID string - KnowledgeID string - RetrievalState governance.RetrievalState + ID string + TestKBID string + KnowledgeID string + TestInstanceURL string + TestInstanceTenant uint64 + RetrievalState governance.RetrievalState } func (s *Store) LoadPublicationForRemoval(ctx context.Context, publicationID string) (PublicationForRemoval, error) { var candidate PublicationForRemoval var retrievalState string - err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,retrieval_state + err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,test_instance_url,test_instance_tenant,retrieval_state FROM test_publications WHERE id=$1 AND knowledge_id<>'' AND retrieval_state='disabling'`, publicationID).Scan( - &candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID, &retrievalState, + &candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID, + &candidate.TestInstanceURL, &candidate.TestInstanceTenant, &retrievalState, ) if errors.Is(err, pgx.ErrNoRows) { return PublicationForRemoval{}, ErrPublicationStateConflict diff --git a/internal/platform/postgres/release_execution_worker_store.go b/internal/platform/postgres/release_execution_worker_store.go index 5e131df..490fa4b 100644 --- a/internal/platform/postgres/release_execution_worker_store.go +++ b/internal/platform/postgres/release_execution_worker_store.go @@ -75,13 +75,32 @@ execution_gate AS ( WHEN 'internal' THEN binding.internal_kb_id WHEN 'external' THEN binding.external_kb_id END, ''), - publication.test_kb_id) AS target_kb_id + publication.test_kb_id) AS target_kb_id, + -- 身份必须与 target_kb_id 来自同一来源:重试/回滚沿用的旧目标若 + -- 没有身份(迁移前),不能拿当前绑定去补,否则会把旧项写到新实例; + -- 这种情况留空,由执行器失败关闭。 + CASE + WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL + THEN COALESCE(prior_item.target_instance_url, '') + ELSE COALESCE(NULLIF(CASE publication.target_scope + WHEN 'internal' THEN binding.internal_instance_url + WHEN 'external' THEN binding.external_instance_url + END, ''), '') + END AS target_instance_url, + CASE + WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL + THEN COALESCE(prior_item.target_tenant_id, 0) + ELSE COALESCE(NULLIF(CASE publication.target_scope + WHEN 'internal' THEN binding.internal_tenant_id + WHEN 'external' THEN binding.external_tenant_id + END, 0), 0) + END AS target_tenant_id FROM started JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id JOIN test_publications AS publication ON publication.id = item.publication_id LEFT JOIN production_kb_bindings AS binding ON binding.id = 'active' LEFT JOIN LATERAL ( - SELECT candidate.target_knowledge_base_id + SELECT candidate.target_knowledge_base_id, candidate.target_instance_url, candidate.target_tenant_id FROM release_item_executions AS candidate JOIN release_executions AS candidate_execution ON candidate_execution.id = candidate.release_execution_id WHERE candidate.publication_id = item.publication_id @@ -94,11 +113,14 @@ execution_gate AS ( ) AS prior_item ON TRUE ), seeded AS ( INSERT INTO release_item_executions ( - id, release_execution_id, publication_id, action, state, created_at, updated_at, target_knowledge_base_id + id, release_execution_id, publication_id, action, state, created_at, updated_at, + target_knowledge_base_id, target_instance_url, target_tenant_id ) SELECT 'ri-' || SUBSTR(MD5(started.id || ':' || item.publication_id), 1, 32), started.id, item.publication_id, item.action, 'pending', $4::TIMESTAMPTZ, $4::TIMESTAMPTZ, - COALESCE(target_base.target_kb_id, '') + COALESCE(target_base.target_kb_id, ''), + COALESCE(target_base.target_instance_url, ''), + COALESCE(target_base.target_tenant_id, 0) FROM started JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id LEFT JOIN target_base ON target_base.publication_id = item.publication_id @@ -129,6 +151,8 @@ execution_gate AS ( item.review_id AS release_revision, publication.test_kb_id, COALESCE(target_base.target_kb_id, '') AS target_kb_id, + COALESCE(target_base.target_instance_url, '') AS target_instance_url, + COALESCE(target_base.target_tenant_id, 0) AS target_tenant_id, publication.knowledge_id, item.decided_visibility, COALESCE(previous.production_revision, '') AS previous_production_revision @@ -180,6 +204,8 @@ SELECT COUNT(DISTINCT started.id)::INTEGER, 'release_revision', plan.release_revision, 'test_knowledge_base_id', plan.test_kb_id, 'target_knowledge_base_id', plan.target_kb_id, + 'target_instance_url', plan.target_instance_url, + 'target_tenant_id', plan.target_tenant_id, 'knowledge_id', plan.knowledge_id, 'decided_visibility', plan.decided_visibility, 'previous_production_revision', plan.previous_production_revision @@ -307,7 +333,8 @@ func (s *Store) StartExecution(ctx context.Context, request releaseworkflow.Star if !validShortID(item.PublicationID) || !validShortID(item.SourceItemVersionID) || !validRemoteIdentifier(item.TestKnowledgeBaseID) || !validRemoteIdentifier(item.TargetKnowledgeBaseID) || !validRemoteIdentifier(item.KnowledgeID) || (item.DecidedVisibility != governance.VisibilityInternal && item.DecidedVisibility != governance.VisibilityExternal) || - len(item.PreviousProductionRevision) > 128 { + len(item.PreviousProductionRevision) > 128 || len(item.TargetInstanceURL) > 300 || + strings.ContainsAny(item.TargetInstanceURL, " \r\n\x00") { return nil, errors.New("invalid release execution plan") } } diff --git a/internal/platform/postgres/release_execution_worker_store_test.go b/internal/platform/postgres/release_execution_worker_store_test.go index b61b212..a26c8df 100644 --- a/internal/platform/postgres/release_execution_worker_store_test.go +++ b/internal/platform/postgres/release_execution_worker_store_test.go @@ -13,7 +13,7 @@ import ( ) func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T) { - payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]` + payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","target_instance_url":"https://instance-a.weknora.example","target_tenant_id":10000,"knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]` db := &recordingDB{row: startExecutionRow{executionCount: 1, payload: []byte(payload)}} items, err := NewStore(db).StartExecution(context.Background(), releaseworkflow.StartExecutionRequest{ ExecutionID: "rx-safe", JobID: "job-safe", Operation: "publish", Now: time.Now(), @@ -24,7 +24,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T) if len(items) != 1 || items[0].PublicationID != "tp-safe" || items[0].Action != "delete" || items[0].KnowledgeID != "knowledge-safe" || items[0].PreviousProductionRevision != "prod-old" { t.Fatalf("items=%#v", items) } - if items[0].TargetBase() != "prod-kb" { + if items[0].TargetBase() != "prod-kb" || items[0].TargetInstanceURL != "https://instance-a.weknora.example" || items[0].TargetTenantID != 10000 { t.Fatalf("target base=%q, want the mapped 源库 → 目标库 target", items[0].TargetBase()) } sql := strings.ToLower(db.queryRowSQL) @@ -39,6 +39,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T) "release_delete_ready", "item.action = 'delete'", "execution_gate.valid_items = execution_gate.item_count", // the 源库 → 目标库 mapping is resolved into the plan and frozen per item "production_kb_bindings", "target_knowledge_base_id", "target_base.target_kb_id", + "target_instance_url", "target_tenant_id", "internal_instance_url", "internal_tenant_id", } { if !strings.Contains(sql, required) { t.Fatalf("start execution SQL missing %q", required) diff --git a/internal/platform/postgres/release_identity_integration_test.go b/internal/platform/postgres/release_identity_integration_test.go new file mode 100644 index 0000000..03ad5ed --- /dev/null +++ b/internal/platform/postgres/release_identity_integration_test.go @@ -0,0 +1,71 @@ +package postgres + +import ( + "context" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + releaseworkflow "knowledge-governance/internal/workflows/release" +) + +// The console verified the production binding on instance A. The release plan +// must freeze that instance identity with each item; the executor later compares +// it with its own route target before writing. Same knowledge-base id/tenant on +// a cloned instance is not enough. +func TestStartReleaseExecutionFreezesTheBindingInstanceIdentity(t *testing.T) { + databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if databaseURL == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, databaseURL) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if err := ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + store := NewStore(pool) + now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC) + if _, err := pool.Exec(ctx, `INSERT INTO source_connections (id, source_type, name) VALUES ('conn-manual', 'manual', 'Manual')`); err != nil { + t.Fatal(err) + } + publicationID := "tp-identity-e2e" + insertReviewFixture(t, ctx, pool, 9, publicationID, now) + if _, err := store.ReviewPublication(ctx, governance.ReviewPublicationRequest{PublicationID: publicationID, Decision: governance.ReviewApproved, DecidedVisibility: governance.VisibilityInternal, ReviewerRef: "engineer-1", DecisionCode: "approved_for_release", Now: now.Add(time.Minute)}); err != nil { + t.Fatal(err) + } + batch, err := store.CreateReleaseBatch(ctx, governance.CreateReleaseBatchRequest{Name: "Identity publish", CreatedBy: "engineer-1", PublicationIDs: []string{publicationID}, Now: now.Add(2 * time.Minute)}) + if err != nil { + t.Fatal(err) + } + if _, err := store.SealReleaseBatch(ctx, governance.SealReleaseBatchRequest{BatchID: batch.ID, SealedBy: "engineer-2", Now: now.Add(3 * time.Minute)}); err != nil { + t.Fatal(err) + } + execution, err := store.AuthorizeReleaseBatch(ctx, governance.AuthorizeReleaseBatchRequest{BatchID: batch.ID, AuthorizedBy: "release-owner", AuthorizationCode: "production_release_authorized", Now: now.Add(4 * time.Minute)}) + if err != nil { + t.Fatal(err) + } + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if err := SaveProductionKBBindingsWithIdentityTx(ctx, tx, "test-kb", "test-kb", "https://instance-a.weknora.example", "https://instance-a.weknora.example", 10000, 10000, "admin", now); err != nil { + t.Fatal(err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatal(err) + } + plan, err := store.StartExecution(ctx, releaseworkflow.StartExecutionRequest{ExecutionID: execution.ID, JobID: execution.JobID, Operation: governance.ReleaseOperationPublish, Now: now.Add(5 * time.Minute)}) + if err != nil || len(plan) != 1 { + t.Fatalf("plan=%#v error=%v", plan, err) + } + if plan[0].TargetKnowledgeBaseID != "test-kb" || plan[0].TargetInstanceURL != "https://instance-a.weknora.example" || plan[0].TargetTenantID != 10000 { + t.Fatalf("plan identity = %s / %s / %d", plan[0].TargetKnowledgeBaseID, plan[0].TargetInstanceURL, plan[0].TargetTenantID) + } +} diff --git a/internal/platform/postgres/routing_bindings.go b/internal/platform/postgres/routing_bindings.go index 7a23e97..d47fdaa 100644 --- a/internal/platform/postgres/routing_bindings.go +++ b/internal/platform/postgres/routing_bindings.go @@ -86,7 +86,7 @@ WHERE stale.superseded_at IS NULL // already in flight keeps its frozen target and stays visible in 待入库. const replanMovePendingSQL = ` UPDATE test_publications pending -SET test_kb_id = $1, updated_at = $3 +SET test_kb_id = $1, test_instance_url = '', test_instance_tenant = 0, updated_at = $3 WHERE pending.superseded_at IS NULL AND pending.test_kb_id <> $1 AND pending.processing_state = 'planned' diff --git a/internal/platform/postgres/test_publications.go b/internal/platform/postgres/test_publications.go index 094ceed..9342115 100644 --- a/internal/platform/postgres/test_publications.go +++ b/internal/platform/postgres/test_publications.go @@ -29,22 +29,27 @@ type PublicationForUpload struct { SourceItemVersionID string TestKBID string KnowledgeID string - IngestState governance.IngestState - ProcessingState governance.ProcessingState - TargetScope governance.Visibility - ContentObjectID string - SHA256 string - SizeBytes int64 - MIME string - ValidatedFormat string - LocalSpoolRef string - Title string + // 对象实际写入的测试实例身份;空 = 迁移前的旧行,无法证明归属。 + TestInstanceURL string + TestInstanceTenant uint64 + IngestState governance.IngestState + ProcessingState governance.ProcessingState + TargetScope governance.Visibility + ContentObjectID string + SHA256 string + SizeBytes int64 + MIME string + ValidatedFormat string + LocalSpoolRef string + Title string } type PublicationForPoll struct { ID string TestKBID string KnowledgeID string + TestInstanceURL string + TestInstanceTenant uint64 ProcessingState governance.ProcessingState PollSequence int LastRemoteStatus string @@ -55,9 +60,11 @@ type PublicationForPoll struct { } type PublicationForValidation struct { - ID string - TestKBID string - KnowledgeID string + ID string + TestKBID string + KnowledgeID string + TestInstanceURL string + TestInstanceTenant uint64 // TargetScope 决定这条知识发到哪个生产库(对内/对外)。自动批准策略依赖它: // 默认只自动批准"对内","对外"仍要人工。 TargetScope string @@ -71,6 +78,7 @@ type LegacyVerificationCandidate struct { const loadPublicationForUploadSQL = ` SELECT p.id, p.source_item_version_id, p.test_kb_id, p.knowledge_id, + p.test_instance_url, p.test_instance_tenant, p.ingest_state, p.processing_state, p.target_scope, co.id, co.sha256, co.size_bytes, co.mime, co.validated_format, co.local_spool_ref, si.title @@ -89,7 +97,8 @@ WHERE p.id = $1 ` const loadPublicationForPollSQL = ` -SELECT id, test_kb_id, knowledge_id, processing_state, poll_sequence, +SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant, + processing_state, poll_sequence, last_remote_status, last_remote_updated_at, processing_started_at, last_observed_at, updated_at FROM test_publications @@ -97,7 +106,7 @@ WHERE id = $1 ` const loadPublicationForValidationSQL = ` -SELECT id, test_kb_id, knowledge_id, target_scope +SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant, target_scope FROM test_publications WHERE id = $1 AND ingest_state = 'uploaded' @@ -223,8 +232,10 @@ ON CONFLICT (idempotency_key) DO NOTHING const markUploadingSQL = ` UPDATE test_publications SET ingest_state = 'uploading', + test_instance_url = $2, + test_instance_tenant = $3, last_error = '', - updated_at = $2 + updated_at = $4 WHERE id = $1 AND ingest_state IN ('pending', 'uploading') AND processing_state = 'pending' @@ -393,6 +404,8 @@ func (s *Store) LoadPublicationForUpload(ctx context.Context, publicationID stri &candidate.SourceItemVersionID, &candidate.TestKBID, &candidate.KnowledgeID, + &candidate.TestInstanceURL, + &candidate.TestInstanceTenant, &ingestState, &processingState, &candidate.TargetScope, @@ -422,6 +435,8 @@ func (s *Store) LoadPublicationForPoll(ctx context.Context, publicationID string &publication.ID, &publication.TestKBID, &publication.KnowledgeID, + &publication.TestInstanceURL, + &publication.TestInstanceTenant, &processingState, &publication.PollSequence, &publication.LastRemoteStatus, @@ -446,6 +461,8 @@ func (s *Store) LoadPublicationForValidation(ctx context.Context, publicationID &publication.ID, &publication.TestKBID, &publication.KnowledgeID, + &publication.TestInstanceURL, + &publication.TestInstanceTenant, &publication.TargetScope, ) if errors.Is(err, pgx.ErrNoRows) { @@ -594,8 +611,8 @@ func (s *Store) RetryPublication(ctx context.Context, publicationID string, now return nil } -func (s *Store) MarkUploading(ctx context.Context, publicationID string, now time.Time) error { - tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, now) +func (s *Store) MarkUploading(ctx context.Context, publicationID, instanceURL string, instanceTenant uint64, now time.Time) error { + tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, instanceURL, instanceTenant, now) if err != nil { return fmt.Errorf("mark test publication uploading: %w", err) } diff --git a/internal/platform/postgres/test_publications_integration_test.go b/internal/platform/postgres/test_publications_integration_test.go index 211bc09..4c68024 100644 --- a/internal/platform/postgres/test_publications_integration_test.go +++ b/internal/platform/postgres/test_publications_integration_test.go @@ -64,7 +64,7 @@ func TestPublicationOrchestrationIsAtomicAndRejectsStaleTransitions(t *testing.T if _, err := store.LoadPublicationForUpload(ctx, "publication-1"); err != nil { t.Fatal(err) } - if err := store.MarkUploading(ctx, "publication-1", now); err != nil { + if err := store.MarkUploading(ctx, "publication-1", "", 0, now); err != nil { t.Fatal(err) } if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 { diff --git a/internal/platform/postgres/test_publications_test.go b/internal/platform/postgres/test_publications_test.go index 255dfe7..6b9eb62 100644 --- a/internal/platform/postgres/test_publications_test.go +++ b/internal/platform/postgres/test_publications_test.go @@ -39,7 +39,7 @@ func TestLoadPublicationForUploadMapsVerifiedCandidate(t *testing.T) { func TestMarkUploadingRejectsStalePublicationState(t *testing.T) { db := &recordingDB{commandTag: pgconn.NewCommandTag("UPDATE 0")} - err := NewStore(db).MarkUploading(context.Background(), "publication-1", time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC)) + err := NewStore(db).MarkUploading(context.Background(), "publication-1", "", 0, time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC)) if !errors.Is(err, ErrPublicationStateConflict) { t.Fatalf("MarkUploading() error = %v, want ErrPublicationStateConflict", err) } @@ -380,6 +380,8 @@ func (publicationValidationRow) Scan(dest ...any) error { *(dest[0].(*string)) = "publication-1" *(dest[1].(*string)) = "kb-1" *(dest[2].(*string)) = "knowledge-1" + *(dest[3].(*string)) = "" + *(dest[4].(*uint64)) = 0 return nil } @@ -547,13 +549,15 @@ func (row publicationPollRow) Scan(dest ...any) error { *(dest[0].(*string)) = "publication-1" *(dest[1].(*string)) = "kb-1" *(dest[2].(*string)) = "knowledge-1" - *(dest[3].(*string)) = string(governance.ProcessingProcessing) - *(dest[4].(*int)) = 2 - *(dest[5].(*string)) = "processing" - *(dest[6].(**time.Time)) = &row.now - *(dest[7].(**time.Time)) = &row.now + *(dest[3].(*string)) = "" + *(dest[4].(*uint64)) = 0 + *(dest[5].(*string)) = string(governance.ProcessingProcessing) + *(dest[6].(*int)) = 2 + *(dest[7].(*string)) = "processing" *(dest[8].(**time.Time)) = &row.now *(dest[9].(**time.Time)) = &row.now + *(dest[10].(**time.Time)) = &row.now + *(dest[11].(**time.Time)) = &row.now return nil } @@ -572,6 +576,8 @@ func (publicationUploadRow) Scan(dest ...any) error { "version-1", "kb-1", "", + "", // test_instance_url + uint64(0), string(governance.IngestPending), string(governance.ProcessingPending), "internal", @@ -589,6 +595,8 @@ func (publicationUploadRow) Scan(dest ...any) error { *target = value.(string) case *int64: *target = value.(int64) + case *uint64: + *target = value.(uint64) case *governance.Visibility: *target = governance.Visibility(value.(string)) case nil: diff --git a/internal/platform/weknora/types.go b/internal/platform/weknora/types.go index 71e5374..b3ebe6f 100644 --- a/internal/platform/weknora/types.go +++ b/internal/platform/weknora/types.go @@ -2,6 +2,8 @@ package weknora import ( "io" + "net/url" + "strings" "time" ) @@ -98,6 +100,34 @@ type knowledgeBaseResponse struct { Data KnowledgeBase `json:"data"` } +// InstanceIdentity is the verifiable identity of the WeKnora instance a call +// actually reached: the normalized service address plus the tenant that owns +// the knowledge base. Knowledge base ids alone cannot distinguish a cloned +// instance, so workflows that stored an object must compare this before using +// the object again. +type InstanceIdentity struct { + BaseURL string + TenantID uint64 +} + +// NormalizeInstanceURL is the single comparison form for service addresses: +// scheme/host are case-insensitive and a trailing slash is not a different +// instance. Userinfo/query/fragment never reach storage (endpoints are +// validated as bare origins), so they are deliberately dropped here. +func NormalizeInstanceURL(raw string) string { + parsed, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || parsed.Host == "" { + return strings.TrimSpace(raw) + } + parsed.Scheme = strings.ToLower(parsed.Scheme) + parsed.Host = strings.ToLower(parsed.Host) + parsed.Path = strings.TrimRight(parsed.Path, "/") + parsed.User = nil + parsed.RawQuery = "" + parsed.Fragment = "" + return parsed.String() +} + type chunkListResponse struct { Success bool `json:"success"` Data []Chunk `json:"data"` diff --git a/internal/releaseadapter/v071/archive_test.go b/internal/releaseadapter/v071/archive_test.go index b73f0f9..b5e7ed6 100644 --- a/internal/releaseadapter/v071/archive_test.go +++ b/internal/releaseadapter/v071/archive_test.go @@ -151,5 +151,5 @@ func testDocumentBundle(t *testing.T) *DocumentBundle { func fixedArchiveTime() time.Time { return time.Date(2026, 9, 6, 11, 0, 0, 0, time.UTC) } func releasePlanForArchive() releaseworkflow.PlanItem { - return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"} + return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"} } diff --git a/internal/releaseadapter/v071/document_target.go b/internal/releaseadapter/v071/document_target.go index d08ad93..b2a5201 100644 --- a/internal/releaseadapter/v071/document_target.go +++ b/internal/releaseadapter/v071/document_target.go @@ -3,7 +3,9 @@ package v071 import ( "context" "errors" + "fmt" + "knowledge-governance/internal/platform/weknora" "knowledge-governance/internal/releasebundle" releaseworkflow "knowledge-governance/internal/workflows/release" ) @@ -49,6 +51,11 @@ type DocumentTargetConfig struct { Search searchDocumentTarget Objects objectDocumentTarget Verifier ProductionVerifier + // TargetInstanceURL/TargetTenantID are the executor's own route target. The + // console freezes the instance it verified the binding on; this side must + // match before any document write/restore. + TargetInstanceURL string + TargetTenantID uint64 } type DocumentTarget struct { @@ -63,6 +70,9 @@ func NewDocumentTarget(config DocumentTargetConfig) (*DocumentTarget, error) { } func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow.PlanItem) (releasebundle.TargetContract, error) { + if err := target.checkInstance(item); err != nil { + return releasebundle.TargetContract{}, err + } contract, err := target.config.Contract.Contract(ctx, item) if err != nil { return releasebundle.TargetContract{}, errors.New("inspect target release contract") @@ -75,6 +85,9 @@ func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow // same target base. The archive itself keeps the canonical source-form bundle: // the remap is deterministic, so a rollback re-derives the same target form. func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision string) (*DocumentBundle, error) { + if err := target.checkInstance(item); err != nil { + return nil, err + } bundle, err := target.config.Archive.Load(revision) if err != nil { return nil, err @@ -86,6 +99,9 @@ func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision } func (target *DocumentTarget) Prepare(ctx context.Context, item releaseworkflow.PlanItem, exported releaseworkflow.ExportedBundle) (releaseworkflow.PreparedChange, error) { + if err := target.checkInstance(item); err != nil { + return releaseworkflow.PreparedChange{}, err + } bundle, ok := exported.(*DocumentBundle) if !ok || validateDocumentBundle(bundle) != nil || bundle.Manifest.ReleaseRevision != item.ReleaseRevision { return releaseworkflow.PreparedChange{}, errors.New("invalid v0.7.1 target bundle") @@ -219,6 +235,30 @@ func (target *DocumentTarget) VerifyRestored(ctx context.Context, item releasewo return nil } +// checkInstance is the single instance-identity boundary for the document +// release path. Empty identity means a pre-identity binding: the executor +// cannot prove which instance it is, so it fails closed instead of writing to a +// cloned instance that happens to expose the same knowledge base id. +func (target *DocumentTarget) checkInstance(item releaseworkflow.PlanItem) error { + if item.TargetInstanceURL == "" || item.TargetTenantID == 0 { + return fmt.Errorf("%w: binding has no verified instance identity", releaseworkflow.ErrTargetInstanceMismatch) + } + if target.config.TargetInstanceURL == "" || target.config.TargetTenantID == 0 { + return fmt.Errorf("%w: executor target identity is not configured", releaseworkflow.ErrTargetInstanceMismatch) + } + if weknora.NormalizeInstanceURL(item.TargetInstanceURL) != weknora.NormalizeInstanceURL(target.config.TargetInstanceURL) { + return fmt.Errorf("%w: binding verified on %s, executor writes %s", + releaseworkflow.ErrTargetInstanceMismatch, + weknora.NormalizeInstanceURL(item.TargetInstanceURL), + weknora.NormalizeInstanceURL(target.config.TargetInstanceURL)) + } + if item.TargetTenantID != target.config.TargetTenantID { + return fmt.Errorf("%w: binding tenant %d, executor tenant %d", + releaseworkflow.ErrTargetInstanceMismatch, item.TargetTenantID, target.config.TargetTenantID) + } + return nil +} + func (target *DocumentTarget) restoreBundle(ctx context.Context, item releaseworkflow.PlanItem, revision string) error { bundle, err := target.loadBundle(item, revision) if err != nil { diff --git a/internal/releaseadapter/v071/document_target_test.go b/internal/releaseadapter/v071/document_target_test.go index 2a972f8..4fd3ba8 100644 --- a/internal/releaseadapter/v071/document_target_test.go +++ b/internal/releaseadapter/v071/document_target_test.go @@ -2,6 +2,7 @@ package v071 import ( "context" + "errors" "os" "reflect" "testing" @@ -20,7 +21,7 @@ func TestDocumentTargetCoordinatesPrepareActivateVerifyAndRollback(t *testing.T) t.Fatal(err) } calls := []string{} - target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(current)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}}) + target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(current)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000}) if err != nil { t.Fatal(err) } @@ -60,7 +61,7 @@ func TestDocumentTargetCompensatesFirstReleaseByDisableWithoutDelete(t *testing. archive, _ := NewBundleArchive(root, 16*1024*1024) bundle := testDocumentBundle(t) calls := []string{} - target, _ := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}}) + target, _ := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000}) item := releasePlanForArchive() change, err := target.Prepare(context.Background(), item, bundle) if err != nil { @@ -179,3 +180,44 @@ func revisionFromSearch(snapshot SearchSnapshot) string { } return "unknown" } + +// 网页在实例 A 上列库并保存了绑定,执行器实际连的是实例 B;即使两边知识库 +// ID 与租户完全相同,也不得写入 B。这里复用 DocumentTarget 的唯一实例身份 +// 检查,正例证明同一实例仍可通过。 +func TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance(t *testing.T) { + root := t.TempDir() + _ = os.Chmod(root, 0o700) + archive, _ := NewBundleArchive(root, 16*1024*1024) + bundle := testDocumentBundle(t) + calls := []string{} + target, err := NewDocumentTarget(DocumentTargetConfig{ + Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, + Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, + Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, + TargetInstanceURL: "https://instance-b.weknora.example", TargetTenantID: 10000, + }) + if err != nil { + t.Fatal(err) + } + item := releasePlanForArchive() // verified on instance A, same kb id, same tenant + item.TargetKnowledgeBaseID = "kb-safe" + if _, err := target.Contract(context.Background(), item); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) { + t.Fatalf("contract error = %v, want ErrTargetInstanceMismatch", err) + } + if _, err := target.Prepare(context.Background(), item, bundle); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) { + t.Fatalf("prepare error = %v, want ErrTargetInstanceMismatch", err) + } + if len(calls) != 0 { + t.Fatalf("no write/stage may happen before identity matches: %v", calls) + } + + item.TargetInstanceURL = "https://instance-b.weknora.example" + item.TargetTenantID = 10000 + if _, err := target.Contract(context.Background(), item); err != nil { + t.Fatalf("same instance must pass: %v", err) + } + item.TargetTenantID = 20000 + if _, err := target.Contract(context.Background(), item); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) { + t.Fatalf("tenant mismatch error = %v, want ErrTargetInstanceMismatch", err) + } +} diff --git a/internal/releaseadapter/v071/three_lane_integration_test.go b/internal/releaseadapter/v071/three_lane_integration_test.go index 29857bd..2478983 100644 --- a/internal/releaseadapter/v071/three_lane_integration_test.go +++ b/internal/releaseadapter/v071/three_lane_integration_test.go @@ -97,7 +97,7 @@ func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) { } verification := &verificationClient{knowledge: weknora.Knowledge{ID: "knowledge-release-safe", KnowledgeBaseID: "kb-release-safe", ParseStatus: "completed"}, chunkTotal: 1, search: []weknora.SearchResult{{ID: "chunk-release-safe", KnowledgeID: "knowledge-release-safe", Score: 0.8}}} verifier, _ := NewWeKnoraVerifier(verification) - target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: contract}, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier}) + target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: contract}, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000}) if err != nil { t.Fatal(err) } @@ -106,7 +106,7 @@ func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) { t.Fatal(err) } - first := releaseworkflow.PlanItem{ReleaseExecutionID: "rx-release-1", PublicationID: "tp-release-1", SourceItemVersionID: "version-release-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-release-1", TestKnowledgeBaseID: "kb-release-safe", KnowledgeID: "knowledge-release-safe", DecidedVisibility: "internal"} + first := releaseworkflow.PlanItem{ReleaseExecutionID: "rx-release-1", PublicationID: "tp-release-1", SourceItemVersionID: "version-release-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-release-1", TestKnowledgeBaseID: "kb-release-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-release-safe", DecidedVisibility: "internal"} if _, err := exporter.Export(ctx, first); err != nil { t.Fatalf("export preflight: %v", err) } diff --git a/internal/releaseadapter/v071/wiki_channel_test.go b/internal/releaseadapter/v071/wiki_channel_test.go index c40a4cf..86aa5b8 100644 --- a/internal/releaseadapter/v071/wiki_channel_test.go +++ b/internal/releaseadapter/v071/wiki_channel_test.go @@ -182,6 +182,7 @@ func TestDocumentTargetAppliesWikiSnapshotWhenWithdrawing(t *testing.T) { Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, + TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, }) if err != nil { t.Fatal(err) diff --git a/internal/weknoraaccess/client.go b/internal/weknoraaccess/client.go index 2ce9dab..dd12f31 100644 --- a/internal/weknoraaccess/client.go +++ b/internal/weknoraaccess/client.go @@ -47,6 +47,37 @@ func (client *Client) with(ctx context.Context, call func(*weknora.Client) error return call(remote) } +func (client *Client) TargetIdentity(ctx context.Context, knowledgeBaseID string) (weknora.InstanceIdentity, error) { + target, err := client.Resolver.Resolve(ctx) + if err != nil { + return weknora.InstanceIdentity{}, err + } + if target.BaseURL == "" || target.APIKey == "" || knowledgeBaseID == "" { + return weknora.InstanceIdentity{}, ErrNotConfigured + } + timeout := client.Timeout + if timeout <= 0 { + timeout = defaultBusinessTimeout + } + remote, err := weknora.NewClient(weknora.ClientConfig{ + BaseURL: target.BaseURL, + APIKey: target.APIKey, + Timeout: timeout, + AllowDockerHTTP: client.AllowDockerHTTP, + }) + if err != nil { + return weknora.InstanceIdentity{}, err + } + base, err := remote.GetKnowledgeBase(ctx, knowledgeBaseID) + if err != nil { + return weknora.InstanceIdentity{}, err + } + return weknora.InstanceIdentity{ + BaseURL: weknora.NormalizeInstanceURL(target.BaseURL), + TenantID: base.TenantID, + }, nil +} + func (client *Client) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) { var knowledge weknora.Knowledge err := client.with(ctx, func(remote *weknora.Client) error { diff --git a/internal/weknoraaccess/client_test.go b/internal/weknoraaccess/client_test.go index 6faedc2..e51db15 100644 --- a/internal/weknoraaccess/client_test.go +++ b/internal/weknoraaccess/client_test.go @@ -108,3 +108,26 @@ func TestExplicitShortBusinessTimeoutStillApplies(t *testing.T) { t.Fatalf("explicit short timeout took %s", elapsed) } } + +func TestTargetIdentityReadsTheOwnedTenantFromTheCurrentBinding(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/v1/knowledge-bases/kb-current" { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-current","name":"Current","tenant_id":10000}}`)) + })) + defer server.Close() + client := &Client{Resolver: readiness.Resolver{ + Endpoint: func(context.Context) string { return server.URL + "/" }, + ReadKey: func() (string, error) { return "isolated-test-key", nil }, + LoadBinding: func(context.Context) (string, error) { return "kb-current", nil }, + }, Timeout: time.Second} + identity, err := client.TargetIdentity(context.Background(), "kb-current") + if err != nil { + t.Fatal(err) + } + if identity.BaseURL != server.URL || identity.TenantID != 10000 { + t.Fatalf("identity = %#v", identity) + } +} diff --git a/internal/workflows/release/handler.go b/internal/workflows/release/handler.go index bdf550b..f9b0a7c 100644 --- a/internal/workflows/release/handler.go +++ b/internal/workflows/release/handler.go @@ -37,6 +37,9 @@ var ( ErrInvalidReleaseJob = errors.New("invalid_release_job") ErrReleaseRetryable = errors.New("release_retryable") ErrReleaseState = errors.New("release_state_failed") + // ErrTargetInstanceMismatch: the binding was verified on instance A while + // the executor writes instance B (even with the same knowledge base id). + ErrTargetInstanceMismatch = errors.New("release_target_instance_mismatch") ) type PlanItem struct { @@ -51,7 +54,13 @@ type PlanItem struct { // TargetKnowledgeBaseID is the 源库 → 目标库 mapping resolved when the // execution started (see production_kb_bindings). It equals the tested base // when the scope is unbound, which is the historical same-id semantics. - TargetKnowledgeBaseID string `json:"target_knowledge_base_id"` + TargetKnowledgeBaseID string `json:"target_knowledge_base_id"` + // TargetInstanceURL/TargetTenantID freeze the instance identity the console + // verified the selected base on. The executor compares them with its own + // route target before any write; a cloned instance with the same base id is + // not the same target. + TargetInstanceURL string `json:"target_instance_url,omitempty"` + TargetTenantID uint64 `json:"target_tenant_id,omitempty"` KnowledgeID string `json:"knowledge_id"` DecidedVisibility governance.Visibility `json:"decided_visibility"` PreviousProductionRevision string `json:"previous_production_revision"` diff --git a/internal/workflows/release/sidecar_publisher.go b/internal/workflows/release/sidecar_publisher.go index 9e4744e..8ec3dd4 100644 --- a/internal/workflows/release/sidecar_publisher.go +++ b/internal/workflows/release/sidecar_publisher.go @@ -132,7 +132,7 @@ func (publisher *SidecarPublisher) Publish(ctx context.Context, item PlanItem) ( } targetContract, err := publisher.target.Contract(ctx, item) if err != nil { - return ItemResult{}, newSidecarError(ErrorCodeTargetUnavailable, true, err) + return ItemResult{}, targetError(err) } if err := releasebundle.Validate(manifest, targetContract, releaseItemMapping(item)); err != nil { return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, err) @@ -166,7 +166,7 @@ func (publisher *SidecarPublisher) Rollback(ctx context.Context, item PlanItem) } restoredRevision, err := publisher.target.Restore(ctx, item, item.PreviousProductionRevision) if err != nil { - return ItemResult{}, newSidecarError(ErrorCodeTargetWriteFailed, true, err) + return ItemResult{}, targetError(err) } if restoredRevision != item.PreviousProductionRevision { return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, errors.New("restored revision mismatch")) @@ -197,7 +197,7 @@ func (publisher *SidecarPublisher) Delete(ctx context.Context, item PlanItem) (I } targetContract, err := publisher.target.Contract(ctx, item) if err != nil { - return ItemResult{}, newSidecarError(ErrorCodeTargetUnavailable, true, err) + return ItemResult{}, targetError(err) } if err := releasebundle.Validate(manifest, targetContract, releaseItemMapping(item)); err != nil { return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, err) @@ -224,6 +224,9 @@ func (publisher *SidecarPublisher) Delete(ctx context.Context, item PlanItem) (I func (publisher *SidecarPublisher) compensateError(ctx context.Context, item PlanItem, change PreparedChange, code string, cause error) error { if err := publisher.target.Compensate(ctx, item, change); err != nil { + if errors.Is(err, ErrTargetInstanceMismatch) { + return newSidecarError(ErrorCodeContractMismatch, false, err) + } return newSidecarError(ErrorCodeRollbackFailed, false, err) } return newSidecarError(code, false, cause) @@ -233,6 +236,15 @@ func newSidecarError(code string, retryable bool, cause error) error { return &ItemError{Code: code, Retryable: retryable, Cause: cause} } +// targetError keeps an instance mismatch non-retryable: retrying the same item +// on the same wrong instance will never become the verified target. +func targetError(err error) error { + if errors.Is(err, ErrTargetInstanceMismatch) { + return newSidecarError(ErrorCodeContractMismatch, false, err) + } + return newSidecarError(ErrorCodeTargetUnavailable, true, err) +} + func validRevision(value string) bool { return value == strings.TrimSpace(value) && value != "" && len(value) <= 128 && !strings.ContainsAny(value, "\x00\r\n\t/?#\\") } diff --git a/internal/workflows/release/sidecar_publisher_test.go b/internal/workflows/release/sidecar_publisher_test.go index efb334f..d375e04 100644 --- a/internal/workflows/release/sidecar_publisher_test.go +++ b/internal/workflows/release/sidecar_publisher_test.go @@ -163,6 +163,7 @@ func (bundle fakeExportedBundle) ReleaseManifest() releasebundle.Manifest { retu type fakeSidecarTarget struct { contract releasebundle.TargetContract + contractErr error calls *[]string prepared PreparedChange prepareErr, activateErr, verifyErr, compensateErr, restoreErr, verifyRestoredErr error @@ -172,7 +173,7 @@ type fakeSidecarTarget struct { func (f *fakeSidecarTarget) Contract(context.Context, PlanItem) (releasebundle.TargetContract, error) { *f.calls = append(*f.calls, "contract") - return f.contract, nil + return f.contract, f.contractErr } func (f *fakeSidecarTarget) Prepare(context.Context, PlanItem, ExportedBundle) (PreparedChange, error) { *f.calls = append(*f.calls, "prepare") @@ -360,3 +361,26 @@ func TestSidecarPublisherGatesDeleteAndRollbackToo(t *testing.T) { } } } + +// Instance identity mismatch is a contract failure, not a transient target +// outage: retrying the same item on the same wrong instance can never succeed. +func TestSidecarPublisherMapsInstanceMismatchToNonRetryableContractError(t *testing.T) { + calls := []string{} + manifest, err := releasebundle.Seal(testManifest()) + if err != nil { + t.Fatal(err) + } + publisher, err := NewSidecarPublisher(&fakeExporter{manifest: manifest, calls: &calls}, + &fakeSidecarTarget{contract: testTargetContract(), contractErr: ErrTargetInstanceMismatch, calls: &calls}) + if err != nil { + t.Fatal(err) + } + _, err = publisher.Publish(context.Background(), testPlanItem()) + var itemErr *ItemError + if !errors.As(err, &itemErr) || itemErr.Code != ErrorCodeContractMismatch || itemErr.Retryable { + t.Fatalf("error=%#v", err) + } + if !reflect.DeepEqual(calls, []string{"export", "contract"}) { + t.Fatalf("calls=%v", calls) + } +} diff --git a/internal/workflows/testweknora/identity.go b/internal/workflows/testweknora/identity.go new file mode 100644 index 0000000..53bd741 --- /dev/null +++ b/internal/workflows/testweknora/identity.go @@ -0,0 +1,38 @@ +package testweknora + +import ( + "context" + + "knowledge-governance/internal/platform/weknora" +) + +// IdentityProvider is implemented by the production WeKnora access client. Unit +// fakes may omit it; a handler must then treat stored identities as unverifiable +// and never write/delete/adopt an object across instances. +type IdentityProvider interface { + TargetIdentity(context.Context, string) (weknora.InstanceIdentity, error) +} + +func resolveIdentity(ctx context.Context, client any, knowledgeBaseID string) (weknora.InstanceIdentity, bool, error) { + provider, ok := client.(IdentityProvider) + if !ok { + return weknora.InstanceIdentity{}, false, nil + } + identity, err := provider.TargetIdentity(ctx, knowledgeBaseID) + if err != nil { + return weknora.InstanceIdentity{}, true, err + } + identity.BaseURL = weknora.NormalizeInstanceURL(identity.BaseURL) + return identity, true, nil +} + +// identityMatches requires BOTH the instance address and the owning tenant to +// match. A cloned instance can expose the same knowledge base id and tenant id; +// an empty stored identity is never treated as "matches anything". +func identityMatches(storedURL string, storedTenant uint64, current weknora.InstanceIdentity) bool { + if storedURL == "" || storedTenant == 0 { + return false + } + return weknora.NormalizeInstanceURL(storedURL) == weknora.NormalizeInstanceURL(current.BaseURL) && + storedTenant == current.TenantID +} diff --git a/internal/workflows/testweknora/identity_test.go b/internal/workflows/testweknora/identity_test.go new file mode 100644 index 0000000..1fd9e97 --- /dev/null +++ b/internal/workflows/testweknora/identity_test.go @@ -0,0 +1,152 @@ +package testweknora + +import ( + "context" + "errors" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/platform/weknora" +) + +const ( + instanceA = "https://instance-a.weknora.example" + instanceB = "https://instance-b.weknora.example" +) + +type identityClient struct { + identity weknora.InstanceIdentity + identityErr error + knowledge weknora.Knowledge + chunkTotal int64 + getCalls int + chunkCalls int + deleteCalls int + uploadCalls int +} + +func (client *identityClient) TargetIdentity(context.Context, string) (weknora.InstanceIdentity, error) { + return client.identity, client.identityErr +} +func (client *identityClient) GetKnowledge(context.Context, string) (weknora.Knowledge, error) { + client.getCalls++ + if client.knowledge.ID == "" { + return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404} + } + return client.knowledge, nil +} +func (client *identityClient) ListChunks(context.Context, string, int, int, []string) ([]weknora.Chunk, int64, error) { + client.chunkCalls++ + return []weknora.Chunk{{ID: "chunk-1"}}, client.chunkTotal, nil +} +func (client *identityClient) DeleteKnowledge(context.Context, string) error { + client.deleteCalls++ + return nil +} +func (client *identityClient) UploadFile(context.Context, weknora.UploadRequest) (weknora.Knowledge, error) { + client.uploadCalls++ + return weknora.Knowledge{}, errors.New("unexpected upload") +} +func (client *identityClient) ListKnowledge(context.Context, string, int, int) ([]weknora.Knowledge, int64, error) { + return nil, 0, nil +} + +func TestPollRejectsObjectUploadedToAnotherInstance(t *testing.T) { + now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC) + store := &pollStoreStub{publication: postgresstore.PublicationForPoll{ + ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1", + TestInstanceURL: instanceA, TestInstanceTenant: 10000, + ProcessingState: governance.ProcessingProcessing, PollSequence: 2, + }} + client := &identityClient{ + identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000}, + knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "completed"}, + } + handler, _ := NewPollHandler(PollHandlerConfig{Store: store, Client: client, PollDelay: time.Second, StallAfter: time.Hour, Now: func() time.Time { return now }}) + if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":2}`)}); err != nil { + t.Fatalf("identity mismatch must be a visible terminal state, not a retry error: %v", err) + } + if client.getCalls != 0 || store.failureCode != "remote_instance_changed" { + t.Fatalf("getCalls=%d failureCode=%q", client.getCalls, store.failureCode) + } +} + +func TestPollAcceptsObjectOnTheSameInstanceAndTenant(t *testing.T) { + now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC) + store := &pollStoreStub{publication: postgresstore.PublicationForPoll{ + ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1", + TestInstanceURL: instanceA, TestInstanceTenant: 10000, + ProcessingState: governance.ProcessingProcessing, PollSequence: 2, + }} + client := &identityClient{ + identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000}, + knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "finalizing"}, + } + handler, _ := NewPollHandler(PollHandlerConfig{Store: store, Client: client, PollDelay: time.Second, StallAfter: time.Hour, Now: func() time.Time { return now }}) + if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":2}`)}); err != nil { + t.Fatal(err) + } + if client.getCalls != 1 || store.recordedState != governance.ProcessingFinalizing { + t.Fatalf("getCalls=%d state=%v", client.getCalls, store.recordedState) + } +} + +func TestRemoveRefusesToDeleteACloneObject(t *testing.T) { + store := &removalStoreStub{candidate: postgresstore.PublicationForRemoval{ + ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1", + TestInstanceURL: instanceA, TestInstanceTenant: 10000, + }} + client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000}, + knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}} + handler, _ := NewRemoveHandler(RemoveHandlerConfig{Store: store, Client: client}) + if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil { + t.Fatal(err) + } + if client.deleteCalls != 0 || client.getCalls != 0 || store.failed != "publication-1:removal_instance_changed" { + t.Fatalf("deleteCalls=%d getCalls=%d failed=%q", client.deleteCalls, client.getCalls, store.failed) + } +} + +func TestValidateFailsClosedWithoutReadingTheClone(t *testing.T) { + store := &validateStoreStub{publication: postgresstore.PublicationForValidation{ + ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1", + TestInstanceURL: instanceA, TestInstanceTenant: 10000, + }} + client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 20000}, + knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}, chunkTotal: 3} + handler, _ := NewValidateHandler(ValidateHandlerConfig{Store: store, Client: client, PolicyVersion: "structural-v1"}) + if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil { + t.Fatal(err) + } + if client.getCalls != 0 || client.chunkCalls != 0 { + t.Fatalf("clone was read: get=%d chunks=%d", client.getCalls, client.chunkCalls) + } + states := map[string]governance.AcceptanceState{} + for _, result := range store.appended { + states[result.CheckType] = result.State + } + if states["knowledge_exists"] != governance.AcceptanceFailed || states["chunks_present"] != governance.AcceptanceFailed { + t.Fatalf("acceptance states = %#v", states) + } +} + +func TestUploadRefusesToWriteAfterRebindingToAnotherInstance(t *testing.T) { + store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{ + ID: "publication-1", TestKBID: "kb-1", TestInstanceURL: instanceA, TestInstanceTenant: 10000, + IngestState: governance.IngestPending, ProcessingState: governance.ProcessingPending, + TargetScope: governance.VisibilityInternal, + }} + client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000}} + handler, _ := NewUploadHandler(UploadHandlerConfig{ + Store: store, Client: client, SpoolRoot: t.TempDir(), MaxUploadBytes: 1024, FirstPollDelay: time.Second, + }) + if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","target_kb_id":"kb-1","target_scope":"internal"}`)}); err != nil { + t.Fatal(err) + } + if client.uploadCalls != 0 || store.uploadFailureCode != "upload_instance_changed" { + t.Fatalf("uploadCalls=%d failure=%q", client.uploadCalls, store.uploadFailureCode) + } +} diff --git a/internal/workflows/testweknora/poll.go b/internal/workflows/testweknora/poll.go index 8af0a59..bc1ffcf 100644 --- a/internal/workflows/testweknora/poll.go +++ b/internal/workflows/testweknora/poll.go @@ -82,6 +82,17 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error { return ErrPollStateConflict } now := handler.now() + identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID) + if identityErr != nil { + return ErrPollRemoteFailed + } + if hasProvider && !identityMatches(publication.TestInstanceURL, publication.TestInstanceTenant, identity) { + // 旧对象属于另一个实例/租户:不能在新实例上按同名/同 ID 的对象继续推进。 + if err := handler.store.RecordProcessingFailure(ctx, publication.ID, publication.PollSequence, "remote_instance_changed", now); err != nil { + return ErrPollStateConflict + } + return nil + } knowledge, err := handler.client.GetKnowledge(ctx, publication.KnowledgeID) if err != nil { return ErrPollRemoteFailed diff --git a/internal/workflows/testweknora/poll_test.go b/internal/workflows/testweknora/poll_test.go index 4987fcc..890c4e5 100644 --- a/internal/workflows/testweknora/poll_test.go +++ b/internal/workflows/testweknora/poll_test.go @@ -158,6 +158,7 @@ type pollStoreStub struct { completedValidated bool stalledMarked bool stalledCutoff time.Time + failureCode string } func (store *pollStoreStub) LoadPublicationForPoll(context.Context, string) (postgresstore.PublicationForPoll, error) { @@ -177,7 +178,8 @@ func (store *pollStoreStub) RecordCompletedAndScheduleValidation(_ context.Conte return nil } -func (store *pollStoreStub) RecordProcessingFailure(context.Context, string, int, string, time.Time) error { +func (store *pollStoreStub) RecordProcessingFailure(_ context.Context, _ string, _ int, code string, _ time.Time) error { + store.failureCode = code return nil } diff --git a/internal/workflows/testweknora/remove.go b/internal/workflows/testweknora/remove.go index ebacadd..b76cba6 100644 --- a/internal/workflows/testweknora/remove.go +++ b/internal/workflows/testweknora/remove.go @@ -65,6 +65,14 @@ func (handler *RemoveHandler) Handle(ctx context.Context, job jobs.Job) error { if err != nil { return ErrRemoveStateConflict } + identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID) + if identityErr != nil { + return ErrRemoveRemoteFailed + } + if hasProvider && !identityMatches(candidate.TestInstanceURL, candidate.TestInstanceTenant, identity) { + // 不能拿旧实例的对象 ID 到新实例上删除同名对象。 + return handler.failClosed(ctx, candidate.ID, "removal_instance_changed") + } knowledge, err := handler.client.GetKnowledge(ctx, candidate.KnowledgeID) if isNotFound(err) { return handler.complete(ctx, candidate.ID) diff --git a/internal/workflows/testweknora/upload.go b/internal/workflows/testweknora/upload.go index d520238..0d794b7 100644 --- a/internal/workflows/testweknora/upload.go +++ b/internal/workflows/testweknora/upload.go @@ -27,7 +27,7 @@ var ( type UploadStore interface { LoadPublicationForUpload(context.Context, string) (postgresstore.PublicationForUpload, error) - MarkUploading(context.Context, string, time.Time) error + MarkUploading(context.Context, string, string, uint64, time.Time) error RecordUploadAndSchedulePoll(context.Context, string, string, time.Time, time.Time) (int, error) RecordUploadFailure(context.Context, string, string, time.Time) error } @@ -93,6 +93,20 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error { if payload.TargetScope != "" && payload.TargetScope != string(candidate.TargetScope) { return ErrUploadStateConflict } + identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID) + if identityErr != nil { + return ErrUploadRemoteFailed + } + if hasProvider { + if candidate.TestInstanceURL != "" || candidate.TestInstanceTenant != 0 { + if !identityMatches(candidate.TestInstanceURL, candidate.TestInstanceTenant, identity) { + return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_instance_changed") + } + } else if candidate.IngestState == governance.IngestUploading { + // 旧行没有实例身份,又可能已经写到了旧实例:不能在克隆实例上恢复/接管。 + return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_instance_unknown") + } + } if candidate.IngestState == governance.IngestUploading { knowledge, err := handler.recoverAmbiguousUpload(ctx, candidate) if err != nil { @@ -117,7 +131,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error { return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_artifact_invalid") } defer artifact.Close() - if err := handler.store.MarkUploading(ctx, candidate.ID, handler.now()); err != nil { + if err := handler.store.MarkUploading(ctx, candidate.ID, identity.BaseURL, identity.TenantID, handler.now()); err != nil { return ErrUploadStateConflict } knowledge, uploadErr := handler.client.UploadFile(ctx, weknora.UploadRequest{ diff --git a/internal/workflows/testweknora/upload_test.go b/internal/workflows/testweknora/upload_test.go index b60826d..257b857 100644 --- a/internal/workflows/testweknora/upload_test.go +++ b/internal/workflows/testweknora/upload_test.go @@ -312,19 +312,23 @@ func TestUploadHandlerRecordsInvalidArtifactForManualRetry(t *testing.T) { } type uploadStoreStub struct { - candidate postgresstore.PublicationForUpload - markedUploading bool - recordedKnowledgeID string - nextPollAt time.Time - uploadFailureCode string + candidate postgresstore.PublicationForUpload + markedUploading bool + markedInstanceURL string + markedInstanceTenant uint64 + recordedKnowledgeID string + nextPollAt time.Time + uploadFailureCode string } func (store *uploadStoreStub) LoadPublicationForUpload(context.Context, string) (postgresstore.PublicationForUpload, error) { return store.candidate, nil } -func (store *uploadStoreStub) MarkUploading(context.Context, string, time.Time) error { +func (store *uploadStoreStub) MarkUploading(_ context.Context, _ string, instanceURL string, tenantID uint64, _ time.Time) error { store.markedUploading = true + store.markedInstanceURL = instanceURL + store.markedInstanceTenant = tenantID return nil } diff --git a/internal/workflows/testweknora/validate.go b/internal/workflows/testweknora/validate.go index 911bb52..17a5d51 100644 --- a/internal/workflows/testweknora/validate.go +++ b/internal/workflows/testweknora/validate.go @@ -101,10 +101,25 @@ func (handler *ValidateHandler) Handle(ctx context.Context, job jobs.Job) error runID = job.ID } - knowledge, knowledgeErr := handler.client.GetKnowledge(ctx, publication.KnowledgeID) + identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID) + identityOK := !hasProvider || (identityErr == nil && + identityMatches(publication.TestInstanceURL, publication.TestInstanceTenant, identity)) + identityReason := "" + if hasProvider { + switch { + case identityErr != nil: + identityReason = "instance_identity_unreadable" + case !identityOK: + identityReason = "instance_changed" + } + } knowledgeState := governance.AcceptancePassed knowledgeEvidence := json.RawMessage(`{"matched":true}`) - if knowledgeErr != nil || knowledge.ID != publication.KnowledgeID || knowledge.KnowledgeBaseID != publication.TestKBID { + if !identityOK { + knowledgeState = governance.AcceptanceFailed + knowledgeEvidence = mustJSON(map[string]any{"matched": false, "reason": identityReason}) + } else if knowledge, knowledgeErr := handler.client.GetKnowledge(ctx, publication.KnowledgeID); knowledgeErr != nil || + knowledge.ID != publication.KnowledgeID || knowledge.KnowledgeBaseID != publication.TestKBID { knowledgeState = governance.AcceptanceFailed knowledgeEvidence = json.RawMessage(`{"matched":false}`) } @@ -112,10 +127,14 @@ func (handler *ValidateHandler) Handle(ctx context.Context, job jobs.Job) error return err } - _, chunkTotal, chunksErr := handler.client.ListChunks(ctx, publication.KnowledgeID, 1, 1, nil) chunksState := governance.AcceptancePassed - if chunksErr != nil || chunkTotal <= 0 { + chunkTotal := int64(0) + if !identityOK { chunksState = governance.AcceptanceFailed + } else if _, total, chunksErr := handler.client.ListChunks(ctx, publication.KnowledgeID, 1, 1, nil); chunksErr != nil || total <= 0 { + chunksState = governance.AcceptanceFailed + } else { + chunkTotal = total } if err := handler.append(ctx, publication.ID, runID, "chunks_present", chunksState, mustJSON(map[string]any{"chunk_total": chunkTotal}), now); err != nil { return err diff --git a/scripts/test-scope.json b/scripts/test-scope.json index 4b6884b..8995585 100644 --- a/scripts/test-scope.json +++ b/scripts/test-scope.json @@ -658,6 +658,11 @@ "test": "TestV090ProductionTargetPublishIsolated", "reason": "需显式一次性本机PG(两份 0.9.0 真 schema 库)/ES/对象存储:真实导出→封存→ProductionLibraryTarget 写入 134 目标→逐表核对→写前镜像回滚,验证 0.9.0 无 wiki_log_entries、chunks 新增 NOT NULL 列走默认值、seq_id 由目标序列分配;普通CI没有这些服务,跳过不是通过" }, + { + "package": "knowledge-governance/internal/platform/postgres", + "test": "TestStartReleaseExecutionFreezesTheBindingInstanceIdentity", + "reason": "需显式一次性本机治理PG(TEST_DATABASE_URL):真实迁移、审核/封存/授权后 StartExecution 必须把绑定实例地址与租户冻结进发布项;普通CI没有该库,跳过不是通过" + }, { "package": "knowledge-governance/internal/kbbinding", "test": "TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction", diff --git a/web/src/KnowledgeBaseBinding.test.tsx b/web/src/KnowledgeBaseBinding.test.tsx index 33dec3f..ff5132c 100644 --- a/web/src/KnowledgeBaseBinding.test.tsx +++ b/web/src/KnowledgeBaseBinding.test.tsx @@ -181,6 +181,26 @@ describe('KnowledgeBaseBinding', () => { expect(body.api_key).toBeUndefined() }) + it('does not allow saving until both directions have an explicit base', async () => { + vi.stubGlobal( + 'fetch', + vi.fn((url: string) => { + if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot)) + if (String(url).includes('/catalog')) return Promise.resolve(json(catalog)) + return Promise.resolve(json({ data: binding('test') })) + }) + ) + await render() + await click('验证并读取知识库') + await choose('对内知识库', 'kb-new-in-0001') + await choose('对外知识库', '') + const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定')) + expect(save?.hasAttribute('disabled')).toBe(true) + expect(host.textContent).toContain('未选择不会回落到旧实例的默认库') + await choose('对外知识库', 'kb-new-out-0001') + expect(save?.hasAttribute('disabled')).toBe(false) + }) + it('gives viewers a read-only summary with no editing inputs', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot))) await render('viewer') diff --git a/web/src/KnowledgeBaseBinding.tsx b/web/src/KnowledgeBaseBinding.tsx index 6e9ce9e..a11e1b6 100644 --- a/web/src/KnowledgeBaseBinding.tsx +++ b/web/src/KnowledgeBaseBinding.tsx @@ -148,6 +148,8 @@ export function KnowledgeBaseBinding() { storageReady && endpointValid && keyReady && + draft.internalID !== '' && + draft.externalID !== '' && !duplicate && catalogReady ) @@ -520,7 +522,7 @@ export function KnowledgeBaseBinding() { }} disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'} > - + {currentOptions.internal.map((option) => ( + {currentOptions.external.map((option) => (