fix(kb): 不再按控制台传输形态拦截 API Key

- 删除 KBBindingSnapshot 的 secret_entry_allowed 能力位与服务端 catalog/save 的 KB 传输门禁
- 非 HTTPS 控制台保留明文传输提示,但不再阻断 Key 录入
- 保留 QA AI 严格 HTTPS/回环校验、管理员认证、写意图头与 Key 不回显
- 补齐明文 HTTP 页面与服务端写入回归测试,同步运行手册和 CHANGELOG
This commit is contained in:
Zhero & Miku
2026-11-25 10:47:53 +08:00
committed by 姚章浩
parent 7926c8e8b9
commit 32c7074f41
14 changed files with 131 additions and 322 deletions
+42 -40
View File
@@ -32,14 +32,11 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
})
const snapshot = {
data: { environments: [binding('test'), binding('production')], storage_ready: true, secret_entry_allowed: true },
}
const snapshotWith = (secretEntryAllowed: boolean) => ({
data: { ...snapshot.data, secret_entry_allowed: secretEntryAllowed },
})
const snapshotWithoutCapability = {
data: { environments: [binding('test'), binding('production')], storage_ready: true },
}
const snapshotWithLegacyCapability = (allowed: boolean) => ({
data: { ...snapshot.data, secret_entry_allowed: allowed },
})
const catalog = {
data: {
status: 'ok',
@@ -279,48 +276,53 @@ describe('KnowledgeBaseBinding', () => {
expect(save?.hasAttribute('disabled')).toBe(true)
})
it('disables key entry when the server reports no accepted transport', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
await render()
await click('更换密钥')
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
expect(input?.disabled).toBe(true)
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
})
it('points an HTTPS console at the untrusted proxy setting instead of asking for HTTPS', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).toContain('QA_AI_TRUST_TLS_PROXY=true')
expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
})
it('does not blame a proxy when an older API omits the capability', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWithoutCapability)))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
})
it('allows key entry on a private plain-HTTP console and warns about plaintext', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
it('submits a typed key from a plain-HTTP console even when a legacy capability says no', async () => {
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWithLegacyCapability(false)))
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
return Promise.resolve(json({ data: binding('test') }))
})
vi.stubGlobal('fetch', fetchMock)
await render('admin', { protocol: 'http:', hostname: '172.29.151.11' })
await click('更换密钥')
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
expect(input?.disabled).toBe(false)
expect(host.textContent).toContain('密钥会以明文经过这段内网')
expect(host.textContent).toContain('WEKNORA_ALLOW_PRIVATE_HTTP=true')
const key = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
expect(key?.disabled).toBe(false)
expect(host.textContent).toContain('当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。')
expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(key, 'typed-on-plain-http')
key!.dispatchEvent(new Event('input', { bubbles: true }))
})
await click('验证并读取知识库')
const catalogCall = fetchMock.mock.calls.find((call) => String(call[0]).includes('/catalog'))
expect(catalogCall).toBeTruthy()
expect(typeof catalogCall?.[1]?.body).toBe('string')
const catalogBody = JSON.parse(String(catalogCall?.[1]?.body))
expect(catalogBody).toMatchObject({ key_action: 'replace', api_key: 'typed-on-plain-http' })
await choose('对内知识库', 'kb-new-in-0001')
await choose('对外知识库', 'kb-new-out-0001')
await click('保存测试绑定')
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
expect(put).toBeTruthy()
expect(typeof put?.[1]?.body).toBe('string')
const saveBody = JSON.parse(String(put?.[1]?.body))
expect(saveBody).toMatchObject({ key_action: 'replace', api_key: 'typed-on-plain-http' })
expect(host.textContent).toContain('已保存测试绑定')
})
it('does not warn on an HTTPS console the server already trusts', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
it('does not warn on an HTTPS console', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).not.toContain('密钥会以明文经过这段内网')
expect(host.textContent).not.toContain('明文 HTTP')
})
it('keeps existing-key operations available while key entry is closed', async () => {
it('keeps existing-key operations available without a fresh key', async () => {
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWith(false)))
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({ data: binding('test') }))
return Promise.resolve(json({ data: binding('test') }))
+4 -19
View File
@@ -147,16 +147,12 @@ export function KnowledgeBaseBinding({
const notice = notices[env]
const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' })
// The server decides whether it will accept a key on this connection; the
// browser URL cannot tell a trusted TLS proxy from an untrusted one.
const secretEntryAllowed = snapshot?.secret_entry_allowed
const secure = secretEntryAllowed === true
const plaintext = secure && plaintextRemoteConsole(console)
const untrustedProxy = secretEntryAllowed === false && console.protocol === 'https:'
// 密钥录入不再由控制台传输形态阻断;明文提示只说明浏览器到控制台这一段的事实。
const plaintext = plaintextRemoteConsole(console)
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 keyEntryBlocked = !storageReady
const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false
const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false
const catalogReady = Boolean(
@@ -535,19 +531,8 @@ export function KnowledgeBaseBinding({
)}
</div>
</div>
{untrustedProxy ? (
<p className="settings-warn">
服务器未信任本控制台的 TLS 反代:HTTPS 在反代终止时需 QA_AI_TRUST_TLS_PROXY=true,并传递
X-Forwarded-Proto。
</p>
) : !secure ? (
<p className="settings-warn">当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。</p>
) : null}
{plaintext ? (
<p className="settings-warn">
当前通过明文 HTTP 录入:密钥会以明文经过这段内网。该部署已放开私网
HTTP(WEKNORA_ALLOW_PRIVATE_HTTP=true)。
</p>
<p className="settings-warn">当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。</p>
) : null}
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
+3 -10
View File
@@ -45,7 +45,7 @@ describe('knowledgeBaseBindings', () => {
expect(parsed.test.base_url).toBe('https://test.example')
expect(parsed.production.internal_kb_name).toBe('内部资料')
expect(parsed.storage_ready).toBe(true)
expect(parsed.secret_entry_allowed).toBe(true)
expect((parsed as unknown as Record<string, unknown>).secret_entry_allowed).toBeUndefined()
const asRecord = parsed.test as unknown as Record<string, unknown>
expect(asRecord.api_key).toBeUndefined()
expect(asRecord.key_ciphertext).toBeUndefined()
@@ -55,14 +55,7 @@ describe('knowledgeBaseBindings', () => {
expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
})
it('leaves the capability absent when an older API does not report it', () => {
const parsed = parseKBBindingSnapshot({
data: { environments: [binding('test'), binding('production')], storage_ready: true },
})
expect(parsed.secret_entry_allowed).toBeUndefined()
})
it('keeps an explicit refusal distinguishable from a missing field', () => {
it('ignores the removed legacy transport capability', () => {
const parsed = parseKBBindingSnapshot({
data: {
environments: [binding('test'), binding('production')],
@@ -70,7 +63,7 @@ describe('knowledgeBaseBindings', () => {
secret_entry_allowed: false,
},
})
expect(parsed.secret_entry_allowed).toBe(false)
expect((parsed as unknown as Record<string, unknown>).secret_entry_allowed).toBeUndefined()
})
it('shows a short id next to the name so same-name bases are distinguishable', () => {
-5
View File
@@ -34,9 +34,6 @@ export interface KBBindingSnapshot {
test: KBEnvironmentBinding
production: KBEnvironmentBinding
storage_ready: boolean
// Absent stays absent: an older API must not be reported as an untrusted
// proxy, and it must still fail closed for key entry.
secret_entry_allowed?: boolean
}
export interface KBCatalogOption {
@@ -137,8 +134,6 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
test,
production,
storage_ready: bool(value.data.storage_ready),
secret_entry_allowed:
typeof value.data.secret_entry_allowed === 'boolean' ? value.data.secret_entry_allowed : undefined,
}
}
+3 -3
View File
@@ -4,9 +4,9 @@ export function secretEntryAllowed(location: { protocol: string; hostname: strin
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
}
// True when a key typed here would cross a network in the clear, even though
// the server presently allows it. Drives the warning only, never the gate:
// the gate is the server-reported capability.
// True when a key typed here would cross a network in the clear. The knowledge
// base page uses this for its warning only; QA AI still uses secretEntryAllowed
// as a hard gate.
export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean {
return !secretEntryAllowed(location)
}