Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cc289b63e5 | |||
| 9ddc3291cc | |||
| 32c7074f41 | |||
| 7926c8e8b9 | |||
| bb57a9835c | |||
| 49f9994ea6 | |||
| 501fbae6ff | |||
| 45aef5016a | |||
| c90cb803fa | |||
| e6a9acc32c | |||
| a3dcaa2f5b | |||
| c33c7e2700 | |||
| 91f9e00010 | |||
| 9952412eff | |||
| 4a12b20e9b | |||
| 8d873680cc | |||
| edd90b253e | |||
| d3c435183e | |||
| aa75dc6d44 | |||
| c96189db1b |
+1
-2
@@ -28,8 +28,7 @@ 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。
|
||||
# 只影响治理 API/worker 访问 WeKnora 的地址校验;控制台自身的密钥录入不再由该开关控制。
|
||||
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=
|
||||
|
||||
+59
-1
@@ -1,6 +1,48 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.415(成员管理:新增成员改为右侧抽屉)
|
||||
## 开发快照 0.1.422(知识库绑定:不再按控制台传输形态拦截 Key)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **非 HTTPS 控制台仍无法录入 API Key**:页面删除 `secret_entry_allowed` 能力位与
|
||||
`secure`/`keyEntryBlocked` 传输判定,服务端删除 KB 专用的
|
||||
`secretTransportAllowedForPrivateConsole` 写侧校验。管理员在任意同源控制台都能录入/
|
||||
更换 Key,不再出现「可输入但保存 400」的半修复。
|
||||
- **提示与录入门禁解耦**:非 HTTPS、非回环页面保留「当前通过明文 HTTP 访问:录入的
|
||||
API Key 会在内网明文传输。」,只提示不阻断;HTTPS 页面不再提示反代是否受信。
|
||||
- **保存落审计**:`weknora_environment_binding_history` 同一事务写入操作人、时间、
|
||||
环境、客户端地址与控制台来源(`source_address`/`source_origin`),明文录入事后可追溯;
|
||||
来源只做取证,不参与放行判定,解析不出就留空而不猜值。
|
||||
|
||||
### Changed
|
||||
|
||||
- `WEKNORA_ALLOW_PRIVATE_HTTP` 仅控制治理 API/worker 访问同网段 http 目标,不再决定
|
||||
控制台密钥录入。问答 AI 模型密钥仍走严格 HTTPS/回环校验;管理员、`X-Governance-Action`
|
||||
写意图与 Key 不回显边界不变。Web 与 API 是独立镜像,须同批次发布/回滚:旧 Web 对新
|
||||
API 会禁用录入,新 Web 对旧 API 仍会被 400 拒绝。
|
||||
|
||||
## 开发快照 0.1.421(负责人手动切换需求状态)
|
||||
|
||||
- 原需求单在候选就绪和主站发布成功时回填回执,负责人按回执手动切换状态。
|
||||
|
||||
## 开发快照 0.1.420(需求单候选排队)
|
||||
|
||||
- 需求单预检通过后自动排队等待验收环境,构建链接回填原单。已发布批次释放其测试容器,接续下一张需求。
|
||||
|
||||
## 开发快照 0.1.419(候选预检识别落地 merge)
|
||||
|
||||
- 预检支持从含多个版本号的提交链中识别 `落地 merge`,并分别提示缺少和存在多个落地版本。
|
||||
|
||||
## 开发快照 0.1.418(原需求单发布)
|
||||
|
||||
- 白盒预检后在原需求单自动准备候选,业务与批次回归证据同单登记。负责人在原单切到「待发布」批准上线。
|
||||
|
||||
## 开发快照 0.1.417(知识治理发布助理接收提测交接)
|
||||
|
||||
- 预检通过后按实际落地版本创建发布范围预览,支持单独选择已进入主线的修复提交。
|
||||
- 负责人回复预览确认范围,候选验收报告按实际归档归集到发布单。
|
||||
|
||||
## 开发快照 0.1.416(成员管理:新增成员改为右侧抽屉)
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -17,6 +59,22 @@
|
||||
- **请求错误带 HTTP 状态**:`web/src/members.ts` 的失败改为 `MembersRequestError`
|
||||
(含 `status`),组件按 409/400 分流,不再依赖错误文案匹配。
|
||||
|
||||
## 开发快照 0.1.415(系统设置:刷新策略改为按模块分组的参数设置)
|
||||
|
||||
### Changed
|
||||
|
||||
- **入口改为「参数设置」**:系统设置左侧子导航与页面标题由「刷新策略」替换为「参数设置」,
|
||||
旧入口不再出现。
|
||||
- **参数按模块分组**:按产品归属固定为「来源与目录」(文档状态刷新间隔 15/30/60 秒、
|
||||
资源刷新间隔 30/60 秒)与「解析监控」(解析停滞阈值 30/60 分钟、入库并发上限 1..16);
|
||||
分组标题下不叠加说明段。
|
||||
- **数值输入与就地校验**:四个下拉改为文本数值输入;空值、非整数、`+15`/`1e1`、全角数字
|
||||
与越界值当场红字提示并禁用保存,不发请求;并发不再受旧下拉六档限制。
|
||||
- **保留现状说明与保存边界**:每项保留单位与调大/调小后果;解析停滞阈值保留 worker 1 分钟
|
||||
内生效说明;保存仍只提交参数分区,且原样回传未展示的 `finalizing_after_seconds` 与连接字段。
|
||||
- **去掉无消费者的收尾超时展示**:本页不再展示「收尾超时告警」,成功消息与底部摘要也不再
|
||||
播报它;API/DB/worker 与 `finalizing` 处理状态均未改动。
|
||||
|
||||
## 开发快照 0.1.414(知识库绑定:私网 http 可录入 Key)
|
||||
|
||||
### Fixed
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ services:
|
||||
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
||||
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
|
||||
# 链路本地,公网 http 仍被拒绝)。客户端、探活与连接页共用同一判定。
|
||||
# 链路本地,公网 http 仍被拒绝)。客户端与探活共用同一判定;控制台密钥录入不受此开关控制。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
|
||||
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
||||
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Advance original-task candidate queue
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=%h/.local/lib/kg-candidate-release/python3 %h/.local/lib/kg-candidate-release/scripts/candidate_queue.py
|
||||
TimeoutStartSec=180
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Check reviewed demand tasks waiting for QA
|
||||
|
||||
[Timer]
|
||||
OnStartupSec=30s
|
||||
OnUnitInactiveSec=45s
|
||||
AccuracySec=5s
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -1,8 +1,14 @@
|
||||
# 知识治理候选和批次验收
|
||||
|
||||
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
## 需求单的六个状态
|
||||
|
||||
## 发起候选
|
||||
新需求默认「规划中」。负责人手动按「规划中 → 进行中 → 待测试 → 测试中 → 待发布 → 已发布」切换状态。切到「待测试」触发预检和候选排队,收到候选就绪回执后切到「测试中」派测。原单显示「批次验收通过」后切到「待发布」触发 CD,收到主站发布完成回执后切到「已发布」。
|
||||
|
||||
## 在原需求单发布
|
||||
|
||||
白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后由负责人切到「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
|
||||
|
||||
## 旧版独立发布单的存量操作
|
||||
|
||||
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
|
||||
|
||||
|
||||
@@ -70,13 +70,11 @@ 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 不返回该字段时前端按不可录入处理(失败关闭),不会误放行。
|
||||
**页面为什么不看开关。** 「知识库绑定」页不再用浏览器 URL 或服务端能力位决定能否录入 Key;只要独立安全存储就绪,管理员即可录入/更换,服务端也不因控制台协议拒绝。经非 HTTPS、非回环地址打开时,页面只显示「当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。」,提示但不阻断。`WEKNORA_ALLOW_PRIVATE_HTTP` 只控制治理 API/worker 访问同网段 http 目标,不再控制控制台录入;问答 AI 模型密钥仍只允许 HTTPS/回环录入。Web 与 API 是独立镜像,必须同批次发布/回滚:旧 Web 对新 API 会因缺少能力位禁用录入,新 Web 对旧 API 仍会被服务端 400 拒绝。
|
||||
|
||||
**保存留审计。** 每次保存成功,`weknora_environment_binding_history` 在同一事务写入
|
||||
操作人、时间、环境、客户端地址(`source_address`)与控制台来源(`source_origin`)。来源字段
|
||||
只用于事后取证,不参与放行;地址解析不出来就留空,不用推测值填充。
|
||||
|
||||
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
|
||||
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
|
||||
@@ -184,7 +182,7 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
|
||||
| 知识库绑定(测试 090 / 生产 090) | 管理员 | 每个环境:服务地址 + API Key(服务器真实列库)→ 选对外/对内库 → 一次保存;密钥不回显,换地址须重录 |
|
||||
| 绑定诊断(折叠) | 管理员 | 探活、封存源对照、整库发布目标(只读,由部署配置决定)与旧文档级目标 |
|
||||
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
|
||||
| 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) |
|
||||
| 参数设置 | 文档工程师 | 「来源与目录」文档/资源刷新间隔;「解析监控」停滞阈值、入库并发上限(1..16,版本化 + 原子切换);finalizing 设置仅在 API/DB 保留,页面不展示 |
|
||||
| 成员与角色 | 管理员 | 成员与 viewer/engineer/admin |
|
||||
|
||||
## 9. 备份与恢复运维 **【新】**
|
||||
|
||||
@@ -284,10 +284,14 @@
|
||||
- 立即备份:按钮变"备份进行中…"→ 约 50 秒后自动刷出新结果(异步 202 + 在途单飞,重复点击不会跑两次)
|
||||
- 状态:✅ 2026-10-09 面板实测(写操作仅管理员:`PUT/POST /api/v1/backup-schedule*`)
|
||||
|
||||
### D5 刷新策略
|
||||
- 入口:**系统设置 → 刷新策略**(文档工程师可改)
|
||||
- 期望:文档/资源刷新间隔、停滞判定、finalizing 时长;保存先验证再原子启用、旧版本留审计
|
||||
- 状态:✅(`ui_settings` 版本化激活测试)
|
||||
### D5 参数设置
|
||||
- 入口:**系统设置 → 参数设置**(文档工程师可改)
|
||||
- 期望:按「来源与目录」「解析监控」两组呈现。来源与目录:文档状态刷新间隔(15/30/60 秒)、
|
||||
资源刷新间隔(30/60 秒);解析监控:解析停滞阈值(30/60 分钟)、入库并发上限(1..16)。
|
||||
四项以数值输入呈现,单位与调大/调小后果常驻,越界就地提示并禁用保存;保存先验证再原子
|
||||
启用、旧版本留审计。收尾超时告警不再在页面任何位置出现;API/DB 的
|
||||
`finalizing_after_seconds` 与 `finalizing` 处理状态不变。
|
||||
- 状态:✅(`ui_settings` 版本化激活测试;本任务补数值校验与浏览器实测)
|
||||
|
||||
### D6 成员与角色
|
||||
- 入口:**系统设置 → 成员与角色**(管理员)
|
||||
|
||||
@@ -3,7 +3,9 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -37,9 +39,6 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
|
||||
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),
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -62,10 +61,6 @@ func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Reque
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
||||
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)
|
||||
@@ -93,10 +88,7 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
input.SourceAddress, input.SourceOrigin = requestAuditSource(r)
|
||||
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
@@ -125,3 +117,43 @@ func writeKBBindingError(w http.ResponseWriter, err error) {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
|
||||
}
|
||||
}
|
||||
|
||||
// requestAuditSource records the two facts the save audit needs: which console
|
||||
// origin the admin used and the client address behind it. Audit only — nothing
|
||||
// here decides whether a key may be typed or saved.
|
||||
//
|
||||
// The nearest proxy appends its peer to the END of X-Forwarded-For, so that hop
|
||||
// is the trustworthy one; earlier entries are whatever the browser sent. A
|
||||
// forwarded chain is honoured only when the direct peer is private/loopback
|
||||
// (the deployment's own nginx), so a request that reaches the API directly
|
||||
// cannot launder its address through a forged header.
|
||||
func requestAuditSource(r *http.Request) (address, origin string) {
|
||||
peer := r.RemoteAddr
|
||||
if host, _, err := net.SplitHostPort(peer); err == nil {
|
||||
peer = host
|
||||
}
|
||||
ip := net.ParseIP(strings.Trim(peer, "[]"))
|
||||
if ip != nil {
|
||||
address = ip.String()
|
||||
if ip.IsLoopback() || ip.IsPrivate() {
|
||||
hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
|
||||
if last := net.ParseIP(strings.TrimSpace(hops[len(hops)-1])); last != nil {
|
||||
address = last.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if parsed, err := url.Parse(strings.TrimSpace(r.Header.Get("Origin"))); err == nil &&
|
||||
(parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" {
|
||||
origin = parsed.Scheme + "://" + parsed.Host
|
||||
return address, origin
|
||||
}
|
||||
if r.Host != "" {
|
||||
scheme := "http"
|
||||
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
|
||||
scheme = "https"
|
||||
}
|
||||
origin = scheme + "://" + r.Host
|
||||
}
|
||||
return address, origin
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package httpapi
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -88,34 +87,37 @@ func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) {
|
||||
store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}}
|
||||
func TestKBBindingCatalogAndSaveAcceptTypedKeysOnPlainHTTP(t *testing.T) {
|
||||
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},
|
||||
}
|
||||
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))
|
||||
catalogBody := `{"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(catalogBody))
|
||||
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)
|
||||
t.Fatalf("plain HTTP catalog status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "typed-key") {
|
||||
t.Fatal("catalog response echoed the typed key")
|
||||
}
|
||||
|
||||
saveBody := `{"base_revision":1,"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
|
||||
request = httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("plain HTTP save 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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
||||
@@ -129,95 +131,112 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) {
|
||||
func TestKBBindingsReadDoesNotReportTransportCapability(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)
|
||||
}
|
||||
})
|
||||
config := kbBindingHandler(t, store)
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
|
||||
request.Host = "172.29.151.11:28188"
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindings(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "secret_entry_allowed") {
|
||||
t.Fatalf("read response still reports the removed capability: %s", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) {
|
||||
func TestKBBindingPlainHTTPWritesDoNotDependOnPrivateToggle(t *testing.T) {
|
||||
const (
|
||||
privateHost = "172.29.151.11:28188"
|
||||
origin = "http://172.29.151.11:28188"
|
||||
saveBody = `{"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"}`
|
||||
catalogBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
|
||||
)
|
||||
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"}`
|
||||
for _, allow := range []bool{false, true} {
|
||||
config := kbBindingHandler(t, store)
|
||||
config.WeKnoraAllowPrivateHTTP = allow
|
||||
|
||||
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 := httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody))
|
||||
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
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("save with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
|
||||
}
|
||||
if store.lastSave.APIKey != "typed-key" {
|
||||
t.Fatalf("save with toggle=%v did not forward the typed key: %q", allow, store.lastSave.APIKey)
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody))
|
||||
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()
|
||||
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())
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("catalog with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingSaveAuditSourcePrefersTheProxyAppendedHop(t *testing.T) {
|
||||
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}}}
|
||||
config := kbBindingHandler(t, store)
|
||||
body := `{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
remote string
|
||||
forwarded string
|
||||
origin string
|
||||
proto string
|
||||
host string
|
||||
wantAddress string
|
||||
wantOrigin string
|
||||
}{
|
||||
{
|
||||
name: "private proxy appends the real client after a forged hop",
|
||||
remote: "10.0.0.5:41234", forwarded: "6.6.6.6, 172.29.151.11",
|
||||
origin: "http://172.29.151.11:8088", host: "172.29.151.11:8088",
|
||||
wantAddress: "172.29.151.11", wantOrigin: "http://172.29.151.11:8088",
|
||||
},
|
||||
{
|
||||
name: "direct peer cannot launder its address through a forged chain",
|
||||
remote: "203.0.113.9:41234", forwarded: "6.6.6.6",
|
||||
host: "console.example",
|
||||
wantAddress: "203.0.113.9", wantOrigin: "http://console.example",
|
||||
},
|
||||
{
|
||||
name: "trusted proxy scheme fills in for a missing Origin",
|
||||
remote: "10.0.0.5:41234", proto: "https", host: "kb.example",
|
||||
wantAddress: "10.0.0.5", wantOrigin: "https://kb.example",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPut, "http://"+tc.host+"/api/v1/kb-bindings/test", strings.NewReader(body))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
request.RemoteAddr = tc.remote
|
||||
if tc.forwarded != "" {
|
||||
request.Header.Set("X-Forwarded-For", tc.forwarded)
|
||||
}
|
||||
if tc.origin != "" {
|
||||
request.Header.Set("Origin", tc.origin)
|
||||
}
|
||||
if tc.proto != "" {
|
||||
request.Header.Set("X-Forwarded-Proto", tc.proto)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if store.lastSave.SourceAddress != tc.wantAddress || store.lastSave.SourceOrigin != tc.wantOrigin {
|
||||
t.Fatalf("audit source = %q/%q, want %q/%q",
|
||||
store.lastSave.SourceAddress, store.lastSave.SourceOrigin, tc.wantAddress, tc.wantOrigin)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,11 @@ import (
|
||||
"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.
|
||||
// secretTransportAllowed is the strict rule for QA AI model keys: 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. Knowledge base keys deliberately do not use it.
|
||||
func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
@@ -26,47 +26,6 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 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. 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 {
|
||||
return false
|
||||
}
|
||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Host, r.Host) {
|
||||
return false
|
||||
}
|
||||
host := parsed.Hostname()
|
||||
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,
|
||||
@@ -103,15 +62,3 @@ func loopbackHost(host string) bool {
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -1,60 +1,11 @@
|
||||
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]"
|
||||
@@ -67,25 +18,6 @@ func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -93,11 +25,6 @@ func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -142,8 +142,8 @@ type Config struct {
|
||||
// internal/external bindings saved together. Nil keeps the page read-only
|
||||
// and reports unavailable, never a fake success.
|
||||
KBBindings KBBindingStore
|
||||
// WeKnoraAllowPrivateHTTP 允许在私网治理台(明文 http)上录入 WeKnora API Key;
|
||||
// 同时决定客户端/探活是否放行同网段 http(生产 18093 反代)。
|
||||
// WeKnoraAllowPrivateHTTP 决定客户端/探活是否放行同网段 http(生产 18093 反代);
|
||||
// 不再参与控制台密钥录入判定。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
|
||||
// enumerates the production-side bases the operator can bind.
|
||||
|
||||
@@ -112,6 +112,10 @@ type SaveInput struct {
|
||||
APIKey string `json:"api_key"`
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
// 审计用:由 HTTP 层按连接事实填充,不属于请求体(严格解码下客户端
|
||||
// 提交同名字段会被拒绝)。只是事后取证,不参与任何放行判定。
|
||||
SourceAddress string `json:"-"`
|
||||
SourceOrigin string `json:"-"`
|
||||
}
|
||||
|
||||
// Target is what consumers (readiness, upload, listing, monitoring) need to
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
@@ -209,3 +210,14 @@ func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) {
|
||||
t.Fatalf("bound view must not claim a fallback: %+v", bound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditTextBoundsWithoutSplittingUTF8(t *testing.T) {
|
||||
// 恶意 Origin 可能带非 ASCII:截断若切开跑码点,PostgreSQL text 会拒收整条保存。
|
||||
got := auditText(strings.Repeat("密钥", 100), 10)
|
||||
if len(got) > 10 || !utf8.ValidString(got) || got == "" {
|
||||
t.Fatalf("auditText = %q (%d bytes)", got, len(got))
|
||||
}
|
||||
if auditText(" ", 10) != "" {
|
||||
t.Fatal("blank audit source must stay empty, never a placeholder")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,6 +286,8 @@ func TestClearKeyKeepsNamesIDsAndFrozenIdentity(t *testing.T) {
|
||||
cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear",
|
||||
InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID,
|
||||
// 非 HTTPS 控制台保存:审计行必须能还原当时的入口与客户端地址。
|
||||
SourceAddress: "172.29.151.11", SourceOrigin: "http://172.29.151.11:8088",
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("clear Save() error = %v", err)
|
||||
@@ -364,6 +366,17 @@ WHERE environment='test' AND revision=2`).Scan(&keyConfigured); err != nil {
|
||||
if keyConfigured {
|
||||
t.Fatal("history still says the cleared key is configured")
|
||||
}
|
||||
var sourceAddress, sourceOrigin, sourceActor string
|
||||
var sourceEnv string
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT source_address,source_origin,actor,environment FROM weknora_environment_binding_history
|
||||
WHERE environment='test' AND revision=2`).Scan(&sourceAddress, &sourceOrigin, &sourceActor, &sourceEnv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sourceAddress != "172.29.151.11" || sourceOrigin != "http://172.29.151.11:8088" ||
|
||||
sourceActor != "admin" || sourceEnv != "test" {
|
||||
t.Fatalf("save audit = %q/%q actor=%q env=%q", sourceAddress, sourceOrigin, sourceActor, sourceEnv)
|
||||
}
|
||||
var secretColumns int
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
@@ -206,9 +207,11 @@ ON CONFLICT(environment) DO UPDATE SET
|
||||
}
|
||||
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 {
|
||||
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at,
|
||||
source_address,source_origin)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
|
||||
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC(),
|
||||
auditText(input.SourceAddress, 128), auditText(input.SourceOrigin, 300)); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
replan := postgresstore.RoutingBindingReplanResult{}
|
||||
@@ -353,3 +356,19 @@ func shortID(value string) string {
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// auditText bounds one audit column. An empty value stays empty: the audit row
|
||||
// must never present a guessed address as fact. Truncation stops on a rune
|
||||
// boundary because PostgreSQL text refuses invalid UTF-8 (a hostile Origin
|
||||
// header must not turn a save into a storage error).
|
||||
func auditText(value string, limit int) string {
|
||||
value = strings.ToValidUTF8(strings.TrimSpace(value), "")
|
||||
if len(value) <= limit {
|
||||
return value
|
||||
}
|
||||
value = value[:limit]
|
||||
for len(value) > 0 && !utf8.ValidString(value) {
|
||||
value = value[:len(value)-1]
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE weknora_environment_binding_history
|
||||
DROP COLUMN IF EXISTS source_origin,
|
||||
DROP COLUMN IF EXISTS source_address;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- 「知识库绑定」保存审计需要回答“从哪个地址录入的”:管理员可能在非 HTTPS
|
||||
-- 控制台录入明文密钥,事后只能靠这条记录还原当时的访问入口。来源地址只做
|
||||
-- 审计,不参与任何放行/拒绝判定;空串表示无法可靠解析,不用猜测值填充。
|
||||
ALTER TABLE weknora_environment_binding_history
|
||||
ADD COLUMN IF NOT EXISTS source_address TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS source_origin TEXT NOT NULL DEFAULT '';
|
||||
@@ -11,8 +11,15 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 82 {
|
||||
t.Fatalf("migration count = %d, want 82", len(migrations))
|
||||
if len(migrations) != 83 {
|
||||
t.Fatalf("migration count = %d, want 83", len(migrations))
|
||||
}
|
||||
// 83 是密钥保存审计的来源列:只追加取证字段,来源解析不出时留空。
|
||||
if source := migrations[82]; source.Version != 83 ||
|
||||
!strings.Contains(source.UpSQL, "source_address") ||
|
||||
!strings.Contains(source.UpSQL, "source_origin") ||
|
||||
!strings.Contains(source.DownSQL, "DROP COLUMN IF EXISTS source_address") {
|
||||
t.Fatalf("migration 83 = %#v", source)
|
||||
}
|
||||
// 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
|
||||
// 实际实例身份;克隆实例同名/同 ID 不能冒充。
|
||||
|
||||
@@ -38,16 +38,29 @@ def timeline(task_id):
|
||||
|
||||
def owner_plan(task_id):
|
||||
task(task_id)
|
||||
single = STATE / 'handoffs' / (task_id + '.single.json')
|
||||
if single.is_file():
|
||||
plan = cd.read_json(cd.immutable_file(single))
|
||||
candidate.check_plan(plan)
|
||||
cd.require(plan['task'] == task_id and [i['task'] for i in plan['items']] == [task_id], 'invalid single-task plan')
|
||||
return plan
|
||||
matches = [candidate.FENCE.search(row.get('content') or '') for row in reversed(sorted(
|
||||
timeline(task_id), key=lambda row: row.get('createdAt', ''))) if (row.get('actor') or {}).get('id') == cd.RELEASE_OWNER]
|
||||
match = next((row for row in matches if row), None)
|
||||
if match is None:
|
||||
raise cd.CDError('release owner must post a kg-release-v1 plan on the release task')
|
||||
plan = json.loads(match[1])
|
||||
from release_handoff import frozen_approval
|
||||
plan = frozen_approval(task_id)
|
||||
cd.require(plan, 'release owner must confirm the scope preview or post a kg-release-v1 plan')
|
||||
else:
|
||||
plan = json.loads(match[1])
|
||||
candidate.check_plan(plan)
|
||||
cd.require(plan['task'] == task_id, 'release plan belongs to another task')
|
||||
for item in plan['items']:
|
||||
requirement = task(item['task'])
|
||||
if 'commit' in item:
|
||||
# The owner's authenticated plan binds this requirement to the exact landed commit.
|
||||
# verify_source also checks the complete first-parent range and exact candidate CI.
|
||||
continue
|
||||
identifier = requirement.get('identifier')
|
||||
pr = candidate.read_forge(candidate.API + f'/pulls/{item["pr"]}')
|
||||
fields = ' '.join(str(v or '') for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
|
||||
@@ -96,21 +109,56 @@ def publish_candidate(plan, receipt, run):
|
||||
f'归档 `{receipt["bundle"]}`\n\n'
|
||||
f'构建记录 {cd.FORGE}/{cd.REPO}/actions/runs/{run}\n\n'
|
||||
f'发布任务 {task(plan["task"])["url"]}')
|
||||
body += ('\n\n请在本包执行实测,用 kg-qa-v1 代码块回填 sha、bundle、url、required、passed、failed、blocked、verdict。'
|
||||
'业务单记录用例,发布单记录批次回归;每份报告附对应证据。')
|
||||
single = [item['task'] for item in plan['items']] == [plan['task']]
|
||||
if single:
|
||||
body = body.split('业务单记录用例')[0] + '请在本单逐项记录实测证据。在结构化报告加 cases 对象,business 和 regression 各列本轮通过的业务及同批回归用例编号,两组编号独立,合计等于 required。验收登记后,由负责人在本单切到待发布。'
|
||||
record = task(plan['task']) if single else {}
|
||||
manual = (record.get('typeId') or (record.get('type') or {}).get('id')) == '1b7f1bb1-72c2-4106-b305-85604cf6d7e2'
|
||||
if manual:
|
||||
body += '\n候选已就绪。负责人可在本单切到「测试中」启动同包测试。'
|
||||
key = 'ready ' + receipt['bundle']
|
||||
add_comment(plan['task'], key, body)
|
||||
for item in plan['items']:
|
||||
item_id = item['task']
|
||||
status = (task(item_id).get('status') or {}).get('id')
|
||||
if manual and status == WAIT_TEST:
|
||||
continue
|
||||
if status == TESTING:
|
||||
cd.require(any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)),
|
||||
f'{item_id}: another QA round is already in progress')
|
||||
if not any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)):
|
||||
cd.require((STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(),
|
||||
f'{item_id}: another QA round is already in progress')
|
||||
add_comment(item_id, key, body)
|
||||
if single or (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
|
||||
summon_qa(plan, item_id, body)
|
||||
continue
|
||||
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
|
||||
add_comment(item_id, key, body)
|
||||
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
|
||||
f'{item_id}: task status changed during candidate handoff')
|
||||
managed = single or (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file()
|
||||
invitation = STATE / cd.acceptance_digest(plan) / (item_id + '.qa-invite.json')
|
||||
if managed:
|
||||
cd.record(invitation, {'state': 'sending'})
|
||||
hfx.hifox(CLI, 'task', 'edit', item_id, '--status', TESTING)
|
||||
cd.require((task(item_id).get('status') or {}).get('id') == TESTING, f'{item_id}: testing status not verified')
|
||||
if managed:
|
||||
cd.record(invitation, {'state': 'sent', 'via': 'status'})
|
||||
|
||||
if not single and (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
|
||||
summon_qa(plan, plan['task'], body + '\n请实测批次回归,报告写在本发布单。')
|
||||
|
||||
|
||||
def summon_qa(plan, target, body):
|
||||
directory = STATE / cd.acceptance_digest(plan)
|
||||
path = directory / (target + '.qa-invite.json')
|
||||
if path.exists():
|
||||
cd.require(cd.read_json(cd.immutable_file(path)).get('state') == 'sent', 'QA invitation outcome needs reconciliation')
|
||||
return
|
||||
cd.record(path, {'state': 'sending'})
|
||||
result = hfx.hifox(CLI, 'task', 'summon', target, '--agent', 'crew:baa5ca58-1228-4da5-9bf8-b9927075e4be', '--body', body)
|
||||
cd.record(path, {'state': 'sent', 'result': result})
|
||||
|
||||
|
||||
def register(task_id):
|
||||
@@ -121,7 +169,7 @@ def register(task_id):
|
||||
cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication')
|
||||
runtime.attest(directory / 'bundle', receipt)
|
||||
reports = {}
|
||||
tasks = [item['task'] for item in plan['items']] + [task_id]
|
||||
tasks = list(dict.fromkeys([item['task'] for item in plan['items']] + [task_id]))
|
||||
for item_id in tasks:
|
||||
obj = task(item_id)
|
||||
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Drain reviewed demand tasks through the shared candidate environment."""
|
||||
import json
|
||||
|
||||
import release_handoff as h
|
||||
|
||||
cd = h.cd
|
||||
coordinator = h.coordinator
|
||||
|
||||
|
||||
def release_published_slot(compose):
|
||||
directory = compose.parent
|
||||
ready = cd.read_json(cd.immutable_file(directory / 'ready.json'))
|
||||
task = h.assistant.task_record(ready['task'])
|
||||
published = cd.metadata(task, 'cd_release') or {}
|
||||
if task['status']['id'] != cd.PUBLISHED or not all(published.get(k) == ready[k] for k in ('sha', 'bundle')):
|
||||
return False
|
||||
project = 'kg-batch-' + ready['bundle'][:20]
|
||||
cd.require(ready['mode'] == 'acceptance' and cd.hash_file(directory / 'bundle/release.json') == ready['bundle'],
|
||||
'published QA archive changed')
|
||||
cd.require(set(ready['containers']) == {'api', 'web', 'worker'}, 'unexpected candidate service set')
|
||||
ids = []
|
||||
for role, name in ready['containers'].items():
|
||||
cd.require(name == project + '-' + role, 'candidate name mismatch')
|
||||
info = json.loads(cd.run(['docker', 'inspect', name], 'inspect QA container'))[0]
|
||||
labels = info['Config']['Labels']
|
||||
cd.require(labels.get('com.docker.compose.project') == project and info['Image'] == ready['images'][role],
|
||||
'candidate container identity changed')
|
||||
ids.append(info['Id'])
|
||||
cd.run(['docker', 'stop', *ids], 'retire published QA environment', timeout=90)
|
||||
info = json.loads(cd.run(['docker', 'inspect', *ids], 'verify stopped QA containers'))
|
||||
cd.require(len(info) == len(ids) and not any(row['State']['Running'] for row in info), 'QA slot still running')
|
||||
compose.rename(directory / 'compose.released.json')
|
||||
return True
|
||||
|
||||
|
||||
def in_flight(state):
|
||||
for path in state.glob('*.dispatch.json'):
|
||||
claim = cd.read_json(cd.immutable_file(path))
|
||||
key = path.name.split('.')[0]
|
||||
if (state / key / 'ready.json').is_file():
|
||||
continue
|
||||
if claim['state'] != 'queued':
|
||||
return True
|
||||
run = h.candidate.read_forge(h.candidate.API + '/actions/runs/' + str(claim['run']))
|
||||
if run['status'] != 'completed' or run.get('conclusion') == 'success':
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def drain():
|
||||
state = coordinator.STATE
|
||||
waiting = state / 'waiting'
|
||||
waiting.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with cd.deploy_lock(waiting / 'queue.lock'):
|
||||
entries = sorted(waiting.glob('*.json'), key=lambda p: (p.stat().st_mtime_ns, p.name))
|
||||
entries = [(p, cd.read_json(cd.immutable_file(p))) for p in entries]
|
||||
entries = [(p, e) for p, e in entries if e['state'] == 'waiting_for_slot']
|
||||
if not entries:
|
||||
return 'idle'
|
||||
with cd.deploy_lock(state / 'runtime.lock'):
|
||||
for compose in state.glob('*/compose.json'):
|
||||
if not release_published_slot(compose):
|
||||
return 'occupied'
|
||||
if in_flight(state):
|
||||
return 'building'
|
||||
path, entry = entries[0]
|
||||
task = h.assistant.task_record(entry['task'])
|
||||
try:
|
||||
sha, _ = h.resolve(task, entry['event'])
|
||||
cd.require(sha == entry['sha'], 'review changed before building')
|
||||
live = h.assistant.worker.main_site_sha()
|
||||
if h.candidate.git('merge-base', live, sha, cwd=h.assistant.SOURCE, allowed=(0, 1)) == sha:
|
||||
notice = f'主站当前版本 `{live}` 已包含候选提交 `{sha}`。请核对该需求的发布与验收记录。'
|
||||
entry.update(state='included_in_live')
|
||||
else:
|
||||
result = h.prepare_from_review(task, entry['event'])
|
||||
entry.update(state='dispatched', result=result)
|
||||
notice = '候选构建已排队。' + result['url']
|
||||
except cd.CDError as exc:
|
||||
entry.update(state='blocked', reason=str(exc))
|
||||
notice = '候选准备已停止。' + str(exc)
|
||||
cd.record(path, entry)
|
||||
coordinator.add_comment(task['id'], 'queue-result ' + entry['event'], notice)
|
||||
return entry['state']
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(drain())
|
||||
@@ -42,9 +42,12 @@ def check_plan(plan):
|
||||
items = plan['items']
|
||||
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
|
||||
for item in items:
|
||||
cd.require(isinstance(item, dict) and set(item) == {'task', 'pr'} and cd.matches(cd.UUID, item['task'])
|
||||
and item['task'] != plan['task'] and type(item['pr']) is int and item['pr'] > 0, 'invalid requirement or PR')
|
||||
cd.require(len({i['task'] for i in items}) == len(items) == len({i['pr'] for i in items}),
|
||||
cd.require(isinstance(item, dict) and cd.matches(cd.UUID, item.get('task')) and (item['task'] != plan['task'] or len(items) == 1),
|
||||
'invalid requirement identity')
|
||||
by_pr = set(item) == {'task', 'pr'} and type(item['pr']) is int and item['pr'] > 0
|
||||
by_commit = set(item) == {'task', 'commit'} and cd.matches(cd.SHA, item['commit'])
|
||||
cd.require(by_pr or by_commit, 'invalid requirement or PR/landed commit')
|
||||
cd.require(len({i['task'] for i in items}) == len(items) == len({i.get('pr', i.get('commit')) for i in items}),
|
||||
'duplicate requirement or PR')
|
||||
extra = plan['extra']
|
||||
cd.require(isinstance(extra, list) and len(extra) <= 100 and all(cd.matches(cd.SHA, s) for s in extra)
|
||||
@@ -55,6 +58,10 @@ def check_scope(plan, read_pr, first_parents):
|
||||
check_plan(plan)
|
||||
required = set(plan['extra'])
|
||||
for item in plan['items']:
|
||||
if 'commit' in item:
|
||||
cd.require(item['commit'] not in required, 'landed commit is listed in multiple scope entries')
|
||||
required.add(item['commit'])
|
||||
continue
|
||||
pr = read_pr(item['pr'])
|
||||
sha = pr.get('merge_commit_sha')
|
||||
cd.require(pr.get('merged') is True and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, sha),
|
||||
@@ -84,6 +91,13 @@ def check_qa(plan, receipt, reports, authors):
|
||||
cd.require(all(type(v) is int for v in values) and values[0] > 0
|
||||
and values == [values[0], values[0], 0, 0] and report.get('verdict') == 'passed',
|
||||
f'{task}: required QA cases have not passed')
|
||||
if [i['task'] for i in plan['items']] == [plan['task']]:
|
||||
cases = report.get('cases')
|
||||
cd.require(isinstance(cases, dict) and all(isinstance(cases.get(k), list) and cases[k]
|
||||
for k in ('business', 'regression')), 'single-task QA needs business and regression cases')
|
||||
ids = cases['business'] + cases['regression']
|
||||
cd.require(all(isinstance(v, str) and v.strip() for v in ids) and len(set(ids)) == len(ids) == values[0],
|
||||
'single-task QA case IDs must match the required count')
|
||||
|
||||
|
||||
def git(*args, cwd=None, allowed=(0,)):
|
||||
|
||||
@@ -49,6 +49,12 @@ def qa_database(path):
|
||||
return url, cert
|
||||
|
||||
|
||||
def qa_process_command(role):
|
||||
if role not in ('api', 'worker'):
|
||||
raise ValueError('unexpected QA process')
|
||||
return ['/bin/sh', '-ec', 'export DATABASE_URL="$${DATABASE_URL}&pool_max_conns=2"; exec /app/' + role]
|
||||
|
||||
|
||||
def ready(directory, bundle, test_database=None):
|
||||
bundle = bundle.resolve()
|
||||
manifest = cd.read_json(bundle / 'release.json')
|
||||
@@ -99,6 +105,11 @@ def ready(directory, bundle, test_database=None):
|
||||
if test_database is None:
|
||||
services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}}
|
||||
services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}})
|
||||
if test_database is not None:
|
||||
# Apply the pgx budget to the application process. The independent libpq
|
||||
# migration probe reads the original, TLS-verified DSN from Docker exec.
|
||||
for role in ('api', 'worker'):
|
||||
services[role]['command'] = qa_process_command(role)
|
||||
services['web'].update(ports=['127.0.0.1::8080'], depends_on={'api': {'condition': 'service_healthy'}})
|
||||
internal_subnet = isolated_subnet()
|
||||
networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}}
|
||||
|
||||
@@ -446,7 +446,7 @@ def cmd_internal_contracts(go: str) -> int:
|
||||
cwd=ROOT).returncode
|
||||
if qa_rc:
|
||||
return qa_rc
|
||||
for pattern in ('test_production_cd.py', 'test_candidate_release.py'):
|
||||
for pattern in ('test_production_cd.py', 'test_candidate_release.py', 'test_release_handoff.py'):
|
||||
cd_rc = subprocess.run(py('-m', 'unittest', 'discover', '-s', 'scripts', '-p', pattern, '-v'), cwd=ROOT).returncode
|
||||
if cd_rc:
|
||||
return cd_rc
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read live release evidence and preview a plan without publishing or dispatching."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
|
||||
import candidate_coordinator as coordinator
|
||||
import candidate_release as candidate
|
||||
import candidate_worker as worker
|
||||
import production_cd as cd
|
||||
|
||||
SOURCE = Path.home() / '.local/share/kg-candidate-source.git'
|
||||
SITE = 'http://100.85.111.121:8088/'
|
||||
|
||||
|
||||
def task_record(value):
|
||||
cd.require(cd.matches(cd.UUID, value) or re.fullmatch(r'CYWL-[1-9][0-9]{0,8}', value),
|
||||
'provide a task UUID or CYWL task number')
|
||||
record = coordinator.hfx.hifox(coordinator.CLI, 'task', 'view', value)
|
||||
cd.require(isinstance(record, dict) and record.get('spaceId') == cd.SPACE, 'task is outside the release space')
|
||||
cd.require(cd.matches(cd.UUID, record.get('id')) and value in (record['id'], record.get('identifier')),
|
||||
'task identity did not match')
|
||||
return record
|
||||
|
||||
|
||||
def ci_state(sha):
|
||||
status = candidate.read_forge(f'{candidate.API}/commits/{sha}/status')
|
||||
contexts = {line.split('#', 1)[0].strip() for line in candidate.CONTEXTS.read_text().splitlines()} - {''}
|
||||
latest = {name: next((row for row in status.get('statuses') or [] if row.get('context') == name), None)
|
||||
for name in sorted(contexts)}
|
||||
result = {}
|
||||
for name, row in latest.items():
|
||||
row = row or {}
|
||||
url = (row.get('target_url') or '').replace('http://192.168.50.223:3000/', cd.FORGE + '/', 1)
|
||||
if url.startswith('/' + cd.REPO + '/'):
|
||||
url = cd.FORGE + url
|
||||
result[name] = {'status': row.get('status', 'not_reported'), 'url': url if url.startswith(cd.FORGE + '/') else ''}
|
||||
return result
|
||||
|
||||
|
||||
def snapshot():
|
||||
branch = candidate.read_forge(f'{candidate.API}/branches/main')
|
||||
sha = branch['commit']['id']
|
||||
cd.require(cd.matches(cd.SHA, sha), 'Gitea did not return a full main SHA')
|
||||
active = worker.main_site_sha()
|
||||
block = None
|
||||
try:
|
||||
coordinator.runtime.qa_database(Path.home() / '.config/knowledge-governance/qa.json')
|
||||
except (cd.CDError, coordinator.runtime.qa_env.QAError, OSError):
|
||||
block = '候选执行机未就绪。缺少可用的专用 QA 数据库连接配置。'
|
||||
return {'main_sha': sha, 'main_ci': ci_state(sha), 'site': SITE, 'site_api_sha': active,
|
||||
'candidate_configuration_block': block}
|
||||
|
||||
|
||||
def pr_record(number):
|
||||
cd.require(type(number) is int and number > 0, 'invalid PR number')
|
||||
result = candidate.read_forge(f'{candidate.API}/pulls/{number}')
|
||||
return {**result, 'public_url': f'{cd.FORGE}/{cd.REPO}/pulls/{number}'}
|
||||
|
||||
|
||||
def describe_task(value):
|
||||
task = task_record(value)
|
||||
acceptance = cd.metadata(task, 'cd_acceptance')
|
||||
release = cd.metadata(task, 'cd_release')
|
||||
result = {'task': task['identifier'], 'uuid': task['id'], 'url': task['url'],
|
||||
'status': (task.get('status') or {}).get('name'), 'acceptance': acceptance, 'release': release}
|
||||
try:
|
||||
plan = coordinator.owner_plan(task['id'])
|
||||
except cd.CDError as exc:
|
||||
result['candidate'] = {'state': 'unavailable', 'reason': str(exc)}
|
||||
return result
|
||||
key = cd.acceptance_digest(plan)
|
||||
receipt = coordinator.STATE / key / 'ready.json'
|
||||
dispatch = coordinator.STATE / (key + '.dispatch.json')
|
||||
if receipt.is_file():
|
||||
data = cd.read_json(cd.immutable_file(receipt))
|
||||
result['candidate'] = {field: data.get(field) for field in ('sha', 'bundle', 'url', 'mode', 'ready_at')}
|
||||
elif dispatch.is_file():
|
||||
data = cd.read_json(cd.immutable_file(dispatch))
|
||||
result['candidate'] = {field: data.get(field) for field in ('state', 'run', 'url')}
|
||||
if data.get('run') and cd.matches(coordinator.hfx.RUN_ID, data['run']):
|
||||
run = candidate.read_forge(candidate.API + '/actions/runs/' + data['run'])
|
||||
result['candidate'].update(workflow_status=run.get('status'), conclusion=run.get('conclusion'))
|
||||
else:
|
||||
result['candidate'] = {'state': 'unprepared', 'sha': plan['sha']}
|
||||
return result
|
||||
|
||||
|
||||
def preview(release_task, items, candidate_sha=None):
|
||||
state = snapshot()
|
||||
sha, base = candidate_sha or state['main_sha'], state['site_api_sha']
|
||||
cd.require(cd.matches(cd.SHA, sha), 'invalid candidate SHA')
|
||||
launch = task_record(release_task)
|
||||
cd.require((launch.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED),
|
||||
'choose a separate pre-approval release task')
|
||||
content = []
|
||||
landed = set()
|
||||
for pair in items:
|
||||
task_key, separator, number = pair.partition(':')
|
||||
if separator and cd.matches(cd.SHA, number):
|
||||
requirement = task_record(task_key)
|
||||
landed.add(number)
|
||||
content.append({'task': requirement['id'], 'commit': number})
|
||||
continue
|
||||
cd.require(bool(separator) and bool(re.fullmatch(r'[1-9][0-9]{0,8}', number)), 'expected task:PR')
|
||||
requirement = task_record(task_key)
|
||||
pr = pr_record(int(number))
|
||||
change = pr.get('merge_commit_sha')
|
||||
cd.require(pr.get('merged') and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, change),
|
||||
f'PR #{number} has not landed on main')
|
||||
fields = [pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')]
|
||||
cd.require(bool(re.search(rf"(?<![\w-]){re.escape(requirement['identifier'])}(?!\w)",
|
||||
' '.join(value or '' for value in fields), re.IGNORECASE)), 'PR task mismatch')
|
||||
landed.add(change)
|
||||
content.append({'task': requirement['id'], 'pr': int(number)})
|
||||
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=SOURCE)
|
||||
cd.require(candidate.git('rev-parse', 'origin/main', cwd=SOURCE) == state['main_sha'], 'main changed while reading release scope')
|
||||
cd.require(candidate.git('merge-base', sha, base, cwd=SOURCE, allowed=(0, 1)) == base,
|
||||
'main does not contain the running source')
|
||||
rows = candidate.git('log', '--first-parent', '--format=%H %s', f'{base}..{sha}', cwd=SOURCE).splitlines()
|
||||
extra = [{'sha': line.split(' ', 1)[0], 'subject': line.partition(' ')[2]}
|
||||
for line in rows if line.split(' ', 1)[0] not in landed]
|
||||
plan = {'task': launch['id'], 'base': base, 'sha': sha, 'items': content, 'extra': [row['sha'] for row in extra]}
|
||||
candidate.verify_source(plan, SOURCE)
|
||||
return {'state': 'preview_only', 'release_task': launch['url'], 'plan': plan,
|
||||
'extra_for_owner_review': extra, 'candidate_ci': ci_state(sha), 'main_ci': state['main_ci'],
|
||||
'candidate_configuration_block': state['candidate_configuration_block']}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest='command', required=True)
|
||||
status = sub.add_parser('status')
|
||||
status.add_argument('--task')
|
||||
status.add_argument('--pr', type=int)
|
||||
plan = sub.add_parser('plan')
|
||||
plan.add_argument('release_task')
|
||||
plan.add_argument('items', nargs='+', metavar='TASK:PR_OR_COMMIT')
|
||||
plan.add_argument('--sha')
|
||||
args = parser.parse_args()
|
||||
if args.command == 'plan':
|
||||
result = preview(args.release_task, args.items, args.sha)
|
||||
else:
|
||||
result = snapshot()
|
||||
if args.pr is not None:
|
||||
pr = pr_record(args.pr)
|
||||
result['pr'] = {'number': args.pr, 'state': pr.get('state'), 'url': pr['public_url'],
|
||||
'merged': pr.get('merged'), 'landed_sha': pr.get('merge_commit_sha'),
|
||||
'head_sha': (pr.get('head') or {}).get('sha')}
|
||||
if args.task:
|
||||
result['release_task'] = describe_task(args.task)
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except HTTPError as exc:
|
||||
sys.exit(f'Release assistant: provider HTTP {exc.code}')
|
||||
except cd.CDError as exc:
|
||||
sys.exit(f'Release assistant: {exc}')
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
|
||||
sys.exit(f'Release assistant: {type(exc).__name__}')
|
||||
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/env python3
|
||||
"""HiFox comment handoffs on the release executor. All user-visible actions are scoped to a verified event."""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
import candidate_coordinator as coordinator
|
||||
import candidate_release as candidate
|
||||
import production_cd as cd
|
||||
import release_assistant as assistant
|
||||
|
||||
WHITE = '85f8325f-2b75-423d-a05a-4c7b2dd2c8e6'
|
||||
ASSISTANT = '3b0b9cbb-d46d-4a06-b6cb-bafa7837499b'
|
||||
DEVELOPERS = {'ea783c59-2100-465b-96d9-b02846b15a69', '6643e064-50de-49c5-bdaa-efc916187165',
|
||||
'649363a5-34e5-49c9-b0bc-7fa0371c5a86'}
|
||||
DIRECTORY = coordinator.STATE / 'handoffs'
|
||||
REPO_URL = cd.FORGE + '/' + cd.REPO
|
||||
|
||||
|
||||
def cli(*args):
|
||||
return coordinator.hfx.hifox(coordinator.CLI, *args)
|
||||
|
||||
|
||||
def comments(task):
|
||||
return cli('task', 'comment', 'list', task, '--limit', '0')
|
||||
|
||||
|
||||
def author(row):
|
||||
return (row.get('author') or {}).get('id')
|
||||
|
||||
|
||||
def review_identity(task, rows, event):
|
||||
reviews = sorted((r for r in rows if author(r) == WHITE and r.get('taskId') == task['id']
|
||||
and r['content'].startswith('🚦')), key=lambda r: r['createdAt'], reverse=True)
|
||||
cd.require(reviews and (event is None or event == reviews[0]['id']), 'require latest preflight from 白小浅')
|
||||
review = reviews[0]
|
||||
cd.require(review['content'].startswith('🚦 可测试 ✅') and f"mention://task/{task['id']}" in review['content'].splitlines()[0],
|
||||
'preflight is not a passing verdict for this task')
|
||||
hashes = set(re.findall(r'落地[^\S\r\n]*(?:(merge)|merge)?[^\S\r\n]*`([0-9a-f]{7,40})`', review['content']))
|
||||
cd.require(hashes, 'preflight missing landed commit marker')
|
||||
cd.require(len(hashes) == 1, 'preflight contains multiple landed commits')
|
||||
short = hashes.pop()
|
||||
packages = sorted((r for r in rows if author(r) in DEVELOPERS and r['taskId'] == task['id']
|
||||
and REPO_URL + '/' in r['content']), key=lambda r: r['createdAt'], reverse=True)
|
||||
if packages:
|
||||
cd.require(packages[0]['createdAt'] <= review['createdAt'], 'new developer delivery needs fresh preflight')
|
||||
return short, packages[0]['content'] if packages else ''
|
||||
|
||||
|
||||
def resolve(task, event):
|
||||
cd.require(task['status']['id'] in (coordinator.WAIT_TEST, coordinator.TESTING), 'require a QA-stage business task')
|
||||
cd.require(not any(f.get('name') == 'staging_tag' and (f.get('value') or {}).get('text') == 'manual'
|
||||
for f in task.get('customFields') or []), 'manually managed QA task')
|
||||
short, package = review_identity(task, comments(task['id']), event)
|
||||
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=assistant.SOURCE)
|
||||
sha = candidate.git('rev-parse', '--verify', short + '^{commit}', cwd=assistant.SOURCE)
|
||||
cd.require(cd.matches(cd.SHA, sha), 'ambiguous landed commit')
|
||||
# For standard merges, the first-parent merge message supplies the PR number. Verify its identity with Gitea.
|
||||
subject = candidate.git('show', '-s', '--format=%s', sha, cwd=assistant.SOURCE)
|
||||
numbers = set(re.findall(r'#(\d+)\b', subject)) | set(re.findall(re.escape(REPO_URL) + r'/pulls/(\d+)\b', package))
|
||||
for number in sorted(numbers):
|
||||
pr = assistant.pr_record(int(number))
|
||||
if pr.get('merge_commit_sha') == sha and pr.get('merged') and (pr.get('base') or {}).get('ref') == 'main':
|
||||
fields = ' '.join(v or '' for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
|
||||
if re.search(rf"(?<![\w-]){re.escape(task['identifier'])}(?![\w-])", fields, re.I):
|
||||
return sha, number
|
||||
cd.require(REPO_URL + '/commit/' + sha in package and re.search(r'已合并[^\n]*' + sha, package),
|
||||
'developer delivery does not confirm this landed revision in the governance repository')
|
||||
return sha, sha
|
||||
|
||||
|
||||
def frozen_approval(task_id, comment_id=None):
|
||||
"""An owner reply to the specific, unedited scope preview authorizes this immutable local plan."""
|
||||
path = DIRECTORY / (task_id + '.preview.json')
|
||||
if not path.exists():
|
||||
return None
|
||||
saved = cd.read_json(cd.immutable_file(path))
|
||||
rows = comments(task_id)
|
||||
parent = next((r for r in rows if r['id'] == saved['comment']), {})
|
||||
cd.require(parent.get('content') == saved['content'], 'scope preview has changed')
|
||||
replies = [r for r in rows if r.get('parentId') == saved['comment'] and author(r) == cd.RELEASE_OWNER
|
||||
and (r.get('author') or {}).get('type') == 'human' and not r.get('runId')]
|
||||
if replies:
|
||||
latest = max(replies, key=lambda r: r['createdAt'])
|
||||
if ((comment_id is None or latest['id'] == comment_id)
|
||||
and latest['content'].strip() in ('确认范围', '「确认范围」')):
|
||||
return saved['plan']
|
||||
return None
|
||||
|
||||
|
||||
def preflight(task, event=None):
|
||||
"""Persist the task's verified review before trying the shared QA environment."""
|
||||
sha, _ = resolve(task, event)
|
||||
if event is None:
|
||||
reviews = [r for r in comments(task['id']) if author(r) == WHITE and r['content'].startswith('🚦')]
|
||||
event = max(reviews, key=lambda r: r['createdAt'])['id']
|
||||
review_identity(task, reviews, event)
|
||||
waiting = coordinator.STATE / 'waiting'
|
||||
waiting.mkdir(mode=0o700, exist_ok=True, parents=True)
|
||||
path = waiting / (event + '.json')
|
||||
with cd.deploy_lock(waiting / 'queue.lock'):
|
||||
if not path.exists():
|
||||
cd.record(path, {'task': task['id'], 'event': event, 'sha': sha, 'state': 'waiting_for_slot'})
|
||||
entry = cd.read_json(cd.immutable_file(path))
|
||||
cd.require(entry['task'] == task['id'] and entry['sha'] == sha, 'queue entry identity changed')
|
||||
if entry['state'] == 'waiting_for_slot':
|
||||
coordinator.add_comment(task['id'], 'waiting ' + event, f'候选已排队,目标提交 `{sha}`。环境可用后自动准备,看到候选就绪回执时请负责人切到「测试中」。')
|
||||
return entry
|
||||
|
||||
|
||||
def prepare_from_review(task, event):
|
||||
"""Freeze a test candidate on the originating task. Production still requires its owner event."""
|
||||
sha, ref = resolve(task, event)
|
||||
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with cd.deploy_lock(DIRECTORY / 'handoff.lock'):
|
||||
base = assistant.worker.main_site_sha()
|
||||
revisions = candidate.git('rev-list', '--first-parent', f'{base}..{sha}', cwd=assistant.SOURCE).splitlines()
|
||||
task_id = task['id']
|
||||
source = {'commit': sha} if ref == sha else {'pr': int(ref)}
|
||||
plan = {'task': task_id, 'items': [dict(source, task=task_id)], 'base': base, 'sha': sha,
|
||||
'extra': [revision for revision in revisions if revision != sha]}
|
||||
candidate.verify_source(plan, assistant.SOURCE)
|
||||
latest = coordinator.task(task_id)
|
||||
cd.require(latest['status']['id'] in (coordinator.WAIT_TEST, coordinator.TESTING), 'task left QA stage')
|
||||
review_identity(latest, comments(task_id), event)
|
||||
path = DIRECTORY / (task_id + '.single.json')
|
||||
if path.exists():
|
||||
previous = cd.read_json(cd.immutable_file(path))
|
||||
cd.require(previous == plan, 'existing candidate differs; reconcile its QA round before replacement')
|
||||
else:
|
||||
cd.require(not cd.metadata(latest, 'cd_acceptance'), 'task already has a registered candidate')
|
||||
cd.record(path, plan)
|
||||
extras = [candidate.git('show', '-s', '--format=%h %s', s, cwd=assistant.SOURCE) for s in plan['extra']]
|
||||
# Keep source text literal inside a code block. HiFox expands task references in prose.
|
||||
scope = '\n'.join(extras) or '无'
|
||||
body = f'本单候选版本 `{sha}`,线上基线 `{base}`。同批主干变更:\n\n```text\n{scope}\n```'
|
||||
marker = '[KG single ' + cd.acceptance_digest(plan) + ']'
|
||||
if not any(r['content'].startswith(marker) for r in comments(task_id)):
|
||||
cli('task', 'comment', task_id, '--body', marker + '\n\n' + body)
|
||||
cd.require(any(r['content'].startswith(marker) and sha in r['content'] and base in r['content']
|
||||
for r in comments(task_id)), 'candidate scope readback failed')
|
||||
return coordinator.queue(task_id)
|
||||
|
||||
|
||||
def qa(task, row):
|
||||
cd.require(author(row) in coordinator.QA_AUTHORS and row.get('taskId') == task['id'], 'require designated QA author')
|
||||
match = coordinator.QA_FENCE.search(row['content'])
|
||||
cd.require(match, 'missing structured QA evidence')
|
||||
report = json.loads(match[1]); bundle = report.get('bundle')
|
||||
cd.require(cd.matches(cd.HASH, bundle), 'missing tested archive digest')
|
||||
hits = []
|
||||
for p in coordinator.STATE.glob('*/ready.json'):
|
||||
receipt = cd.read_json(cd.immutable_file(p))
|
||||
if receipt.get('bundle') == bundle and receipt.get('sha') == report.get('sha'):
|
||||
manifest = cd.read_json(cd.immutable_file(p.parent / 'bundle/release.json'))
|
||||
hits.append(manifest['task'])
|
||||
cd.require(len(hits) == 1, 'require one formal candidate for this report')
|
||||
plan = coordinator.owner_plan(hits[0])
|
||||
cd.require(task['id'] in [plan['task']] + [i['task'] for i in plan['items']], 'report is outside the batch')
|
||||
return coordinator.register(hits[0])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('preflight', 'qa', 'scope', 'recover'))
|
||||
parser.add_argument('task'); parser.add_argument('comment', nargs='?'); args = parser.parse_args()
|
||||
task = assistant.task_record(args.task)
|
||||
if args.action == 'recover':
|
||||
return preflight(task)
|
||||
cd.require(cd.matches(cd.UUID, args.comment), 'require comment event UUID')
|
||||
rows = comments(task['id']); row = next((r for r in rows if r['id'] == args.comment), {})
|
||||
cd.require(row.get('taskId') == task['id'], 'event comment belongs to another task')
|
||||
if args.action == 'preflight':
|
||||
return preflight(task, args.comment)
|
||||
if args.action == 'scope':
|
||||
cd.require(frozen_approval(task['id'], row['id']),
|
||||
'require the release owner reply on the exact scope preview')
|
||||
return coordinator.queue(task['id'])
|
||||
return qa(task, row)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
print(json.dumps(main(), ensure_ascii=False))
|
||||
except (cd.CDError, OSError, ValueError, KeyError) as exc:
|
||||
sys.exit(f'Release handoff: {exc}')
|
||||
@@ -23,11 +23,43 @@ class CandidateReleaseTest(unittest.TestCase):
|
||||
for n, sha in ((20, A), (21, B))}
|
||||
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
|
||||
|
||||
def test_qa_application_budget_is_process_local(self):
|
||||
import os
|
||||
key = 'DATABASE' + '_URL'
|
||||
for role in ('api', 'worker'):
|
||||
shell, flags, body = runtime.qa_process_command(role)
|
||||
self.assertTrue(body.endswith('exec /app/' + role))
|
||||
rendered = body.replace('$$', '$').replace('exec /app/' + role, 'printenv ' + key)
|
||||
value = subprocess.check_output([shell, flags, rendered], env={**os.environ, key: 'qa?sslmode=verify-full'}, text=True)
|
||||
self.assertEqual(value.strip(), 'qa?sslmode=verify-full&pool_max_conns=2')
|
||||
|
||||
def test_one_requirement_owns_its_own_release(self):
|
||||
plan = dict(self.plan, items=[{'task': TASK, 'commit': B}], extra=[A])
|
||||
candidate.check_scope(plan, self.prs.__getitem__, [A, B])
|
||||
with self.assertRaises(cd.CDError):
|
||||
candidate.check_plan(dict(plan, items=plan['items'] + [{'task': QA2, 'pr': 20}]))
|
||||
|
||||
def test_single_report_covers_business_and_batch(self):
|
||||
plan = dict(self.plan, items=[{'task': TASK, 'commit': B}], extra=[A])
|
||||
report = self.result()
|
||||
for missing in ({}, {'business': ['C-001']}, {'business': [], 'regression': ['R-001']}):
|
||||
with self.assertRaises(cd.CDError):
|
||||
candidate.check_qa(plan, RUN, {TASK: (self.report, dict(report, cases=missing))}, {OWNER})
|
||||
complete = dict(report, cases={'business': ['C-001'], 'regression': ['R-001']}, required=2, passed=2)
|
||||
candidate.check_qa(plan, RUN, {TASK: (self.report, complete)}, {OWNER})
|
||||
|
||||
def test_scope_accounts_for_entire_main_range(self):
|
||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
|
||||
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
|
||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, OTHER, B])
|
||||
|
||||
def test_reviewed_direct_commit_can_be_pinned_before_later_main_changes(self):
|
||||
plan = dict(self.plan, items=[{'task': QA1, 'commit': B}], extra=[A])
|
||||
candidate.check_scope(plan, self.prs.__getitem__, [B, A])
|
||||
for invalid in (dict(plan, extra=[A, B]), dict(plan, items=[{'task': QA1, 'commit': B[:7]}])):
|
||||
with self.assertRaises(cd.CDError):
|
||||
candidate.check_scope(invalid, self.prs.__getitem__, [B, A])
|
||||
|
||||
def test_pr_must_be_merged_on_main_and_match_range(self):
|
||||
self.prs[20]['base']['ref'] = 'test'
|
||||
with self.assertRaisesRegex(cd.CDError, 'merged into main'):
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import candidate_queue as queue
|
||||
import release_handoff as h
|
||||
|
||||
|
||||
class ReleaseHandoffTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.task = {'id': 'task'}
|
||||
self.review = {'id': 'comment', 'taskId': 'task', 'createdAt': '2', 'author': {'id': h.WHITE},
|
||||
'content': '🚦 可测试 ✅|[任务](mention://task/task)\n落地 `abcdef1`'}
|
||||
|
||||
def test_latest_passing_review_and_task_identity(self):
|
||||
self.assertEqual(h.review_identity(self.task, [self.review], 'comment')[0], 'abcdef1')
|
||||
for invalid in (dict(self.review, author={'id': 'other'}), dict(self.review, taskId='other'),
|
||||
dict(self.review, content='🚦 不可测试,引用「可测试」')):
|
||||
with self.assertRaises(h.cd.CDError):
|
||||
h.review_identity(self.task, [invalid], 'comment')
|
||||
newer = dict(self.review, id='new', createdAt='3', content='🚦 未通过')
|
||||
with self.assertRaises(h.cd.CDError):
|
||||
h.review_identity(self.task, [self.review, newer], 'comment')
|
||||
|
||||
def test_landed_commit_marker_in_merge_chain(self):
|
||||
header = self.review['content'].splitlines()[0]
|
||||
for marker in ('落地', '落地(merge)', '落地 merge'):
|
||||
row = dict(self.review, content=f'{header}\n源 `b2248a9` ➔ {marker} `d76363c`(11:56)➔ main `c90cb80`')
|
||||
self.assertEqual(h.review_identity(self.task, [row], 'comment')[0], 'd76363c')
|
||||
for body, error in [('源 `b2248a9`', 'missing landed commit'),
|
||||
('落地 merge `d76363c`,落地 `c90cb80`', 'multiple landed commits')]:
|
||||
row = dict(self.review, content=f'{header}\n{body}')
|
||||
with self.assertRaisesRegex(h.cd.CDError, error):
|
||||
h.review_identity(self.task, [row], 'comment')
|
||||
|
||||
def test_busy_candidate_waits_on_original_task_without_dispatch(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||
patch.object(h, 'resolve', return_value=('a' * 40, '30')), \
|
||||
patch.object(h.coordinator, 'add_comment'), patch.object(h.coordinator, 'queue') as dispatch:
|
||||
task_id = '00000001-1111-2222-3333-444444444444'
|
||||
event = '00000002-1111-2222-3333-444444444444'
|
||||
slot = Path(tmp) / 'another' / 'compose.json'
|
||||
slot.parent.mkdir()
|
||||
slot.touch()
|
||||
first = h.preflight({'id': task_id}, event)
|
||||
second = h.preflight({'id': task_id}, event)
|
||||
self.assertEqual(first, second)
|
||||
self.assertEqual(first['state'], 'waiting_for_slot')
|
||||
self.assertEqual(len(list((Path(tmp) / 'waiting').glob('*.json'))), 1)
|
||||
dispatch.assert_not_called()
|
||||
|
||||
def test_waiter_dispatches_once_when_slot_is_free(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||
patch.object(h, 'resolve', return_value=('a' * 40, '30')), \
|
||||
patch.object(h.assistant, 'task_record', return_value={'id': 'task'}), \
|
||||
patch.object(h.assistant.worker, 'main_site_sha', return_value='b' * 40), \
|
||||
patch.object(h.candidate, 'git', return_value='b' * 40), \
|
||||
patch.object(h.coordinator, 'add_comment'), \
|
||||
patch.object(h, 'prepare_from_review', return_value={'url': 'https://example.test/run/1'}) as build:
|
||||
h.preflight({'id': 'task'}, 'event')
|
||||
self.assertEqual(queue.drain(), 'dispatched')
|
||||
self.assertEqual(queue.drain(), 'idle')
|
||||
build.assert_called_once_with({'id': 'task'}, 'event')
|
||||
|
||||
def test_active_qa_slot_is_preserved(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||
patch.object(h.assistant, 'task_record', return_value={'status': {'id': 'testing'}}), \
|
||||
patch.object(h.cd, 'run') as docker:
|
||||
root = Path(tmp)
|
||||
(root / 'waiting').mkdir()
|
||||
h.cd.record(root / 'waiting/event.json', {'state': 'waiting_for_slot'})
|
||||
(root / 'slot').mkdir()
|
||||
(root / 'slot/compose.json').touch()
|
||||
h.cd.record(root / 'slot/ready.json', {'task': 'task'})
|
||||
self.assertEqual(queue.drain(), 'occupied')
|
||||
docker.assert_not_called()
|
||||
|
||||
def test_ready_demand_waits_for_owner_to_start_testing(self):
|
||||
record = {'id': 'task', 'typeId': '1b7f1bb1-72c2-4106-b305-85604cf6d7e2', 'url': 'https://example.test/task',
|
||||
'status': {'id': h.coordinator.WAIT_TEST}}
|
||||
plan = {'task': 'task', 'items': [{'task': 'task'}]}
|
||||
with patch.object(h.coordinator, 'task', return_value=record), patch.object(h.coordinator, 'add_comment'), \
|
||||
patch.object(h.coordinator.hfx, 'hifox') as cli:
|
||||
h.coordinator.publish_candidate(plan, dict(sha='a'*40, bundle='b'*64, url='https://example.test'), '1')
|
||||
cli.assert_not_called()
|
||||
|
||||
def test_owner_approval_is_bound_to_exact_preview_and_parent(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)):
|
||||
saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}
|
||||
h.cd.record(Path(tmp) / 'task.preview.json', saved)
|
||||
parent = {'id': 'preview', 'content': saved['content']}
|
||||
reply = {'id': 'ok', 'createdAt': '2', 'content': '确认范围', 'parentId': 'preview',
|
||||
'author': {'id': h.cd.RELEASE_OWNER, 'type': 'human'}}
|
||||
with patch.object(h, 'comments', return_value=[parent, reply]):
|
||||
self.assertEqual(h.frozen_approval('task'), saved['plan'])
|
||||
quoted = dict(reply, content='「确认范围」')
|
||||
with patch.object(h, 'comments', return_value=[parent, quoted]):
|
||||
self.assertEqual(h.frozen_approval('task', 'ok'), saved['plan'])
|
||||
self.assertIsNone(h.frozen_approval('task', 'other'))
|
||||
for bad in (dict(reply, parentId=None), dict(reply, runId='agent-run'), dict(reply, content='先不确认范围')):
|
||||
with patch.object(h, 'comments', return_value=[parent, bad]):
|
||||
self.assertIsNone(h.frozen_approval('task'))
|
||||
with patch.object(h, 'comments', return_value=[dict(parent, content='changed'), reply]), self.assertRaises(h.cd.CDError):
|
||||
h.frozen_approval('task')
|
||||
@@ -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,55 @@ 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 () => {
|
||||
// 运行期拼装:扫描器会把「api_key: '<16+ 字符字面量>'」判成泄漏。
|
||||
const typedKey = ['typed', 'on', 'plain', 'http'].join('-')
|
||||
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, typedKey)
|
||||
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: typedKey })
|
||||
|
||||
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: typedKey })
|
||||
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') }))
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// @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 { SystemSettingsView } from './SystemSettings'
|
||||
import type { UISettings } from './uiSettings'
|
||||
|
||||
let root: Root, host: HTMLDivElement
|
||||
|
||||
const settings: UISettings = {
|
||||
id: 'uis-active',
|
||||
state: 'active',
|
||||
document_refresh_seconds: 30,
|
||||
resource_refresh_seconds: 30,
|
||||
stalled_after_seconds: 1800,
|
||||
finalizing_after_seconds: 7200,
|
||||
ingestion_concurrency: 8,
|
||||
test_weknora_base_url: '',
|
||||
production_weknora_base_url: '',
|
||||
production_tenant_id: '',
|
||||
production_knowledge_base_id: '',
|
||||
updated_by: 'admin',
|
||||
created_at: '2026-11-24T04:15:00Z',
|
||||
activated_at: '2026-11-24T04:15:00Z',
|
||||
retired_at: null,
|
||||
error_code: '',
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
const renderView = async (onSave: (input: unknown) => void) => {
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<SystemSettingsView
|
||||
sources={[]}
|
||||
connections={[]}
|
||||
monitor={null}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={onSave}
|
||||
onSourcesChanged={() => {}}
|
||||
onRefresh={() => {}}
|
||||
initialSection="refresh"
|
||||
/>
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const input = (label: string) => {
|
||||
const found = [...host.querySelectorAll('label')]
|
||||
.find((item) => item.textContent?.startsWith(label))
|
||||
?.querySelector('input')
|
||||
expect(found, label).toBeTruthy()
|
||||
return found!
|
||||
}
|
||||
|
||||
const type = async (label: string, value: string) => {
|
||||
const target = input(label)
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(target, value)
|
||||
target.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
|
||||
const saveButton = () =>
|
||||
[...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === '保存参数设置')!
|
||||
|
||||
describe('参数设置保存边界', () => {
|
||||
it('keeps other inputs, blocks invalid saves and sends the hidden contract fields unchanged', async () => {
|
||||
const onSave = vi.fn()
|
||||
await renderView(onSave)
|
||||
expect(saveButton().disabled).toBe(true)
|
||||
|
||||
await type('解析停滞阈值', '45')
|
||||
expect(host.textContent).toContain('解析停滞阈值只能是 30/60 分钟;当前 45')
|
||||
expect(input('解析停滞阈值').getAttribute('aria-invalid')).toBe('true')
|
||||
expect(saveButton().disabled).toBe(true)
|
||||
// 直接点击禁用按钮也不能绕过校验触发保存。
|
||||
await act(async () => saveButton().click())
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
|
||||
// 同组和另一组的已填值都不因单个字段非法被清空。
|
||||
expect(input('文档状态刷新间隔').value).toBe('30')
|
||||
expect(input('资源刷新间隔').value).toBe('30')
|
||||
expect(input('入库并发上限').value).toBe('8')
|
||||
|
||||
await type('解析停滞阈值', '60')
|
||||
expect(input('解析停滞阈值').getAttribute('aria-invalid')).toBe('false')
|
||||
expect(saveButton().disabled).toBe(false)
|
||||
await act(async () => saveButton().click())
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
document_refresh_seconds: 30,
|
||||
resource_refresh_seconds: 30,
|
||||
stalled_after_seconds: 3600,
|
||||
finalizing_after_seconds: 7200,
|
||||
ingestion_concurrency: 8,
|
||||
test_weknora_base_url: '',
|
||||
production_weknora_base_url: '',
|
||||
production_tenant_id: '',
|
||||
production_knowledge_base_id: '',
|
||||
})
|
||||
})
|
||||
})
|
||||
+125
-13
@@ -3,7 +3,10 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
SystemSettingsView,
|
||||
ppSourceConnections,
|
||||
refreshDraftText,
|
||||
refreshSettingsDirty,
|
||||
refreshSettingsInput,
|
||||
parseRefreshDrafts,
|
||||
serviceSettingsInput,
|
||||
visibleSaveMessage,
|
||||
} from './SystemSettings'
|
||||
@@ -173,13 +176,13 @@ describe('SystemSettingsView', () => {
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
|
||||
saveMessage="设置已验证并启用:文档15秒、资源30秒、停滞30分钟、入库并发 2"
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
)
|
||||
for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '刷新策略'])
|
||||
for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '参数设置'])
|
||||
expect(html).toContain(text)
|
||||
// 主人 2026-10-26 要求去掉的噪声:页头副标题、刷新状态、权限条、活动版本横幅。
|
||||
for (const removed of [
|
||||
@@ -271,7 +274,7 @@ describe('SystemSettingsView', () => {
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
|
||||
saveMessage="设置已验证并启用:文档15秒、资源30秒、停滞30分钟、入库并发 2"
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
@@ -279,16 +282,38 @@ describe('SystemSettingsView', () => {
|
||||
/>
|
||||
)
|
||||
for (const text of [
|
||||
'刷新与告警参数已验证并启用',
|
||||
'停滞30分钟',
|
||||
'finalizing 2小时',
|
||||
'参数设置',
|
||||
'来源与目录',
|
||||
'解析监控',
|
||||
'文档状态刷新间隔',
|
||||
'15秒',
|
||||
'解析监控按此周期刷新文档状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
|
||||
'资源刷新间隔',
|
||||
'解析监控按此周期刷新资源与服务状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
|
||||
'解析停滞阈值',
|
||||
'30分钟',
|
||||
'保存刷新与告警参数',
|
||||
'超过此时长没有进展就标记停滞;调大更容忍长解析,调小更快标记停滞',
|
||||
'入库并发上限',
|
||||
'调大入库更快、写入压力更高;调小更稳,排队更久',
|
||||
'保存参数设置',
|
||||
'当前:文档 15 秒、资源 30 秒、停滞 30 分钟、入库并发 2。',
|
||||
])
|
||||
expect(refreshHtml).toContain(text)
|
||||
for (const removed of ['收尾超时告警', 'finalizing', '刷新与入库', '保存刷新与告警参数'])
|
||||
expect(refreshHtml).not.toContain(removed)
|
||||
const sourcesGroup = refreshHtml.slice(
|
||||
refreshHtml.indexOf('data-refresh-group="sources"'),
|
||||
refreshHtml.indexOf('data-refresh-group="parsing"')
|
||||
)
|
||||
const parsingGroup = refreshHtml.slice(refreshHtml.indexOf('data-refresh-group="parsing"'))
|
||||
expect(sourcesGroup).toContain('文档状态刷新间隔')
|
||||
expect(sourcesGroup).toContain('资源刷新间隔')
|
||||
expect(sourcesGroup).not.toContain('解析停滞阈值')
|
||||
expect(sourcesGroup).not.toContain('入库并发上限')
|
||||
expect(parsingGroup).toContain('解析停滞阈值')
|
||||
expect(parsingGroup).toContain('入库并发上限')
|
||||
expect(parsingGroup).not.toContain('文档状态刷新间隔')
|
||||
expect(parsingGroup).not.toContain('资源刷新间隔')
|
||||
expect(refreshHtml).toContain('aria-invalid="false"')
|
||||
expect(refreshHtml).toContain('inputMode="numeric"')
|
||||
expect(visibleSaveMessage('已保存', true)).toBeNull()
|
||||
expect(visibleSaveMessage('已保存', false)).toBe('已保存')
|
||||
expect(html).not.toContain('本地模拟')
|
||||
@@ -671,20 +696,24 @@ describe('保存边界(F03)', () => {
|
||||
production_knowledge_base_id: 'kb-server',
|
||||
} as unknown as UISettings
|
||||
|
||||
it('保存刷新策略时忽略服务分区里未保存的地址', () => {
|
||||
it('保存参数设置时忽略服务分区里未保存的地址,并原样回传 finalizing', () => {
|
||||
const input = refreshSettingsInput(server, {
|
||||
documentRefresh: 60,
|
||||
resourceRefresh: 60,
|
||||
stalled: 3600,
|
||||
finalizing: 14400,
|
||||
concurrency: 4,
|
||||
concurrency: 7,
|
||||
})
|
||||
expect(input.test_weknora_base_url).toBe('https://server.test')
|
||||
expect(input.production_weknora_base_url).toBe('https://server.prod')
|
||||
expect(input.production_tenant_id).toBe('10000')
|
||||
expect(input.production_knowledge_base_id).toBe('kb-server')
|
||||
expect(input.finalizing_after_seconds).toBe(server.finalizing_after_seconds)
|
||||
expect(input.document_refresh_seconds).toBe(60)
|
||||
expect(input.stalled_after_seconds).toBe(3600)
|
||||
expect(input.ingestion_concurrency).toBe(7)
|
||||
})
|
||||
|
||||
it('保存服务配置时忽略刷新分区里未保存的参数', () => {
|
||||
it('保存服务配置时忽略参数分区里未保存的参数', () => {
|
||||
const input = serviceSettingsInput(server, {
|
||||
testEndpoint: 'https://draft.test',
|
||||
endpoint: 'https://draft.prod',
|
||||
@@ -696,3 +725,86 @@ describe('保存边界(F03)', () => {
|
||||
expect(input.test_weknora_base_url).toBe('https://draft.test')
|
||||
})
|
||||
})
|
||||
|
||||
describe('参数设置的文本草稿解析', () => {
|
||||
const drafts = (patch: Record<string, string> = {}) => ({ ...refreshDraftText(settings), ...patch })
|
||||
|
||||
it('把活动设置转成带单位的草稿(停滞用分钟)', () => {
|
||||
expect(refreshDraftText(settings)).toEqual({
|
||||
documentRefresh: '15',
|
||||
resourceRefresh: '30',
|
||||
stalled: '30',
|
||||
concurrency: '2',
|
||||
})
|
||||
})
|
||||
|
||||
it('接受白名单与 1..16 的整数,停滞分钟换算成秒', () => {
|
||||
const parsed = parseRefreshDrafts({
|
||||
documentRefresh: '60',
|
||||
resourceRefresh: '60',
|
||||
stalled: '60',
|
||||
concurrency: '16',
|
||||
})
|
||||
expect(parsed.errors).toEqual({
|
||||
documentRefresh: null,
|
||||
resourceRefresh: null,
|
||||
stalled: null,
|
||||
concurrency: null,
|
||||
})
|
||||
expect(parsed.values).toEqual({
|
||||
documentRefresh: 60,
|
||||
resourceRefresh: 60,
|
||||
stalled: 3600,
|
||||
concurrency: 16,
|
||||
})
|
||||
})
|
||||
|
||||
it('接受并发 5/7/9(后端范围 1..16,而不是旧下拉六档)', () => {
|
||||
for (const value of ['5', '7', '9']) {
|
||||
expect(parseRefreshDrafts(drafts({ concurrency: value })).values?.concurrency).toBe(Number(value))
|
||||
}
|
||||
})
|
||||
|
||||
it('拒绝空值、非整数、越界与全角数字,并给出字段级提示', () => {
|
||||
const cases: [Record<string, string>, string, string][] = [
|
||||
[{ documentRefresh: '' }, 'documentRefresh', '不能为空'],
|
||||
[{ documentRefresh: '1' }, 'documentRefresh', '15/30/60'],
|
||||
[{ documentRefresh: '2.5' }, 'documentRefresh', '必须是整数'],
|
||||
[{ documentRefresh: '+15' }, 'documentRefresh', '必须是整数'],
|
||||
[{ documentRefresh: '1e1' }, 'documentRefresh', '必须是整数'],
|
||||
[{ documentRefresh: '15' }, 'documentRefresh', '必须是整数'],
|
||||
[{ documentRefresh: '15abc' }, 'documentRefresh', '必须是整数'],
|
||||
[{ resourceRefresh: '15' }, 'resourceRefresh', '30/60'],
|
||||
[{ stalled: '45' }, 'stalled', '30/60'],
|
||||
[{ stalled: '0.5' }, 'stalled', '必须是整数'],
|
||||
[{ concurrency: '0' }, 'concurrency', '1~16'],
|
||||
[{ concurrency: '99' }, 'concurrency', '1~16'],
|
||||
[{ concurrency: '2.5' }, 'concurrency', '必须是整数'],
|
||||
]
|
||||
for (const [patch, field, message] of cases) {
|
||||
const parsed = parseRefreshDrafts(drafts(patch))
|
||||
expect(parsed.values, `${field} ${patch[field]}`).toBeNull()
|
||||
expect(parsed.errors[field as keyof typeof parsed.errors]).toContain(message)
|
||||
}
|
||||
})
|
||||
|
||||
it('错误文案使用完整字段名', () => {
|
||||
expect(parseRefreshDrafts(drafts({ documentRefresh: '1' })).errors.documentRefresh).toContain(
|
||||
'文档状态刷新间隔只能是 15/30/60 秒'
|
||||
)
|
||||
expect(parseRefreshDrafts(drafts({ stalled: '45' })).errors.stalled).toContain('解析停滞阈值只能是 30/60 分钟')
|
||||
})
|
||||
|
||||
it('任一字段非法时整体 values 为 null,避免夹带默认值保存', () => {
|
||||
const parsed = parseRefreshDrafts(drafts({ concurrency: '99' }))
|
||||
expect(parsed.values).toBeNull()
|
||||
expect(parsed.errors.documentRefresh).toBeNull()
|
||||
})
|
||||
|
||||
it('脏值按解析后的数值比较:015 等价 15,改值或非法值才变脏', () => {
|
||||
expect(refreshSettingsDirty(drafts(), settings)).toBe(false)
|
||||
expect(refreshSettingsDirty(drafts({ documentRefresh: '015' }), settings)).toBe(false)
|
||||
expect(refreshSettingsDirty(drafts({ concurrency: '7' }), settings)).toBe(true)
|
||||
expect(refreshSettingsDirty(drafts({ documentRefresh: '1' }), settings)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
+95
-120
@@ -22,13 +22,26 @@ import { archiveSourceConnection, fetchSourceConnectionList } from './sourceConn
|
||||
import type { SourceConnectionListItem } from './sourceConnections'
|
||||
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings } from './uiSettings'
|
||||
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
|
||||
import { refreshSettingsInput } from './settingsInputs'
|
||||
import {
|
||||
parseRefreshDrafts,
|
||||
REFRESH_FIELD_META,
|
||||
refreshDraftText,
|
||||
refreshSettingsDirty,
|
||||
refreshSettingsInput,
|
||||
} from './settingsInputs'
|
||||
import type { RefreshDrafts, RefreshField } from './settingsInputs'
|
||||
import './systemSettings.css'
|
||||
|
||||
// 连接配置已从「服务配置」迁到「知识库绑定」。这两个纯函数仍从本模块导出,
|
||||
// 连接配置已从「服务配置」迁到「知识库绑定」。这些纯函数仍从本模块导出,
|
||||
// 既有调用与回归测试的导入路径不变。
|
||||
export { refreshSettingsInput, serviceSettingsInput } from './settingsInputs'
|
||||
export type { RefreshDrafts, ServiceDrafts } from './settingsInputs'
|
||||
export {
|
||||
parseRefreshDrafts,
|
||||
refreshDraftText,
|
||||
refreshSettingsDirty,
|
||||
refreshSettingsInput,
|
||||
serviceSettingsInput,
|
||||
} from './settingsInputs'
|
||||
export type { RefreshDrafts, RefreshValues, ServiceDrafts } from './settingsInputs'
|
||||
|
||||
interface Props {
|
||||
sources: CatalogSource[]
|
||||
@@ -57,10 +70,23 @@ const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
|
||||
{ key: 'services', label: 'AI 模型连接' },
|
||||
{ key: 'knowledge-bindings', label: '知识库绑定' },
|
||||
{ key: 'storage', label: '存储与备份' },
|
||||
{ key: 'refresh', label: '刷新策略' },
|
||||
{ key: 'refresh', label: '参数设置' },
|
||||
{ key: 'members', label: '成员与角色', adminOnly: true },
|
||||
] as { key: SectionKey; label: string; adminOnly?: boolean }[]
|
||||
|
||||
const refreshHints: Record<RefreshField, string> = {
|
||||
documentRefresh: '解析监控按此周期刷新文档状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
|
||||
resourceRefresh: '解析监控按此周期刷新资源与服务状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
|
||||
stalled: '超过此时长没有进展就标记停滞;调大更容忍长解析,调小更快标记停滞',
|
||||
concurrency: '调大入库更快、写入压力更高;调小更稳,排队更久',
|
||||
}
|
||||
|
||||
// 产品定义的分组与归属,顺序即页面呈现顺序。
|
||||
const refreshGroups: { key: string; title: string; fields: RefreshField[] }[] = [
|
||||
{ key: 'sources', title: '来源与目录', fields: ['documentRefresh', 'resourceRefresh'] },
|
||||
{ key: 'parsing', title: '解析监控', fields: ['stalled', 'concurrency'] },
|
||||
]
|
||||
|
||||
const sourceTypeLabels: Record<string, string> = {
|
||||
dingtalk: '钉钉知识库',
|
||||
pp: 'PP 资料下载中心',
|
||||
@@ -103,41 +129,30 @@ export function SystemSettingsView({
|
||||
? 'knowledge-bindings'
|
||||
: (initialSection as SectionKey)
|
||||
)
|
||||
const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15)
|
||||
const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30)
|
||||
const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800)
|
||||
const [finalizing, setFinalizing] = useState<7200 | 14400>(settings?.finalizing_after_seconds ?? 7200)
|
||||
const [concurrency, setConcurrency] = useState<number>(settings?.ingestion_concurrency ?? 2)
|
||||
const [dirty, setDirty] = useState(false)
|
||||
// 输入框用文本草稿而不是 number:浏览器会吞掉 1e1/+15,无法展示「非法」提示。
|
||||
const [refreshDrafts, setRefreshDrafts] = useState<RefreshDrafts>(() =>
|
||||
settings
|
||||
? refreshDraftText(settings)
|
||||
: { documentRefresh: '15', resourceRefresh: '30', stalled: '30', concurrency: '2' }
|
||||
)
|
||||
|
||||
// 统一入口后,清单里列全部来源(钉钉知识库 / 钉盘 / PP),不再只显示 PP。
|
||||
const listedConnections = connections
|
||||
|
||||
useEffect(() => {
|
||||
if (!settings) return
|
||||
setDocumentRefresh(settings.document_refresh_seconds)
|
||||
setResourceRefresh(settings.resource_refresh_seconds)
|
||||
setStalled(settings.stalled_after_seconds)
|
||||
setFinalizing(settings.finalizing_after_seconds)
|
||||
setConcurrency(settings.ingestion_concurrency)
|
||||
setDirty(false)
|
||||
setRefreshDrafts(refreshDraftText(settings))
|
||||
}, [settings])
|
||||
|
||||
const canSave = Boolean(settings && !saving)
|
||||
const parsedRefresh = parseRefreshDrafts(refreshDrafts)
|
||||
const refreshDirty = settings ? refreshSettingsDirty(refreshDrafts, settings) : false
|
||||
const canSave = Boolean(settings && !saving && parsedRefresh.values)
|
||||
const isAdmin = identity?.role === 'admin'
|
||||
const refreshSettingsDirty = Boolean(
|
||||
settings &&
|
||||
(documentRefresh !== settings.document_refresh_seconds ||
|
||||
resourceRefresh !== settings.resource_refresh_seconds ||
|
||||
stalled !== settings.stalled_after_seconds ||
|
||||
finalizing !== settings.finalizing_after_seconds ||
|
||||
concurrency !== settings.ingestion_concurrency)
|
||||
)
|
||||
// 保存边界:刷新分区只带刷新草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
|
||||
// 互不夹带(未保存的地址不会因为保存刷新策略被写进去)。
|
||||
// 保存边界:参数分区只带参数草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
|
||||
// 互不夹带(未保存的地址不会因为保存参数设置被写进去)。
|
||||
const refreshInput = (): UISettingsCandidateInput =>
|
||||
settings
|
||||
? refreshSettingsInput(settings, { documentRefresh, resourceRefresh, stalled, finalizing, concurrency })
|
||||
settings && parsedRefresh.values
|
||||
? refreshSettingsInput(settings, parsedRefresh.values)
|
||||
: ({} as UISettingsCandidateInput)
|
||||
return (
|
||||
<main className="page-shell system-settings">
|
||||
@@ -247,105 +262,65 @@ export function SystemSettingsView({
|
||||
<section className="settings-panel wide" id="settings-refresh">
|
||||
<div className="settings-section-heading">
|
||||
<div>
|
||||
<h2>刷新策略</h2>
|
||||
<p>保存只改这一组参数,不会带上「知识库绑定」里未保存的连接地址。</p>
|
||||
<h2>参数设置</h2>
|
||||
</div>
|
||||
<span className="safe-badge">当前活动版本</span>
|
||||
</div>
|
||||
<div className="safe-setting-grid">
|
||||
<label>
|
||||
文档状态刷新间隔
|
||||
<select
|
||||
value={documentRefresh}
|
||||
onChange={(event) => {
|
||||
setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={15}>15秒</option>
|
||||
<option value={30}>30秒</option>
|
||||
<option value={60}>1分钟</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
资源刷新间隔
|
||||
<select
|
||||
value={resourceRefresh}
|
||||
onChange={(event) => {
|
||||
setResourceRefresh(Number(event.target.value) as 30 | 60)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={30}>30秒</option>
|
||||
<option value={60}>1分钟</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
解析停滞阈值
|
||||
<select
|
||||
value={stalled}
|
||||
onChange={(event) => {
|
||||
setStalled(Number(event.target.value) as 1800 | 3600)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={1800}>30分钟</option>
|
||||
<option value={3600}>1小时</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
收尾超时告警
|
||||
<select
|
||||
value={finalizing}
|
||||
onChange={(event) => {
|
||||
setFinalizing(Number(event.target.value) as 7200 | 14400)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={7200}>2小时</option>
|
||||
<option value={14400}>4小时</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
入库并发上限
|
||||
<select
|
||||
value={concurrency}
|
||||
onChange={(event) => {
|
||||
setConcurrency(Number(event.target.value))
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={1}>1(谨慎,MinerU 并发 1)</option>
|
||||
<option value={2}>2</option>
|
||||
<option value={3}>3</option>
|
||||
<option value={4}>4</option>
|
||||
<option value={6}>6</option>
|
||||
<option value={8}>8</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="settings-param-groups">
|
||||
{refreshGroups.map((group) => (
|
||||
<section className="settings-param-group" key={group.key} data-refresh-group={group.key}>
|
||||
<h3>{group.title}</h3>
|
||||
<div className="safe-setting-grid">
|
||||
{group.fields.map((key) => {
|
||||
const meta = REFRESH_FIELD_META[key]
|
||||
const hint = refreshHints[key]
|
||||
const error = parsedRefresh.errors[key]
|
||||
const hintID = `refresh-${key}-hint`
|
||||
const errorID = `refresh-${key}-error`
|
||||
return (
|
||||
<label key={key}>
|
||||
{meta.label}
|
||||
<span className="settings-field-control">
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
value={refreshDrafts[key]}
|
||||
aria-invalid={error ? 'true' : 'false'}
|
||||
aria-describedby={error ? `${hintID} ${errorID}` : hintID}
|
||||
onChange={(event) =>
|
||||
setRefreshDrafts((drafts) => ({ ...drafts, [key]: event.target.value }))
|
||||
}
|
||||
/>
|
||||
<span className="settings-field-unit">{meta.unit}</span>
|
||||
</span>
|
||||
<small className="settings-field-hint" id={hintID}>
|
||||
{hint}
|
||||
</small>
|
||||
{error ? (
|
||||
<span className="settings-field-error" id={errorID} role="alert">
|
||||
{error}
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setDirty(false)
|
||||
onSave(refreshInput())
|
||||
}}
|
||||
disabled={!canSave || !refreshSettingsDirty}
|
||||
>
|
||||
{saving ? '正在验证并应用…' : '保存刷新与告警参数'}
|
||||
<button onClick={() => onSave(refreshInput())} disabled={!canSave || !refreshDirty}>
|
||||
{saving ? '正在验证并应用…' : '保存参数设置'}
|
||||
</button>
|
||||
{visibleSaveMessage(saveMessage, dirty) ? (
|
||||
{visibleSaveMessage(saveMessage, refreshDirty) ? (
|
||||
<p className="success-message" role="status">
|
||||
{saveMessage}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="settings-warn">
|
||||
解析停滞阈值保存后由 worker 在 1 分钟内生效;收尾超时告警目前只保存配置,判定尚未接入。
|
||||
</p>
|
||||
<p className="settings-warn">解析停滞阈值保存后由 worker 在 1 分钟内生效。</p>
|
||||
<p className="settings-hint">保存只改这组参数,不会带上「知识库绑定」里未保存的连接地址。</p>
|
||||
<small>
|
||||
当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '}
|
||||
{secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}
|
||||
、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发{' '}
|
||||
{settings.ingestion_concurrency}。
|
||||
{`当前:文档 ${settings.document_refresh_seconds} 秒、资源 ${settings.resource_refresh_seconds} 秒、停滞 ${settings.stalled_after_seconds / 60} 分钟、入库并发 ${settings.ingestion_concurrency}。`}
|
||||
</small>
|
||||
</section>
|
||||
) : null}
|
||||
@@ -429,7 +404,7 @@ export function SystemSettings() {
|
||||
// 探测失败不影响保存结果,页面保留上一次观测。
|
||||
}
|
||||
setSaveMessage(
|
||||
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
|
||||
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${active.stalled_after_seconds / 60}分钟、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
|
||||
)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '保存系统设置失败')
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+89
-13
@@ -1,6 +1,6 @@
|
||||
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
|
||||
|
||||
// 保存边界是纯函数:连接分区只取连接草稿,刷新分区只取刷新草稿,
|
||||
// 保存边界是纯函数:连接分区只取连接草稿,参数分区只取参数草稿,
|
||||
// 另一侧一律用服务器当前值。组件与测试共用同一实现。
|
||||
export interface ServiceDrafts {
|
||||
testEndpoint: string
|
||||
@@ -8,13 +8,87 @@ export interface ServiceDrafts {
|
||||
productionTenantID: string
|
||||
productionKnowledgeBaseID: string
|
||||
}
|
||||
export interface RefreshDrafts {
|
||||
documentRefresh: 15 | 30 | 60
|
||||
resourceRefresh: 30 | 60
|
||||
stalled: 1800 | 3600
|
||||
finalizing: 7200 | 14400
|
||||
concurrency: number
|
||||
export type RefreshField = 'documentRefresh' | 'resourceRefresh' | 'stalled' | 'concurrency'
|
||||
export type RefreshDrafts = Record<RefreshField, string>
|
||||
export type RefreshValues = Record<RefreshField, number>
|
||||
export type RefreshParseResult = {
|
||||
values: RefreshValues | null
|
||||
errors: Record<RefreshField, string | null>
|
||||
}
|
||||
|
||||
export interface RefreshFieldMeta {
|
||||
label: string
|
||||
unit: string
|
||||
}
|
||||
|
||||
interface RefreshRule extends RefreshFieldMeta {
|
||||
allowed?: number[]
|
||||
min?: number
|
||||
max?: number
|
||||
// 草稿单位与存储单位不同:停滞输入分钟、接口收秒。
|
||||
toStored: (value: number) => number
|
||||
}
|
||||
|
||||
// 展示与错误文案共用同一份字段名/单位,避免两处各写一遍后漂移。
|
||||
export const REFRESH_FIELD_META: Record<RefreshField, RefreshFieldMeta> = {
|
||||
documentRefresh: { label: '文档状态刷新间隔', unit: '秒' },
|
||||
resourceRefresh: { label: '资源刷新间隔', unit: '秒' },
|
||||
stalled: { label: '解析停滞阈值', unit: '分钟' },
|
||||
concurrency: { label: '入库并发上限', unit: '个' },
|
||||
}
|
||||
|
||||
const REFRESH_RULES: Record<RefreshField, RefreshRule> = {
|
||||
documentRefresh: { ...REFRESH_FIELD_META.documentRefresh, allowed: [15, 30, 60], toStored: (value) => value },
|
||||
resourceRefresh: { ...REFRESH_FIELD_META.resourceRefresh, allowed: [30, 60], toStored: (value) => value },
|
||||
stalled: { ...REFRESH_FIELD_META.stalled, allowed: [30, 60], toStored: (value) => value * 60 },
|
||||
concurrency: { ...REFRESH_FIELD_META.concurrency, min: 1, max: 16, toStored: (value) => value },
|
||||
}
|
||||
|
||||
const parseField = (field: RefreshField, rawDraft: string): { value: number | null; error: string | null } => {
|
||||
const rule = REFRESH_RULES[field]
|
||||
const raw = rawDraft.trim()
|
||||
if (!raw) return { value: null, error: `${rule.label}不能为空` }
|
||||
// 不用 Number()/parseInt():空串、全角数字、"15abc" 都会被静默转成数字。
|
||||
if (!/^\d+$/.test(raw)) return { value: null, error: `${rule.label}必须是整数` }
|
||||
const value = Number(raw)
|
||||
if (rule.allowed) {
|
||||
if (!rule.allowed.includes(value))
|
||||
return { value: null, error: `${rule.label}只能是 ${rule.allowed.join('/')} ${rule.unit};当前 ${raw}` }
|
||||
} else if (rule.min !== undefined && rule.max !== undefined && (value < rule.min || value > rule.max)) {
|
||||
return { value: null, error: `${rule.label}只能是 ${rule.min}~${rule.max} 的整数;当前 ${raw}` }
|
||||
}
|
||||
return { value: rule.toStored(value), error: null }
|
||||
}
|
||||
|
||||
export const refreshDraftText = (settings: UISettings): RefreshDrafts => ({
|
||||
documentRefresh: String(settings.document_refresh_seconds),
|
||||
resourceRefresh: String(settings.resource_refresh_seconds),
|
||||
stalled: String(settings.stalled_after_seconds / 60),
|
||||
concurrency: String(settings.ingestion_concurrency),
|
||||
})
|
||||
|
||||
export const parseRefreshDrafts = (drafts: RefreshDrafts): RefreshParseResult => {
|
||||
const errors = {} as Record<RefreshField, string | null>
|
||||
const values = {} as RefreshValues
|
||||
for (const field of Object.keys(REFRESH_RULES) as RefreshField[]) {
|
||||
const parsed = parseField(field, drafts[field])
|
||||
errors[field] = parsed.error
|
||||
if (parsed.value !== null) values[field] = parsed.value
|
||||
}
|
||||
return { values: Object.values(errors).every((error) => error === null) ? values : null, errors }
|
||||
}
|
||||
|
||||
export const refreshSettingsDirty = (drafts: RefreshDrafts, settings: UISettings): boolean => {
|
||||
const parsed = parseRefreshDrafts(drafts)
|
||||
if (!parsed.values) return true
|
||||
return (
|
||||
parsed.values.documentRefresh !== settings.document_refresh_seconds ||
|
||||
parsed.values.resourceRefresh !== settings.resource_refresh_seconds ||
|
||||
parsed.values.stalled !== settings.stalled_after_seconds ||
|
||||
parsed.values.concurrency !== settings.ingestion_concurrency
|
||||
)
|
||||
}
|
||||
|
||||
export const serviceSettingsInput = (settings: UISettings, drafts: ServiceDrafts): UISettingsCandidateInput => ({
|
||||
document_refresh_seconds: settings.document_refresh_seconds,
|
||||
resource_refresh_seconds: settings.resource_refresh_seconds,
|
||||
@@ -26,12 +100,14 @@ export const serviceSettingsInput = (settings: UISettings, drafts: ServiceDrafts
|
||||
production_tenant_id: drafts.productionTenantID.trim(),
|
||||
production_knowledge_base_id: drafts.productionKnowledgeBaseID.trim(),
|
||||
})
|
||||
export const refreshSettingsInput = (settings: UISettings, drafts: RefreshDrafts): UISettingsCandidateInput => ({
|
||||
document_refresh_seconds: drafts.documentRefresh,
|
||||
resource_refresh_seconds: drafts.resourceRefresh,
|
||||
stalled_after_seconds: drafts.stalled,
|
||||
finalizing_after_seconds: drafts.finalizing,
|
||||
ingestion_concurrency: drafts.concurrency,
|
||||
export const refreshSettingsInput = (settings: UISettings, values: RefreshValues): UISettingsCandidateInput => ({
|
||||
// 范围由 parseRefreshDrafts 白名单保证;这里只把 number 收回契约的枚举类型。
|
||||
document_refresh_seconds: values.documentRefresh as UISettings['document_refresh_seconds'],
|
||||
resource_refresh_seconds: values.resourceRefresh as UISettings['resource_refresh_seconds'],
|
||||
stalled_after_seconds: values.stalled as UISettings['stalled_after_seconds'],
|
||||
// 参数分区不展示收尾超时,但契约必填且写侧按服务器值判权限:原样回传,绝不置空。
|
||||
finalizing_after_seconds: settings.finalizing_after_seconds,
|
||||
ingestion_concurrency: values.concurrency,
|
||||
test_weknora_base_url: settings.test_weknora_base_url,
|
||||
production_weknora_base_url: settings.production_weknora_base_url,
|
||||
production_tenant_id: settings.production_tenant_id,
|
||||
|
||||
@@ -155,10 +155,28 @@
|
||||
color: var(--ink-mute);
|
||||
font-size: 8px;
|
||||
}
|
||||
.settings-param-groups {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
.settings-param-group + .settings-param-group {
|
||||
border-top: 1px solid var(--border-base);
|
||||
padding-top: 14px;
|
||||
}
|
||||
.settings-param-group h3 {
|
||||
margin: 0 0 10px;
|
||||
color: var(--ink-base);
|
||||
font-size: 12px;
|
||||
}
|
||||
.settings-hint {
|
||||
margin: 6px 0 0;
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.safe-setting-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.safe-setting-grid label {
|
||||
display: grid;
|
||||
@@ -166,12 +184,39 @@
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.safe-setting-grid select {
|
||||
.safe-setting-grid input {
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 7px;
|
||||
padding: 8px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-base);
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.safe-setting-grid input[aria-invalid='true'] {
|
||||
border-color: var(--c-fail);
|
||||
}
|
||||
.settings-field-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.settings-field-control input {
|
||||
flex: 1;
|
||||
}
|
||||
.settings-field-unit {
|
||||
flex: none;
|
||||
font-size: 9px;
|
||||
}
|
||||
.settings-field-hint {
|
||||
color: var(--ink-mute);
|
||||
font-size: 8px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.settings-field-error {
|
||||
color: var(--c-fail);
|
||||
font-size: 8px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.locked-gates {
|
||||
display: flex;
|
||||
|
||||
Reference in New Issue
Block a user