fix(kb-bindings): allow key entry on private HTTP consoles
build / build (push) Successful in 2m26s

- Accept the private-console transport with an exact Origin/Host match; the http console is not a secure context, so Chrome sends no Sec-Fetch-Site and that requirement made every real write 400.
- Reject bracketed non-IPv6 host spellings, including ported forms, instead of normalising them to loopback.
- Show the plaintext-warning copy or the disabled state from a tri-state capability field; old APIs keep the legacy message.
- Document WEKNORA_ALLOW_PRIVATE_HTTP in .env.example and the operations runbook.
This commit is contained in:
狐友 GXXP & Miku
2026-11-24 10:29:33 +08:00
committed by 姚章浩
parent 660320d646
commit 8c84c9c601
13 changed files with 470 additions and 22 deletions
+70 -2
View File
@@ -32,6 +32,12 @@ 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 catalog = {
@@ -110,11 +116,11 @@ afterEach(async () => {
vi.unstubAllGlobals()
})
const render = async (role: 'admin' | 'viewer' = 'admin') => {
const render = async (role: 'admin' | 'viewer' = 'admin', consoleLocation?: { protocol: string; hostname: string }) => {
await act(async () => {
root.render(
<AuthContext.Provider value={auth(role)}>
<KnowledgeBaseBinding />
<KnowledgeBaseBinding consoleLocation={consoleLocation} />
</AuthContext.Provider>
)
})
@@ -272,4 +278,66 @@ describe('KnowledgeBaseBinding', () => {
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
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))))
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')
})
it('does not warn on an HTTPS console the server already trusts', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).not.toContain('密钥会以明文经过这段内网')
})
it('keeps existing-key operations available while key entry is closed', 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).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()
await click('验证并读取知识库')
await choose('对内知识库', 'kb-new-in-0001')
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
// 没有新密钥也能改选库:keep 不经过密钥传输闸门。
expect(save?.hasAttribute('disabled')).toBe(false)
await click('保存测试绑定')
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
expect(put).toBeTruthy()
const body = JSON.parse(String(put![1]?.body))
expect(body.key_action).toBe('keep')
expect(body.api_key).toBeUndefined()
expect(host.textContent).toContain('已保存测试绑定')
})
})
+32 -4
View File
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useOptionalAuth } from './auth'
import { secretEntryAllowed } from './secureEntry'
import { plaintextRemoteConsole } from './secureEntry'
import {
KBBindingError,
duplicateSelection,
@@ -82,7 +82,18 @@ const fallbackLabel = (fallback: string): string =>
const statusTone = (status: KBCatalog['status']): string =>
status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error'
export function KnowledgeBaseBinding() {
interface ConsoleLocation {
protocol: string
hostname: string
}
// consoleLocation is injected by tests that need both console shapes; the app
// always uses the real window.
export function KnowledgeBaseBinding({
consoleLocation,
}: {
consoleLocation?: ConsoleLocation
} = {}) {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [snapshot, setSnapshot] = useState<KBBindingSnapshot | null>(null)
@@ -135,7 +146,13 @@ export function KnowledgeBaseBinding() {
const busyNow = busy[env]
const notice = notices[env]
const secure = typeof window !== 'undefined' && secretEntryAllowed(window.location)
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 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() !== ''
@@ -518,9 +535,20 @@ export function KnowledgeBaseBinding() {
)}
</div>
</div>
{!secure ? (
{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>
) : null}
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
) : null}
+20
View File
@@ -39,11 +39,13 @@ describe('knowledgeBaseBindings', () => {
data: {
environments: [binding('test'), binding('production')],
storage_ready: true,
secret_entry_allowed: true,
},
})
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)
const asRecord = parsed.test as unknown as Record<string, unknown>
expect(asRecord.api_key).toBeUndefined()
expect(asRecord.key_ciphertext).toBeUndefined()
@@ -53,6 +55,24 @@ 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', () => {
const parsed = parseKBBindingSnapshot({
data: {
environments: [binding('test'), binding('production')],
storage_ready: true,
secret_entry_allowed: false,
},
})
expect(parsed.secret_entry_allowed).toBe(false)
})
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…)')
+10 -1
View File
@@ -34,6 +34,9 @@ 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 {
@@ -130,7 +133,13 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
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) }
return {
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,
}
}
// 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import { plaintextRemoteConsole, secretEntryAllowed } from './secureEntry'
describe('secureEntry', () => {
it('accepts HTTPS and loopback whatever the deployment toggle says', () => {
for (const location of [
{ protocol: 'https:', hostname: 'kb.example' },
{ protocol: 'http:', hostname: 'localhost' },
{ protocol: 'http:', hostname: '127.0.0.1' },
{ protocol: 'http:', hostname: '[::1]' },
{ protocol: 'http:', hostname: '::1' },
]) {
expect(secretEntryAllowed(location), JSON.stringify(location)).toBe(true)
expect(plaintextRemoteConsole(location)).toBe(false)
}
})
it('treats plain HTTP from any other host as a plaintext network path', () => {
for (const hostname of ['172.29.151.11', '10.0.0.5', 'kb.internal.example', '203.0.113.10']) {
const location = { protocol: 'http:', hostname }
expect(secretEntryAllowed(location), hostname).toBe(false)
expect(plaintextRemoteConsole(location), hostname).toBe(true)
}
})
})
+7
View File
@@ -3,3 +3,10 @@
export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean {
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.
export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean {
return !secretEntryAllowed(location)
}