Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 65476750b0 | |||
| b59ec66387 | |||
| 7801c163e4 | |||
| 15dbc2469b | |||
| da568dfa2c | |||
| 7b4ec1f89d | |||
| 6a6fa7129a | |||
| c12152529c | |||
| 4d73aa999b | |||
| cc289b63e5 | |||
| 9ddc3291cc | |||
| 32c7074f41 | |||
| 7926c8e8b9 | |||
| bb57a9835c | |||
| 49f9994ea6 | |||
| 501fbae6ff | |||
| 45aef5016a | |||
| c90cb803fa |
+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=
|
||||
|
||||
@@ -80,3 +80,39 @@ jobs:
|
||||
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
|
||||
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
|
||||
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
|
||||
notify:
|
||||
needs: [guard, publish]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: 取同一提交的上报脚本
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
test "$GITHUB_REF" = refs/heads/main
|
||||
git init -q .
|
||||
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
|
||||
git checkout -q --detach "$GITHUB_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
- name: 上报 ci-bridge(发布结果,通知失败不改变发布结论)
|
||||
if: always()
|
||||
env:
|
||||
BRIDGE_URL: ${{ vars.CI_BRIDGE_URL }}
|
||||
BRIDGE_TOKEN: ${{ secrets.CI_BRIDGE_TOKEN }}
|
||||
CI_PUBLIC_BASE_URL: https://gitea.zheromiku.top
|
||||
GUARD_RESULT: ${{ needs.guard.result }}
|
||||
PUBLISH_RESULT: ${{ needs.publish.result }}
|
||||
DEPLOY_SHA: ${{ inputs.sha }}
|
||||
DEPLOY_BUNDLE: ${{ inputs.bundle }}
|
||||
DEPLOY_TASK: ${{ inputs.task }}
|
||||
run: |
|
||||
set +e; set +o pipefail
|
||||
B="${BRIDGE_URL:-}"
|
||||
for cand in "$B" "http://172.17.0.1:8899" "http://192.168.50.134:8899" "http://100.92.49.78:8899"; do
|
||||
if [ -n "$cand" ]; then curl -s -m 5 -o /dev/null "$cand/healthz" && { B="$cand"; break; }; fi
|
||||
done
|
||||
echo "使用 ci-bridge: ${B:-(不可达)}"
|
||||
CI_BRIDGE_RESOLVED="$B" python3 scripts/cd_notify.py
|
||||
echo "上报结束(通知失败不改变发布结论)"
|
||||
|
||||
@@ -1,5 +1,38 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 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(原需求单发布)
|
||||
|
||||
- 白盒预检后在原需求单自动准备候选,业务与批次回归证据同单登记。负责人在原单切到「待发布」批准上线。
|
||||
|
||||
+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,12 @@
|
||||
# 知识治理候选和批次验收
|
||||
|
||||
## 需求单的六个状态
|
||||
|
||||
新需求默认「规划中」。负责人手动按「规划中 → 进行中 → 待测试 → 测试中 → 待发布 → 已发布」切换状态。切到「待测试」触发预检和候选排队,收到候选就绪回执后切到「测试中」派测。原单显示「批次验收通过」后切到「待发布」触发 CD,收到主站发布完成回执后切到「已发布」。
|
||||
|
||||
## 在原需求单发布
|
||||
|
||||
白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后进入「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
|
||||
白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后由负责人切到「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
|
||||
|
||||
## 旧版独立发布单的存量操作
|
||||
|
||||
@@ -30,6 +34,20 @@
|
||||
|
||||
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
|
||||
|
||||
### 候选访问测试 WeKnora
|
||||
|
||||
候选容器不能直连测试宿主的内网地址。宿主用 `kg-qa-weknora-test-hop.service` 把 `0.0.0.0:18090` 转到测试 WeKnora 的 `127.0.0.1:8092`,候选与所有 docker 网桥都能通过 `http://172.17.0.1:18090` 访问;`172.17.0.1` 是 docker0 的固定地址,换候选不变。绑定地址要填 IP,服务端不接受主机名。API Key 由测试负责人经授权渠道录入,不写进评论。
|
||||
|
||||
### 候选的知识库绑定密钥
|
||||
|
||||
验收候选运行在 QA 库上,知识库绑定需要独立的 32 字节主密钥。执行器在 `~/.local/state/kg-candidate-release/qa-binding-master.key` 维护唯一一份(0600、属主为容器应用用户),以只读方式挂到 API 与 worker 的 `/run/qa/binding-master.key`。所有候选共用这一份,已保存的绑定在下一轮候选仍可解开。文件缺失时首个候选自动生成;权限、长度或属主不符时拒绝启动,不静默降级。
|
||||
|
||||
### 原需求单的逐项报告
|
||||
|
||||
测试机将 `scripts/qa_report.py` 安装为 `~/.local/bin/kg-qa-report`。在 QA 的 HiFox 任务会话中,从本轮测试设计取得完整编号,保存到 `plan.json` 的 `business`、`regression` 数组。执行 `kg-qa-report init <任务> plan.json sheet.json` 读取原单候选回执并生成待填清单。测试中填写各编号的 `status`(`passed`、`failed`、`blocked`)和 `evidence`。`candidate_check` 记录指定候选部署上的实际验证结果及证据。环境受阻时记录原因。
|
||||
|
||||
使用 `kg-qa-report check <任务> plan.json sheet.json` 预检。缺失项按编号提示。使用同一参数将 `check` 换为 `submit` 后,由 QA 本人的 HiFox 执行上下文发表评论。回执变化时,工具会提示重新核对。登记端重新核算汇总和候选实测结论。
|
||||
|
||||
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
|
||||
## 执行器配置
|
||||
|
||||
@@ -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」;
|
||||
|
||||
@@ -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 不能冒充。
|
||||
|
||||
@@ -8,6 +8,7 @@ import re
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
|
||||
import qa_report
|
||||
import candidate_release as candidate
|
||||
import candidate_runtime as runtime
|
||||
import hifox_release_trigger as hfx
|
||||
@@ -114,11 +115,19 @@ def publish_candidate(plan, receipt, run):
|
||||
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候选已就绪。负责人可在本单切到「测试中」启动同包测试。'
|
||||
if single:
|
||||
body += '\nQA 请在测试机用 ~/.local/bin/kg-qa-report 从本轮用例清单生成报告,逐项填写结果和证据,正式候选无法登录时报告 blocked。'
|
||||
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:
|
||||
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(),
|
||||
@@ -155,6 +164,27 @@ def summon_qa(plan, target, body):
|
||||
cd.record(path, {'state': 'sent', 'result': result})
|
||||
|
||||
|
||||
def acceptance_body(sha, bundle, tasks, reports, url_of, links):
|
||||
"""State the registered verdict and its counts on the task itself, not only in metadata."""
|
||||
lines = ['批次验收通过', '', f'提交 `{sha}`', '', f'归档 `{bundle}`', '']
|
||||
single = len(tasks) == 1
|
||||
for item in tasks:
|
||||
row, result = reports[item]
|
||||
if single:
|
||||
lines.append(f'必测 {result["required"]} · 通过 {result["passed"]} · 失败 {result["failed"]} '
|
||||
f'· 阻塞 {result["blocked"]} · 结论 {result["verdict"]}')
|
||||
if result.get('url'):
|
||||
lines.append(f'候选地址 {result["url"]}')
|
||||
cases = result.get('cases') or {}
|
||||
for group, label in (('business', '业务用例'), ('regression', '回归用例')):
|
||||
if isinstance(cases.get(group), list) and cases[group]:
|
||||
lines.append(f'{label}({len(cases[group])}):' + '、'.join(cases[group]))
|
||||
else:
|
||||
lines.append(f'{url_of(item)}#comment-{row["id"]}')
|
||||
lines += ['', '需求验收与批次回归报告', links]
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def register(task_id):
|
||||
plan = owner_plan(task_id)
|
||||
directory = STATE / cd.acceptance_digest(plan)
|
||||
@@ -179,6 +209,13 @@ def register(task_id):
|
||||
row = reports[item_id][0]
|
||||
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
|
||||
'invalid QA evidence link')
|
||||
if [item['task'] for item in plan['items']] == [task_id] and task_id in reports:
|
||||
accepted = cd.metadata(task(task_id), 'cd_acceptance') or {}
|
||||
if (accepted.get('sha'), accepted.get('bundle')) != (receipt['sha'], receipt['bundle']):
|
||||
try:
|
||||
qa_report.verify_report(reports[task_id][1])
|
||||
except ValueError as error:
|
||||
raise cd.CDError(f'QA 请在测试机提交逐项报告:{error}') from error
|
||||
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
|
||||
fresh = owner_plan(task_id)
|
||||
cd.require(fresh == plan, 'release plan changed during registration')
|
||||
@@ -187,7 +224,7 @@ def register(task_id):
|
||||
'register QA before the owner moves the release task to 待发布')
|
||||
sha, bundle = receipt['sha'], receipt['bundle']
|
||||
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks)
|
||||
body = f'批次验收通过\n\n提交 `{sha}`\n\n归档 `{bundle}`\n\n需求验收与批次回归报告\n{links}'
|
||||
body = acceptance_body(sha, bundle, tasks, reports, lambda item: task(item)['url'], links)
|
||||
comment = add_comment(task_id, 'acceptance ' + bundle, body)
|
||||
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
|
||||
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
|
||||
|
||||
@@ -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())
|
||||
@@ -15,6 +15,8 @@ from urllib.parse import quote
|
||||
import production_cd as cd
|
||||
import qa_env
|
||||
|
||||
STATE = Path.home() / '.local/state/kg-candidate-release'
|
||||
|
||||
|
||||
def isolated_subnet(exclude=()):
|
||||
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
|
||||
@@ -49,6 +51,29 @@ 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]
|
||||
|
||||
|
||||
APP_UID = 65532
|
||||
|
||||
|
||||
def qa_binding_key(image):
|
||||
"""Give QA candidates one stable binding master key, readable by the application user."""
|
||||
path = STATE / 'qa-binding-master.key'
|
||||
if not path.exists():
|
||||
cd.atomic_write(path, secrets.token_bytes(32), mode=0o600)
|
||||
cd.run(['docker', 'run', '--rm', '--user', '0', '-v', f'{path.parent}:/run/kg-key', image,
|
||||
'chown', f'{APP_UID}:{APP_UID}', f'/run/kg-key/{path.name}'],
|
||||
'hand the QA binding master key to the application user', timeout=90)
|
||||
info = path.lstat()
|
||||
cd.require(info.st_mode & 0o777 == 0o600 and info.st_size == 32 and info.st_uid == APP_UID,
|
||||
'QA binding master key must be a 32-byte file owned by the application user with mode 0600')
|
||||
return path
|
||||
|
||||
|
||||
def ready(directory, bundle, test_database=None):
|
||||
bundle = bundle.resolve()
|
||||
manifest = cd.read_json(bundle / 'release.json')
|
||||
@@ -82,6 +107,9 @@ def ready(directory, bundle, test_database=None):
|
||||
url, cert = qa_database(test_database)
|
||||
env['DATA' + 'BASE_URL'] = url
|
||||
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
|
||||
env['WEKNORA_BINDING_MASTER_KEY_FILE'] = '/run/qa/binding-master.key'
|
||||
# 验收候选要连 QA 的测试 WeKnora(同网段明文 http),与生产部署口径一致。
|
||||
env['WEKNORA_ALLOW_PRIVATE_HTTP'] = 'true'
|
||||
app_env = directory / 'app.env'
|
||||
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
|
||||
names = {role: f'{project}-{role}' for role in cd.ROLES}
|
||||
@@ -90,15 +118,22 @@ def ready(directory, bundle, test_database=None):
|
||||
cd.verify_archive(archive, item['id'])
|
||||
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
|
||||
services[role] = {'image': item['id'], 'container_name': names[role]}
|
||||
key = qa_binding_key(manifest['images']['api']['id']) if test_database is not None else None
|
||||
for role in ('api', 'worker'):
|
||||
services[role]['env_file'] = [str(app_env)]
|
||||
if test_database is not None:
|
||||
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro']
|
||||
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro',
|
||||
f'{key}:/run/qa/binding-master.key:ro']
|
||||
services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'],
|
||||
'interval': '2s', 'timeout': '3s', 'retries': 45}
|
||||
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}]}}}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把一次发布运行的结果上报 ci-bridge,与 build 的通知同一出口。
|
||||
|
||||
发布失败也必须上报:群里要知道是「发布失败」而不是没有消息。
|
||||
上报失败只打印,不改变发布的结论。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
def env(name, default=''):
|
||||
return (os.environ.get(name) or default).strip()
|
||||
|
||||
|
||||
def git(*args):
|
||||
try:
|
||||
return subprocess.check_output(['git', *args], text=True, stderr=subprocess.DEVNULL).strip()
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return ''
|
||||
|
||||
|
||||
def result_status(value):
|
||||
return {'success': 'success', 'failure': 'failure', 'cancelled': 'cancelled'}.get(value, 'failure')
|
||||
|
||||
|
||||
def payload():
|
||||
deploy_sha = env('DEPLOY_SHA') or env('GITHUB_SHA')
|
||||
publish = result_status(env('PUBLISH_RESULT'))
|
||||
guard = result_status(env('GUARD_RESULT'))
|
||||
status = publish if publish != 'success' else guard
|
||||
subject = git('log', '-1', '--format=%s', deploy_sha) if deploy_sha else ''
|
||||
steps = []
|
||||
for name, value in (('guard', env('GUARD_RESULT')), ('publish', env('PUBLISH_RESULT'))):
|
||||
steps.append({'name': name, 'status': result_status(value), 'duration_s': ''})
|
||||
return {
|
||||
'repo': env('GITHUB_REPOSITORY', 'unknown/unknown'),
|
||||
'sha': deploy_sha,
|
||||
'branch': 'main',
|
||||
'actor': env('GITHUB_ACTOR'),
|
||||
'workflow': 'deploy-production',
|
||||
'kind': 'deploy',
|
||||
'site_url': env('DEPLOY_SITE_URL', 'http://100.85.111.121:8088/'),
|
||||
'status': status,
|
||||
'commit_subject': subject,
|
||||
'commit_count': '1',
|
||||
'duration_s': '',
|
||||
'preview_url': '',
|
||||
'steps': steps,
|
||||
'manifest': ['guard', 'publish'],
|
||||
'bundle': env('DEPLOY_BUNDLE'),
|
||||
'task': env('DEPLOY_TASK'),
|
||||
'run_id': env('GITHUB_RUN_ID'),
|
||||
'run_number': env('GITHUB_RUN_NUMBER'),
|
||||
'run_attempt': env('GITHUB_RUN_ATTEMPT', '1'),
|
||||
'commit_url': f"{env('CI_PUBLIC_BASE_URL', env('GITHUB_SERVER_URL'))}/{env('GITHUB_REPOSITORY')}/commit/{deploy_sha}",
|
||||
'run_url': f"{env('CI_PUBLIC_BASE_URL', env('GITHUB_SERVER_URL'))}/{env('GITHUB_REPOSITORY')}/actions/runs/{env('GITHUB_RUN_ID')}",
|
||||
}
|
||||
|
||||
|
||||
def post(data, base, token):
|
||||
body = json.dumps(data, ensure_ascii=False).encode()
|
||||
req = urllib.request.Request(base.rstrip('/') + '/api/ci/report', data=body, method='POST',
|
||||
headers={'Content-Type': 'application/json', 'X-CI-Token': token})
|
||||
with urllib.request.urlopen(req, timeout=30) as response:
|
||||
return response.read().decode()[:300]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--no-post', action='store_true')
|
||||
args = parser.parse_args()
|
||||
data = payload()
|
||||
if args.no_post:
|
||||
print(json.dumps(data, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
base = env('CI_BRIDGE_RESOLVED') or env('BRIDGE_URL') or env('CI_BRIDGE_URL')
|
||||
if not base:
|
||||
print('跳过上报:未找到 ci-bridge 地址', file=sys.stderr)
|
||||
return 0
|
||||
try:
|
||||
print('✅ 已上报 ci-bridge:' + post(data, base, env('BRIDGE_TOKEN')))
|
||||
except (urllib.error.URLError, OSError) as error:
|
||||
# 通知失败不改变发布结论,只记一行。
|
||||
print(f'❌ 上报 ci-bridge 失败(发布结论不变):{error}', file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare candidate QA reports from a case list and per-case evidence."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
POLICY = 'KG-QA-REPORT/v1'
|
||||
STATES = ('passed', 'failed', 'blocked')
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def summarize(plan, results, host):
|
||||
require(isinstance(plan, dict), '缺少原用例清单')
|
||||
ids = []
|
||||
for group in ('business', 'regression'):
|
||||
group_ids = plan.get(group)
|
||||
require(isinstance(group_ids, list) and group_ids, f'缺少 {group} 用例编号')
|
||||
for case_id in group_ids:
|
||||
require(isinstance(case_id, str) and case_id.strip() == case_id and case_id, '存在空用例编号')
|
||||
require(case_id not in ids, f'重复编号 {case_id}')
|
||||
ids.append(case_id)
|
||||
require(isinstance(results, dict), '缺少逐项结果')
|
||||
extras = set(results) - set(ids)
|
||||
require(not extras, '清单外编号 ' + ', '.join(sorted(extras)))
|
||||
counts = dict.fromkeys(STATES, 0)
|
||||
missing = []
|
||||
for case_id in ids:
|
||||
entry = results.get(case_id)
|
||||
if not valid_entry(entry):
|
||||
missing.append(case_id)
|
||||
else:
|
||||
counts[entry['status']] += 1
|
||||
require(not missing, '请填写结果和证据:' + ', '.join(missing))
|
||||
require(valid_entry(host), '请填写正式候选环境的实测结果和证据,无法登录请填 blocked')
|
||||
states = {host['status']} | {k for k, count in counts.items() if count}
|
||||
verdict = 'failed' if 'failed' in states else 'blocked' if 'blocked' in states else 'passed'
|
||||
return dict(cases=plan, results=results, candidate_check=host, required=len(ids), verdict=verdict, **counts)
|
||||
|
||||
|
||||
def valid_entry(entry):
|
||||
return (isinstance(entry, dict) and entry.get('status') in STATES
|
||||
and isinstance(entry.get('evidence'), str) and bool(entry['evidence'].strip()))
|
||||
|
||||
|
||||
def verify_report(report):
|
||||
expected = summarize(report.get('cases'), report.get('results'), report.get('candidate_check'))
|
||||
for key, value in expected.items():
|
||||
require(type(report.get(key)) is type(value) and report[key] == value, f'报告字段 {key} 与逐项结果不一致')
|
||||
|
||||
|
||||
def cli(*args, body=None):
|
||||
program = shutil.which('hifox') or str(Path.home() / '.local/bin/hifox')
|
||||
output = subprocess.check_output([program, *args, '--output', 'json'], input=body, text=True, timeout=45)
|
||||
return json.loads(output)
|
||||
|
||||
|
||||
def ready(rows):
|
||||
candidates = sorted((r for r in rows if r['content'].startswith('[KG candidate ready ')
|
||||
and (r.get('author') or {}).get('id') == '39ae59fb-876c-4587-ab5d-a12a841c6c09'),
|
||||
key=lambda r: r['createdAt'])
|
||||
require(candidates, '原单缺少候选就绪回执')
|
||||
row = candidates[-1]
|
||||
text = row['content']
|
||||
def field(pattern):
|
||||
match = re.search(pattern, text, re.M)
|
||||
require(match is not None, '候选回执字段不完整')
|
||||
return match[1]
|
||||
bundle = field(r'^归档 `([0-9a-f]{64})`$')
|
||||
require(text.startswith('[KG candidate ready ' + bundle + ']'), '候选归档不一致')
|
||||
return dict(task=row['taskId'], ready=row['id'], url=field(r'^候选验收地址 (https?://\S+)$'),
|
||||
sha=field(r'^提交 `([0-9a-f]{40})`$'), bundle=bundle), field(r'用 ([\w.-]+) 代码块回填')
|
||||
|
||||
|
||||
def load(path):
|
||||
return json.loads(Path(path).read_text())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=['init', 'check', 'submit'])
|
||||
parser.add_argument('task')
|
||||
parser.add_argument('plan', help='原用例清单 JSON,含 business、regression 编号数组')
|
||||
parser.add_argument('sheet', help='逐项填写的结果文件')
|
||||
args = parser.parse_args()
|
||||
task = cli('task', 'view', args.task)
|
||||
def comments():
|
||||
return cli('task', 'comment', 'list', task['id'], '--limit', '0')
|
||||
rows = comments()
|
||||
receipt, fence = ready(rows)
|
||||
require(receipt['task'] == task['id'], '回执不属于本需求')
|
||||
plan = load(args.plan)
|
||||
fingerprint = hashlib.sha256(json.dumps(plan, sort_keys=True).encode()).hexdigest()
|
||||
if args.action == 'init':
|
||||
blank = {'status': '', 'evidence': ''}
|
||||
ids = [k for group in ('business', 'regression') for k in plan[group]]
|
||||
skeleton = dict(receipt=receipt, plan_digest=fingerprint, candidate_check=blank,
|
||||
results={k: blank for k in ids})
|
||||
with Path(args.sheet).open('x') as stream:
|
||||
json.dump(skeleton, stream, indent=2, ensure_ascii=False)
|
||||
return
|
||||
sheet = load(args.sheet)
|
||||
require(sheet['receipt'] == receipt, '候选版本已变化,请为新候选准备结果清单')
|
||||
require(sheet['plan_digest'] == fingerprint, '原用例清单已变化,请核对用例范围')
|
||||
report = dict(**receipt, **summarize(plan, sheet['results'], sheet['candidate_check']))
|
||||
verify_report(report)
|
||||
payload = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2)
|
||||
require('```' not in payload, '证据请填写简短结论或附件名,避免嵌套代码围栏')
|
||||
text = f'{POLICY} 候选实测结果 {report["verdict"]}\n\n```{fence}\n{payload}\n```'
|
||||
if args.action == 'check':
|
||||
print(text)
|
||||
return
|
||||
qa_authors = {'62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
|
||||
def existing(rows):
|
||||
return next((r for r in rows if r['content'] == text and (r.get('author') or {}).get('id') in qa_authors), None)
|
||||
found = existing(rows)
|
||||
if not found:
|
||||
# The child CLI inherits the QA session's identity. Never replace it with an operator login.
|
||||
cli('task', 'comment', task['id'], '--body-stdin', body=text)
|
||||
found = existing(comments())
|
||||
if found is None:
|
||||
raise ValueError('请在原单核对评论及 QA 署名后再决定是否重试')
|
||||
print(found['id'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (OSError, KeyError, TypeError, ValueError, subprocess.SubprocessError) as error:
|
||||
sys.exit(f'QA 报告:{error}')
|
||||
@@ -30,15 +30,23 @@ def author(row):
|
||||
return (row.get('author') or {}).get('id')
|
||||
|
||||
|
||||
def reviewer_comments(task, rows):
|
||||
return sorted((row for row in rows if author(row) == WHITE and row.get('taskId') == task['id']),
|
||||
key=lambda row: row['createdAt'], reverse=True)
|
||||
|
||||
|
||||
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)
|
||||
reviews = reviewer_comments(task, rows)
|
||||
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],
|
||||
header = review['content'].partition('\n')[0]
|
||||
verdict = re.match(r'^[🚦✅\s*]*可测试(?=$|[\s✅||((,,::。*])', header)
|
||||
mentions = re.findall(r'mention://task/([\w-]+)', header)
|
||||
cd.require(verdict and (not mentions or mentions == [task['id']]),
|
||||
'preflight is not a passing verdict for this task')
|
||||
hashes = set(re.findall(r'落地\s*(?:(merge))?\s*`([0-9a-f]{7,40})`', review['content']))
|
||||
cd.require(len(hashes) == 1, 'preflight needs an unambiguous landed commit')
|
||||
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)
|
||||
@@ -89,6 +97,27 @@ def frozen_approval(task_id, comment_id=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 = reviewer_comments(task, comments(task['id']))
|
||||
cd.require(reviews, 'require latest preflight from 白小浅')
|
||||
event = reviews[0]['id']
|
||||
cd.require(resolve(task, event)[0] == sha, 'preflight changed during recovery')
|
||||
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)
|
||||
|
||||
@@ -23,6 +23,41 @@ 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_qa_candidate_gets_a_stable_binding_master_key(self):
|
||||
import os
|
||||
with tempfile.TemporaryDirectory() as tmp, patch.object(runtime, 'STATE', Path(tmp)), \
|
||||
patch.object(runtime, 'APP_UID', os.getuid()), patch.object(runtime.cd, 'run') as docker:
|
||||
path = runtime.qa_binding_key('image')
|
||||
self.assertEqual((path.stat().st_mode & 0o777, path.stat().st_size), (0o600, 32))
|
||||
first = path.read_bytes()
|
||||
self.assertEqual(runtime.qa_binding_key('image').read_bytes(), first)
|
||||
self.assertEqual(docker.call_count, 1)
|
||||
path.chmod(0o644)
|
||||
with self.assertRaises(runtime.cd.CDError):
|
||||
runtime.qa_binding_key('image')
|
||||
|
||||
def test_acceptance_comment_states_counts_and_cases(self):
|
||||
import candidate_coordinator as coordinator
|
||||
result = {'required': 10, 'passed': 10, 'failed': 0, 'blocked': 0, 'verdict': 'passed',
|
||||
'url': 'http://127.0.0.1:32789',
|
||||
'cases': {'business': ['KB-01', 'KB-07'], 'regression': ['RG-01']}}
|
||||
body = coordinator.acceptance_body('a' * 40, 'b' * 64, ['t'], {'t': ({'id': 'c'}, result)},
|
||||
lambda item: 'u', '- u#comment-c')
|
||||
self.assertIn('必测 10 · 通过 10 · 失败 0 · 阻塞 0 · 结论 passed', body)
|
||||
self.assertIn('业务用例(2):KB-01、KB-07', body)
|
||||
self.assertIn('回归用例(1):RG-01', body)
|
||||
self.assertIn('候选地址 http://127.0.0.1:32789', body)
|
||||
|
||||
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])
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import unittest
|
||||
|
||||
import qa_report as qa
|
||||
|
||||
|
||||
class QAReportTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.plan = {'business': ['A'], 'regression': ['R']}
|
||||
self.host = {'status': 'passed', 'evidence': 'QA login and operations on the candidate'}
|
||||
self.rows = {i: {'status': 'passed', 'evidence': i + '.log'} for i in ('A', 'R')}
|
||||
|
||||
def test_missing_id_named_before_output(self):
|
||||
del self.rows['R']
|
||||
with self.assertRaisesRegex(ValueError, 'R'):
|
||||
qa.summarize(self.plan, self.rows, self.host)
|
||||
|
||||
def test_duplicate_across_groups(self):
|
||||
with self.assertRaisesRegex(ValueError, 'A'):
|
||||
qa.summarize(dict(self.plan, regression=['A']), self.rows, self.host)
|
||||
|
||||
def test_candidate_login_blocks_local_green(self):
|
||||
report = qa.summarize(self.plan, self.rows, {'status': 'blocked', 'evidence': 'candidate login 401'})
|
||||
self.assertEqual(report['verdict'], 'blocked')
|
||||
|
||||
def test_generated_report_reconciles(self):
|
||||
report = qa.summarize(self.plan, self.rows, self.host)
|
||||
self.assertEqual((report['cases'], report['required'], report['passed']), (self.plan, 2, 2))
|
||||
qa.verify_report(report)
|
||||
report['passed'] = 1
|
||||
with self.assertRaisesRegex(ValueError, 'passed'):
|
||||
qa.verify_report(report)
|
||||
@@ -3,6 +3,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import candidate_queue as queue
|
||||
import release_handoff as h
|
||||
|
||||
|
||||
@@ -22,6 +23,77 @@ class ReleaseHandoffTest(unittest.TestCase):
|
||||
with self.assertRaises(h.cd.CDError):
|
||||
h.review_identity(self.task, [self.review, newer], 'comment')
|
||||
|
||||
def test_plain_verdict_resolves_each_reports_own_commit(self):
|
||||
for title, sha in [('可测试', 'ea20abc'), ('🚦 ✅ 可测试', 'abc123def')]:
|
||||
row = dict(self.review, content=f'{title}|[任务](mention://task/task)\n落地合并 `{sha}`')
|
||||
self.assertEqual(h.review_identity(self.task, [row], row['id'])[0], sha)
|
||||
for title in ['不可测试', '是否可测试?', '未通过,引用「可测试」']:
|
||||
row = dict(self.review, content=f'{title}|[任务](mention://task/task)\n落地合并 `ea20abc`')
|
||||
with self.assertRaises(h.cd.CDError):
|
||||
h.review_identity(self.task, [row], row['id'])
|
||||
|
||||
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}}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user