Compare commits

...

8 Commits

Author SHA1 Message Date
狐友 GXXP & Miku 8c84c9c601 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.
2026-11-24 11:22:06 +08:00
zheromiku 660320d646 Merge pull request 'fix(cd): 核验主站首页的 SSO 同源改写' (#29) from fix/cd-serving-proof into main
build / build (push) Successful in 1m46s
2026-11-23 22:00:48 +08:00
姚章浩 0e33f21206 fix(cd): 校验主站单点登录代理处理后的首页
build / build (push) Successful in 1m51s
2026-11-23 21:58:48 +08:00
zheromiku 83bba09cde Merge pull request 'fix(cd): 派发前交接并校验验收归档' (#28) from fix/cd-verified-bundle-handoff into main
build / build (push) Successful in 1m53s
2026-11-23 21:48:05 +08:00
姚章浩 868924d074 fix(cd): 核验容器引擎使用的镜像清单摘要
build / build (push) Successful in 1m53s
2026-11-23 21:46:03 +08:00
姚章浩 03e622e9c7 fix(cd): 派发前交接并核验主站候选归档
build / build (push) Successful in 2m10s
2026-11-23 21:10:50 +08:00
zheromiku 9eef078ed0 Merge pull request 'fix(settings): CYWL-4 知识库绑定与主站基线对齐' (#23) from hifox-agent/len/CYWL-4-fix into main
build / build (push) Successful in 1m56s
Reviewed-on: #23
2026-11-23 14:32:01 +08:00
zheromiku 746b982c43 Merge pull request 'chore(repo): 纳入云治理主站运行基线' (#27) from integrate/cloud-main-baseline into main
build / build (push) Successful in 1m54s
2026-11-23 14:23:57 +08:00
19 changed files with 650 additions and 36 deletions
+2
View File
@@ -28,6 +28,8 @@ QA_AI_MASTER_KEY_FILE=
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
WEKNORA_BINDING_MASTER_KEY_FILE=
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
# 同时决定「知识库绑定」页是否允许录入新 Key(能力位来自服务端);开启后页面显示明文传输风险。
# 控制台自身经 TLS 反代提供时,仍需 QA_AI_TRUST_TLS_PROXY=true 且反代传 X-Forwarded-Proto=https。
WEKNORA_ALLOW_PRIVATE_HTTP=false
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
QA_AI_DNS_OVER_TLS=
+13
View File
@@ -1,5 +1,18 @@
# Changelog
## 开发快照 0.1.414(知识库绑定:私网 http 可录入 Key)
### Fixed
- **私网 http 控制台无法录入 API Key**:页面过去只看浏览器 URL 决定能否录入,而服务端写侧
已按 `WEKNORA_ALLOW_PRIVATE_HTTP` 放行私网 http,导致「开关开着、输入框仍禁用」。GET
`/api/v1/kb-bindings` 现在返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
开关与受信反代判定;API 未返回该字段时前端按不可录入处理(失败关闭)。写侧判定不变。
- **明文录入没有风险提示**:能力位开启且页面经非回环 http 打开时,Key 输入下方常驻提示密钥
将明文传输;HTTPS 反代未配置 `QA_AI_TRUST_TLS_PROXY` 时改为提示该配置,不再笼统要求 HTTPS。
- **`Host: [::1]`(无端口)被误判为非回环**:地址规范化统一去掉 IPv6 方括号与可选端口,
回环写入不再被拒;受信反代能力位对 GET 只依赖 `X-Forwarded-Proto`(浏览器无法伪造该头)。
## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离)
### Fixed
+1 -1
View File
@@ -28,7 +28,7 @@
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
运维按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)将已验收归档传到主站只读收件目录并核对摘要。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
## 执行器配置
+8
View File
@@ -70,6 +70,14 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
**页面为什么能看到开关。** 「知识库绑定」页不再用浏览器 URL 自行判断能否录入 Key;GET
`/api/v1/kb-bindings` 返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
`WEKNORA_ALLOW_PRIVATE_HTTP` 与受信反代判定。开启开关后,经私网 http 打开的控制台可以
录入/更换 Key,并显示「密钥会以明文经过这段内网」;关闭时保持 HTTPS/回环要求。控制台
自身经 TLS 反代提供时,必须同时设置 `QA_AI_TRUST_TLS_PROXY=true` 且反代传
`X-Forwarded-Proto: https`,否则页面提示「服务器未信任本控制台的 TLS 反代」并禁用录入。
先升级 API 再升级 Web:旧 API 不返回该字段时前端按不可录入处理(失败关闭),不会误放行。
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
+2 -2
View File
@@ -24,7 +24,7 @@
```
4. 由验收人使用获授权的 HiFox CLI 登记业务结论,读回任务、验收字段和状态。`cd_acceptance` 是 JSON 字符串类型的 metadata,其解析结果为 `{"verdict":"passed","sha":"…","bundle":"…","evidence":"https://…"}`。录入人应先核对真实报告与运行身份。自动发布时,`evidence` 使用同一 HiFox 任务的验收报告评论链接(带 `#comment-<UUID>`)。评论须正文包含完整提交和归档清单摘要,并在发布人确认前完成。用 `task view --output json` 核对实际任务 UUID、空间、状态和验收字段。验收登记重试复用原归档摘要与原记录。以当前版本只接受一个任务,多个任务分别验收。
5. 在首次发布前,由运维把四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
5. HiFox 触发器在派发 Gitea 前自动通过执行机的 `weknora-test` SSH 通道交接四个文件,并用主站控制器校验。人工 Actions 入口仍须由运维提前将四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
## 在 HiFox 确认发布
@@ -49,5 +49,5 @@
- 目标机安装仓库 `scripts/{production_cd.py,cd_migration_probe.py,deploy-api-web.sh,production-cd-ssh.sh}` 到 `/opt/knowledge-governance/cd/bin/`。创建私有 `receipts/`、`bundles/`、`hifox-home/`,初始化 `source.git` 为 bare Git 仓,并将 `.gitea/required-contexts.txt` 安装到该目录。仅发布运维可更新这些文件。
- 填写目标机 `/opt/knowledge-governance/cd/deploy-production.yml`,内容与 Gitea 主分支的工作流逐字节相同。控制器用 Gitea 发布人账号 ID 和只读日志验证确认。目标端 `authorized_keys` 为 CI 单独公钥设置 `restrict,command="/opt/knowledge-governance/cd/bin/production-cd-ssh.sh"`。校验云主机 SSH host key 后将其按 `kg-governance-cd` 别名写入 `KG_CD_KNOWN_HOSTS`。对应独立 SSH 私钥保存在 `KG_CD_SSH_KEY`。Runner 标签为 `kg-production-cd`,使用 `KG_CD_SSH_HOST` 和 `KG_CD_SSH_PORT` 接入批准的 Tailscale 或本机 IPv6 隧道。
- 将受控 HiFox CLI 安装至 `bin/hifox`,由账号持有人在目标主机使用 `hifox-home` 对应的私有配置目录完成登录。身份须能读取指定空间的任务、写 `cd_release` metadata 并完成对应状态迁移。状态绑定前分别读回组织状态和实际任务类型,复用原有待发布、已发布 ID,保留其余工作流配置。
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py,cd_bundle_handoff.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
- 常规 push CI 负责验证和静态预览。这个 workflow 的唯一事件是 `workflow_dispatch`。`make verify` 的 `contracts` 子项运行 CD 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
+7 -1
View File
@@ -34,7 +34,13 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
for _, view := range views {
storageReady = storageReady || view.StorageReady
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}})
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"environments": views,
"storage_ready": storageReady,
// The page cannot test the server's transport rule from the browser URL
// alone (a TLS proxy and an untrusted proxy look identical there).
"secret_entry_allowed": consoleSecretEntryAllowed(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP),
}})
}
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
+93
View File
@@ -128,3 +128,96 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
}
}
}
func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
for _, tc := range []struct {
name string
host string
allow bool
want bool
}{
{name: "private console with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private console without toggle", host: "172.29.151.11:28188", want: false},
{name: "loopback console", host: "127.0.0.1:8080", want: true},
} {
t.Run(tc.name, func(t *testing.T) {
config := kbBindingHandler(t, store)
config.WeKnoraAllowPrivateHTTP = tc.allow
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
request.Host = tc.host
response := httptest.NewRecorder()
config.handleKBBindings(response, request)
if response.Code != http.StatusOK {
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
}
var payload struct {
Data struct {
SecretEntryAllowed bool `json:"secret_entry_allowed"`
} `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.SecretEntryAllowed != tc.want {
t.Fatalf("secret_entry_allowed = %v, want %v", payload.Data.SecretEntryAllowed, tc.want)
}
})
}
}
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) {
const (
privateHost = "172.29.151.11:28188"
origin = "http://172.29.151.11:28188"
)
store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
}
body := `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
save := func(config *Config) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPut, "http://"+privateHost+"/api/v1/kb-bindings/test", bytes.NewBufferString(body))
request.Host = privateHost
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingSave(response, request)
return response
}
catalog := func(config *Config) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPost, "http://"+privateHost+"/api/v1/kb-bindings/test/catalog",
bytes.NewBufferString(`{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`))
request.Host = privateHost
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
return response
}
enabled := kbBindingHandler(t, store)
enabled.WeKnoraAllowPrivateHTTP = true
if response := save(enabled); response.Code != http.StatusOK {
t.Fatalf("save with toggle status=%d body=%s", response.Code, response.Body.String())
}
if store.lastSave.APIKey != "typed-key" {
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
}
if response := catalog(enabled); response.Code != http.StatusOK {
t.Fatalf("catalog with toggle status=%d body=%s", response.Code, response.Body.String())
}
disabled := kbBindingHandler(t, store)
if response := save(disabled); response.Code != http.StatusBadRequest {
t.Fatalf("save without toggle status=%d body=%s", response.Code, response.Body.String())
}
if response := catalog(disabled); response.Code != http.StatusBadRequest {
t.Fatalf("catalog without toggle status=%d body=%s", response.Code, response.Body.String())
}
}
+71 -14
View File
@@ -16,14 +16,7 @@ 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() {
if loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
@@ -36,12 +29,14 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
// fetch from the operator console itself when it is served over plain http on a
// private address. That is the only non-TLS shape this deployment needs, and it
// still requires an exact Origin/Host match.
// still requires an exact Origin/Host match. It deliberately does not require
// Sec-Fetch-Site: Chrome only sends Sec-Fetch-* from secure contexts, so an
// http console on a private address never carries that header.
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if secretTransportAllowed(r, trustTLSProxy) {
return true
}
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
if !allowPrivateHTTP {
return false
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
@@ -53,8 +48,70 @@ func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, all
return false
}
host := parsed.Hostname()
if ip := net.ParseIP(host); ip != nil {
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
}
return strings.EqualFold(host, "localhost")
return privateAddressHost(host)
}
// consoleSecretEntryAllowed mirrors the transports the write gates accept, but
// it cannot simply call secretTransportAllowed: that gate guards a write and
// therefore insists on a same-origin Origin header, which a GET navigation
// never sends. Trusting X-Forwarded-Proto alone on a read is safe because
// browsers cannot set it and the deployment already declares the proxy
// trusted; a forged header still cannot make the write gate accept anything.
func consoleSecretEntryAllowed(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if r.TLS != nil || loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" {
return true
}
return allowPrivateHTTP && privateAddressHost(r.Host)
}
// requestHostname strips the optional port and IPv6 brackets. Brackets come
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
// ported forms are not address spellings the server or a browser ever emits,
// so they stay untouched and keep failing the address checks.
func requestHostname(host string) string {
host = strings.TrimSpace(host)
if strings.HasPrefix(host, "[") {
end := strings.Index(host, "]")
if end <= 0 {
return host
}
ip := net.ParseIP(host[1:end])
if ip == nil || ip.To4() != nil {
return host
}
if rest := host[end+1:]; rest != "" && (rest[0] != ':' || rest == ":" || strings.Trim(rest[1:], "0123456789") != "") {
return host
}
return ip.String()
}
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
return parsedHost
}
return host
}
// loopbackHost is the address-only part of the secret transport rule: a
// request from this machine never crosses a network.
func loopbackHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
// privateAddressHost accepts loopback and private addresses. Names other than
// localhost are rejected because the deployment toggle is about addresses,
// not about trusting whatever DNS resolves to.
func privateAddressHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && (ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast())
}
+112
View File
@@ -0,0 +1,112 @@
package httpapi
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
)
func TestConsoleSecretEntryAllowedMatrix(t *testing.T) {
cases := []struct {
name string
host string
tls bool
xfp string
trust bool
allow bool
want bool
}{
{name: "direct TLS", host: "console.example", tls: true, want: true},
{name: "loopback name", host: "localhost:8080", want: true},
{name: "loopback v4", host: "127.0.0.1:8080", want: true},
{name: "loopback v6 with port", host: "[::1]:8080", want: true},
{name: "loopback v6 without port", host: "[::1]", want: true},
// Bracketed non-IPv6 hosts are not address spellings; they must not
// borrow loopback trust from the bracket stripper.
{name: "bracketed v4 is not loopback", host: "[127.0.0.1]", want: false},
{name: "bracketed localhost is not loopback", host: "[localhost]", want: false},
{name: "bracketed v4 with toggle is not private", host: "[127.0.0.1]", allow: true, want: false},
{name: "private address with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private address without toggle", host: "172.29.151.11:28188", want: false},
{name: "link-local with toggle", host: "169.254.10.7:8080", allow: true, want: true},
{name: "public address with toggle", host: "203.0.113.10:8080", allow: true, want: false},
{name: "public name with toggle", host: "console.example", allow: true, want: false},
{name: "trusted proxy https", host: "console.example", xfp: "https", trust: true, want: true},
{name: "untrusted proxy https", host: "console.example", xfp: "https", want: false},
{name: "trusted proxy reports http", host: "console.example", xfp: "http", trust: true, want: false},
// A forged header must not beat the address rule when the proxy is not trusted.
{name: "untrusted proxy on private host", host: "172.29.151.11:28188", xfp: "https", want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://placeholder/api/v1/kb-bindings", nil)
request.Host = tc.host
if tc.tls {
request.TLS = &tls.ConnectionState{}
}
if tc.xfp != "" {
request.Header.Set("X-Forwarded-Proto", tc.xfp)
}
if got := consoleSecretEntryAllowed(request, tc.trust, tc.allow); got != tc.want {
t.Fatalf("consoleSecretEntryAllowed = %v, want %v", got, tc.want)
}
})
}
}
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = "[::1]"
if !secretTransportAllowed(request, false) {
t.Fatal("bare [::1] Host was rejected as a loopback transport")
}
request.Host = "console.example"
if secretTransportAllowed(request, false) {
t.Fatal("public name without TLS was accepted")
}
}
// Plain-http consoles are not secure contexts, so Chrome never sends
// Sec-Fetch-* with their fetches. A matching Origin is the whole contract.
func TestSecretTransportPrivateConsoleNeedsOriginNotSecFetch(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test/catalog", nil)
request.Host = "192.168.50.134:18093"
request.Header.Set("Origin", "http://192.168.50.134:18093")
if !secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("same-origin private console without Sec-Fetch-Site was rejected")
}
request.Header.Set("Origin", "http://evil.example")
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("cross-origin request was accepted as a private console")
}
request.Header.Set("Origin", "http://192.168.50.134:18093")
if secretTransportAllowedForPrivateConsole(request, false, false) {
t.Fatal("private console was accepted with the deployment toggle off")
}
}
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", "http://"+host)
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatalf("Host %q was accepted as a private console", host)
}
}
}
func TestSecretTransportRejectsMalformedIPv6Suffixes(t *testing.T) {
for _, host := range []string{"[::1]junk", "[::1]:", "[::1]:abc"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
}
}
+83
View File
@@ -0,0 +1,83 @@
"""Stage an accepted bundle on the governance host before dispatch."""
import json
import re
import shlex
import subprocess
from pathlib import Path
import production_cd as cd
ROOT = '/opt/knowledge-governance/cd/bundles'
FILES = ('release.json', 'api.tar', 'web.tar', 'worker.tar')
SSH = ['ssh', '-T', '-oBatchMode=yes', '-oStrictHostKeyChecking=yes', '-oClearAllForwardings=yes', '-oConnectTimeout=10']
HOST = 'weknora-test'
# Runs on the target using its installed controller. Exit 3 means absent only.
VERIFY = '''import json, os, runpy, stat, sys
from pathlib import Path
p = Path(sys.argv[1])
try:
info = p.lstat()
except FileNotFoundError:
sys.exit(3)
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022:
sys.exit('unsafe bundle directory')
files = {'release.json', 'api.tar', 'web.tar', 'worker.tar'}
if {f.name for f in p.iterdir()} != files or any(stat.S_IMODE(f.lstat().st_mode) != 0o600 for f in p.iterdir()):
sys.exit('unexpected bundle files or permissions')
cd = runpy.run_path('/opt/knowledge-governance/cd/bin/production_cd.py')
cd['verify_bundle'](p, dict(zip(('sha', 'task', 'bundle'), sys.argv[2:])))
print(sys.argv[4])'''
def remote(argv, *, allow_absent=False):
proc = subprocess.run([*SSH, HOST, shlex.join(argv)], capture_output=True, text=True, timeout=240)
if allow_absent and proc.returncode == 3:
return None
if proc.returncode:
raise cd.CDError('target archive handoff failed at ' + argv[0] + ': ' + proc.stderr.strip()[-300:])
return proc.stdout.strip()
def stage_bundle(request, candidates=None):
sha, task, digest = (request[k] for k in ('sha', 'task', 'bundle'))
cd.require(cd.matches(cd.SHA, sha) and cd.matches(cd.UUID, task) and cd.matches(cd.HASH, digest),
'invalid archive identity')
final = ROOT + '/' + digest
def verify(path, absent=False):
result = remote(['/usr/bin/python3', '-I', '-c', VERIFY, path, sha, task, digest], allow_absent=absent)
if absent and result is None:
return False
cd.require(result == digest, 'target archive verification returned a different digest')
return True
if verify(final, absent=True):
return digest
if candidates is None:
candidates = Path.home() / '.local/state/kg-candidate-release'
sources = []
for receipt in candidates.glob('*/ready.json'):
if not re.fullmatch('[0-9a-f]{64}', receipt.parent.name) or receipt.parent.is_symlink():
continue
ready = cd.read_json(cd.immutable_file(receipt))
if ready.get('mode') == 'acceptance' and all(ready.get(k) == request[k] for k in ('sha', 'task', 'bundle')):
sources.append(receipt.parent / 'bundle')
cd.require(len(sources) == 1, 'no unique accepted local archive matching task, commit and bundle')
source = sources[0]
cd.require(not source.is_symlink(), 'unexpected local archive directory')
cd.verify_bundle(source, request, archives=False)
paths = [str(cd.immutable_file(source / name)) for name in FILES]
temp = remote(['mktemp', '-d', ROOT + '/.handoff-XXXXXXXXXXXX'])
if not temp or not re.fullmatch(re.escape(ROOT) + r'/\.handoff-[A-Za-z0-9]{12}', temp):
raise cd.CDError('invalid target staging path')
try:
subprocess.run(['rsync', '-t', '--chmod=F600', '--perms', '-e', shlex.join(SSH), '--',
*paths, HOST + ':' + temp + '/'], check=True, timeout=1500)
verify(temp)
remote(['mv', '-Tn', '--', temp, final])
verify(final)
return digest
except (subprocess.SubprocessError, OSError) as exc:
raise cd.CDError('archive transfer incomplete before dispatch: ' + type(exc).__name__) from exc
finally:
remote(['rm', '-rf', '--', temp])
+10
View File
@@ -43,6 +43,11 @@ def hifox(cli, *args):
return result
def stage_bundle(inputs):
from cd_bundle_handoff import stage_bundle as stage
return stage(inputs)
def queue(task_id, cli, base=PATH):
cd.require(cd.matches(cd.UUID, task_id), 'use the triggering task UUID')
task = hifox(cli, 'task', 'view', task_id)
@@ -68,6 +73,11 @@ def queue(task_id, cli, base=PATH):
cd.require(result.get('inputs') == inputs, 'HiFox approval already used for a different release')
cd.require(result.get('state') == 'queued', 'dispatch outcome unknown; reconcile Gitea before retry')
return result
cd.require(stage_bundle(inputs) == inputs['bundle'], 'target archive handoff did not verify')
fresh_task = hifox(cli, 'task', 'view', task_id)
fresh_timeline = hifox(cli, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
cd.require(cd.release_approval(fresh_task, fresh_timeline, inputs) == (binding, approved_at),
'release approval changed during archive handoff')
result = {'state': 'submitting', 'inputs': inputs, 'started_at': cd.stamp()}
cd.record(claim, result)
response = forge('POST', DISPATCH, {'ref': 'main', 'inputs': inputs})
+45 -9
View File
@@ -247,7 +247,7 @@ def release(host, request):
require(existing and existing['state'] in ('deployed_hifox_pending', 'published'),
'writeback requires a verified deployment receipt')
require(all(existing[k] == request[k] for k in ('sha', 'task', 'bundle')), 'receipt binding mismatch')
manifest = verify_bundle(host.bundle_path(request), request, archives=False)
manifest = verify_bundle(host.bundle_path(request), request)
host.approve(request)
host.verify(manifest)
return writeback(host, request, existing)
@@ -268,7 +268,7 @@ def release(host, request):
host.approve(request)
require(accepted_task(host, request) == accepted, 'business acceptance changed before switch')
except (CDError, OSError, ValueError, KeyError) as exc:
receipt.update(state='failed_before_cutover')
receipt.update(state='failed_before_cutover', failure=str(exc) if isinstance(exc, CDError) else type(exc).__name__)
record(path, receipt)
raise CDError(f'failed_before_cutover: {exc}' if isinstance(exc, CDError) else 'failed_before_cutover') from exc
@@ -418,6 +418,28 @@ def verify_archive(archive, expected):
key not in descriptor.get('annotations', {}) for descriptor in oci['manifests']
for key in ('org.opencontainers.image.ref.name', 'io.containerd.image.name')),
'archive OCI index contains a mutable name')
descriptor = oci['manifests'][0].get('digest')
require(matches(IMAGE, descriptor), 'invalid OCI image descriptor')
entry = t.getmember('blobs/sha256/' + descriptor[7:])
require(entry.isfile() and entry.size < 2**20, 'unexpected OCI image manifest')
raw = t.extractfile(entry).read()
require('sha256:' + hashlib.sha256(raw).hexdigest() == descriptor, 'OCI manifest digest mismatch')
require(json.loads(raw).get('config', {}).get('digest') == expected, 'OCI config digest mismatch')
return descriptor
return expected
def engine_image(config, descriptor, revision):
# Classic storage uses the config ID. Containerd storage can expose the OCI manifest ID.
for ref in dict.fromkeys((descriptor, config)):
try:
info = image_inspect(ref)
except CDError:
continue
require(info['Id'] in (descriptor, config) and info['Config']['Labels'].get(REVISION) == revision,
'loaded image identity differs from approved archive')
return info['Id']
raise CDError('approved image unavailable by config and manifest digest')
class LiveHost:
@@ -601,13 +623,13 @@ class LiveHost:
def load(self, directory, manifest):
archives = {role: directory / (role + '.tar') for role in ROLES}
for role, archive in archives.items():
verify_archive(archive, manifest['images'][role]['id'])
descriptors = {role: verify_archive(archive, manifest['images'][role]['id'])
for role, archive in archives.items()}
self.loaded_images = {}
for role, archive in archives.items():
image = manifest['images'][role]['id']
run(['docker', 'image', 'load', '-i', str(archive)], f'load {role} image', timeout=600)
require(image_inspect(image)['Id'] == image and image_label(image) == manifest['sha'],
f'{role} loaded image differs from approved build')
self.loaded_images[role] = engine_image(image, descriptors[role], manifest['sha'])
@property
def backup(self):
@@ -616,7 +638,7 @@ class LiveHost:
def switch(self, previous, manifest):
current = self.compose.read_bytes()
require(hashlib.sha256(current).hexdigest() == previous['compose_sha256'], 'Compose changed before switch')
images = {role: manifest['images'][role]['id'] for role in ROLES}
images = self.loaded_images
changed = with_images(json.loads(current), images)
for role, image in previous['images'].items():
run(['docker', 'image', 'tag', image, f'knowledge-governance-cd-rollback:{self.request["bundle"]}-{role}'],
@@ -645,13 +667,27 @@ class LiveHost:
def read_asset(path):
return run(['docker', 'exec', name, 'cat', '/usr/share/nginx/html' + path], 'read running web asset')
require(origin_index == read_asset('/index.html'), 'served index differs from running web image')
image_index = read_asset('/index.html')
if origin_index != image_index:
# The main site's SSO proxy strips the crossorigin attribute on same-origin assets.
config = run(['docker', 'exec', name, 'cat', '/etc/nginx/conf.d/default.conf'],
'read active web configuration')
expected = re.sub(rb'(<(?:script|link)\b[^<>]*?) crossorigin(?= (?:src|href)="/assets/)',
rb'\1 ', image_index)
require(b"sub_filter 'crossorigin' '';" in config and origin_index == expected,
'served index differs from running web image')
for path, served_digest in assets.items():
require(hashlib.sha256(read_asset(path)).hexdigest() == served_digest, 'served asset differs from running web image')
return assets
def verify(self, manifest):
images = {role: manifest['images'][role]['id'] for role in ROLES}
images = getattr(self, 'loaded_images', None)
if images is None: # A separate writeback invocation must reconstruct the same identities.
directory = self.bundle_path(self.request)
images = {}
for role, item in manifest['images'].items():
descriptor = verify_archive(directory / (role + '.tar'), item['id'])
images[role] = engine_image(item['id'], descriptor, manifest['sha'])
def check():
require(self.runtime() == images, 'running image IDs differ from approved bundle')
require(api_identity(self.containers['api']) == manifest['sha'], 'running API SHA mismatches approval')
+39 -2
View File
@@ -51,6 +51,30 @@ class ProductionCD(unittest.TestCase):
self.host.switch.assert_not_called()
self.host.callback.assert_not_called()
def test_archive_binds_engine_descriptor_to_approved_config(self):
import io
import tarfile
config = b'{"architecture":"amd64"}'
digest = lambda raw: 'sha256:' + hashlib.sha256(raw).hexdigest()
expected = digest(config)
for target in (expected, 'sha256:' + '0' * 64):
blob = json.dumps({'schemaVersion': 2, 'config': {'digest': target}}).encode()
manifest_id = digest(blob)
archive = self.root / 'identity.tar'
files = {'manifest.json': json.dumps([{'Config': 'config.json'}]).encode(), 'config.json': config,
'index.json': json.dumps({'manifests': [{'digest': manifest_id}]}).encode(),
'blobs/sha256/' + manifest_id[7:]: blob}
with tarfile.open(archive, 'w') as tar:
for name, raw in files.items():
entry = tarfile.TarInfo(name)
entry.size = len(raw)
tar.addfile(entry, io.BytesIO(raw))
if target == expected:
self.assertEqual(cd.verify_archive(archive, expected), manifest_id)
else:
with self.assertRaisesRegex(cd.CDError, 'config digest'):
cd.verify_archive(archive, expected)
def test_no_confirmation_has_zero_side_effects(self):
self.request['confirm'] = ''
with self.assertRaisesRegex(cd.CDError, 'confirmation'):
@@ -152,7 +176,8 @@ class ProductionCD(unittest.TestCase):
task, timeline = self.hifox_fixture()
timeline[-1]['createdAt'] = '2026-11-22T18:00:01Z'
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline, task, timeline]), \
with patch.object(trigger, 'hifox', side_effect=[task, timeline] * 3), \
patch.object(trigger, 'stage_bundle', side_effect=lambda inputs: inputs['bundle']), \
patch.object(trigger, 'forge', return_value={'workflow_run_id': 42}) as dispatch:
first = trigger.queue(TASK, 'unused', self.root)
replay = trigger.queue(TASK, 'unused', self.root)
@@ -161,10 +186,22 @@ class ProductionCD(unittest.TestCase):
dispatch.assert_called_once_with('POST', trigger.DISPATCH, {'ref': 'main', 'inputs': first['inputs']})
self.assertEqual(first['inputs']['approval_event'], timeline[-1]['id'])
def test_missing_target_bundle_holds_dispatch_without_claim(self):
task, timeline = self.hifox_fixture()
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline]), \
patch.object(trigger, 'stage_bundle', create=True, side_effect=cd.CDError('archive unavailable')), \
patch.object(trigger, 'forge', return_value={'workflow_run_id': 42}) as dispatch:
with self.assertRaisesRegex(cd.CDError, 'archive unavailable'):
trigger.queue(TASK, 'unused', self.root)
dispatch.assert_not_called()
self.assertFalse((self.root / (timeline[-1]['id'] + '.json')).exists())
def test_unknown_dispatch_outcome_is_held(self):
task, timeline = self.hifox_fixture()
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline, task, timeline]), \
with patch.object(trigger, 'hifox', side_effect=[task, timeline] * 3), \
patch.object(trigger, 'stage_bundle', side_effect=lambda inputs: inputs['bundle']), \
patch.object(trigger, 'forge', side_effect=TimeoutError()) as dispatch:
with self.assertRaises(TimeoutError):
trigger.queue(TASK, 'unused', self.root)
+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)
}