Compare commits

..

3 Commits

Author SHA1 Message Date
zheromiku 922ff66533 Merge pull request 'feat(cd): 接入候选构建与批次验收' (#25) from feat/candidate-release-batch into main
build / build (push) Successful in 1m25s
2026-11-23 13:31:41 +08:00
姚章浩 0246db357f fix(cd): 校验候选部署入口并隔离凭据
build / build (push) Successful in 1m30s
2026-11-23 13:28:40 +08:00
姚章浩 1beaa31771 feat(cd): 接入候选构建与批次验收
build / build (push) Successful in 1m30s
2026-11-23 13:20:25 +08:00
61 changed files with 1156 additions and 3417 deletions
-6
View File
@@ -43,12 +43,6 @@ PRODUCTION_RELEASE_REQUESTS_ENABLED=false
PRODUCTION_WEKNORA_BASE_URL=
PRODUCTION_WEKNORA_API_KEY_FILE=
PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP=false
# 连接(地址 + 写-only 密钥)密文存治理库;主密钥是独立的 0600 32 字节文件。
WEKNORA_BINDING_MASTER_KEY_FILE=
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
WEKNORA_ALLOW_PRIVATE_HTTP=false
# 可信 TLS 反代之后录入密钥(X-Forwarded-Proto=https + 同源)。
WEKNORA_BINDING_TRUST_TLS_PROXY=false
PP_SCAN_ENABLED=false
PP_SCAN_HOST_DATA_ROOT=/home/zheromiku/dobot-portal-sync/data
PP_SCAN_CONTAINER_DATA_ROOT=/home/zheromiku/dobot-portal-sync/data
+80
View File
@@ -0,0 +1,80 @@
name: prepare-candidate
on:
workflow_dispatch:
inputs:
plan:
description: 'Release task UUID, exact SHA, baseline, requirement PRs and additional reviewed commits (JSON)'
required: true
mode:
description: 'verify or prepare'
required: true
default: verify
permissions:
contents: read
concurrency:
group: knowledge-governance-candidate
cancel-in-progress: false
jobs:
guard:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Verify release scope and CI
env:
KG_CANDIDATE_READ_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
case "$GITHUB_REF" in refs/heads/*) ;; *) exit 1 ;; esac
git init -q .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
auth() { git -c credential.helper='!f() { printf "username=x-access-token\npassword=%s\n" "$KG_CANDIDATE_READ_TOKEN"; }; f' "$@"; }
auth fetch -q origin "$GITHUB_REF" +refs/heads/main:refs/remotes/origin/main
git checkout --detach -q "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
export KG_CANDIDATE_FORGE="$GITHUB_SERVER_URL"
python3 scripts/candidate_release.py guard --event "$GITHUB_EVENT_PATH" --repo .
prepare:
if: ${{ inputs.mode == 'prepare' && gitea.ref == 'refs/heads/main' }}
needs: [guard]
runs-on: kg-candidate
timeout-minutes: 45
steps:
- name: Build and deploy isolated candidate
env:
KG_CANDIDATE_ACCESS: ${{ secrets.KG_CANDIDATE_ACCESS }}
run: |
set -eu
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REF" = refs/heads/main
test -n "$KG_CANDIDATE_ACCESS"
python3 - <<'PY'
import json, os, sys
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener
with open(os.environ['GITHUB_EVENT_PATH']) as source:
event = json.load(source)
if event.get('inputs', {}).get('mode') != 'prepare':
sys.exit('candidate workflow mode is not prepare')
data = json.dumps({'run': os.environ['GITHUB_RUN_ID'], 'plan': json.loads(event['inputs']['plan'])}).encode()
request = Request('http://127.0.0.1:38984/prepare', data=data, headers={
'Authorization': 'Bearer ' + os.environ['KG_CANDIDATE_ACCESS'], 'Content-Type': 'application/json'})
opener = build_opener(ProxyHandler({}))
try:
with opener.open(request, timeout=2540) as response:
print(response.read(65536).decode())
except HTTPError as exc:
print(exc.read(4096).decode(), file=sys.stderr)
sys.exit(1)
PY
-11
View File
@@ -33,22 +33,11 @@
worker 完全相同的 `LIBRARY_*` 配置与维护协调器,绝不触碰封存源;任一步失败都
保持维护并写报告,不伪造通过。
- `internal/librarystack`:目标/预备份/维护栈的唯一装配点(同步、恢复、基线、演练共用)。
- **测试/生产 WeKnora 连接可在页面上配置**(`GET /api/v1/weknora-connections`、
`POST /api/v1/weknora-connections/{environment}/test`、
`PUT /api/v1/weknora-connections/{environment}`):API Key 以 AES-GCM 密文存治理库
(主密钥为独立 0600 文件),页面与接口只回显尾 4 位;「测试连接」真实请求该实例的
知识库列表并区分地址不可达 / 密钥无效(401) / 无权限(403) / 成功(库数量),换地址或
换密钥必须测通才能保存。密钥存储抽成 `internal/sealedsecret`,QA-AI 侧改为复用同一实现。
### Changed
- 基线作业的"已有生效版本"判定改为三种状态(own / foreign / none),并在
阶段里写明是否走"只收尾"续作。
- WeKnora 的可达性判定收敛为一份(`weknora.HTTPAllowed`):客户端与监控探活共用,
不再出现「卡片可达、列库失败」。新增 `WEKNORA_ALLOW_PRIVATE_HTTP` 只放行
RFC1918/回环/链路本地 http,公网 http 仍拒绝;生产 `18093` 同网段反代因此可用。
- 「生产知识库绑定」只保留下拉选择,删除手输 ID 的降级入口;保存后回报
「已冻结目标 / 仍可改指向」条数,已冻结的执行目标不被改写。
## 开发快照(首次发布入口:同步授权、目标权威基线与维护能力)
+1 -1
View File
@@ -100,7 +100,7 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
## 配置与安全边界
- 网页服务地址用于控制台探活与配置核验;真正的发布目标由受限发布运行时配置决定,两者不能混为一谈。
- 测试/生产 WeKnora 的地址与 API Key 可在「系统设置 → 测试/生产知识库绑定」里录入:密钥以 AES-GCM 密文存治理库(主密钥是独立 0600 文件),页面与接口只回显尾 4 位,日志、审计与响应都不出现明文。部署期仍可用文件引用作为兜底;示例配置不是真实凭据。
- 密钥通过文件或 secret 引用提供,不写入 Git、网页响应或日志。示例配置不是真实凭据。
- 生产请求与 Release Worker 默认关闭;启用状态必须现场确认。测试处理成功、自动审核或批次锁定都不能绕过生产门禁。
- 来源扫描与取件不应改写原始业务资料;目标知识库的发布、移除和回滚属于独立受控动作。
- 发布与恢复前必须按目标环境准备备份,并核验可恢复性。
-162
View File
@@ -3387,117 +3387,6 @@
}
}
},
"/api/v1/weknora-connections": {
"get": {
"tags": [
"Settings"
],
"operationId": "listWeKnoraConnections",
"summary": "读取测试/生产 WeKnora 连接状态(只回显密钥尾4位)",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/weknora-connections/{environment}/test": {
"post": {
"tags": [
"Settings"
],
"operationId": "testWeKnoraConnection",
"summary": "用真实列库区分地址不可达/密钥无效/无权限/成功(管理员)",
"parameters": [
{
"name": "environment",
"in": "path",
"required": true,
"schema": {
"type": "string",
"enum": [
"test",
"production"
]
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/WeKnoraConnectionTest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/weknora-connections/{environment}": {
"put": {
"tags": [
"Settings"
],
"operationId": "saveWeKnoraConnection",
"summary": "保存测通的连接;密钥密文入库,响应只回尾4位(管理员)",
"parameters": [
{
"$ref": "#/components/parameters/IdempotencyKey"
},
{
"name": "environment",
"in": "path",
"required": true,
"schema": {
"type": "string",
"enum": [
"test",
"production"
]
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/WeKnoraConnectionSave"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/ui-settings": {
"get": {
"tags": [
@@ -5787,57 +5676,6 @@
}
},
"schemas": {
"WeKnoraConnectionTest": {
"type": "object",
"additionalProperties": false,
"properties": {
"endpoint": {
"type": "string"
},
"api_key": {
"type": "string",
"writeOnly": true
},
"key_action": {
"type": "string",
"enum": [
"keep",
"replace",
"clear"
]
}
}
},
"WeKnoraConnectionSave": {
"type": "object",
"additionalProperties": false,
"required": [
"endpoint",
"key_action",
"base_revision"
],
"properties": {
"endpoint": {
"type": "string"
},
"api_key": {
"type": "string",
"writeOnly": true
},
"key_action": {
"type": "string",
"enum": [
"keep",
"replace",
"clear"
]
},
"base_revision": {
"type": "integer",
"minimum": 0
}
}
},
"QAReportedHistoricalRate": {
"type": "object",
"additionalProperties": false,
+8 -59
View File
@@ -26,7 +26,6 @@ import (
"knowledge-governance/internal/qawemail"
"knowledge-governance/internal/serviceverify"
"knowledge-governance/internal/version"
"knowledge-governance/internal/weknoraconn"
)
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
@@ -130,26 +129,17 @@ func run(ctx context.Context, getenv func(string) string) error {
}
return settings.TestWeKnoraBaseURL
}
// 「连接」是页面可配的一等状态:地址 + 写-only 密钥密文入库,其他功能只从
// 这里解析,不再各自读文件凭据,避免出现两个来源。
connectionService := weknoraconn.New(postgresstore.NewStore(pool), weknoraconn.Config{
MasterKeyFile: config.WeKnoraBindingMasterKeyFile,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
})
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
if err != nil {
return err
}
serviceTargetVerifier := serviceverify.New(serviceverify.Config{
TestAPIKeyFile: config.TestWeKnoraAPIKeyFile,
ProductionAPIKeyFile: config.ProductionWeKnoraAPIKeyFile,
TestBaseURLFallback: config.TestWeKnoraBaseURL,
ProductionBaseURLFallback: config.ProductionWeKnoraBaseURL,
TestAllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
ProductionAllowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP,
ProductionAllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
TestAllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
ConnectionResolver: connectionService,
TestAPIKeyFile: config.TestWeKnoraAPIKeyFile,
ProductionAPIKeyFile: config.ProductionWeKnoraAPIKeyFile,
TestBaseURLFallback: config.TestWeKnoraBaseURL,
ProductionBaseURLFallback: config.ProductionWeKnoraBaseURL,
TestAllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
ProductionAllowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP,
})
// 「版本记录」:只读查询面在 API 侧接线;真正的抓取在 worker 侧(未配置来源即未接线)。
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
@@ -195,14 +185,10 @@ func run(ctx context.Context, getenv func(string) string) error {
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
RoutingBindings: postgresstore.NewStore(pool),
KnowledgeBases: connectionAwareBases{service: connectionService, fallback: knowledgeBaseLister, allowPrivate: config.WeKnoraAllowPrivateHTTP},
KnowledgeBases: knowledgeBaseLister,
ProductionBindings: postgresstore.NewStore(pool),
ProductionKnowledgeBases: serviceTargetVerifier,
ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL,
WeKnoraConnections: connectionService,
WeKnoraAllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
WeKnoraTrustTLSProxy: config.WeKnoraBindingTrustTLSProxy,
WeKnoraConnectionResolver: connectionService,
ServiceTargetVerifier: serviceTargetVerifier,
ProductionReleaseRequestsEnabled: config.ProductionReleaseRequestsEnabled,
TestAutoReviewPolicy: config.TestAutoReviewPolicy,
@@ -269,40 +255,3 @@ func run(ctx context.Context, getenv func(string) string) error {
return server.Shutdown(shutdownCtx)
}
}
// connectionAwareBases prefers the admin-managed connection over the bootstrap
// env credential, so 「测试知识库绑定」 lists the very instance the connection card
// probes — one source, not two.
type connectionAwareBases struct {
service *weknoraconn.Service
fallback httpapi.KnowledgeBaseLister
allowPrivate bool
}
func (lister connectionAwareBases) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) {
if endpoint, apiKey, ok := lister.service.Resolve(ctx, weknoraconn.EnvironmentTest); ok {
client, err := weknora.NewClient(weknora.ClientConfig{
BaseURL: endpoint,
APIKey: apiKey,
Timeout: 10 * time.Second,
AllowPrivateHTTP: lister.allowPrivate,
})
if err != nil {
return nil, err
}
return client.ListKnowledgeBases(ctx)
}
if lister.service != nil {
configured, err := lister.service.Configured(ctx, weknoraconn.EnvironmentTest)
if err != nil {
return nil, err
}
if configured {
return nil, errors.New("测试 WeKnora 已保存连接但没有可用密钥:请重新录入 API Key(不会回落到文件里的旧 Key)")
}
}
if lister.fallback == nil {
return nil, errors.New("测试 WeKnora 未配置:请先在系统设置里录入连接")
}
return lister.fallback.ListKnowledgeBases(ctx)
}
-6
View File
@@ -70,12 +70,6 @@ services:
PRODUCTION_WEKNORA_BASE_URL: "${PRODUCTION_WEKNORA_BASE_URL:-}"
PRODUCTION_WEKNORA_API_KEY_FILE: "${PRODUCTION_WEKNORA_API_KEY_FILE:-}"
PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP: "${PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
# 连接(地址 + 写-only 密钥)密文存治理库:主密钥是独立的 0600 文件。
# 生产 18093 是同网段 http 反代,因此需要显式放行私网 http(只放行
# RFC1918/回环/链路本地,公网 http 仍被拒绝)。
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
WEKNORA_BINDING_TRUST_TLS_PROXY: "${WEKNORA_BINDING_TRUST_TLS_PROXY:-false}"
# 数据源发现(系统设置 → 数据源配置):api 用 dws 只读列举钉钉知识库与钉盘空间。
DWS_BIN: /usr/local/bin/dws
DWS_CONFIG_DIR: /data/dws
+44
View File
@@ -0,0 +1,44 @@
# 知识治理候选和批次验收
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
## 发起候选
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
````markdown
```kg-release-v1
{"task":"<发布任务 UUID>","base":"<当前主站 SHA>","sha":"<候选 SHA>","items":[{"task":"<业务任务 UUID>","pr":123}],"extra":[]}
```
````
2. Agent 执行 `candidate_coordinator.py prepare <发布任务 UUID>`。Gitea 核对候选 SHA 的 CI、每个 PR 的落地提交和完整主干范围。需准备候选时,独立 Runner 通过回环入口调度本机执行器。执行器复查发布负责人评论、Gitea 作业证明和当前主站 SHA 后,从准确提交构建镜像并封存。
3. 执行器在独立验收数据库上启动同份归档,核验 API 提交、三个运行镜像、迁移账本、Web 入口及归档摘要。在发布任务和业务任务回填候选版本与地址。对「待测试」业务任务,由执行器转「测试中」。本地候选地址绑定回环,验收 Agent 应和执行器同机,或使用经工程侧验证的私有转发。
4. `candidate_coordinator.py status <发布任务 UUID>` 读取候选回执或对应 Gitea 运行链接。遇到调度结果不明,先从 Gitea 读回运行再决定恢复路径。
## 登记验收
业务验收报告分别放在原业务任务,批次共享功能回归报告放在发布任务。保持测试角色原有输出,使用获授权的验收人或测试 Agent 在对应任务评论追加以下结构化结论。报告应保留用例明细和原始证据链接。该段的 `required` 是本轮登记的必测用例数。
````markdown
```kg-qa-v1
{"sha":"<完整提交 SHA>","bundle":"<归档清单 SHA256>","url":"<候选地址>","verdict":"passed","required":3,"passed":3,"failed":0,"blocked":0}
```
````
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
运维按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)将已验收归档传到主站只读收件目录并核对摘要。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
## 执行器配置
- 版本管理机使用 Python 3.11 及以上、Docker Compose、HiFox CLI 和已有 Gitea 凭据。候选执行器通过 `candidate_worker.py <仓库工作树> <访问文件>` 绑定 `127.0.0.1:38984`,仓库工作树允许读取 `origin/main`。执行器通过现有 Gitea 凭据读取作业与日志。运行账户需能以 `weknora-test` 执行只读版本检查。
- 为候选执行器单独配置 `kg-candidate` Runner。作业使用同机回环网络,通过仓库 Secrets 的 `KG_CANDIDATE_ACCESS` 访问执行器。访问文件由执行器用户持有,内容为独立 64 位十六进制随机凭据。候选作业使用的容器须无宿主 Docker socket 和生产密钥挂载。
- 业务验收使用 `~/.config/knowledge-governance/{qa.json,qa.pgpass,rds-ca.pem}`。复用 `qa_env.py` 的专用 `kg_qa_` RDS 库和角色校验。验收使用专用账号与测试数据。需要验证外部系统的用例须先准备各自的隔离资源。
- 候选执行器采用单验收槽。新批次启动前由运维确认前一批验收结束,按上一批 `ready.json` 中的容器身份停止其 Compose 项目,归档原有配置和回执后释放槽位。保留已验收的归档及审批记录。
## 演练和当前环境
`prepare-candidate.yml` 的 `verify` 模式校验 Gitea 范围与 CI。可在评审分支验证。`prepare` 模式只接受 `main` 的调度。`candidate_release.py build` 和 `candidate_runtime.py <bundle>` 可在隔离开发机演练打包及冒烟。后者使用临时 Docker 数据库,退出后停止演练容器。
主站当前运行的提交必须在候选的 `main` 主干历史内。若现有主站来自分叉的现场分支,先评审并同步运行基线,再以新提交打包。现有临时候选所用的 RDS 库需要先核验身份,主站数据库不用于候选业务验收。
+2 -3
View File
@@ -162,9 +162,8 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
| 分区 | 谁 | 现在要管什么 |
|---|---|---|
| 服务配置 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) |
| 测试知识库绑定 | 管理员 | 顶部连接卡:测试地址 + API Key(测试连接 → 保存;只回显尾4位);下方标注往哪个测试库路由(对内 ≠ 对外) |
| 生产连接 | 管理员 | 生产地址填同网段反代 `http://172.29.151.11:18093`(需要 `WEKNORA_ALLOW_PRIVATE_HTTP=true`),密钥录入后只回显尾4位;停止 `ssh -L 18092` 隧道后仍可用 |
| 生产知识库绑定 | 管理员 | 源库 → 目标库映射(发布写哪个生产库);选项来自生产实例真实库,禁止手填 ID;保存后回报「已冻结 / 仍可改指向」条数 |
| 测试知识库绑定 | 管理员 | 标注往哪个测试库路由(对内 ≠ 对外) |
| 生产知识库绑定 | 管理员 | 源库 → 目标库映射(发布写哪个生产库) |
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
| 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) |
| 成员与角色 | 管理员 | 成员与 viewer/engineer/admin |
-6
View File
@@ -260,12 +260,6 @@
- 规则:只配四项(测试地址、生产地址、生产 ID、知识库 ID);**保存时真探测**,无效才拒;凭据只写不读
- 状态:✅(见 `P41/P42` 与 `ui_settings_*` 测试)
### D1b 连接(地址 + API Key,测试 / 生产各一张)
- 入口:**系统设置 → 测试知识库绑定 / 生产知识库绑定** 分区顶部的连接卡(管理员)
- 步骤:填地址 → 粘贴 API Key(密码框)→ **测试连接** → 成功后才可 **保存连接**;换地址或换密钥必须重新测通
- 期望:密钥密文入库、页面只显示「已配置 · 尾4位」;四态文案分别是 地址不可达 / 密钥无效 / 密钥无权限读取知识库列表 / 可达(读到 N 个知识库);保存不触发任何同步或发布
- 状态:✅(`internal/weknoraconn` 单测 + `internal/httpapi/weknora_connections_test.go`;迁移 000083)
### D2 测试知识库绑定(对内 / 对外)
- 入口:**系统设置 → 测试知识库绑定** → 选库 → 保存绑定
- 期望:保存立即生效并重排"还没上传"的待入库项;对内 ≠ 对外
+22 -43
View File
@@ -31,33 +31,28 @@ type Config struct {
ProductionWeKnoraBaseURL string
ProductionWeKnoraAPIKeyFile string
ProductionWeKnoraAllowDockerHTTP bool
// 连接(地址 + 写-only 密钥)密文存治理库;主密钥是独立的 0600 文件。
WeKnoraBindingMasterKeyFile string
// 允许同网段 http(生产 18093 反代)与可信 TLS 反代后录入密钥。
WeKnoraAllowPrivateHTTP bool
WeKnoraBindingTrustTLSProxy bool
PPScanEnabled bool
PPScanAllowedRoot string
PPScanLedgerPath string
PPScanManifestPath string
TestWeKnoraEnabled bool
TestWeKnoraAllowDockerHTTP bool
TestWeKnoraBaseURL string
MinerUBaseURL string
TestWeKnoraKBID string
InternalRoutingKnowledgeBaseID string
ExternalRoutingKnowledgeBaseID string
TestWeKnoraAPIKeyFile string
GovernanceSpoolRoot string
IngestionSpoolRoot string
ArtifactFetchMaxBytes int64
WorkerLivenessStaleAfter time.Duration
TestWeKnoraHTTPTimeout time.Duration
TestWeKnoraPollInitial time.Duration
TestWeKnoraPollMax time.Duration
TestWeKnoraStalledAfter time.Duration
TestWeKnoraMaxUploadBytes int64
TestAcceptancePolicyVersion string
PPScanEnabled bool
PPScanAllowedRoot string
PPScanLedgerPath string
PPScanManifestPath string
TestWeKnoraEnabled bool
TestWeKnoraAllowDockerHTTP bool
TestWeKnoraBaseURL string
MinerUBaseURL string
TestWeKnoraKBID string
InternalRoutingKnowledgeBaseID string
ExternalRoutingKnowledgeBaseID string
TestWeKnoraAPIKeyFile string
GovernanceSpoolRoot string
IngestionSpoolRoot string
ArtifactFetchMaxBytes int64
WorkerLivenessStaleAfter time.Duration
TestWeKnoraHTTPTimeout time.Duration
TestWeKnoraPollInitial time.Duration
TestWeKnoraPollMax time.Duration
TestWeKnoraStalledAfter time.Duration
TestWeKnoraMaxUploadBytes int64
TestAcceptancePolicyVersion string
// TestAutoReviewPolicy:验收通过后是否自动批准(off|internal|all;默认 internal)。
TestAutoReviewPolicy string
// 目标库所在主机(整库逻辑备份真正执行的地方)。凭据是挂载进来的 0600 ssh
@@ -173,7 +168,6 @@ func Load(getenv func(string) string) (Config, error) {
ProductionReleaseAuthTokenFile: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTH_TOKEN_FILE")),
ProductionWeKnoraBaseURL: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_BASE_URL")),
ProductionWeKnoraAPIKeyFile: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_API_KEY_FILE")),
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
PPScanAllowedRoot: strings.TrimSpace(getenv("PP_SCAN_ALLOWED_ROOT")),
PPScanLedgerPath: strings.TrimSpace(getenv("PP_SCAN_LEDGER_PATH")),
PPScanManifestPath: strings.TrimSpace(getenv("PP_SCAN_MANIFEST_PATH")),
@@ -294,21 +288,6 @@ func Load(getenv func(string) string) (Config, error) {
return Config{}, fmt.Errorf("PRODUCTION_WEKNORA_BASE_URL: %w", err)
}
}
if raw := getenv("WEKNORA_ALLOW_PRIVATE_HTTP"); raw != "" {
config.WeKnoraAllowPrivateHTTP, err = strconv.ParseBool(raw)
if err != nil {
return Config{}, fmt.Errorf("WEKNORA_ALLOW_PRIVATE_HTTP: %w", err)
}
}
if raw := getenv("WEKNORA_BINDING_TRUST_TLS_PROXY"); raw != "" {
config.WeKnoraBindingTrustTLSProxy, err = strconv.ParseBool(raw)
if err != nil {
return Config{}, fmt.Errorf("WEKNORA_BINDING_TRUST_TLS_PROXY: %w", err)
}
}
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
}
if config.ProductionWeKnoraAPIKeyFile != "" {
if config.ProductionWeKnoraBaseURL == "" {
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE requires PRODUCTION_WEKNORA_BASE_URL")
-6
View File
@@ -138,12 +138,6 @@ func classifyRole(method, path string) string {
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
return roleAdmin
}
// Recording an endpoint or an API key changes which instance the whole
// platform talks to, and the key is a credential: read is viewer, every
// write (including 测试连接, which spends the key) is admin.
if strings.HasPrefix(path, "/api/v1/weknora-connections") && method != http.MethodGet {
return roleAdmin
}
// Choosing the production base a release writes into is a production
// authority change, exactly like the annotation binding above.
if path == "/api/v1/production-kb-bindings" && method != http.MethodGet {
+2 -10
View File
@@ -411,16 +411,8 @@ func TestClassifyRoleMatrix(t *testing.T) {
http.MethodPost + " /api/v1/users": roleAdmin,
http.MethodPost + " /api/v1/source-connections/c-1/settings/revisions": roleAdmin,
// Choosing a release's production base is a production authority change.
http.MethodPut + " /api/v1/production-kb-bindings": roleAdmin,
http.MethodGet + " /api/v1/production-kb-bindings": roleViewer,
// An endpoint or an API key decides which instance the platform talks
// to; 测试连接 also spends the credential, so every write is admin.
http.MethodGet + " /api/v1/weknora-connections": roleViewer,
http.MethodPost + " /api/v1/weknora-connections/test/test": roleAdmin,
http.MethodPut + " /api/v1/weknora-connections/production": roleAdmin,
// The test-side annotation binding is the same authority as production.
http.MethodGet + " /api/v1/routing-bindings": roleViewer,
http.MethodPut + " /api/v1/routing-bindings": roleAdmin,
http.MethodPut + " /api/v1/production-kb-bindings": roleAdmin,
http.MethodGet + " /api/v1/production-kb-bindings": roleViewer,
http.MethodPost + " /api/v1/review-candidates/tp-1/decision": roleEngineer,
http.MethodPost + " /api/v1/release-batches/rb-1/seal": roleEngineer,
http.MethodPost + " /api/v1/test-publications/start": roleEngineer,
+13 -90
View File
@@ -6,7 +6,6 @@ import (
"strings"
"time"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
@@ -16,14 +15,7 @@ import (
// such base exists on the target.
type ProductionBindingStore interface {
LoadProductionKBBindings(context.Context) (string, string, string, error)
LoadProductionKBBindingNames(context.Context) (string, string, error)
// SaveProductionKBBindingsWithReplan also re-points 待入库 publications
// that were still waiting for the previous production target.
SaveProductionKBBindingsWithReplan(ctx context.Context, save postgresstore.ProductionBindingSave, previous, effective postgresstore.EffectiveKBIDs, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
// ProductionExecutionCounts reports frozen vs still re-targetable release
// items. A binding change never rewrites a target that was already frozen
// when an execution started; the count is how the page says so.
ProductionExecutionCounts(ctx context.Context) (frozen int, retargetable int, err error)
SaveProductionKBBindings(ctx context.Context, internalID, externalID, updatedBy string, now time.Time) error
}
// ProductionKnowledgeBaseLister enumerates the knowledge bases of the production
@@ -41,44 +33,11 @@ type productionBindingView struct {
ProductionBaseURL string `json:"production_base_url"`
ProductionConnected bool `json:"production_connected"`
ProductionMessage string `json:"production_message"`
// Frozen / Retargetable describe what a binding change can still affect.
Frozen int `json:"frozen"`
Retargetable int `json:"retargetable"`
// Replanned / RetiredDuplicates describe what THIS save did to 待入库 items.
Replanned int `json:"replanned"`
RetiredDuplicates int `json:"retired_duplicates"`
}
// WeKnoraConnectionResolver reads the admin-managed connection for one
// environment. When it answers, that endpoint is the only truth.
type WeKnoraConnectionResolver interface {
Resolve(ctx context.Context, environment string) (endpoint string, apiKey string, ok bool)
Configured(ctx context.Context, environment string) (bool, error)
}
// connectionKeyUnusable distinguishes "a saved row whose key was cleared or
// cannot be decrypted" from "saved and usable, but the endpoint is down". Only
// the former must block a binding save; the latter stays an honest warning.
func (config Config) connectionKeyUnusable(ctx context.Context, environment string) bool {
if config.WeKnoraConnectionResolver == nil {
return false
}
if _, _, ok := config.WeKnoraConnectionResolver.Resolve(ctx, environment); ok {
return false
}
configured, err := config.WeKnoraConnectionResolver.Configured(ctx, environment)
return err == nil && configured
}
// productionTargetBaseURL is the production endpoint the picker reads from: the
// connection card first, the operator-managed 「服务配置 · 生产地址」 second, the
// deployment default last.
// operator-managed 「服务配置 · 生产地址」 first, the deployment default second.
func (config Config) productionTargetBaseURL(ctx context.Context) string {
if config.WeKnoraConnectionResolver != nil {
if endpoint, _, ok := config.WeKnoraConnectionResolver.Resolve(ctx, "production"); ok {
return endpoint
}
}
if settings, err := config.Store.GetActiveUISettings(ctx); err == nil {
if resolved := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); resolved != "" {
return resolved
@@ -96,7 +55,7 @@ func (config Config) productionKnowledgeBases(ctx context.Context) ([]weknora.Kn
}
baseURL := config.productionTargetBaseURL(ctx)
if baseURL == "" {
return nil, "未配置生产地址(系统设置 → 生产知识库绑定 → 连接卡)"
return nil, "未配置生产地址(系统设置 → 服务配置)"
}
bases, err := config.ProductionKnowledgeBases.ListProductionKnowledgeBases(ctx, baseURL)
if err != nil {
@@ -105,40 +64,21 @@ func (config Config) productionKnowledgeBases(ctx context.Context) ([]weknora.Kn
return bases, ""
}
func (config Config) productionBindingPayload(ctx context.Context, replan postgresstore.RoutingBindingReplanResult) (productionBindingView, error) {
func (config Config) productionBindingPayload(ctx context.Context) (productionBindingView, error) {
storedInternal, storedExternal, updatedBy, err := config.ProductionBindings.LoadProductionKBBindings(ctx)
if err != nil {
return productionBindingView{}, err
}
storedInternalName, storedExternalName, err := config.ProductionBindings.LoadProductionKBBindingNames(ctx)
if err != nil {
return productionBindingView{}, err
}
bases, message := config.productionKnowledgeBases(ctx)
names := make(map[string]string, len(bases))
for _, base := range bases {
names[base.ID] = base.Name
}
nameFor := func(id, storedName string) string {
if id == "" {
return ""
}
if message == "" {
return names[id]
}
return storedName
}
frozen, retargetable := 0, 0
if frozenItems, retargetableItems, countsErr := config.ProductionBindings.ProductionExecutionCounts(ctx); countsErr == nil {
frozen, retargetable = frozenItems, retargetableItems
}
return productionBindingView{
InternalKBID: storedInternal, ExternalKBID: storedExternal,
InternalKBName: nameFor(storedInternal, storedInternalName), ExternalKBName: nameFor(storedExternal, storedExternalName),
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
UpdatedBy: updatedBy, ProductionBaseURL: config.productionTargetBaseURL(ctx),
ProductionConnected: message == "", ProductionMessage: message,
Frozen: frozen, Retargetable: retargetable,
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
}, nil
}
@@ -147,7 +87,7 @@ func (config Config) handleProductionBindings(w http.ResponseWriter, r *http.Req
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "production bindings are not configured"})
return
}
view, err := config.productionBindingPayload(r.Context(), postgresstore.RoutingBindingReplanResult{})
view, err := config.productionBindingPayload(r.Context())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
return
@@ -197,16 +137,11 @@ func (config Config) handleSaveProductionBindings(w http.ResponseWriter, r *http
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内与对外必须绑定不同的生产知识库"})
return
}
bases, message := config.productionKnowledgeBases(r.Context())
if message != "" && config.connectionKeyUnusable(r.Context(), "production") {
writeJSON(w, http.StatusConflict, map[string]string{"error": "生产 WeKnora 已保存连接但没有可用密钥:请重新录入 API Key 并测通后再改发布目标"})
return
}
names := make(map[string]string, len(bases))
for _, base := range bases {
names[base.ID] = base.Name
}
if message == "" {
if bases, message := config.productionKnowledgeBases(r.Context()); message == "" {
names := make(map[string]string, len(bases))
for _, base := range bases {
names[base.ID] = base.Name
}
if internal != "" {
if _, ok := names[internal]; !ok {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内绑定的生产知识库在该 WeKnora 实例中不存在"})
@@ -220,23 +155,11 @@ func (config Config) handleSaveProductionBindings(w http.ResponseWriter, r *http
}
}
}
previousInternal, previousExternal, _, err := config.ProductionBindings.LoadProductionKBBindings(r.Context())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
return
}
replan, err := config.ProductionBindings.SaveProductionKBBindingsWithReplan(r.Context(), postgresstore.ProductionBindingSave{
InternalID: internal, ExternalID: external,
InternalName: names[internal], ExternalName: names[external],
UpdatedBy: actorFor(r),
}, postgresstore.EffectiveKBIDs{Internal: previousInternal, External: previousExternal},
postgresstore.EffectiveKBIDs{Internal: internal, External: external},
config.Now().UTC())
if err != nil {
if err := config.ProductionBindings.SaveProductionKBBindings(r.Context(), internal, external, actorFor(r), config.Now().UTC()); err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save production bindings"})
return
}
view, err := config.productionBindingPayload(r.Context(), replan)
view, err := config.productionBindingPayload(r.Context())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
return
+8 -51
View File
@@ -11,44 +11,25 @@ import (
"time"
"knowledge-governance/internal/governance"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
type productionBindingStoreFake struct {
internal, external, saver string
internalName, externalName string
savedInternal, savedExternal string
savedInternalName, savedExternalName string
previousInternal, previousExternal string
effectiveInternal, effectiveExternal string
saveCallCount int
frozen, retargetable int
replanResult postgresstore.RoutingBindingReplanResult
internal, external, saver string
savedInternal, savedExternal string
saveCallCount int
}
func (fake *productionBindingStoreFake) LoadProductionKBBindings(context.Context) (string, string, string, error) {
return fake.internal, fake.external, fake.saver, nil
}
func (fake *productionBindingStoreFake) LoadProductionKBBindingNames(context.Context) (string, string, error) {
return fake.internalName, fake.externalName, nil
}
func (fake *productionBindingStoreFake) SaveProductionKBBindingsWithReplan(_ context.Context, save postgresstore.ProductionBindingSave, previous, effective postgresstore.EffectiveKBIDs, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
fake.savedInternal, fake.savedExternal = save.InternalID, save.ExternalID
fake.savedInternalName, fake.savedExternalName = save.InternalName, save.ExternalName
fake.previousInternal, fake.previousExternal = previous.Internal, previous.External
fake.effectiveInternal, fake.effectiveExternal = effective.Internal, effective.External
fake.saver = save.UpdatedBy
func (fake *productionBindingStoreFake) SaveProductionKBBindings(_ context.Context, internal, external, updatedBy string, _ time.Time) error {
fake.savedInternal, fake.savedExternal = internal, external
fake.saver = updatedBy
fake.saveCallCount++
fake.internal, fake.external = save.InternalID, save.ExternalID
fake.internalName, fake.externalName = save.InternalName, save.ExternalName
return fake.replanResult, nil
}
func (fake *productionBindingStoreFake) ProductionExecutionCounts(context.Context) (int, int, error) {
return fake.frozen, fake.retargetable, nil
fake.internal, fake.external = internal, external
return nil
}
type productionListerFake struct {
@@ -132,9 +113,6 @@ func TestProductionBindingsSaveStoresValidatedPair(t *testing.T) {
if store.savedInternal != "kb-prod-internal" || store.savedExternal != "kb-prod-external" {
t.Fatalf("saved = %q/%q", store.savedInternal, store.savedExternal)
}
if store.savedInternalName != "对内知识库-wiki" || store.savedExternalName != "对外知识库-wiki" {
t.Fatalf("saved names = %q/%q", store.savedInternalName, store.savedExternalName)
}
var envelope struct {
Data productionBindingView `json:"data"`
}
@@ -200,24 +178,3 @@ func TestProductionBindingOptionsReportUnavailableReason(t *testing.T) {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
}
// A cleared production key must not erase the display snapshot: the page keeps
// saying which production bases are bound even when it cannot list them.
func TestProductionBindingsReadFallsBackToStoredNamesWhenUnavailable(t *testing.T) {
store := &productionBindingStoreFake{internal: "kb-prod-internal", external: "kb-prod-external", internalName: "对内知识库-wiki", externalName: "对外知识库-wiki"}
handler := productionBindingsHandler(t, store, &productionListerFake{err: errors.New("no key")}, "https://weknora-test.dobot.cn/")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/production-kb-bindings", nil))
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
var envelope struct {
Data productionBindingView `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
if envelope.Data.InternalKBName != "对内知识库-wiki" || envelope.Data.ExternalKBName != "对外知识库-wiki" || envelope.Data.ProductionConnected {
t.Fatalf("view = %#v", envelope.Data)
}
}
+13 -47
View File
@@ -14,10 +14,10 @@ import (
// (migration 000034). Empty stored values fall back to env defaults.
type RoutingBindingStore interface {
LoadRoutingKBBindings(context.Context) (string, string, string, error)
LoadRoutingKBBindingNames(context.Context) (string, string, error)
SaveRoutingKBBindings(context.Context, string, string, string) error
// SaveRoutingKBBindingsWithReplan also re-points 待入库 publications that
// were still waiting for the previous knowledge base (same transaction).
SaveRoutingKBBindingsWithReplan(ctx context.Context, save postgresstore.RoutingBindingSave, previous, effective postgresstore.EffectiveKBIDs, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
}
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
@@ -31,15 +31,12 @@ type routingBindingView struct {
ExternalKBID string `json:"external_kb_id"`
InternalEnvFallback bool `json:"internal_env_fallback"`
ExternalEnvFallback bool `json:"external_env_fallback"`
// 取消绑定时必须说清「回退到了哪个库」,否则「留空」等于没说。
InternalFallbackKBID string `json:"internal_fallback_kb_id"`
ExternalFallbackKBID string `json:"external_fallback_kb_id"`
InternalBoundByUI bool `json:"internal_bound_by_ui"`
ExternalBoundByUI bool `json:"external_bound_by_ui"`
InternalKBName string `json:"internal_kb_name"`
ExternalKBName string `json:"external_kb_name"`
UpdatedBy string `json:"updated_by"`
WeKnoraConnected bool `json:"weknora_connected"`
InternalBoundByUI bool `json:"internal_bound_by_ui"`
ExternalBoundByUI bool `json:"external_bound_by_ui"`
InternalKBName string `json:"internal_kb_name"`
ExternalKBName string `json:"external_kb_name"`
UpdatedBy string `json:"updated_by"`
WeKnoraConnected bool `json:"weknora_connected"`
// Replanned / RetiredDuplicates describe what THIS save did to 待入库 items
// that had not been uploaded yet. A plain read reports zeros.
Replanned int `json:"replanned"`
@@ -97,33 +94,13 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress
if err != nil {
return routingBindingView{}, err
}
storedInternalName, storedExternalName, err := config.RoutingBindings.LoadRoutingKBBindingNames(ctx)
if err != nil {
return routingBindingView{}, err
}
internal, external := storedInternal, storedExternal
if internal == "" {
internal = config.InternalRoutingKnowledgeBaseID
}
if external == "" {
external = config.ExternalRoutingKnowledgeBaseID
}
nameFor := func(id, storedName string) string {
if id == "" {
return ""
}
if connected {
return names[id]
}
return storedName
}
internal, external := config.effectiveRoutingTargets(ctx)
return routingBindingView{
InternalKBID: internal, ExternalKBID: external,
InternalBoundByUI: storedInternal != "", ExternalBoundByUI: storedExternal != "",
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
InternalFallbackKBID: config.InternalRoutingKnowledgeBaseID, ExternalFallbackKBID: config.ExternalRoutingKnowledgeBaseID,
InternalKBName: nameFor(internal, storedInternalName), ExternalKBName: nameFor(external, storedExternalName),
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
UpdatedBy: updatedBy, WeKnoraConnected: connected,
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
}, nil
@@ -180,10 +157,6 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
// offline saves fall through to the DB so the page never hard-fails, but
// the response reports connected=false honestly.
names, connected := config.routingBindingNames(r.Context())
if !connected && config.connectionKeyUnusable(r.Context(), "test") {
writeJSON(w, http.StatusConflict, map[string]string{"error": "测试 WeKnora 已保存连接但没有可用密钥:请重新录入 API Key 并测通后再改绑定"})
return
}
if connected {
if internal != "" {
if _, ok := names[internal]; !ok {
@@ -209,14 +182,7 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
if effectiveExternal == "" {
effectiveExternal = config.ExternalRoutingKnowledgeBaseID
}
previousInternal, previousExternal := config.effectiveRoutingTargets(r.Context())
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), postgresstore.RoutingBindingSave{
InternalID: internal, ExternalID: external,
InternalName: names[internal], ExternalName: names[external],
UpdatedBy: actorFor(r),
}, postgresstore.EffectiveKBIDs{Internal: previousInternal, External: previousExternal},
postgresstore.EffectiveKBIDs{Internal: effectiveInternal, External: effectiveExternal},
config.Now().UTC())
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), internal, external, effectiveInternal, effectiveExternal, actorFor(r), config.Now().UTC())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
return
+10 -80
View File
@@ -3,7 +3,6 @@ package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
@@ -15,14 +14,11 @@ import (
)
type bindingStoreFake struct {
internal string
external string
internalName string
externalName string
saver string
internal string
external string
saver string
// replan records what the last save asked for, so tests can assert that the
// previous and effective (env-fallback aware) targets were used.
replanPrevious [2]string
// effective (env-fallback aware) targets were used.
replanEffective [2]string
replanResult postgresstore.RoutingBindingReplanResult
replanCallCount int
@@ -32,15 +28,14 @@ func (fake *bindingStoreFake) LoadRoutingKBBindings(context.Context) (string, st
return fake.internal, fake.external, fake.saver, nil
}
func (fake *bindingStoreFake) LoadRoutingKBBindingNames(context.Context) (string, string, error) {
return fake.internalName, fake.externalName, nil
func (fake *bindingStoreFake) SaveRoutingKBBindings(_ context.Context, internal, external, updatedBy string) error {
fake.internal, fake.external, fake.saver = internal, external, updatedBy
return nil
}
func (fake *bindingStoreFake) SaveRoutingKBBindingsWithReplan(_ context.Context, save postgresstore.RoutingBindingSave, previous, effective postgresstore.EffectiveKBIDs, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
fake.internal, fake.external, fake.saver = save.InternalID, save.ExternalID, save.UpdatedBy
fake.internalName, fake.externalName = save.InternalName, save.ExternalName
fake.replanPrevious = [2]string{previous.Internal, previous.External}
fake.replanEffective = [2]string{effective.Internal, effective.External}
func (fake *bindingStoreFake) SaveRoutingKBBindingsWithReplan(_ context.Context, internal, external, effectiveInternal, effectiveExternal, updatedBy string, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
fake.internal, fake.external, fake.saver = internal, external, updatedBy
fake.replanEffective = [2]string{effectiveInternal, effectiveExternal}
fake.replanCallCount++
return fake.replanResult, nil
}
@@ -139,9 +134,6 @@ func TestRoutingBindingsSaveReportsReplanAndUsesEffectiveTargets(t *testing.T) {
if store.replanEffective != [2]string{"kb-in", "env-external"} {
t.Fatalf("effective targets = %#v, want the env fallback on the unbound side", store.replanEffective)
}
if store.replanPrevious != [2]string{"env-internal", "env-external"} {
t.Fatalf("previous targets = %#v, want the pre-save effective pair", store.replanPrevious)
}
var envelope struct {
Data struct {
Replanned int `json:"replanned"`
@@ -171,65 +163,3 @@ func TestRouteCatalogFilesUsesUIBinding(t *testing.T) {
t.Fatalf("capabilities = %#v", envelope.Data)
}
}
// Clearing the API key must not blank the already-saved binding names: the
// page has no live listing then, so it reads the snapshot written at save time.
func TestRoutingBindingsReadFallsBackToStoredNamesWhenDisconnected(t *testing.T) {
store := &bindingStoreFake{internal: "kb-in", external: "kb-ex", internalName: "对内库", externalName: "对外库"}
handler := bindingsTestHandler(t, store, &kbListerFake{err: errors.New("no key")}, "", "")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/routing-bindings", nil))
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
var envelope struct {
Data routingBindingView `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
if envelope.Data.InternalKBName != "对内库" || envelope.Data.ExternalKBName != "对外库" || envelope.Data.WeKnoraConnected {
t.Fatalf("view = %#v", envelope.Data)
}
}
type connectionResolverFake struct {
resolveOK bool
configured bool
}
func (fake connectionResolverFake) Resolve(context.Context, string) (string, string, bool) {
if !fake.resolveOK {
return "", "", false
}
return "http://127.0.0.1:8092", "key", true
}
func (fake connectionResolverFake) Configured(context.Context, string) (bool, error) {
return fake.configured, nil
}
// A saved row whose key was cleared must reject a binding save instead of
// silently falling back to the deployment file key or writing unverifiable ids.
func TestRoutingBindingsSaveRejectsClearedConnectionKey(t *testing.T) {
store := &bindingStoreFake{internal: "kb-old", external: "kb-old-external"}
handler, err := NewHandler(Config{
Store: &fakeJobStore{}, RoutingBindings: store,
KnowledgeBases: &kbListerFake{err: errors.New("no key")},
WeKnoraConnectionResolver: connectionResolverFake{configured: true},
InternalRoutingKnowledgeBaseID: "env-internal", ExternalRoutingKnowledgeBaseID: "env-external",
Now: func() time.Time { return time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC) },
})
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings",
strings.NewReader(`{"internal_kb_id":"kb-new","external_kb_id":"kb-old-external"}`)))
if recorder.Code != http.StatusConflict {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
if store.replanCallCount != 0 {
t.Fatal("a cleared-key save must not reach the store")
}
}
+8 -27
View File
@@ -177,24 +177,14 @@ type Config struct {
// 它不是运行时开关:生产部署不设置它,那次探测仍然直连目标库逐表计数。
LibraryScopeProbe func(ctx context.Context, scope string) (bool, map[string]int64, error)
// LibraryRetentionVersions/Days 是保留策略;都为 0 = 未设置(不生成清理候选)。
LibraryRetentionVersions int
LibraryRetentionDays int
BackupSchedule BackupScheduleStore
BackupHost BackupHost
BackupRuns *BackupRunTracker
ProductionBindings ProductionBindingStore
ProductionKnowledgeBases ProductionKnowledgeBaseLister
ProductionWeKnoraBaseURL string
// WeKnoraConnections 是「连接(地址 + 写-only 密钥)」服务;未接线时三条路由
// 返回 503,页面显示「未接线」而不是假装已配置。
WeKnoraConnections WeKnoraConnections
// WeKnoraAllowPrivateHTTP 允许同网段 http(生产 18093 反代);与客户端、监控
// 探活共用同一个判定。WeKnoraTrustTLSProxy 允许在可信 TLS 反代后录入密钥。
WeKnoraAllowPrivateHTTP bool
WeKnoraTrustTLSProxy bool
// WeKnoraConnectionResolver 读页面保存的连接(地址 + 密钥);页面上显示的
// 生产地址必须来自这里,否则会出现「连接卡写 18093、绑定页还在用旧地址」。
WeKnoraConnectionResolver WeKnoraConnectionResolver
LibraryRetentionVersions int
LibraryRetentionDays int
BackupSchedule BackupScheduleStore
BackupHost BackupHost
BackupRuns *BackupRunTracker
ProductionBindings ProductionBindingStore
ProductionKnowledgeBases ProductionKnowledgeBaseLister
ProductionWeKnoraBaseURL string
ServiceTargetVerifier ServiceTargetVerifier
Now func() time.Time
RequireWeKnoraReady bool
@@ -431,15 +421,6 @@ func NewHandler(config Config) (http.Handler, error) {
}
config.handleSaveProductionBindings(w, r)
})
mux.HandleFunc("GET /api/v1/weknora-connections", func(w http.ResponseWriter, r *http.Request) {
config.handleWeKnoraConnections(w, r)
})
mux.HandleFunc("POST /api/v1/weknora-connections/{environment}/test", func(w http.ResponseWriter, r *http.Request) {
config.handleWeKnoraConnectionTest(w, r)
})
mux.HandleFunc("PUT /api/v1/weknora-connections/{environment}", func(w http.ResponseWriter, r *http.Request) {
config.handleSaveWeKnoraConnection(w, r)
})
mux.HandleFunc("POST /api/v1/source-catalog/route", func(w http.ResponseWriter, r *http.Request) {
routeCatalogFiles(w, r, config)
})
-153
View File
@@ -1,153 +0,0 @@
package httpapi
import (
"context"
"errors"
"net"
"net/http"
"net/url"
"strings"
"knowledge-governance/internal/weknoraconn"
)
// WeKnoraConnections is the connection service the routes below call. It is
// deliberately narrow: the page may read state, run one real test, and save a
// tested configuration — nothing here triggers a sync, a release or a reparse.
type WeKnoraConnections interface {
View(ctx context.Context, environment string) ([]weknoraconn.View, error)
Test(ctx context.Context, environment string, input weknoraconn.TestInput) (weknoraconn.TestResult, error)
Save(ctx context.Context, environment string, input weknoraconn.SaveInput, actor string) (weknoraconn.View, error)
}
func weKnoraConnectionError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, weknoraconn.ErrNotFound):
writeJSON(w, http.StatusNotFound, map[string]string{"error": "未知的 WeKnora 环境(只支持 test / production)"})
case errors.Is(err, weknoraconn.ErrStaleRevision):
writeJSON(w, http.StatusConflict, map[string]string{"error": "连接配置已被他人修改,请重新读取后再保存"})
case errors.Is(err, weknoraconn.ErrNotTested):
writeJSON(w, http.StatusBadRequest, map[string]string{
"code": "weknora_connection_not_tested",
"error": "请先点「测试连接」并成功,才能保存这一侧的配置",
})
case errors.Is(err, weknoraconn.ErrStorageUnavailable):
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "密钥存储不可用:主密钥文件缺失或权限不是 0600,本次未保存任何密钥",
})
case errors.Is(err, weknoraconn.ErrInvalid):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "连接配置不合法:地址必填,且更换地址必须重新录入密钥"})
default:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "WeKnora 连接配置处理失败"})
}
}
// weKnoraSecretTransportWithPrivateHTTP decides whether a plaintext key may be
// accepted on this request. It reuses the QA-AI rule (TLS, loopback, trusted
// TLS proxy + same origin) and adds the one case this deployment needs: the
// operator console itself is reached over plain http on a private address, so a
// same-origin fetch from that console is the only accepted non-TLS shape.
func weKnoraSecretTransportWithPrivateHTTP(config Config, r *http.Request) bool {
if qaAISecretTransport(r, config) {
return true
}
if config.WeKnoraTrustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" &&
r.Header.Get("Sec-Fetch-Site") == "same-origin" {
origin, err := url.Parse(r.Header.Get("Origin"))
if err == nil && origin.Scheme == "https" {
return true
}
}
if !config.WeKnoraAllowPrivateHTTP {
return false
}
if r.Header.Get("Sec-Fetch-Site") != "same-origin" {
return false
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" {
return false
}
parsed, err := url.Parse(origin)
if err != nil || parsed.Host == "" {
return false
}
if !strings.EqualFold(parsed.Host, r.Host) {
return false
}
host := parsed.Hostname()
if ip := net.ParseIP(host); ip != nil {
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
}
return strings.EqualFold(host, "localhost")
}
func (config Config) handleWeKnoraConnections(w http.ResponseWriter, r *http.Request) {
if config.WeKnoraConnections == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
return
}
w.Header().Set("Cache-Control", "no-store")
views, err := config.WeKnoraConnections.View(r.Context(), r.PathValue("environment"))
if err != nil {
weKnoraConnectionError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": views})
}
func (config Config) handleWeKnoraConnectionTest(w http.ResponseWriter, r *http.Request) {
if config.WeKnoraConnections == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
return
}
w.Header().Set("Cache-Control", "no-store")
var input weknoraconn.TestInput
if err := decodeStrictJSON(r, &input); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请求体不合法"})
return
}
if strings.TrimSpace(input.APIKey) != "" && !weKnoraSecretTransportWithPrivateHTTP(config, r) {
writeJSON(w, http.StatusBadRequest, map[string]string{
"code": "weknora_secret_secure_transport_required",
"error": "密钥仅可在有效 HTTPS、本机回环地址,或已放行的私网治理台同源页面录入;本次未保存、未发送密钥",
})
return
}
result, err := config.WeKnoraConnections.Test(r.Context(), r.PathValue("environment"), input)
if err != nil {
weKnoraConnectionError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": result})
}
func (config Config) handleSaveWeKnoraConnection(w http.ResponseWriter, r *http.Request) {
if config.WeKnoraConnections == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora 连接配置未接线"})
return
}
w.Header().Set("Cache-Control", "no-store")
if _, ok := requireOperationID(w, r); !ok {
return
}
var input weknoraconn.SaveInput
if err := decodeStrictJSON(r, &input); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请求体不合法"})
return
}
if input.KeyAction != weknoraconn.KeyActionClear && strings.TrimSpace(input.APIKey) != "" &&
!weKnoraSecretTransportWithPrivateHTTP(config, r) {
writeJSON(w, http.StatusBadRequest, map[string]string{
"code": "weknora_secret_secure_transport_required",
"error": "密钥仅可在有效 HTTPS、本机回环地址,或已放行的私网治理台同源页面录入;本次未保存、未发送密钥",
})
return
}
view, err := config.WeKnoraConnections.Save(r.Context(), r.PathValue("environment"), input, actorFor(r))
if err != nil {
weKnoraConnectionError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": view})
}
@@ -1,174 +0,0 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/weknoraconn"
)
type weknoraConnectionsFake struct {
views []weknoraconn.View
testResult weknoraconn.TestResult
testErr error
savedResult weknoraconn.View
saveErr error
lastTest weknoraconn.TestInput
lastSave weknoraconn.SaveInput
lastActor string
}
func (fake *weknoraConnectionsFake) View(_ context.Context, environment string) ([]weknoraconn.View, error) {
if environment == "" {
return fake.views, nil
}
if !weknoraconn.ValidEnvironment(environment) {
return nil, weknoraconn.ErrNotFound
}
for _, view := range fake.views {
if view.Environment == environment {
return []weknoraconn.View{view}, nil
}
}
return []weknoraconn.View{{Environment: environment, Verification: weknoraconn.VerificationNotConfigured}}, nil
}
func (fake *weknoraConnectionsFake) Test(_ context.Context, environment string, input weknoraconn.TestInput) (weknoraconn.TestResult, error) {
if !weknoraconn.ValidEnvironment(environment) {
return weknoraconn.TestResult{}, weknoraconn.ErrNotFound
}
fake.lastTest = input
return fake.testResult, fake.testErr
}
func (fake *weknoraConnectionsFake) Save(_ context.Context, environment string, input weknoraconn.SaveInput, actor string) (weknoraconn.View, error) {
if !weknoraconn.ValidEnvironment(environment) {
return weknoraconn.View{}, weknoraconn.ErrNotFound
}
fake.lastSave, fake.lastActor = input, actor
return fake.savedResult, fake.saveErr
}
func weknoraConnectionsHandler(t *testing.T, fake *weknoraConnectionsFake, allowPrivate bool) http.Handler {
t.Helper()
handler, err := NewHandler(Config{
Store: &fakeJobStore{},
WeKnoraConnections: fake,
WeKnoraAllowPrivateHTTP: allowPrivate,
Now: func() time.Time { return time.Date(2026, time.November, 22, 7, 0, 0, 0, time.UTC) },
})
if err != nil {
t.Fatalf("NewHandler: %v", err)
}
return handler
}
func TestWeKnoraConnectionRoutesProjectStateWithoutSecrets(t *testing.T) {
fake := &weknoraConnectionsFake{views: []weknoraconn.View{
{Environment: "test", Endpoint: "http://127.0.0.1:8092", KeyConfigured: true, KeyTail: "9f2c", Verification: weknoraconn.OutcomeOK, LibraryCount: 3, Revision: 2, StorageReady: true},
{Environment: "production", Verification: weknoraconn.VerificationNotConfigured, StorageReady: true},
}}
handler := weknoraConnectionsHandler(t, fake, true)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/weknora-connections", nil))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d %s", rec.Code, rec.Body.String())
}
if rec.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("cache-control = %q", rec.Header().Get("Cache-Control"))
}
body := rec.Body.String()
if !strings.Contains(body, `"key_tail":"9f2c"`) || strings.Contains(body, "key_ciphertext") || strings.Contains(body, "api_key") {
t.Fatalf("body leaks or loses key projection: %s", body)
}
}
func TestWeKnoraConnectionTestKeepsFourAnswers(t *testing.T) {
for _, outcome := range []string{weknoraconn.OutcomeOK, weknoraconn.OutcomeUnreachable, weknoraconn.OutcomeKeyInvalid, weknoraconn.OutcomeKeyForbidden} {
fake := &weknoraConnectionsFake{testResult: weknoraconn.TestResult{
Environment: "production", Endpoint: "http://172.29.151.11:18093", Outcome: outcome, Message: outcome,
}}
handler := weknoraConnectionsHandler(t, fake, true)
rec := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/weknora-connections/production/test", strings.NewReader(`{"endpoint":"http://172.29.151.11:18093","key_action":"keep"}`))
request.Header.Set("Content-Type", "application/json")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"outcome":"`+outcome+`"`) {
t.Fatalf("%s: status = %d body = %s", outcome, rec.Code, rec.Body.String())
}
}
}
func TestWeKnoraConnectionTestRejectsPlainKeyFromAPublicOrigin(t *testing.T) {
fake := &weknoraConnectionsFake{}
handler := weknoraConnectionsHandler(t, fake, true)
rec := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/weknora-connections/test/test", strings.NewReader(`{"endpoint":"http://127.0.0.1:8092","api_key":"sk-live","key_action":"replace"}`))
request.Header.Set("Content-Type", "application/json")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "weknora_secret_secure_transport_required") {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String())
}
if fake.lastTest.APIKey != "" {
t.Fatal("a rejected key must never reach the service")
}
}
func TestWeKnoraConnectionTestAcceptsSameOriginPrivateConsole(t *testing.T) {
fake := &weknoraConnectionsFake{testResult: weknoraconn.TestResult{Environment: "test", Outcome: weknoraconn.OutcomeOK}}
handler := weknoraConnectionsHandler(t, fake, true)
rec := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/weknora-connections/test/test", strings.NewReader(`{"endpoint":"http://127.0.0.1:8092","api_key":"sk-live","key_action":"replace"}`))
request.Host = "172.29.151.10:8088"
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Origin", "http://172.29.151.10:8088")
request.Header.Set("Sec-Fetch-Site", "same-origin")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String())
}
if fake.lastTest.APIKey != "sk-live" {
t.Fatalf("service saw key %q", fake.lastTest.APIKey)
}
}
func TestSaveWeKnoraConnectionRequiresIdempotencyKeyAndMapsNotTested(t *testing.T) {
fake := &weknoraConnectionsFake{saveErr: weknoraconn.ErrNotTested}
handler := weknoraConnectionsHandler(t, fake, false)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPut, "/api/v1/weknora-connections/production", strings.NewReader(`{"endpoint":"https://prod.example","key_action":"keep","base_revision":1}`)))
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "Idempotency-Key") {
t.Fatalf("missing idempotency key: %d %s", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPut, "/api/v1/weknora-connections/production", strings.NewReader(`{"endpoint":"https://prod.example","key_action":"keep","base_revision":1}`))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "op-1")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "weknora_connection_not_tested") {
t.Fatalf("not tested mapping: %d %s", rec.Code, rec.Body.String())
}
}
func TestWeKnoraConnectionUnknownEnvironmentIs404(t *testing.T) {
fake := &weknoraConnectionsFake{}
handler := weknoraConnectionsHandler(t, fake, false)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/weknora-connections?environment=staging", nil))
// The list route reads the path value, not the query: unknown environments
// only matter on the per-environment routes.
rec = httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/weknora-connections/staging/test", strings.NewReader(`{"endpoint":"https://x.example","key_action":"keep"}`))
request.Header.Set("Content-Type", "application/json")
handler.ServeHTTP(rec, request)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String())
}
}
var _ = json.Marshal
+1 -6
View File
@@ -13,7 +13,6 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
)
// P10: every configured dependency reports Liveness ("process reachable") and
@@ -198,14 +197,10 @@ func (provider *RealProvider) productionWeKnoraProbe(ctx context.Context, now ti
func (provider *RealProvider) httpProbeOutcome(ctx context.Context, baseURL string, now time.Time) ProbeOutcome {
parsed, err := url.Parse(baseURL)
outcome := ProbeOutcome{ObservedAt: now}
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
if err != nil || parsed.Scheme != "http" && parsed.Scheme != "https" || parsed.Host == "" {
outcome.Reachability = errors.New("探测配置无效")
return outcome
}
if !weknora.HTTPAllowed(baseURL, weknora.HTTPPolicy{AllowPrivateHTTP: provider.allowPrivateHTTP}) {
outcome.Reachability = errors.New("探测配置无效:该地址不被允许(https 或已放行的私网/回环 http)")
return outcome
}
parsed.Path = strings.TrimSuffix(parsed.Path, "/") + "/health"
parsed.RawQuery, parsed.Fragment = "", ""
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
+1 -6
View File
@@ -50,10 +50,6 @@ type RealProviderConfig struct {
// WorkerStaleAfter bounds how long a missing worker heartbeat still counts
// as alive (P10).
WorkerStaleAfter time.Duration
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses. The
// console probes use the very same judgement as the WeKnora client, so a
// card can never say 「可达」 while the client refuses the same URL.
AllowPrivateHTTP bool
}
type RealProvider struct {
@@ -67,7 +63,6 @@ type RealProvider struct {
productionWeKnoraResolver func(ctx context.Context) string
weknoraReadiness func(ctx context.Context) error
workerStaleAfter time.Duration
allowPrivateHTTP bool
health *healthTracker
}
@@ -108,7 +103,7 @@ func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
if stale <= 0 {
stale = time.Minute
}
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, allowPrivateHTTP: config.AllowPrivateHTTP, health: newHealthTracker()}, nil
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, health: newHealthTracker()}, nil
}
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
@@ -1,3 +0,0 @@
DROP TABLE IF EXISTS weknora_environment_connection_tests;
DROP TABLE IF EXISTS weknora_environment_connection_history;
DROP TABLE IF EXISTS weknora_environment_connections;
@@ -1,45 +0,0 @@
-- 连接是「地址 + 写-only 密钥」的一份状态,绑定仍然是「对内/对外目标库」的另一份
-- 状态(routing_kb_bindings / production_kb_bindings)。两者刻意不合并:现场那张
-- 把两者塞进一张表的孤表正是重复列的来源。
--
-- 编号从 000083 起:现场 0.9.0 的 schema_migrations 已登记到 82,而迁移器按号跳过、
-- 没有顺序守卫 —— 76..82 号会被静默丢弃。仓内最大号到 75 不影响 83 的排序与执行。
CREATE TABLE weknora_environment_connections (
environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')),
revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0),
endpoint TEXT NOT NULL DEFAULT '',
key_ciphertext BYTEA NOT NULL DEFAULT '\x',
key_tail VARCHAR(8) NOT NULL DEFAULT '',
verification TEXT NOT NULL DEFAULT 'not_configured'
CHECK (verification IN ('not_configured','ok','unreachable','key_invalid','key_forbidden')),
library_count INTEGER NOT NULL DEFAULT 0 CHECK (library_count >= 0),
checked_at TIMESTAMPTZ,
updated_by TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- 历史只记「有没有配过密钥」,不记尾号也不记密文:一个可审计的时间线不需要能
-- 反推出任何一位密钥。
CREATE TABLE weknora_environment_connection_history (
environment VARCHAR(16) NOT NULL CHECK (environment IN ('test','production')),
revision BIGINT NOT NULL,
endpoint TEXT NOT NULL,
key_configured BOOLEAN NOT NULL,
verification TEXT NOT NULL,
actor TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (environment, revision)
);
-- 「测通才可保存」需要一条可核对的证据:这次测试用的是哪个地址、哪把密钥(只存
-- 指纹)、结论如何。保存时按 (environment, endpoint, key_fingerprint, ok) 匹配。
CREATE TABLE weknora_environment_connection_tests (
environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')),
endpoint TEXT NOT NULL,
key_fingerprint CHAR(64) NOT NULL CHECK (key_fingerprint ~ '^[0-9a-f]{64}$'),
outcome TEXT NOT NULL
CHECK (outcome IN ('ok','unreachable','key_invalid','key_forbidden')),
library_count INTEGER NOT NULL DEFAULT 0 CHECK (library_count >= 0),
message TEXT NOT NULL DEFAULT '',
checked_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
@@ -1,7 +0,0 @@
ALTER TABLE production_kb_bindings
DROP COLUMN IF EXISTS internal_kb_name,
DROP COLUMN IF EXISTS external_kb_name;
ALTER TABLE routing_kb_bindings
DROP COLUMN IF EXISTS internal_kb_name,
DROP COLUMN IF EXISTS external_kb_name;
@@ -1,10 +0,0 @@
-- 「知识库绑定」保存选择时的库名快照:页面在密钥被清除或连接暂时不可达时
-- 仍要显示「对内/对外绑定的是哪个库」,不能退化成裸 ID。库名只是展示缓存,
-- 路由与发布仍以 *_kb_id 为准;换库时保存路径会同步覆盖或清空对应快照。
ALTER TABLE routing_kb_bindings
ADD COLUMN IF NOT EXISTS internal_kb_name TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS external_kb_name TEXT NOT NULL DEFAULT '';
ALTER TABLE production_kb_bindings
ADD COLUMN IF NOT EXISTS internal_kb_name TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS external_kb_name TEXT NOT NULL DEFAULT '';
+12 -28
View File
@@ -11,67 +11,51 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 77 {
t.Fatalf("migration count = %d, want 77", len(migrations))
}
// 84 adds the display-name snapshots written with each binding save, so a
// cleared key keeps showing which base is bound instead of a raw id.
if names := migrations[len(migrations)-1]; names.Version != 84 ||
!strings.Contains(names.UpSQL, "internal_kb_name") ||
!strings.Contains(names.UpSQL, "production_kb_bindings") ||
!strings.Contains(names.DownSQL, "DROP COLUMN IF EXISTS external_kb_name") {
t.Fatalf("migration 84 = %#v", names)
}
// 83 把「连接(地址 + 写-only 密钥)」从文件引用搬进治理库;编号必须 ≥83,
// 因为现场 0.9.0 的 schema_migrations 已到 82,迁移器按号跳过且无顺序守卫。
if connections := migrations[len(migrations)-2]; connections.Version != 83 ||
!strings.Contains(connections.UpSQL, "weknora_environment_connections") ||
!strings.Contains(connections.UpSQL, "key_ciphertext") ||
!strings.Contains(connections.DownSQL, "DROP TABLE IF EXISTS weknora_environment_connections") {
t.Fatalf("migration 83 = %#v", connections)
if len(migrations) != 75 {
t.Fatalf("migration count = %d, want 75", len(migrations))
}
// 75 允许"建立目标权威基线"作为独立业务作业,并与 sync/restore 共用写互斥。
if baseline := migrations[len(migrations)-3]; baseline.Version != 75 ||
if baseline := migrations[len(migrations)-1]; baseline.Version != 75 ||
!strings.Contains(baseline.UpSQL, "library_jobs_write_target") ||
!strings.Contains(baseline.UpSQL, "'baseline'") {
t.Fatalf("migration 75 = %#v", baseline)
}
// 74 记录封存执行器的运行时状态:页面可用性来自真实观测,不来自配置字符串。
if executor := migrations[len(migrations)-4]; executor.Version != 74 ||
if executor := migrations[len(migrations)-2]; executor.Version != 74 ||
!strings.Contains(executor.UpSQL, "library_executor_status") {
t.Fatalf("migration 74 = %#v", executor)
}
// 73 记录死信精确解除:保留上游行,只绑定指纹、重放引用与观测摘要。
if release := migrations[len(migrations)-5]; release.Version != 73 ||
if release := migrations[len(migrations)-3]; release.Version != 73 ||
!strings.Contains(release.UpSQL, "library_dead_letter_releases") {
t.Fatalf("migration 73 = %#v", release)
}
// 72 让维护占用按实例互斥(internal/external 不再各有各的锁)。
if instance := migrations[len(migrations)-6]; instance.Version != 72 ||
if instance := migrations[len(migrations)-4]; instance.Version != 72 ||
!strings.Contains(instance.UpSQL, "library_instance_maintenance") {
t.Fatalf("migration 72 = %#v", instance)
}
// 71 让维护记录能区分实例级维护与仅治理库互斥。
if level := migrations[len(migrations)-7]; level.Version != 71 ||
if level := migrations[len(migrations)-5]; level.Version != 71 ||
!strings.Contains(level.UpSQL, "level") || !strings.Contains(level.UpSQL, "ingress_state") {
t.Fatalf("migration 71 = %#v", level)
}
if maint := migrations[len(migrations)-8]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
if maint := migrations[len(migrations)-6]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
t.Fatalf("migration 70 = %#v", maint)
}
if tail := migrations[len(migrations)-9]; tail.Version != 69 ||
if tail := migrations[len(migrations)-7]; tail.Version != 69 ||
!strings.Contains(tail.UpSQL, "library_jobs_write_target") {
t.Fatalf("migration 69 = %#v", tail)
}
if restore := migrations[len(migrations)-10]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
if restore := migrations[len(migrations)-8]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
t.Fatalf("migration 68 = %#v", restore)
}
if last := migrations[len(migrations)-11]; last.Version != 67 ||
if last := migrations[len(migrations)-9]; last.Version != 67 ||
!strings.Contains(last.UpSQL, "library_release_authorizations") ||
!strings.Contains(last.UpSQL, "params_digest") {
t.Fatalf("migration 67 = %#v", last)
}
if flow := migrations[len(migrations)-12]; flow.Version != 66 ||
if flow := migrations[len(migrations)-10]; flow.Version != 66 ||
!strings.Contains(flow.UpSQL, "CREATE TABLE library_versions") ||
!strings.Contains(flow.UpSQL, "library_jobs_active") {
t.Fatalf("migration 66 = %#v", flow)
@@ -3,7 +3,6 @@ package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
@@ -14,105 +13,43 @@ import (
// right side is the production-side base this table chooses. An empty side
// keeps the historical same-id semantics.
type ProductionBinding struct {
InternalKBID string
ExternalKBID string
InternalKBName string
ExternalKBName string
UpdatedBy string
}
// ProductionBindingSave is one UI save of the production-side targets. Names
// are display snapshots; see RoutingBindingSave for the preserve rules.
type ProductionBindingSave struct {
InternalID string
ExternalID string
InternalName string
ExternalName string
InternalKBID string
ExternalKBID string
UpdatedBy string
}
func (s *Store) loadProductionKBBinding(ctx context.Context) (ProductionBinding, bool, error) {
var binding ProductionBinding
err := s.db.QueryRow(ctx, `
SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by
FROM production_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.InternalKBName, &binding.ExternalKBName, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return ProductionBinding{}, false, nil
}
if err != nil {
return ProductionBinding{}, false, errors.New("load production kb bindings")
}
return binding, true, nil
}
// LoadProductionKBBindings reads the single active mapping row. A missing row
// reads back as unbound rather than an error.
func (s *Store) LoadProductionKBBindings(ctx context.Context) (string, string, string, error) {
binding, _, err := s.loadProductionKBBinding(ctx)
var binding ProductionBinding
err := s.db.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id,updated_by FROM production_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", "", nil
}
if err != nil {
return "", "", "", err
return "", "", "", errors.New("load production kb bindings")
}
return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil
}
// LoadProductionKBBindingNames reads the display snapshot stored with the
// production mapping.
func (s *Store) LoadProductionKBBindingNames(ctx context.Context) (string, string, error) {
binding, _, err := s.loadProductionKBBinding(ctx)
if err != nil {
return "", "", err
}
return binding.InternalKBName, binding.ExternalKBName, nil
}
// SaveProductionKBBindingsWithReplan saves the production mapping and, in the
// SAME transaction, re-points 待入库 publications that were still waiting for
// the previous production target. Only rows already aimed at the previous
// production id move; a test-side publication with the same scope is untouched.
func (s *Store) SaveProductionKBBindingsWithReplan(ctx context.Context, save ProductionBindingSave, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
var result RoutingBindingReplanResult
// SaveProductionKBBindings upserts the mapping row. The knowledge base ids must
// already have been validated against the live production WeKnora by the caller.
func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, externalID, updatedBy string, now time.Time) error {
if now.IsZero() {
return result, errors.New("production binding replan requires a timestamp")
return errors.New("production binding save requires a timestamp")
}
tx, err := s.db.Begin(ctx)
if err != nil {
return result, fmt.Errorf("begin production binding save: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
var previousRow ProductionBinding
err = tx.QueryRow(ctx, `
SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name
FROM production_kb_bindings WHERE id='active' FOR UPDATE`).
Scan(&previousRow.InternalKBID, &previousRow.ExternalKBID, &previousRow.InternalKBName, &previousRow.ExternalKBName)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return result, errors.New("load previous production kb bindings")
}
internalName := preservedBindingName(save.InternalID, save.InternalName, previousRow.InternalKBID, previousRow.InternalKBName)
externalName := preservedBindingName(save.ExternalID, save.ExternalName, previousRow.ExternalKBID, previousRow.ExternalKBName)
if _, err := tx.Exec(ctx, `
INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4,$5,$6)
if _, err := s.db.Exec(ctx, `
INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4)
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
internal_kb_name=EXCLUDED.internal_kb_name,
external_kb_name=EXCLUDED.external_kb_name,
updated_by=EXCLUDED.updated_by,
updated_at=EXCLUDED.updated_at`,
save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil {
return result, errors.New("save production kb bindings")
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
return errors.New("save production kb bindings")
}
result, err = replanPendingPublicationsTx(ctx, tx, previous, effective, now)
if err != nil {
return RoutingBindingReplanResult{}, err
}
if err := tx.Commit(ctx); err != nil {
return result, fmt.Errorf("commit production binding save: %w", err)
}
return result, nil
return nil
}
// ResolveProductionTargetKB maps a publication scope to the production base the
@@ -27,12 +27,6 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
}
store := NewStore(pool)
now := time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC)
save := func(internal, external, updatedBy string, at time.Time) error {
_, err := store.SaveProductionKBBindingsWithReplan(ctx, ProductionBindingSave{
InternalID: internal, ExternalID: external, UpdatedBy: updatedBy,
}, EffectiveKBIDs{}, EffectiveKBIDs{}, at)
return err
}
internal, external, _, err := store.LoadProductionKBBindings(ctx)
if err != nil {
@@ -45,7 +39,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
t.Fatalf("unbound resolve = %q/%v, want the tested base", target, err)
}
if err := save("prod-internal", "prod-external", "admin", now); err != nil {
if err := store.SaveProductionKBBindings(ctx, "prod-internal", "prod-external", "admin", now); err != nil {
t.Fatal(err)
}
if target, err := store.ResolveProductionTargetKB(ctx, "internal", "test-kb"); err != nil || target != "prod-internal" {
@@ -59,7 +53,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
}
// Unbinding one side returns that side to the same-id semantics only.
if err := save("", "prod-external", "admin", now); err != nil {
if err := store.SaveProductionKBBindings(ctx, "", "prod-external", "admin", now); err != nil {
t.Fatal(err)
}
if target, err := store.ResolveProductionTargetKB(ctx, "internal", "test-kb"); err != nil || target != "test-kb" {
@@ -72,7 +66,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
if err != nil || saver != "admin" {
t.Fatalf("updated_by = %q (%v)", saver, err)
}
if err := save("prod-internal", "", "admin", time.Time{}); err == nil {
if err := store.SaveProductionKBBindings(ctx, "prod-internal", "", "admin", time.Time{}); err == nil {
t.Fatal("a save without a timestamp must be rejected")
}
}
+55 -124
View File
@@ -9,68 +9,29 @@ import (
"github.com/jackc/pgx/v5"
)
// EffectiveKBIDs are the knowledge-base ids the platform actually routes to:
// the UI binding when set, the deployment default otherwise.
type EffectiveKBIDs struct {
Internal string
External string
}
// RoutingBindingSave is one UI save of the test-side 对内/对外 targets. Names
// are display snapshots captured while the connected instance still answered;
// an empty name preserves the previous snapshot only when the id is unchanged.
type RoutingBindingSave struct {
InternalID string
ExternalID string
InternalName string
ExternalName string
UpdatedBy string
}
// RoutingBinding is the UI-managed knowledge base binding row. Empty ids mean
// "not bound in the UI"; callers fall back to their environment defaults.
type RoutingBinding struct {
InternalKBID string
ExternalKBID string
InternalKBName string
ExternalKBName string
UpdatedBy string
}
func (s *Store) loadRoutingKBBinding(ctx context.Context) (RoutingBinding, bool, error) {
var binding RoutingBinding
err := s.db.QueryRow(ctx, `
SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by
FROM routing_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.InternalKBName, &binding.ExternalKBName, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return RoutingBinding{}, false, nil
}
if err != nil {
return RoutingBinding{}, false, errors.New("load routing kb bindings")
}
return binding, true, nil
InternalKBID string
ExternalKBID string
UpdatedBy string
}
// LoadRoutingKBBindings reads the single active binding row. A missing row
// reads back as unbound rather than an error.
func (s *Store) LoadRoutingKBBindings(ctx context.Context) (string, string, string, error) {
binding, _, err := s.loadRoutingKBBinding(ctx)
var binding RoutingBinding
err := s.db.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id,updated_by FROM routing_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", "", nil
}
if err != nil {
return "", "", "", err
return "", "", "", errors.New("load routing kb bindings")
}
return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil
}
// LoadRoutingKBBindingNames reads the display snapshot stored with the binding.
func (s *Store) LoadRoutingKBBindingNames(ctx context.Context) (string, string, error) {
binding, _, err := s.loadRoutingKBBinding(ctx)
if err != nil {
return "", "", err
}
return binding.InternalKBName, binding.ExternalKBName, nil
}
// RoutingBindingReplanResult reports what a binding change did to publications
// that were still waiting in 待入库.
type RoutingBindingReplanResult struct {
@@ -82,16 +43,31 @@ type RoutingBindingReplanResult struct {
RetiredDuplicates int
}
// SaveRoutingKBBindings upserts the binding row. Each side is either empty
// (unbind, fall back to env) or a knowledge base id validated by the caller.
func (s *Store) SaveRoutingKBBindings(ctx context.Context, internalID, externalID, updatedBy string) error {
_, err := s.db.Exec(ctx, `
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,NOW())
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
updated_by=EXCLUDED.updated_by,
updated_at=NOW()`, internalID, externalID, updatedBy)
if err != nil {
return errors.New("save routing kb bindings")
}
return nil
}
// replanRetireDuplicatesSQL retires a pending publication whose twin for the
// new knowledge base already exists — the unique key is
// (source_item_version_id, test_kb_id), so the row cannot simply be moved.
// It is scoped to the previous target ($3): a production-side pending row must
// never be retargeted by a test-side binding save.
const replanRetireDuplicatesSQL = `
UPDATE test_publications stale
SET superseded_at = $4, updated_at = $4
SET superseded_at = $3, updated_at = $3
WHERE stale.superseded_at IS NULL
AND stale.test_kb_id = $3
AND stale.test_kb_id <> $1
AND stale.processing_state = 'planned'
AND stale.ingest_state = 'pending'
AND stale.knowledge_id = ''
@@ -110,9 +86,9 @@ WHERE stale.superseded_at IS NULL
// already in flight keeps its frozen target and stays visible in 待入库.
const replanMovePendingSQL = `
UPDATE test_publications pending
SET test_kb_id = $1, updated_at = $4
SET test_kb_id = $1, updated_at = $3
WHERE pending.superseded_at IS NULL
AND pending.test_kb_id = $3
AND pending.test_kb_id <> $1
AND pending.processing_state = 'planned'
AND pending.ingest_state = 'pending'
AND pending.knowledge_id = ''
@@ -126,60 +102,16 @@ WHERE pending.superseded_at IS NULL
AND twin.superseded_at IS NULL)
`
func preservedBindingName(newID, newName, previousID, previousName string) string {
if newID == "" {
return ""
}
if newName != "" {
return newName
}
if newID == previousID {
return previousName
}
return ""
}
// replanPendingPublicationsTx moves only rows aimed at the SAME side's previous
// effective target. Test and production bindings share test_publications, so
// matching on target_scope alone would let one environment steal the other's
// pending rows.
func replanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
var result RoutingBindingReplanResult
for _, scope := range []struct {
name string
from, to string
}{
{"internal", previous.Internal, effective.Internal},
{"external", previous.External, effective.External},
} {
if scope.from == "" || scope.to == "" || scope.from == scope.to {
continue
}
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.to, scope.name, scope.from, now)
if err != nil {
return result, fmt.Errorf("retire duplicate pending publications: %w", err)
}
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.to, scope.name, scope.from, now)
if err != nil {
return result, fmt.Errorf("replan pending publications: %w", err)
}
result.RetiredDuplicates += int(retired.RowsAffected())
result.Replanned += int(moved.RowsAffected())
}
return result, nil
}
// SaveRoutingKBBindingsWithReplan saves the binding and, in the SAME
// transaction, re-points 待入库 items that were still waiting for the old
// knowledge base. Without this, changing the binding left every pending
// publication aimed at the previous (possibly deleted) KB, and re-marking the
// file created a SECOND publication instead of moving the first.
//
// previous/effective are the ids this environment actually routed to before
// and after the save (the saved binding, or the deployment default when a side
// is unbound). An empty previous target skips that scope: there is no reliable
// row to move.
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, save RoutingBindingSave, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
// effectiveInternal/effectiveExternal are the ids the platform actually routes
// to (the saved binding, or the deployment default when a side is unbound);
// an empty effective id means that scope cannot be routed and is skipped.
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (RoutingBindingReplanResult, error) {
var result RoutingBindingReplanResult
if now.IsZero() {
return result, errors.New("binding replan requires a timestamp")
@@ -189,34 +121,33 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, save Routin
return result, fmt.Errorf("begin routing binding save: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
var previousRow RoutingBinding
err = tx.QueryRow(ctx, `
SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name
FROM routing_kb_bindings WHERE id='active' FOR UPDATE`).
Scan(&previousRow.InternalKBID, &previousRow.ExternalKBID, &previousRow.InternalKBName, &previousRow.ExternalKBName)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return result, errors.New("load previous routing kb bindings")
}
internalName := preservedBindingName(save.InternalID, save.InternalName, previousRow.InternalKBID, previousRow.InternalKBName)
externalName := preservedBindingName(save.ExternalID, save.ExternalName, previousRow.ExternalKBID, previousRow.ExternalKBName)
if _, err := tx.Exec(ctx, `
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4,$5,$6)
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4)
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
internal_kb_name=EXCLUDED.internal_kb_name,
external_kb_name=EXCLUDED.external_kb_name,
updated_by=EXCLUDED.updated_by,
updated_at=EXCLUDED.updated_at`,
save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil {
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
return result, errors.New("save routing kb bindings")
}
result, err = replanPendingPublicationsTx(ctx, tx, previous, effective, now)
if err != nil {
return RoutingBindingReplanResult{}, err
for _, scope := range []struct{ name, kbID string }{
{"internal", effectiveInternal},
{"external", effectiveExternal},
} {
if scope.kbID == "" {
continue
}
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.kbID, scope.name, now)
if err != nil {
return result, fmt.Errorf("retire duplicate pending publications: %w", err)
}
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.kbID, scope.name, now)
if err != nil {
return result, fmt.Errorf("replan pending publications: %w", err)
}
result.RetiredDuplicates += int(retired.RowsAffected())
result.Replanned += int(moved.RowsAffected())
}
if err := tx.Commit(ctx); err != nil {
return result, fmt.Errorf("commit routing binding save: %w", err)
@@ -33,21 +33,18 @@ INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_ur
('item-in','conn-replan','n-in',repeat('b',64),'docs/in.docx','in.docx','document','locator:r1','internal','configured_scope'),
('item-ext','conn-replan','n-ext',repeat('b',64),'docs/ext.docx','ext.docx','document','locator:r2','external','configured_scope'),
('item-sent','conn-replan','n-sent',repeat('b',64),'docs/sent.docx','sent.docx','document','locator:r3','internal','configured_scope'),
('item-dup','conn-replan','n-dup',repeat('b',64),'docs/dup.docx','dup.docx','document','locator:r4','internal','configured_scope'),
('item-prod','conn-replan','n-prod',repeat('b',64),'docs/prod.docx','prod.docx','document','locator:r5','internal','configured_scope');
('item-dup','conn-replan','n-dup',repeat('b',64),'docs/dup.docx','dup.docx','document','locator:r4','internal','configured_scope');
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
('v-in','item-in','locator:r1',NULL,'unknown'),
('v-ext','item-ext','locator:r2',NULL,'unknown'),
('v-sent','item-sent','locator:r3',NULL,'unknown'),
('v-dup','item-dup','locator:r4',NULL,'unknown'),
('v-prod','item-prod','locator:r5',NULL,'unknown');
('v-dup','item-dup','locator:r4',NULL,'unknown');
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
('pub-in','v-in','kb-old-internal','planned','pending','internal'),
('pub-ext','v-ext','kb-old-external','planned','pending','external'),
('pub-sent','v-sent','kb-old-internal','pending','uploaded','internal'),
('pub-dup-old','v-dup','kb-old-internal','planned','pending','internal'),
('pub-dup-new','v-dup','kb-new-internal','planned','pending','internal'),
('pub-prod','v-prod','prod-old-internal','planned','pending','internal');
('pub-dup-new','v-dup','kb-new-internal','planned','pending','internal');
INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
('job-sent','test.upload','{"publication_id":"pub-sent"}'::jsonb,'completed','test-start:pub-sent');
`); err != nil {
@@ -56,11 +53,7 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
store := NewStore(pool)
now := time.Date(2026, time.October, 8, 7, 0, 0, 0, time.UTC)
result, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
InternalID: "kb-new-internal", ExternalID: "kb-new-external",
InternalName: "新对内库", ExternalName: "新对外库", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "kb-old-internal", External: "kb-old-external"},
EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now)
result, err := store.SaveRoutingKBBindingsWithReplan(ctx, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now)
if err != nil {
t.Fatalf("SaveRoutingKBBindingsWithReplan() error = %v", err)
}
@@ -102,39 +95,9 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
if states["pub-dup-old"].kb != "kb-old-internal" || !states["pub-dup-old"].superseded {
t.Fatalf("the duplicate stale row must be retired: %#v", states["pub-dup-old"])
}
// A production-side pending row with the same scope must not be stolen by
// the test-side binding change.
if states["pub-prod"].kb != "prod-old-internal" || states["pub-prod"].superseded {
t.Fatalf("production pending row was retargeted by a test save: %#v", states["pub-prod"])
}
// Production save moves only the row aimed at its previous target.
prodResult, err := store.SaveProductionKBBindingsWithReplan(ctx, ProductionBindingSave{
InternalID: "prod-new-internal", ExternalID: "prod-new-external",
InternalName: "生产对内库", ExternalName: "生产对外库", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "prod-old-internal", External: "prod-old-external"},
EffectiveKBIDs{Internal: "prod-new-internal", External: "prod-new-external"}, now)
if err != nil {
t.Fatal(err)
}
if prodResult.Replanned != 1 || prodResult.RetiredDuplicates != 0 {
t.Fatalf("production replan result = %#v, want 1 moved", prodResult)
}
prodState := states["pub-prod"]
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod'`).Scan(&prodState.kb); err != nil {
t.Fatal(err)
}
states["pub-prod"] = prodState
if states["pub-prod"].kb != "prod-new-internal" {
t.Fatalf("production pending row = %q", states["pub-prod"].kb)
}
// Re-saving the same binding is a no-op: nothing left to move or retire.
again, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
InternalID: "kb-new-internal", ExternalID: "kb-new-external",
InternalName: "新对内库", ExternalName: "新对外库", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now)
again, err := store.SaveRoutingKBBindingsWithReplan(ctx, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now)
if err != nil {
t.Fatal(err)
}
@@ -149,41 +112,4 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
if internal != "kb-new-internal" || external != "kb-new-external" || updatedBy != "tester" {
t.Fatalf("binding row = %s / %s / %s", internal, external, updatedBy)
}
var internalName, externalName string
if err = pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`).
Scan(&internalName, &externalName); err != nil {
t.Fatal(err)
}
if internalName != "新对内库" || externalName != "新对外库" {
t.Fatalf("binding names = %q / %q", internalName, externalName)
}
// A disconnected/cleared-key save carries no live names. Unchanged ids keep
// the snapshot; a changed id must not inherit the old name.
if _, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
InternalID: "kb-new-internal", ExternalID: "kb-new-external", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`).
Scan(&internalName, &externalName); err != nil {
t.Fatal(err)
}
if internalName != "新对内库" || externalName != "新对外库" {
t.Fatalf("same-id save lost the name snapshot: %q / %q", internalName, externalName)
}
if _, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
InternalID: "kb-new-internal", ExternalID: "kb-other-external", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-other-external"}, now); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`).
Scan(&internalName, &externalName); err != nil {
t.Fatal(err)
}
if internalName != "新对内库" || externalName != "" {
t.Fatalf("changed id inherited a stale name: %q / %q", internalName, externalName)
}
}
@@ -52,20 +52,15 @@ func TestProcessingConfirmationMigrationBackfillsHistoricalExternalPublication(t
t.Fatal(err)
}
defer pool.Close()
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
latest := int(migrations[len(migrations)-1].Version)
if err := ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
// Roll back by the applied ledger, not by number: migrations are not
// contiguous (76-82 are deliberately absent), so a numeric countdown would
// remove the earlier schema this test needs.
for {
var latest int
if err := pool.QueryRow(ctx, `SELECT MAX(version)::INTEGER FROM schema_migrations`).Scan(&latest); err != nil {
t.Fatal(err)
}
if latest <= 10 {
break
}
for version := latest; version > 10; version-- {
if err := RollbackLatestMigration(ctx, pool); err != nil {
t.Fatal(err)
}
@@ -1,203 +0,0 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
)
// WeKnoraConnection is one environment's 地址 + 写-only 密钥. The ciphertext is
// opened only in the service layer; everything below this line treats it as an
// opaque blob so no query result can accidentally be rendered as a secret.
type WeKnoraConnection struct {
Environment string
Revision int64
Endpoint string
KeyCiphertext []byte
KeyTail string
Verification string
LibraryCount int
CheckedAt *time.Time
UpdatedBy string
UpdatedAt time.Time
}
// WeKnoraConnectionTest is the evidence a save needs: which endpoint, which key
// (fingerprint only) and what the last real listing said.
type WeKnoraConnectionTest struct {
Environment string
Endpoint string
KeyFingerprint string
Outcome string
LibraryCount int
Message string
CheckedAt time.Time
}
// LoadWeKnoraConnections reads both environments. A missing row is simply absent
// from the result: 「未配置」 is a state, not an error.
func (s *Store) LoadWeKnoraConnections(ctx context.Context) ([]WeKnoraConnection, error) {
rows, err := s.db.Query(ctx, `
SELECT environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at
FROM weknora_environment_connections
ORDER BY environment`)
if err != nil {
return nil, errors.New("load weknora connections")
}
defer rows.Close()
connections := make([]WeKnoraConnection, 0, 2)
for rows.Next() {
var connection WeKnoraConnection
if err := rows.Scan(&connection.Environment, &connection.Revision, &connection.Endpoint,
&connection.KeyCiphertext, &connection.KeyTail, &connection.Verification,
&connection.LibraryCount, &connection.CheckedAt, &connection.UpdatedBy, &connection.UpdatedAt); err != nil {
return nil, errors.New("load weknora connections")
}
connections = append(connections, connection)
}
if rows.Err() != nil {
return nil, errors.New("load weknora connections")
}
return connections, nil
}
// LoadWeKnoraConnection reads one environment. The boolean is false when the
// environment was never configured.
func (s *Store) LoadWeKnoraConnection(ctx context.Context, environment string) (WeKnoraConnection, bool, error) {
var connection WeKnoraConnection
err := s.db.QueryRow(ctx, `
SELECT environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at
FROM weknora_environment_connections WHERE environment=$1`, environment).
Scan(&connection.Environment, &connection.Revision, &connection.Endpoint,
&connection.KeyCiphertext, &connection.KeyTail, &connection.Verification,
&connection.LibraryCount, &connection.CheckedAt, &connection.UpdatedBy, &connection.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return WeKnoraConnection{}, false, nil
}
if err != nil {
return WeKnoraConnection{}, false, errors.New("load weknora connection")
}
return connection, true, nil
}
// SaveWeKnoraConnection writes one revision and its history row in a single
// transaction. The advisory lock is per environment so two concurrent saves
// cannot both pick the same revision.
func (s *Store) SaveWeKnoraConnection(ctx context.Context, connection WeKnoraConnection, now time.Time) error {
if now.IsZero() {
return errors.New("weknora connection save requires a timestamp")
}
tx, err := s.db.Begin(ctx)
if err != nil {
return fmt.Errorf("begin weknora connection save: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext('weknora_connection:'||$1))`, connection.Environment); err != nil {
return fmt.Errorf("lock weknora connection: %w", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO weknora_environment_connections(environment,revision,endpoint,key_ciphertext,key_tail,verification,library_count,checked_at,updated_by,updated_at)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
ON CONFLICT(environment) DO UPDATE SET
revision=EXCLUDED.revision,
endpoint=EXCLUDED.endpoint,
key_ciphertext=EXCLUDED.key_ciphertext,
key_tail=EXCLUDED.key_tail,
verification=EXCLUDED.verification,
library_count=EXCLUDED.library_count,
checked_at=EXCLUDED.checked_at,
updated_by=EXCLUDED.updated_by,
updated_at=EXCLUDED.updated_at`,
connection.Environment, connection.Revision, connection.Endpoint, connection.KeyCiphertext,
connection.KeyTail, connection.Verification, connection.LibraryCount, connection.CheckedAt,
connection.UpdatedBy, now); err != nil {
return errors.New("save weknora connection")
}
if _, err := tx.Exec(ctx, `
INSERT INTO weknora_environment_connection_history(environment,revision,endpoint,key_configured,verification,actor,created_at)
VALUES($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT(environment,revision) DO NOTHING`,
connection.Environment, connection.Revision, connection.Endpoint, len(connection.KeyCiphertext) > 0,
connection.Verification, connection.UpdatedBy, now); err != nil {
return errors.New("record weknora connection history")
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit weknora connection save: %w", err)
}
return nil
}
// SaveWeKnoraConnectionTest stores the outcome of the real listing a save will
// later point at. Only the key fingerprint is kept — never the key.
func (s *Store) SaveWeKnoraConnectionTest(ctx context.Context, result WeKnoraConnectionTest, now time.Time) error {
if now.IsZero() {
return errors.New("weknora connection test requires a timestamp")
}
if _, err := s.db.Exec(ctx, `
INSERT INTO weknora_environment_connection_tests(environment,endpoint,key_fingerprint,outcome,library_count,message,checked_at)
VALUES($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT(environment) DO UPDATE SET
endpoint=EXCLUDED.endpoint,
key_fingerprint=EXCLUDED.key_fingerprint,
outcome=EXCLUDED.outcome,
library_count=EXCLUDED.library_count,
message=EXCLUDED.message,
checked_at=EXCLUDED.checked_at`,
result.Environment, result.Endpoint, result.KeyFingerprint, result.Outcome,
result.LibraryCount, result.Message, now); err != nil {
return errors.New("save weknora connection test")
}
return nil
}
// LoadWeKnoraConnectionTest reads the last test for one environment.
func (s *Store) LoadWeKnoraConnectionTest(ctx context.Context, environment string) (WeKnoraConnectionTest, bool, error) {
var result WeKnoraConnectionTest
err := s.db.QueryRow(ctx, `
SELECT environment,endpoint,key_fingerprint,outcome,library_count,message,checked_at
FROM weknora_environment_connection_tests WHERE environment=$1`, environment).
Scan(&result.Environment, &result.Endpoint, &result.KeyFingerprint, &result.Outcome,
&result.LibraryCount, &result.Message, &result.CheckedAt)
if errors.Is(err, pgx.ErrNoRows) {
return WeKnoraConnectionTest{}, false, nil
}
if err != nil {
return WeKnoraConnectionTest{}, false, errors.New("load weknora connection test")
}
return result, true, nil
}
// UpdateWeKnoraConnectionVerification refreshes the card state without touching
// the saved endpoint or ciphertext.
func (s *Store) UpdateWeKnoraConnectionVerification(ctx context.Context, environment, verification string, libraryCount int, checkedAt time.Time, now time.Time) error {
if _, err := s.db.Exec(ctx, `
UPDATE weknora_environment_connections
SET verification=$2, library_count=$3, checked_at=$4, updated_at=$5
WHERE environment=$1`, environment, verification, libraryCount, checkedAt, now); err != nil {
return errors.New("update weknora connection verification")
}
return nil
}
// ProductionExecutionCounts reports, for executions that are still in flight,
// how many items already have a frozen production target and how many do not yet.
// A production binding change never rewrites the frozen ones: an execution that
// already started keeps the knowledge base it was authorized against. Lifetime
// counts are deliberately excluded — completed executions are history, not
// something a binding change could still affect.
func (s *Store) ProductionExecutionCounts(ctx context.Context) (int, int, error) {
var frozen, retargetable int
if err := s.db.QueryRow(ctx, `
SELECT
COUNT(*) FILTER (WHERE item.target_knowledge_base_id <> ''),
COUNT(*) FILTER (WHERE item.target_knowledge_base_id = '')
FROM release_item_executions item
JOIN release_executions execution ON execution.id = item.release_execution_id
WHERE execution.state IN ('pending','running')`).Scan(&frozen, &retargetable); err != nil {
return 0, 0, errors.New("load production execution counts")
}
return frozen, retargetable, nil
}
@@ -1,134 +0,0 @@
package postgres
import (
"context"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// 连接(地址 + 写-only 密钥)是新的持久状态:一环境一行、修订递增、历史只记
// 「有没有配过密钥」。测试必须证明 000083 真能 up/down,而不是只证明 SQL 解析通过。
func TestWeKnoraConnectionsMigrationUpDownAndStore(t *testing.T) {
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if databaseURL == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, databaseURL)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err = ApplyMigrations(ctx, pool); err != nil {
t.Fatalf("apply migrations: %v", err)
}
var applied bool
if err = pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = 83)").Scan(&applied); err != nil || !applied {
t.Fatalf("migration 83 not recorded: %v %v", applied, err)
}
store := NewStore(pool)
now := time.Date(2026, time.November, 22, 7, 0, 0, 0, time.UTC)
checked := now.Add(-time.Minute)
connection := WeKnoraConnection{
Environment: "production",
Revision: 2,
Endpoint: "http://172.29.151.11:18093",
KeyCiphertext: []byte{1, 2, 3, 4},
KeyTail: "9f2c",
Verification: "ok",
LibraryCount: 4,
CheckedAt: &checked,
UpdatedBy: "admin",
}
if err := store.SaveWeKnoraConnection(ctx, connection, now); err != nil {
t.Fatalf("save connection: %v", err)
}
loaded, exists, err := store.LoadWeKnoraConnection(ctx, "production")
if err != nil || !exists {
t.Fatalf("load connection: %v %v", exists, err)
}
if loaded.Endpoint != connection.Endpoint || loaded.Revision != 2 || loaded.KeyTail != "9f2c" || string(loaded.KeyCiphertext) != string(connection.KeyCiphertext) {
t.Fatalf("loaded = %+v", loaded)
}
var configured bool
var actor string
if err := pool.QueryRow(ctx, `SELECT key_configured,actor FROM weknora_environment_connection_history WHERE environment='production' AND revision=2`).Scan(&configured, &actor); err != nil {
t.Fatalf("history row: %v", err)
}
if !configured || actor != "admin" {
t.Fatalf("history = %v %q", configured, actor)
}
// 历史里不能出现尾号或密文:只有布尔。
var historyColumns int
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='weknora_environment_connection_history' AND column_name IN ('key_tail','key_ciphertext')`).Scan(&historyColumns); err != nil {
t.Fatal(err)
}
if historyColumns != 0 {
t.Fatalf("history table exposes %d secret columns", historyColumns)
}
// 测试证据:同一环境只保留最后一次,且只存密钥指纹。
fingerprint := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
if err := store.SaveWeKnoraConnectionTest(ctx, WeKnoraConnectionTest{
Environment: "production", Endpoint: connection.Endpoint, KeyFingerprint: fingerprint,
Outcome: "ok", LibraryCount: 4, Message: "接口可达",
}, now); err != nil {
t.Fatalf("save test evidence: %v", err)
}
proof, found, err := store.LoadWeKnoraConnectionTest(ctx, "production")
if err != nil || !found || proof.KeyFingerprint != fingerprint || proof.Outcome != "ok" {
t.Fatalf("load test evidence = %+v %v %v", proof, found, err)
}
// 冻结/未冻结计数按 target_knowledge_base_id 判定,不能用 IS NULL。
frozen, retargetable, err := store.ProductionExecutionCounts(ctx)
if err != nil {
t.Fatalf("production execution counts: %v", err)
}
if frozen != 0 || retargetable != 0 {
t.Fatalf("empty execution counts = %d/%d", frozen, retargetable)
}
// down 必须只删这三张新表,不碰既有绑定表。Roll 84 first so this test
// keeps exercising 83 specifically as later migrations land.
for {
var latest int64
if err := pool.QueryRow(ctx, "SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1").Scan(&latest); err != nil {
t.Fatalf("read latest migration: %v", err)
}
if latest == 83 {
break
}
if latest < 83 {
t.Fatalf("migration 83 is no longer applied (latest %d)", latest)
}
if err := RollbackLatestMigration(ctx, pool); err != nil {
t.Fatalf("rollback migration %d: %v", latest, err)
}
}
if err := RollbackLatestMigration(ctx, pool); err != nil {
t.Fatalf("rollback 83: %v", err)
}
for _, table := range []string{"weknora_environment_connections", "weknora_environment_connection_history", "weknora_environment_connection_tests"} {
var present bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=current_schema() AND table_name=$1)`, table).Scan(&present); err != nil {
t.Fatal(err)
}
if present {
t.Fatalf("%s survived the down migration", table)
}
}
for _, table := range []string{"routing_kb_bindings", "production_kb_bindings"} {
var present bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=current_schema() AND table_name=$1)`, table).Scan(&present); err != nil {
t.Fatal(err)
}
if !present {
t.Fatalf("%s must not be dropped by migration 83 down", table)
}
}
}
+1 -49
View File
@@ -48,43 +48,6 @@ type ClientConfig struct {
Timeout time.Duration
MaxResponseBytes int64
AllowDockerHTTP bool
// AllowPrivateHTTP relaxes the http-only rule for RFC1918, link-local and
// ULA literals. It exists because the production instance sits behind a
// same-LAN nginx that speaks plain http; https stays the default and any
// public http host is still refused.
AllowPrivateHTTP bool
}
// HTTPPolicy is the single reachability judgement shared by the WeKnora client
// and the console probes: two callers must never disagree about whether a
// configured endpoint is acceptable.
type HTTPPolicy struct {
AllowPrivateHTTP bool
AllowDockerHTTP bool
}
// HTTPAllowed reports whether baseURL may be called at all. https is always
// allowed; http only for loopback, an opted-in private address, or (legacy)
// a single-label docker host.
func HTTPAllowed(rawURL string, policy HTTPPolicy) bool {
parsed, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || parsed.Host == "" || parsed.User != nil {
return false
}
switch parsed.Scheme {
case "https":
return true
case "http":
host := parsed.Hostname()
if isLoopbackHost(host) {
return true
}
if policy.AllowPrivateHTTP && isPrivateHost(host) {
return true
}
return policy.AllowDockerHTTP && isSingleLabelDockerHost(host)
}
return false
}
type Client struct {
@@ -102,7 +65,7 @@ func NewClient(config ClientConfig) (*Client, error) {
if baseURL.Scheme == "" || baseURL.Host == "" || baseURL.User != nil || baseURL.RawQuery != "" || baseURL.Fragment != "" {
return nil, errors.New("invalid WeKnora base URL")
}
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
if baseURL.Scheme != "https" && !(baseURL.Scheme == "http" && (isLoopbackHost(baseURL.Hostname()) || (config.AllowDockerHTTP && isSingleLabelDockerHost(baseURL.Hostname())))) {
return nil, errors.New("WeKnora base URL must use HTTPS")
}
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
@@ -136,17 +99,6 @@ func isLoopbackHost(host string) bool {
return ip != nil && ip.IsLoopback()
}
// isPrivateHost reports the addresses a same-LAN deployment legitimately uses:
// RFC1918, link-local and IPv6 ULA. A public name is never private, so opting
// in cannot widen the client to the internet.
func isPrivateHost(host string) bool {
ip := net.ParseIP(host)
if ip == nil {
return false
}
return ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()
}
func isSingleLabelDockerHost(host string) bool {
if host == "" || strings.Contains(host, ".") || net.ParseIP(host) != nil || len(host) > 63 {
return false
@@ -1,44 +0,0 @@
package weknora
import "testing"
func TestHTTPAllowedSharesOneJudgement(t *testing.T) {
cases := []struct {
name string
url string
policy HTTPPolicy
want bool
}{
{"https always", "https://weknora.example", HTTPPolicy{}, true},
{"loopback http", "http://127.0.0.1:8092", HTTPPolicy{}, true},
{"localhost http", "http://localhost:8092", HTTPPolicy{}, true},
{"private http refused by default", "http://172.29.151.11:18093", HTTPPolicy{}, false},
{"private http allowed when opted in", "http://172.29.151.11:18093", HTTPPolicy{AllowPrivateHTTP: true}, true},
{"rfc1918 /8", "http://10.1.2.3", HTTPPolicy{AllowPrivateHTTP: true}, true},
{"rfc1918 /16", "http://192.168.1.10", HTTPPolicy{AllowPrivateHTTP: true}, true},
{"link-local", "http://169.254.10.10", HTTPPolicy{AllowPrivateHTTP: true}, true},
{"public http still refused", "http://203.0.113.9", HTTPPolicy{AllowPrivateHTTP: true}, false},
{"public name still refused", "http://weknora.example", HTTPPolicy{AllowPrivateHTTP: true}, false},
{"docker single label opt-in", "http://weknora", HTTPPolicy{AllowDockerHTTP: true}, true},
{"docker single label off", "http://weknora", HTTPPolicy{}, false},
{"credentials refused", "http://user:pass@127.0.0.1:8092", HTTPPolicy{}, false},
{"empty host", "http://", HTTPPolicy{}, false},
{"other scheme", "ftp://127.0.0.1", HTTPPolicy{}, false},
}
for _, testCase := range cases {
if got := HTTPAllowed(testCase.url, testCase.policy); got != testCase.want {
t.Fatalf("%s: HTTPAllowed(%q, %+v) = %v, want %v", testCase.name, testCase.url, testCase.policy, got, testCase.want)
}
}
}
func TestNewClientAcceptsPrivateHTTPOnlyWhenOptedIn(t *testing.T) {
base := ClientConfig{BaseURL: "http://172.29.151.11:18093", APIKey: "k", Timeout: 1}
if _, err := NewClient(base); err == nil {
t.Fatal("private http must be refused without the opt-in")
}
base.AllowPrivateHTTP = true
if _, err := NewClient(base); err != nil {
t.Fatalf("private http must be accepted with the opt-in: %v", err)
}
}
+40 -20
View File
@@ -1,35 +1,55 @@
package qaopsai
import (
"knowledge-governance/internal/sealedsecret"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"os"
)
// QA-AI keeps one write-only credential per revision. The AES-GCM convention
// itself lives in internal/sealedsecret so a second feature cannot grow a
// second, slightly different crypto path; only the AAD domain and the error
// vocabulary stay here.
const qaAISecretScope = "qa-ai"
// The independently provisioned master key never lives in source, settings JSON or database backups.
func (s *Store) masterKey() ([]byte, error) {
info, err := os.Lstat(s.options.KeyFile)
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 {
return nil, ErrUnavailable
}
raw, err := os.ReadFile(s.options.KeyFile)
if err != nil || len(raw) != 32 {
return nil, ErrUnavailable
}
return raw, nil
}
func (s *Store) aead() (cipher.AEAD, error) {
key, err := s.masterKey()
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, ErrUnavailable
}
return cipher.NewGCM(block)
}
func (s *Store) seal(secret string, revision int64) ([]byte, error) {
key, err := sealedsecret.LoadKeyFile(s.options.KeyFile)
aead, err := s.aead()
if err != nil {
return nil, err
}
nonce := make([]byte, aead.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return nil, ErrUnavailable
}
sealed, err := sealedsecret.Seal(key, secret, sealedsecret.AAD(qaAISecretScope, s.tenant, revision))
if err != nil {
return nil, ErrUnavailable
}
return sealed, nil
return aead.Seal(nonce, nonce, []byte(secret), []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))), nil
}
func (s *Store) unseal(sealed []byte, revision int64) (string, error) {
key, err := sealedsecret.LoadKeyFile(s.options.KeyFile)
aead, err := s.aead()
if err != nil || len(sealed) < aead.NonceSize() {
return "", ErrUnavailable
}
raw, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision)))
if err != nil {
return "", ErrUnavailable
}
plain, err := sealedsecret.Open(key, sealed, sealedsecret.AAD(qaAISecretScope, s.tenant, revision))
if err != nil {
return "", ErrUnavailable
}
return plain, nil
return string(raw), nil
}
+1 -3
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"strings"
"time"
"knowledge-governance/internal/sealedsecret"
)
type Options struct {
@@ -69,7 +67,7 @@ func (s *Store) readSettings(ctx context.Context, q settingsQuery) (privateSetti
return out, ErrUnavailable
}
out.KeyConfigured = len(out.sealed) > 0
_, keyErr := sealedsecret.LoadKeyFile(s.options.KeyFile)
_, keyErr := s.masterKey()
out.StorageReady = keyErr == nil
return out, nil
}
-91
View File
@@ -1,91 +0,0 @@
// Package sealedsecret holds the one AES-GCM convention this platform uses to
// keep a write-only credential (model key, WeKnora key) inside a database row
// without ever storing the plaintext or a reversible copy elsewhere.
//
// Two rules make it safe to have only one implementation:
// - the master key is an independently provisioned 32-byte 0600 file, never
// in source, settings JSON or database backups;
// - every ciphertext is bound to a caller-supplied AAD (tenant + revision),
// so a sealed value cannot be replayed onto a different row or revision.
package sealedsecret
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"os"
)
// ErrUnavailable means the master key is not usable, so sealing and opening are
// both impossible. Callers degrade honestly (they must not pretend it works).
var ErrUnavailable = errors.New("sealed secret storage is unavailable")
// KeySize is the only accepted master-key length (AES-256).
const KeySize = 32
// LoadKeyFile reads the master key. A missing file, a non-regular file, group or
// other permissions, or a wrong length are all ErrUnavailable: a half-configured
// secret store must never be silently substituted by a weaker one.
func LoadKeyFile(path string) ([]byte, error) {
if path == "" {
return nil, ErrUnavailable
}
info, err := os.Lstat(path)
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 {
return nil, ErrUnavailable
}
raw, err := os.ReadFile(path)
if err != nil || len(raw) != KeySize {
return nil, ErrUnavailable
}
return raw, nil
}
func aead(key []byte) (cipher.AEAD, error) {
if len(key) != KeySize {
return nil, ErrUnavailable
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, ErrUnavailable
}
return cipher.NewGCM(block)
}
// Seal returns nonce||ciphertext bound to aad.
func Seal(key []byte, plaintext, aad string) ([]byte, error) {
sealer, err := aead(key)
if err != nil {
return nil, err
}
nonce := make([]byte, sealer.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return nil, ErrUnavailable
}
return sealer.Seal(nonce, nonce, []byte(plaintext), []byte(aad)), nil
}
// Open reverses Seal. A different aad, a truncated value or a rotated key all
// return ErrUnavailable rather than an empty credential.
func Open(key, sealed []byte, aad string) (string, error) {
opener, err := aead(key)
if err != nil {
return "", err
}
if len(sealed) < opener.NonceSize() {
return "", ErrUnavailable
}
raw, err := opener.Open(nil, sealed[:opener.NonceSize()], sealed[opener.NonceSize():], []byte(aad))
if err != nil {
return "", ErrUnavailable
}
return string(raw), nil
}
// AAD builds the canonical associated data for one row revision. Every caller
// goes through it so two features cannot accidentally share a binding domain.
func AAD(scope, subject string, revision int64) string {
return fmt.Sprintf("%s:%s:%d", scope, subject, revision)
}
@@ -1,73 +0,0 @@
package sealedsecret
import (
"bytes"
"os"
"path/filepath"
"testing"
)
func writeKey(t *testing.T, content []byte, mode os.FileMode) string {
t.Helper()
path := filepath.Join(t.TempDir(), "master.key")
if err := os.WriteFile(path, content, mode); err != nil {
t.Fatalf("write key file: %v", err)
}
if err := os.Chmod(path, mode); err != nil {
t.Fatalf("chmod key file: %v", err)
}
return path
}
func TestSealOpenRoundTripBindsAAD(t *testing.T) {
key := bytes.Repeat([]byte{0x7a}, KeySize)
sealed, err := Seal(key, "sk-live-1234", AAD("weknora-connection", "test", 3))
if err != nil {
t.Fatalf("Seal() error = %v", err)
}
if bytes.Contains(sealed, []byte("sk-live-1234")) {
t.Fatal("ciphertext must not contain the plaintext")
}
plain, err := Open(key, sealed, AAD("weknora-connection", "test", 3))
if err != nil || plain != "sk-live-1234" {
t.Fatalf("Open() = %q, %v", plain, err)
}
if _, err := Open(key, sealed, AAD("weknora-connection", "test", 4)); err == nil {
t.Fatal("a different revision must not open the same ciphertext")
}
if _, err := Open(key, sealed, AAD("weknora-connection", "production", 3)); err == nil {
t.Fatal("a different environment must not open the same ciphertext")
}
}
func TestOpenRejectsTruncatedAndRotatedKey(t *testing.T) {
key := bytes.Repeat([]byte{0x11}, KeySize)
sealed, err := Seal(key, "secret", AAD("qa-ai", "tenant", 1))
if err != nil {
t.Fatalf("Seal() error = %v", err)
}
if _, err := Open(key, sealed[:4], AAD("qa-ai", "tenant", 1)); err == nil {
t.Fatal("truncated ciphertext must not open")
}
rotated := bytes.Repeat([]byte{0x22}, KeySize)
if _, err := Open(rotated, sealed, AAD("qa-ai", "tenant", 1)); err == nil {
t.Fatal("a rotated master key must not open old ciphertext")
}
}
func TestLoadKeyFileRequirements(t *testing.T) {
good := writeKey(t, bytes.Repeat([]byte{0x01}, KeySize), 0o600)
if _, err := LoadKeyFile(good); err != nil {
t.Fatalf("LoadKeyFile(0600, 32B) error = %v", err)
}
cases := map[string]string{
"missing": "",
"short": writeKey(t, bytes.Repeat([]byte{0x01}, 16), 0o600),
"group-visible": writeKey(t, bytes.Repeat([]byte{0x01}, KeySize), 0o640),
}
for name, path := range cases {
if _, err := LoadKeyFile(path); err != ErrUnavailable {
t.Fatalf("%s: LoadKeyFile() error = %v, want ErrUnavailable", name, err)
}
}
}
+1 -19
View File
@@ -13,24 +13,6 @@ import (
// the operator to paste an id. A missing endpoint or credential is an error the
// caller reports honestly rather than a silently empty picker.
func (verifier *Verifier) ListProductionKnowledgeBases(ctx context.Context, baseURL string) ([]weknora.KnowledgeBase, error) {
// The admin-managed connection wins: the page is where operators record the
// endpoint and key, and a second (file) source would silently disagree.
if verifier.config.ConnectionResolver != nil {
if endpoint, apiKey, ok := verifier.config.ConnectionResolver.Resolve(ctx, "production"); ok {
client, err := verifier.clientWithPolicy(endpoint, apiKey, verifier.config.ProductionAllowDockerHTTP, verifier.config.ProductionAllowPrivateHTTP)
if err != nil {
return nil, err
}
return client.ListKnowledgeBases(ctx)
}
configured, err := verifier.config.ConnectionResolver.Configured(ctx, "production")
if err != nil {
return nil, err
}
if configured {
return nil, errors.New("production WeKnora connection has no usable API key; re-enter it instead of falling back to the file")
}
}
resolved := firstNonEmpty(baseURL, verifier.config.ProductionBaseURLFallback)
if resolved == "" {
return nil, errors.New("production WeKnora endpoint is not configured")
@@ -39,7 +21,7 @@ func (verifier *Verifier) ListProductionKnowledgeBases(ctx context.Context, base
if apiKey == "" {
return nil, errors.New("production WeKnora API key file is not available")
}
client, err := verifier.clientWithPolicy(resolved, apiKey, verifier.config.ProductionAllowDockerHTTP, verifier.config.ProductionAllowPrivateHTTP)
client, err := verifier.client(resolved, apiKey, verifier.config.ProductionAllowDockerHTTP)
if err != nil {
return nil, err
}
+11 -41
View File
@@ -40,20 +40,8 @@ type Config struct {
ProductionBaseURLFallback string
TestAllowDockerHTTP bool
ProductionAllowDockerHTTP bool
// ProductionAllowPrivateHTTP mirrors WEKNORA_ALLOW_PRIVATE_HTTP: the
// production instance is reachable only as a same-LAN http endpoint.
ProductionAllowPrivateHTTP bool
TestAllowPrivateHTTP bool
// ConnectionResolver reads the admin-managed connection (endpoint + key)
// from the governance database. When it answers, it wins over the env
// defaults and over the credential file — the page is the place operators
// configure these, and a second source would drift.
ConnectionResolver interface {
Resolve(ctx context.Context, environment string) (string, string, bool)
Configured(ctx context.Context, environment string) (bool, error)
}
Timeout time.Duration
Now func() time.Time
Timeout time.Duration
Now func() time.Time
}
// Verifier asks endpoints what they really hold. It is safe for concurrent use.
@@ -87,25 +75,12 @@ func (verifier *Verifier) VerifyServiceTarget(ctx context.Context, target govern
testBaseURL := firstNonEmpty(target.TestBaseURL, verifier.config.TestBaseURLFallback)
productionKey := verifier.apiKey(verifier.config.ProductionAPIKeyFile)
testKey := verifier.apiKey(verifier.config.TestAPIKeyFile)
if verifier.config.ConnectionResolver != nil {
if endpoint, key, ok := verifier.config.ConnectionResolver.Resolve(ctx, "test"); ok {
testBaseURL, testKey = endpoint, key
} else if configured, err := verifier.config.ConnectionResolver.Configured(ctx, "test"); err == nil && configured {
// A cleared key must not silently fall back to the credential file.
testKey = ""
}
if endpoint, key, ok := verifier.config.ConnectionResolver.Resolve(ctx, "production"); ok {
productionBaseURL, productionKey = endpoint, key
} else if configured, err := verifier.config.ConnectionResolver.Configured(ctx, "production"); err == nil && configured {
productionKey = ""
}
}
verification := governance.ServiceTargetVerification{
Status: governance.ServiceTargetNotConfigured,
Message: "未配置:两项 ID 都留空,没有可核验的值",
TestEndpoint: verifier.probeEndpointWithPolicy(ctx, testBaseURL, testKey, "测试地址", verifier.config.TestAllowDockerHTTP, verifier.config.TestAllowPrivateHTTP),
ProductionEndpoint: verifier.probeEndpointWithPolicy(ctx, productionBaseURL, productionKey, "生产地址", verifier.config.ProductionAllowDockerHTTP, verifier.config.ProductionAllowPrivateHTTP),
TestEndpoint: verifier.probeEndpoint(ctx, testBaseURL, testKey, "测试地址", verifier.config.TestAllowDockerHTTP),
ProductionEndpoint: verifier.probeEndpoint(ctx, productionBaseURL, productionKey, "生产地址", verifier.config.ProductionAllowDockerHTTP),
CheckedAt: verifier.config.Now().UTC(),
}
if target.ProductionKnowledgeBaseID == "" && target.ProductionTenantID == "" {
@@ -121,7 +96,7 @@ func (verifier *Verifier) VerifyServiceTarget(ctx context.Context, target govern
verification.Message = "未核验:没有可用的生产 API Key 文件(PRODUCTION_WEKNORA_API_KEY_FILE),保存未被阻断"
return verification
}
client, err := verifier.clientWithPolicy(productionBaseURL, productionKey, verifier.config.ProductionAllowDockerHTTP, verifier.config.ProductionAllowPrivateHTTP)
client, err := verifier.client(productionBaseURL, productionKey, verifier.config.ProductionAllowDockerHTTP)
if err != nil {
verification.Status = governance.ServiceTargetCannotVerify
verification.Message = "未核验:生产地址不能作为 WeKnora 端点(" + err.Error() + "),保存未被阻断"
@@ -223,15 +198,11 @@ func (verifier *Verifier) verifyTenantOnly(ctx context.Context, client *weknora.
// is available, otherwise a plain /health liveness call. Advisory — the caller
// only reports it.
func (verifier *Verifier) probeEndpoint(ctx context.Context, baseURL, apiKey, label string, allowDockerHTTP bool) governance.ServiceEndpointStatus {
return verifier.probeEndpointWithPolicy(ctx, baseURL, apiKey, label, allowDockerHTTP, false)
}
func (verifier *Verifier) probeEndpointWithPolicy(ctx context.Context, baseURL, apiKey, label string, allowDockerHTTP, allowPrivateHTTP bool) governance.ServiceEndpointStatus {
if strings.TrimSpace(baseURL) == "" {
return governance.ServiceEndpointStatus{Status: governance.ServiceEndpointNotConfigured, Message: label + "未配置"}
}
if apiKey != "" {
if client, err := verifier.clientWithPolicy(baseURL, apiKey, allowDockerHTTP, allowPrivateHTTP); err == nil {
if client, err := verifier.client(baseURL, apiKey, allowDockerHTTP); err == nil {
bases, listErr := client.ListKnowledgeBases(ctx)
switch {
case listErr == nil:
@@ -300,13 +271,12 @@ func (verifier *Verifier) candidateSuffix(ctx context.Context, client *weknora.C
return fmt.Sprintf(";该地址现有 %d 个知识库:%s", len(bases), strings.Join(listed, "、"))
}
func (verifier *Verifier) clientWithPolicy(baseURL, apiKey string, allowDockerHTTP, allowPrivateHTTP bool) (*weknora.Client, error) {
func (verifier *Verifier) client(baseURL, apiKey string, allowDockerHTTP bool) (*weknora.Client, error) {
return weknora.NewClient(weknora.ClientConfig{
BaseURL: baseURL,
APIKey: apiKey,
Timeout: verifier.config.Timeout,
AllowDockerHTTP: allowDockerHTTP,
AllowPrivateHTTP: allowPrivateHTTP,
BaseURL: baseURL,
APIKey: apiKey,
Timeout: verifier.config.Timeout,
AllowDockerHTTP: allowDockerHTTP,
})
}
-469
View File
@@ -1,469 +0,0 @@
// Package weknoraconn owns the two WeKnora connections the console configures:
// endpoint + write-only API key per environment, with a real listing as the only
// proof a configuration is usable.
//
// It deliberately stores no knowledge-base binding. Which base receives 对内 /
// 对外 content stays in routing_kb_bindings / production_kb_bindings, because one
// meaning may only have one home.
package weknoraconn
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"strconv"
"strings"
"time"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/sealedsecret"
)
const (
EnvironmentTest = "test"
EnvironmentProduction = "production"
KeyActionKeep = "keep"
KeyActionReplace = "replace"
KeyActionClear = "clear"
// Outcome vocabulary shared by the API, the stored evidence and the page.
OutcomeOK = "ok"
OutcomeUnreachable = "unreachable"
OutcomeKeyInvalid = "key_invalid"
OutcomeKeyForbidden = "key_forbidden"
// VerificationNotConfigured means there is nothing to verify yet.
VerificationNotConfigured = "not_configured"
// proofTTL bounds how long a successful 测试连接 vouches for a candidate.
proofTTL = 15 * time.Minute
)
var (
ErrInvalid = errors.New("weknora connection request is invalid")
ErrNotFound = errors.New("unknown weknora environment")
ErrStaleRevision = errors.New("weknora connection revision is stale")
ErrNotTested = errors.New("weknora connection must be tested before saving")
ErrStorageUnavailable = errors.New("weknora connection secret storage is unavailable")
)
// Store is the persistence the service needs. The postgres store implements it.
type Store interface {
LoadWeKnoraConnection(ctx context.Context, environment string) (postgresstore.WeKnoraConnection, bool, error)
LoadWeKnoraConnections(ctx context.Context) ([]postgresstore.WeKnoraConnection, error)
SaveWeKnoraConnection(ctx context.Context, connection postgresstore.WeKnoraConnection, now time.Time) error
SaveWeKnoraConnectionTest(ctx context.Context, result postgresstore.WeKnoraConnectionTest, now time.Time) error
LoadWeKnoraConnectionTest(ctx context.Context, environment string) (postgresstore.WeKnoraConnectionTest, bool, error)
UpdateWeKnoraConnectionVerification(ctx context.Context, environment, verification string, libraryCount int, checkedAt time.Time, now time.Time) error
}
// KnowledgeBaseLister is the narrow client the service needs; tests inject it.
type KnowledgeBaseLister interface {
ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error)
}
type Config struct {
// MasterKeyFile is the 0600 32-byte master key. Empty or unreadable means
// the page can read state but cannot store a key — reported, never faked.
MasterKeyFile string
// AllowPrivateHTTP follows WEKNORA_ALLOW_PRIVATE_HTTP: same-LAN plain http
// is usable, public http is not.
AllowPrivateHTTP bool
Timeout time.Duration
Now func() time.Time
// NewLister is overridable in tests. Production leaves it nil.
NewLister func(endpoint, apiKey string) (KnowledgeBaseLister, error)
}
type Service struct {
store Store
config Config
}
func New(store Store, config Config) *Service {
if config.Timeout <= 0 {
config.Timeout = 10 * time.Second
}
if config.Now == nil {
config.Now = time.Now
}
return &Service{store: store, config: config}
}
// View is the page projection. It never carries the key or the ciphertext.
type View struct {
Environment string `json:"environment"`
Endpoint string `json:"endpoint"`
KeyConfigured bool `json:"key_configured"`
KeyTail string `json:"key_tail"`
Verification string `json:"verification"`
LibraryCount int `json:"library_count"`
CheckedAt *time.Time `json:"checked_at"`
UpdatedBy string `json:"updated_by"`
Revision int64 `json:"revision"`
StorageReady bool `json:"storage_ready"`
}
// TestInput is one 测试连接 request. An empty endpoint means "the saved one"; an
// empty key_action means keep.
type TestInput struct {
Endpoint string `json:"endpoint"`
APIKey string `json:"api_key"`
KeyAction string `json:"key_action"`
}
type TestResult struct {
Environment string `json:"environment"`
Endpoint string `json:"endpoint"`
Outcome string `json:"outcome"`
LibraryCount int `json:"library_count"`
Message string `json:"message"`
CheckedAt time.Time `json:"checked_at"`
}
type SaveInput struct {
Endpoint string `json:"endpoint"`
APIKey string `json:"api_key"`
KeyAction string `json:"key_action"`
BaseRevision int64 `json:"base_revision"`
}
func ValidEnvironment(value string) bool {
return value == EnvironmentTest || value == EnvironmentProduction
}
// View reads both environments, or one when environment is non-empty. A missing
// row is projected as 未配置 so the page has a stable shape.
func (service *Service) View(ctx context.Context, environment string) ([]View, error) {
stored, err := service.store.LoadWeKnoraConnections(ctx)
if err != nil {
return nil, err
}
byEnvironment := make(map[string]postgresstore.WeKnoraConnection, len(stored))
for _, connection := range stored {
byEnvironment[connection.Environment] = connection
}
environments := []string{EnvironmentTest, EnvironmentProduction}
if environment != "" {
if !ValidEnvironment(environment) {
return nil, ErrNotFound
}
environments = []string{environment}
}
_, masterKeyErr := sealedsecret.LoadKeyFile(service.config.MasterKeyFile)
views := make([]View, 0, len(environments))
for _, name := range environments {
connection := byEnvironment[name]
verification := connection.Verification
if verification == "" {
verification = VerificationNotConfigured
}
views = append(views, View{
Environment: name,
Endpoint: connection.Endpoint,
KeyConfigured: len(connection.KeyCiphertext) > 0,
KeyTail: connection.KeyTail,
Verification: verification,
LibraryCount: connection.LibraryCount,
CheckedAt: connection.CheckedAt,
UpdatedBy: connection.UpdatedBy,
Revision: connection.Revision,
StorageReady: masterKeyErr == nil,
})
}
return views, nil
}
// Test performs the real GET /api/v1/knowledge-bases against the candidate
// endpoint and key, and records the outcome as the evidence a later save needs.
func (service *Service) Test(ctx context.Context, environment string, input TestInput) (TestResult, error) {
if !ValidEnvironment(environment) {
return TestResult{}, ErrNotFound
}
saved, exists, err := service.store.LoadWeKnoraConnection(ctx, environment)
if err != nil {
return TestResult{}, err
}
endpoint := strings.TrimSpace(input.Endpoint)
if endpoint == "" && exists {
endpoint = saved.Endpoint
}
if endpoint == "" {
return TestResult{}, ErrInvalid
}
action := normalizeKeyAction(input.KeyAction)
apiKey, err := service.candidateKey(saved, exists, action, input.APIKey)
if err != nil {
return TestResult{}, err
}
now := service.config.Now().UTC()
result := TestResult{Environment: environment, Endpoint: endpoint, CheckedAt: now}
if !weknora.HTTPAllowed(endpoint, weknora.HTTPPolicy{AllowPrivateHTTP: service.config.AllowPrivateHTTP}) {
result.Outcome = OutcomeUnreachable
result.Message = "地址不可达:只接受 https,或已放行的私网/回环 http 地址"
_ = service.recordTest(ctx, result, apiKey)
return result, nil
}
lister, err := service.newLister(endpoint, apiKey)
if err != nil {
result.Outcome = OutcomeUnreachable
result.Message = "地址不可达:" + err.Error()
_ = service.recordTest(ctx, result, apiKey)
return result, nil
}
probeCtx, cancel := context.WithTimeout(ctx, service.config.Timeout)
defer cancel()
bases, listErr := lister.ListKnowledgeBases(probeCtx)
if listErr != nil {
result.Outcome, result.Message = classifyListError(listErr)
_ = service.recordTest(ctx, result, apiKey)
return result, nil
}
result.Outcome = OutcomeOK
result.LibraryCount = len(bases)
result.Message = "接口可达 · 已读到 " + strconv.Itoa(len(bases)) + " 个知识库"
if recordErr := service.recordTest(ctx, result, apiKey); recordErr != nil {
// The listing worked but the proof did not land: say so now, because the
// save gate will refuse this configuration a moment later.
result.Message += "(测试证据未能落库,保存会被拒绝,请重试)"
}
// The card may only claim 「可达」 for the configuration it actually probed.
if exists && action != KeyActionReplace && endpoint == saved.Endpoint {
_ = service.store.UpdateWeKnoraConnectionVerification(ctx, environment, result.Outcome, result.LibraryCount, result.CheckedAt, now)
}
return result, nil
}
// Save stores a tested configuration. A new key or a new endpoint must have a
// successful test behind it; keeping a tested configuration is not blocked by a
// jittery endpoint.
func (service *Service) Save(ctx context.Context, environment string, input SaveInput, actor string) (View, error) {
if !ValidEnvironment(environment) {
return View{}, ErrNotFound
}
saved, exists, err := service.store.LoadWeKnoraConnection(ctx, environment)
if err != nil {
return View{}, err
}
endpoint := strings.TrimSpace(input.Endpoint)
if endpoint == "" {
return View{}, ErrInvalid
}
action := normalizeKeyAction(input.KeyAction)
if exists && input.BaseRevision != saved.Revision {
return View{}, ErrStaleRevision
}
if exists && endpoint != saved.Endpoint && action != KeyActionReplace {
return View{}, ErrInvalid
}
apiKey, err := service.candidateKey(saved, exists, action, input.APIKey)
if err != nil {
return View{}, err
}
now := service.config.Now().UTC()
revision := int64(1)
if exists {
revision = saved.Revision + 1
}
verification := VerificationNotConfigured
libraryCount := 0
var checkedAt *time.Time
if apiKey != "" {
if !weknora.HTTPAllowed(endpoint, weknora.HTTPPolicy{AllowPrivateHTTP: service.config.AllowPrivateHTTP}) {
return View{}, ErrInvalid
}
if !exists || action == KeyActionReplace || endpoint != saved.Endpoint {
proof, found, proofErr := service.store.LoadWeKnoraConnectionTest(ctx, environment)
if proofErr != nil {
return View{}, proofErr
}
if !found || proof.Outcome != OutcomeOK || proof.Endpoint != endpoint ||
proof.KeyFingerprint != fingerprint(apiKey) || now.Sub(proof.CheckedAt) > proofTTL {
return View{}, ErrNotTested
}
libraryCount = proof.LibraryCount
checkedAt = &proof.CheckedAt
} else {
libraryCount = saved.LibraryCount
checkedAt = saved.CheckedAt
}
verification = OutcomeOK
}
sealed := []byte{}
if apiKey != "" {
masterKey, keyErr := sealedsecret.LoadKeyFile(service.config.MasterKeyFile)
if keyErr != nil {
return View{}, ErrStorageUnavailable
}
sealed, err = sealedsecret.Seal(masterKey, apiKey, sealedsecret.AAD("weknora-connection", environment, revision))
if err != nil {
return View{}, ErrStorageUnavailable
}
}
connection := postgresstore.WeKnoraConnection{
Environment: environment,
Revision: revision,
Endpoint: endpoint,
KeyCiphertext: sealed,
KeyTail: keyTail(apiKey),
Verification: verification,
LibraryCount: libraryCount,
CheckedAt: checkedAt,
UpdatedBy: actor,
}
if err := service.store.SaveWeKnoraConnection(ctx, connection, now); err != nil {
return View{}, err
}
views, err := service.View(ctx, environment)
if err != nil {
return View{}, err
}
return views[0], nil
}
// Resolve returns the endpoint and key the platform should use for one
// environment. It is the single source other features read instead of guessing
// from environment variables.
func (service *Service) Resolve(ctx context.Context, environment string) (string, string, bool) {
if !ValidEnvironment(environment) {
return "", "", false
}
saved, exists, err := service.store.LoadWeKnoraConnection(ctx, environment)
if err != nil || !exists || saved.Endpoint == "" || len(saved.KeyCiphertext) == 0 {
return "", "", false
}
masterKey, keyErr := sealedsecret.LoadKeyFile(service.config.MasterKeyFile)
if keyErr != nil {
return "", "", false
}
apiKey, openErr := sealedsecret.Open(masterKey, saved.KeyCiphertext, sealedsecret.AAD("weknora-connection", environment, saved.Revision))
if openErr != nil {
return "", "", false
}
return saved.Endpoint, apiKey, true
}
// Configured reports whether an operator has saved a connection row for this
// environment. It distinguishes "never configured, use bootstrap files" from
// "configured but the key was cleared", which must fail closed instead of
// silently falling back to an old file key.
func (service *Service) Configured(ctx context.Context, environment string) (bool, error) {
if !ValidEnvironment(environment) {
return false, ErrNotFound
}
_, exists, err := service.store.LoadWeKnoraConnection(ctx, environment)
if err != nil {
return false, err
}
return exists, nil
}
// HTTPPolicy exposes the endpoint policy the client uses, so a caller that
// builds its own client stays in agreement with the service.
func (service *Service) HTTPPolicy() weknora.HTTPPolicy {
return weknora.HTTPPolicy{AllowPrivateHTTP: service.config.AllowPrivateHTTP}
}
func (service *Service) candidateKey(saved postgresstore.WeKnoraConnection, exists bool, action, inputKey string) (string, error) {
switch action {
case KeyActionClear:
return "", nil
case KeyActionReplace:
trimmed := strings.TrimSpace(inputKey)
if trimmed == "" {
return "", ErrInvalid
}
return trimmed, nil
default:
if !exists || len(saved.KeyCiphertext) == 0 {
return "", ErrInvalid
}
masterKey, err := sealedsecret.LoadKeyFile(service.config.MasterKeyFile)
if err != nil {
return "", ErrStorageUnavailable
}
apiKey, err := sealedsecret.Open(masterKey, saved.KeyCiphertext, sealedsecret.AAD("weknora-connection", saved.Environment, saved.Revision))
if err != nil {
return "", ErrStorageUnavailable
}
return apiKey, nil
}
}
func (service *Service) newLister(endpoint, apiKey string) (KnowledgeBaseLister, error) {
if service.config.NewLister != nil {
return service.config.NewLister(endpoint, apiKey)
}
return weknora.NewClient(weknora.ClientConfig{
BaseURL: endpoint,
APIKey: apiKey,
Timeout: service.config.Timeout,
AllowPrivateHTTP: service.config.AllowPrivateHTTP,
})
}
func (service *Service) recordTest(ctx context.Context, result TestResult, apiKey string) error {
return service.store.SaveWeKnoraConnectionTest(ctx, postgresstore.WeKnoraConnectionTest{
Environment: result.Environment,
Endpoint: result.Endpoint,
KeyFingerprint: fingerprint(apiKey),
Outcome: result.Outcome,
LibraryCount: result.LibraryCount,
Message: result.Message,
}, result.CheckedAt)
}
// classifyListError maps one failed listing onto the four answers the page
// promises, so 「密钥无效」 and 「密钥无权限」 never collapse into one message.
func classifyListError(err error) (string, string) {
var httpErr *weknora.HTTPError
if errors.As(err, &httpErr) {
switch httpErr.StatusCode {
case 401:
return OutcomeKeyInvalid, "密钥无效:该实例拒绝了这把 API Key(401)"
case 403:
return OutcomeKeyForbidden, "密钥无权限读取知识库列表(403)"
}
}
switch {
case errors.Is(err, context.DeadlineExceeded):
return OutcomeUnreachable, "地址不可达:请求超时"
default:
var netErr interface{ Timeout() bool }
if errors.As(err, &netErr) && netErr.Timeout() {
return OutcomeUnreachable, "地址不可达:请求超时"
}
return OutcomeUnreachable, "地址不可达:连接失败"
}
}
func normalizeKeyAction(action string) string {
switch strings.TrimSpace(action) {
case KeyActionReplace:
return KeyActionReplace
case KeyActionClear:
return KeyActionClear
default:
return KeyActionKeep
}
}
func fingerprint(apiKey string) string {
sum := sha256.Sum256([]byte(apiKey))
return hex.EncodeToString(sum[:])
}
// keyTail is the only part of a key the page may show: the last four characters.
func keyTail(apiKey string) string {
if apiKey == "" {
return ""
}
runes := []rune(apiKey)
if len(runes) <= 4 {
return string(runes)
}
return string(runes[len(runes)-4:])
}
-249
View File
@@ -1,249 +0,0 @@
package weknoraconn
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"
"knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
type fakeStore struct {
connections map[string]postgres.WeKnoraConnection
tests map[string]postgres.WeKnoraConnectionTest
}
func newFakeStore() *fakeStore {
return &fakeStore{
connections: map[string]postgres.WeKnoraConnection{},
tests: map[string]postgres.WeKnoraConnectionTest{},
}
}
func (store *fakeStore) LoadWeKnoraConnection(_ context.Context, environment string) (postgres.WeKnoraConnection, bool, error) {
connection, ok := store.connections[environment]
return connection, ok, nil
}
func (store *fakeStore) LoadWeKnoraConnections(context.Context) ([]postgres.WeKnoraConnection, error) {
result := make([]postgres.WeKnoraConnection, 0, len(store.connections))
for _, connection := range store.connections {
result = append(result, connection)
}
return result, nil
}
func (store *fakeStore) SaveWeKnoraConnection(_ context.Context, connection postgres.WeKnoraConnection, _ time.Time) error {
store.connections[connection.Environment] = connection
return nil
}
func (store *fakeStore) SaveWeKnoraConnectionTest(_ context.Context, result postgres.WeKnoraConnectionTest, now time.Time) error {
result.CheckedAt = now
store.tests[result.Environment] = result
return nil
}
func (store *fakeStore) LoadWeKnoraConnectionTest(_ context.Context, environment string) (postgres.WeKnoraConnectionTest, bool, error) {
result, ok := store.tests[environment]
return result, ok, nil
}
func (store *fakeStore) UpdateWeKnoraConnectionVerification(_ context.Context, environment, verification string, libraryCount int, checkedAt time.Time, _ time.Time) error {
connection, ok := store.connections[environment]
if !ok {
return nil
}
connection.Verification = verification
connection.LibraryCount = libraryCount
connection.CheckedAt = &checkedAt
store.connections[environment] = connection
return nil
}
type fakeLister struct {
bases []weknora.KnowledgeBase
err error
}
func (lister fakeLister) ListKnowledgeBases(context.Context) ([]weknora.KnowledgeBase, error) {
return lister.bases, lister.err
}
func newService(t *testing.T, store Store, lister fakeLister) *Service {
t.Helper()
path := filepath.Join(t.TempDir(), "master.key")
if err := os.WriteFile(path, []byte("0123456789abcdef0123456789abcdef"), 0o600); err != nil {
t.Fatalf("write master key: %v", err)
}
if err := os.Chmod(path, 0o600); err != nil {
t.Fatalf("chmod master key: %v", err)
}
now := time.Date(2026, 11, 22, 7, 0, 0, 0, time.UTC)
return New(store, Config{
MasterKeyFile: path,
AllowPrivateHTTP: true,
Timeout: time.Second,
Now: func() time.Time { return now },
NewLister: func(endpoint, apiKey string) (KnowledgeBaseLister, error) {
if endpoint == "" || apiKey == "" {
return nil, errors.New("missing endpoint or key")
}
return lister, nil
},
})
}
func TestTestClassifiesTheFourAnswers(t *testing.T) {
cases := []struct {
name string
err error
wantOutcome string
wantMessage string
}{
{"unauthorized", &weknora.HTTPError{StatusCode: 401}, OutcomeKeyInvalid, "密钥无效"},
{"forbidden", &weknora.HTTPError{StatusCode: 403}, OutcomeKeyForbidden, "密钥无权限"},
{"timeout", context.DeadlineExceeded, OutcomeUnreachable, "地址不可达"},
{"refused", errors.New("dial tcp: connection refused"), OutcomeUnreachable, "地址不可达"},
}
for _, testCase := range cases {
service := newService(t, newFakeStore(), fakeLister{err: testCase.err})
result, err := service.Test(context.Background(), EnvironmentTest, TestInput{
Endpoint: "http://127.0.0.1:8092", APIKey: "sk-test-1234", KeyAction: KeyActionReplace,
})
if err != nil {
t.Fatalf("%s: Test() error = %v", testCase.name, err)
}
if result.Outcome != testCase.wantOutcome {
t.Fatalf("%s: outcome = %q, want %q", testCase.name, result.Outcome, testCase.wantOutcome)
}
if !contains(result.Message, testCase.wantMessage) {
t.Fatalf("%s: message = %q, want it to mention %q", testCase.name, result.Message, testCase.wantMessage)
}
}
}
func TestTestSuccessReportsLibraryCount(t *testing.T) {
service := newService(t, newFakeStore(), fakeLister{bases: []weknora.KnowledgeBase{{ID: "a"}, {ID: "b"}, {ID: "c"}}})
result, err := service.Test(context.Background(), EnvironmentProduction, TestInput{
Endpoint: "http://172.29.151.11:18093", APIKey: "prod-key-9999", KeyAction: KeyActionReplace,
})
if err != nil {
t.Fatalf("Test() error = %v", err)
}
if result.Outcome != OutcomeOK || result.LibraryCount != 3 {
t.Fatalf("result = %+v", result)
}
if !contains(result.Message, "3 个知识库") {
t.Fatalf("message = %q", result.Message)
}
}
func TestSaveRequiresTestProofAndProjectsTailOnly(t *testing.T) {
store := newFakeStore()
service := newService(t, store, fakeLister{bases: []weknora.KnowledgeBase{{ID: "a"}, {ID: "b"}}})
ctx := context.Background()
save := SaveInput{Endpoint: "http://127.0.0.1:8092", APIKey: "sk-live-abcd", KeyAction: KeyActionReplace}
if _, err := service.Save(ctx, EnvironmentTest, save, "admin"); !errors.Is(err, ErrNotTested) {
t.Fatalf("Save() without a test = %v, want ErrNotTested", err)
}
if _, err := service.Test(ctx, EnvironmentTest, TestInput{Endpoint: save.Endpoint, APIKey: save.APIKey, KeyAction: KeyActionReplace}); err != nil {
t.Fatalf("Test() error = %v", err)
}
view, err := service.Save(ctx, EnvironmentTest, save, "admin")
if err != nil {
t.Fatalf("Save() error = %v", err)
}
if !view.KeyConfigured || view.KeyTail != "abcd" || view.Verification != OutcomeOK || view.LibraryCount != 2 {
t.Fatalf("view = %+v", view)
}
if view.Revision != 1 {
t.Fatalf("revision = %d", view.Revision)
}
endpoint, apiKey, ok := service.Resolve(ctx, EnvironmentTest)
if !ok || endpoint != save.Endpoint || apiKey != save.APIKey {
t.Fatalf("Resolve() = %q %q %v", endpoint, apiKey, ok)
}
// The proof is bound to the key: another key must not reuse it.
other := SaveInput{Endpoint: save.Endpoint, APIKey: "sk-live-zzzz", KeyAction: KeyActionReplace, BaseRevision: 1}
if _, err := service.Save(ctx, EnvironmentTest, other, "admin"); !errors.Is(err, ErrNotTested) {
t.Fatalf("Save() with a different untested key = %v, want ErrNotTested", err)
}
}
func TestSaveRejectsEndpointChangeWithoutReenteringKey(t *testing.T) {
store := newFakeStore()
service := newService(t, store, fakeLister{bases: []weknora.KnowledgeBase{{ID: "a"}}})
ctx := context.Background()
first := SaveInput{Endpoint: "http://127.0.0.1:8092", APIKey: "sk-live-abcd", KeyAction: KeyActionReplace}
if _, err := service.Test(ctx, EnvironmentTest, TestInput{Endpoint: first.Endpoint, APIKey: first.APIKey, KeyAction: KeyActionReplace}); err != nil {
t.Fatal(err)
}
if _, err := service.Save(ctx, EnvironmentTest, first, "admin"); err != nil {
t.Fatalf("first Save() error = %v", err)
}
if _, err := service.Save(ctx, EnvironmentTest, SaveInput{Endpoint: "http://127.0.0.1:9092", KeyAction: KeyActionKeep, BaseRevision: 1}, "admin"); !errors.Is(err, ErrInvalid) {
t.Fatalf("endpoint change with keep = %v, want ErrInvalid", err)
}
if _, err := service.Save(ctx, EnvironmentTest, SaveInput{Endpoint: "http://127.0.0.1:8092", KeyAction: KeyActionKeep, BaseRevision: 7}, "admin"); !errors.Is(err, ErrStaleRevision) {
t.Fatalf("stale revision = %v, want ErrStaleRevision", err)
}
// Keeping the tested configuration must not be blocked by proof age.
view, err := service.Save(ctx, EnvironmentTest, SaveInput{Endpoint: "http://127.0.0.1:8092", KeyAction: KeyActionKeep, BaseRevision: 1}, "admin")
if err != nil || view.Verification != OutcomeOK || view.KeyTail != "abcd" {
t.Fatalf("keep Save() = %+v, %v", view, err)
}
}
func TestClearKeyResetsVerification(t *testing.T) {
store := newFakeStore()
service := newService(t, store, fakeLister{bases: []weknora.KnowledgeBase{{ID: "a"}}})
ctx := context.Background()
if _, err := service.Test(ctx, EnvironmentProduction, TestInput{Endpoint: "https://prod.example", APIKey: "prod-key", KeyAction: KeyActionReplace}); err != nil {
t.Fatal(err)
}
if _, err := service.Save(ctx, EnvironmentProduction, SaveInput{Endpoint: "https://prod.example", APIKey: "prod-key", KeyAction: KeyActionReplace}, "admin"); err != nil {
t.Fatal(err)
}
view, err := service.Save(ctx, EnvironmentProduction, SaveInput{Endpoint: "https://prod.example", KeyAction: KeyActionClear, BaseRevision: 1}, "admin")
if err != nil {
t.Fatalf("clear Save() error = %v", err)
}
if view.KeyConfigured || view.KeyTail != "" || view.Verification != VerificationNotConfigured {
t.Fatalf("cleared view = %+v", view)
}
if _, _, ok := service.Resolve(ctx, EnvironmentProduction); ok {
t.Fatal("a cleared connection must not resolve")
}
}
func TestPublicHTTPIsRefusedEvenWhenPrivateHTTPIsAllowed(t *testing.T) {
service := newService(t, newFakeStore(), fakeLister{})
result, err := service.Test(context.Background(), EnvironmentTest, TestInput{Endpoint: "http://weknora.example", APIKey: "k", KeyAction: KeyActionReplace})
if err != nil {
t.Fatalf("Test() error = %v", err)
}
if result.Outcome != OutcomeUnreachable {
t.Fatalf("outcome = %q", result.Outcome)
}
if _, err := service.Save(context.Background(), EnvironmentTest, SaveInput{Endpoint: "http://weknora.example", APIKey: "k", KeyAction: KeyActionReplace}, "admin"); err == nil {
t.Fatal("saving a public http endpoint must fail")
}
}
func contains(value, needle string) bool {
return len(needle) == 0 || (len(value) >= len(needle) && indexOf(value, needle) >= 0)
}
func indexOf(value, needle string) int {
for i := 0; i+len(needle) <= len(value); i++ {
if value[i:i+len(needle)] == needle {
return i
}
}
return -1
}
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
"""Coordinate candidate preparation and record independently authored QA evidence."""
import argparse
import json
from pathlib import Path
import re
import sys
from urllib.error import HTTPError
import candidate_release as candidate
import candidate_runtime as runtime
import hifox_release_trigger as hfx
import production_cd as cd
STATE = Path.home() / '.local/state/kg-candidate-release'
CLI = str(Path.home() / '.local/bin/hifox')
WORKFLOW = candidate.API + '/actions/workflows/prepare-candidate.yml/dispatches?return_run_details=true'
QA_AUTHORS = {cd.RELEASE_OWNER, '62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
WAIT_TEST = 'b59c34ee-94f4-41a8-8577-dea73b2c6414'
TESTING = 'f8906482-bad7-4af8-9a3b-d52630eff3f7'
QA_FENCE = re.compile(r'^```kg-qa-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
def task(task_id):
cd.require(cd.matches(cd.UUID, task_id), 'provide the task UUID')
obj = hfx.hifox(CLI, 'task', 'view', task_id)
if not isinstance(obj, dict) or obj.get('id') != task_id or obj.get('spaceId') != cd.SPACE:
raise cd.CDError('task is outside the release space')
return obj
def timeline(task_id):
rows = hfx.hifox(CLI, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
cd.require(isinstance(rows, list), 'task timeline unavailable')
return [row for row in rows if row.get('event') == 'commented']
def owner_plan(task_id):
task(task_id)
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])
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'])
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')))
cd.require(isinstance(identifier, str) and re.search(rf'(?<![\w-]){re.escape(identifier)}(?!\w)', fields, re.IGNORECASE),
f"PR #{item['pr']} does not identify its HiFox requirement")
return plan
def queue(task_id):
plan = owner_plan(task_id)
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
key = cd.acceptance_digest(plan)
path = STATE / (key + '.dispatch.json')
with cd.deploy_lock(STATE / 'dispatch.lock'):
if path.exists():
result = cd.read_json(cd.immutable_file(path))
cd.require(result['state'] == 'queued', 'candidate dispatch outcome unknown; reconcile Gitea before retry')
return result
conf = Path.home() / '.config/knowledge-governance/qa.json'
runtime.qa_database(conf)
cd.record(path, {'state': 'submitting', 'plan': plan})
result = hfx.forge('POST', WORKFLOW, {'ref': 'main', 'inputs': {'plan': json.dumps(plan), 'mode': 'prepare'}})
run = str(result.get('workflow_run_id', ''))
cd.require(cd.matches(hfx.RUN_ID, run), 'missing candidate run ID; reconcile Gitea before retry')
receipt = {'state': 'queued', 'plan': plan, 'run': run, 'url': f'{cd.FORGE}/{cd.REPO}/actions/runs/{run}'}
cd.record(path, receipt)
return receipt
def add_comment(task_id, key, body):
marker = f'[KG candidate {key}]'
def existing():
return [row for row in timeline(task_id) if marker in (row.get('content') or '')]
if not existing():
hfx.hifox(CLI, 'task', 'comment', task_id, '--body', f'{marker}\n\n{body}')
rows = existing()
cd.require(len(rows) == 1 and cd.matches(cd.UUID, rows[0].get('id')) and body in rows[0].get('content', ''),
'candidate comment not uniquely verified')
return rows[0]['id']
def publish_candidate(plan, receipt, run):
body = (f'候选验收地址 {receipt["url"]}\n\n提交 `{receipt["sha"]}`\n\n'
f'归档 `{receipt["bundle"]}`\n\n'
f'构建记录 {cd.FORGE}/{cd.REPO}/actions/runs/{run}\n\n'
f'发布任务 {task(plan["task"])["url"]}')
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 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')
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')
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')
def register(task_id):
plan = owner_plan(task_id)
directory = STATE / cd.acceptance_digest(plan)
with cd.deploy_lock(directory / 'registration.lock'):
receipt = cd.read_json(cd.immutable_file(directory / 'ready.json'))
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]
for item_id in tasks:
obj = task(item_id)
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
for row in rows:
match = QA_FENCE.search(row.get('content') or '')
if not match or (row.get('actor') or {}).get('id') not in QA_AUTHORS:
continue
result = json.loads(match[1])
if result.get('bundle') == receipt['bundle']:
reports[item_id] = (row, result)
break
if item_id in reports:
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')
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
fresh = owner_plan(task_id)
cd.require(fresh == plan, 'release plan changed during registration')
rel = task(task_id)
cd.require((rel.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED),
'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}'
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:
hfx.hifox(CLI, 'task', 'metadata', 'set', task_id, 'cd_acceptance', json.dumps(json.dumps(acceptance)))
cd.require(cd.metadata(task(task_id), 'cd_acceptance') == acceptance, 'acceptance writeback not verified')
return acceptance
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('prepare', 'register', 'status'))
parser.add_argument('task')
args = parser.parse_args()
if args.action == 'prepare':
result = queue(args.task)
elif args.action == 'register':
result = register(args.task)
else:
plan = owner_plan(args.task)
key = cd.acceptance_digest(plan)
results = [STATE / key / 'ready.json', STATE / (key + '.dispatch.json')]
result = next((cd.read_json(cd.immutable_file(p)) for p in results if p.exists()), {'state': 'unprepared'})
print(json.dumps(result, ensure_ascii=False))
if __name__ == '__main__':
try:
main()
except HTTPError as exc:
sys.exit(f'Candidate coordinator: HTTP {exc.code}; reconcile Gitea before retry')
except (cd.CDError, runtime.qa_env.QAError, OSError, ValueError) as exc:
sys.exit(f'Candidate coordinator: {exc}')
+203
View File
@@ -0,0 +1,203 @@
#!/usr/bin/env python3
"""Validate a release batch and build its immutable candidate bundle."""
import argparse
import datetime
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
from types import SimpleNamespace
from urllib.request import Request
import hifox_release_trigger as integration
import production_cd as cd
API = f'/api/v1/repos/{cd.REPO}'
CONTEXTS = Path(__file__).resolve().parents[1] / '.gitea/required-contexts.txt'
FENCE = re.compile(r'^```kg-release-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
def read_forge(path):
token = os.getenv('KG_CANDIDATE_READ_TOKEN')
if not token:
return integration.forge('GET', path)
from urllib.request import ProxyHandler, build_opener
server = os.getenv('KG_CANDIDATE_FORGE', cd.FORGE)
cd.require(server in (cd.FORGE, 'http://192.168.50.223:3000'), 'untrusted Gitea origin')
request = Request(server + path, headers={'Authorization': 'token ' + token})
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=20) as response:
return json.load(response)
def check_plan(plan):
cd.require(isinstance(plan, dict) and set(plan) == {'task', 'sha', 'base', 'items', 'extra'},
'invalid release plan fields')
cd.require(cd.matches(cd.UUID, plan['task']) and cd.matches(cd.SHA, plan['sha'])
and cd.matches(cd.SHA, plan['base']) and plan['base'] != plan['sha'], 'invalid release task or SHA range')
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}),
'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)
and len(set(extra)) == len(extra), 'invalid additional reviewed commits')
def check_scope(plan, read_pr, first_parents):
check_plan(plan)
required = set(plan['extra'])
for item in plan['items']:
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),
f"PR #{item['pr']} must be merged into main")
cd.require(sha not in required, 'landed commit is listed in multiple scope entries')
required.add(sha)
cd.require(required == set(first_parents), 'commits outside the release scope, or planned commits absent from main range')
def instant(value):
cd.require(isinstance(value, str) and bool(re.search(r'(Z|[+-]\d\d:\d\d)$', value)), 'invalid QA timestamp')
return datetime.datetime.fromisoformat(value.replace('Z', '+00:00'))
def check_qa(plan, receipt, reports, authors):
check_plan(plan)
tasks = {item['task'] for item in plan['items']} | {plan['task']}
cd.require(set(reports) == tasks, 'require reports on every requirement and the release task')
cd.require(cd.matches(cd.HASH, receipt.get('bundle')) and receipt.get('sha') == plan['sha'], 'invalid candidate receipt')
for task, (comment, report) in reports.items():
cd.require((comment.get('actor') or {}).get('id') in authors, f'{task}: require authorized QA report author')
cd.require(all(report.get(k) == receipt[k] for k in ('sha', 'bundle', 'url')), f'{task}: report is for a different candidate')
cd.require(instant(comment.get('createdAt')) > instant(receipt['ready_at']), f'{task}: report predates candidate')
cd.require(not comment.get('updatedAt') or instant(comment['updatedAt']) >= instant(comment['createdAt']),
f'{task}: invalid report revision timestamp')
values = [report.get(field) for field in ('required', 'passed', 'failed', 'blocked')]
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')
def git(*args, cwd=None):
env = dict(os.environ, GIT_TERMINAL_PROMPT='0')
return cd.run(['git', *args], 'read candidate source', cwd=cwd, env=env, timeout=120).decode().strip()
def verify_source(plan, repo):
main_line = git('rev-list', '--first-parent', 'origin/main', cwd=repo).splitlines()
sha, base = plan['sha'], plan['base']
cd.require(sha in main_line and base in main_line and main_line.index(sha) < main_line.index(base),
'candidate and baseline must be ordered commits on main first-parent history')
check_scope(plan, lambda n: read_forge(API + f'/pulls/{n}'),
main_line[main_line.index(sha):main_line.index(base)])
contexts = {line.split('#', 1)[0].strip() for line in CONTEXTS.read_text().splitlines()} - {''}
cd.verify_contexts(read_forge(API + f'/commits/{sha}/status'), contexts)
def build(plan, repo, destination):
check_plan(plan)
verify_source(plan, repo)
sha = plan['sha']
destination = destination.resolve()
if destination.exists():
digest = cd.hash_file(destination / 'release.json')
cd.verify_bundle(destination, {'task': plan['task'], 'sha': sha, 'bundle': digest})
return digest
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
with tempfile.TemporaryDirectory(prefix='kg-candidate-source-') as name:
src = Path(name) / 'source'
git('clone', '--no-checkout', '--shared', str(repo.resolve()), str(src))
git('checkout', '--detach', sha, cwd=src)
cd.require(git('rev-parse', 'HEAD', cwd=src) == sha and not git('status', '--porcelain', cwd=src),
'candidate checkout differs from selected commit')
identity = json.loads(cd.run([sys.executable, 'scripts/version.py', '--identity'], 'read build version', cwd=src))
cd.require(identity.get('commit_sha') == sha, 'version script returned another SHA')
flags = {'VERSION': identity['release_version'] or 'dev', 'RELEASE_VERSION': identity['release_version'] or '',
'BUILD_KIND': identity['build_kind'], 'COMMITS_SINCE_RELEASE': identity['commits_since_release'] or '',
'COMMIT_SHA': sha, 'BUILD_TIME': identity['built_at']}
common = ['docker', 'build', '--pull=false', '--label', f'{cd.REVISION}={sha}']
# Only pass the explicitly configured build proxy, never the agent's inherited credentials.
for variable in ('HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY'):
value = os.getenv('KG_BUILD_' + variable)
if value:
cd.require('@' not in value, 'build proxy must not contain credentials')
common += ['--build-arg', f'{variable}={value}']
tags = {name: f'kg-release-candidate-{name}:{sha}' for name in ('backend', 'web')}
for role, dockerfile in (('backend', 'Dockerfile'), ('web', 'Dockerfile.web')):
args = common + ['-f', dockerfile, '-t', tags[role]]
if role == 'backend':
for key, value in flags.items():
args += ['--build-arg', f'{key}={value}']
subprocess.run(args + ['.'], cwd=src, check=True, timeout=1800)
image_ids = {key: cd.image_inspect(tag)['Id'] for key, tag in tags.items()}
# pack takes its migration list from this commit and validates the OCI revision and image IDs.
original = Path.cwd()
try:
os.chdir(src)
cd.pack(SimpleNamespace(sha=sha, task=plan['task'], api=image_ids['backend'], worker=image_ids['backend'],
web=image_ids['web'], output=destination))
finally:
os.chdir(original)
return cd.hash_file(destination / 'release.json')
def event_plan(event, env):
cd.require(env.get('GITHUB_EVENT_NAME') == 'workflow_dispatch' and env.get('GITHUB_REPOSITORY') == cd.REPO,
'candidate workflow requires an explicit dispatch in the governance repository')
inputs = event.get('inputs') or {}
mode = inputs.get('mode')
cd.require(mode in ('verify', 'prepare'), 'unknown candidate mode')
if mode == 'prepare':
cd.require(env.get('GITHUB_REF') == 'refs/heads/main', 'prepare requires the workflow from main')
plan = json.loads(inputs['plan'])
check_plan(plan)
return plan, mode
def proof(plan, mode):
return 'KG_CANDIDATE_PLAN_V1 ' + cd.acceptance_digest({'plan': plan, 'mode': mode})
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='action', required=True)
guard = sub.add_parser('guard')
guard.add_argument('--event', required=True, type=Path)
guard.add_argument('--repo', required=True, type=Path)
for name in ('verify', 'build'):
arg = sub.add_parser(name)
arg.add_argument('--plan', required=True, type=Path)
arg.add_argument('--repo', required=True, type=Path)
if name == 'build':
arg.add_argument('--output', required=True, type=Path)
args = parser.parse_args()
if args.action == 'guard':
plan, mode = event_plan(cd.read_json(args.event), os.environ)
verify_source(plan, args.repo)
print(proof(plan, mode))
return
plan = cd.read_json(args.plan)
check_plan(plan)
if args.action == 'verify':
verify_source(plan, args.repo)
print(json.dumps({'state': 'verified', 'sha': plan['sha'], 'task': plan['task']}))
else:
digest = build(plan, args.repo, args.output)
print(json.dumps({'state': 'built', 'sha': plan['sha'], 'task': plan['task'], 'bundle': digest}))
if __name__ == '__main__':
try:
main()
except cd.CDError as exc:
sys.exit(f'Candidate: {exc}')
except (OSError, ValueError, KeyError, subprocess.SubprocessError) as exc:
sys.exit(f'Candidate: {type(exc).__name__}; check build or release input')
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""Run the sealed candidate on an isolated acceptance stack."""
import argparse
import ipaddress
import json
from pathlib import Path
import re
import secrets
import sys
import tempfile
from types import SimpleNamespace
from urllib.parse import quote
import production_cd as cd
import qa_env
def isolated_subnet(exclude=()):
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
data = json.loads(cd.run(['docker', 'network', 'inspect', *nets], 'read Docker networks')) if nets else []
occupied = [ipaddress.ip_network(row['Subnet']) for net in data for row in net['IPAM']['Config'] or []
if row.get('Subnet') and ':' not in row['Subnet']]
routes = json.loads(cd.run(['ip', '-j', '-4', 'route'], 'read host routes'))
occupied += [ipaddress.ip_network(route['dst'], strict=False) for route in routes if route['dst'] != 'default']
occupied += [ipaddress.ip_network(subnet) for subnet in exclude]
for subnet in ipaddress.ip_network('10.241.233.0/24').subnets(new_prefix=28):
if not any(subnet.overlaps(other) for other in occupied):
return str(subnet)
raise cd.CDError('no available candidate subnet')
def qa_database(path):
db = qa_env.database_config(path)
passfile, cert = [path.parent / name for name in ('qa.pgpass', 'rds-ca.pem')]
qa_env.private_file(passfile)
qa_env.private_file(cert)
expected = f"{db['host']}:{db['port']}:{db['database']}:{db['user']}:"
entries = [line for line in passfile.read_text().splitlines() if line and not line.startswith('#')]
cd.require(len(entries) == 1 and entries[0].startswith(expected), 'pgpass must authorize exactly the dedicated QA database')
password = re.sub(r'\\(.)', r'\1', entries[0][len(expected):])
cd.require(bool(password), 'dedicated QA database password missing')
url = (f"postgresql://{db['user']}:{quote(password, safe='')}@{db['host']}:{db['port']}/{db['database']}"
'?sslmode=verify-full&sslrootcert=/run/qa/rds-ca.pem')
return url, cert
def ready(directory, bundle, test_database=None):
bundle = bundle.resolve()
manifest = cd.read_json(bundle / 'release.json')
digest = cd.hash_file(bundle / 'release.json')
request = {key: manifest[key] for key in ('sha', 'task')}
request['bundle'] = digest
cd.verify_bundle(bundle, request)
project = 'kg-batch-' + digest[:20] + ('-smoke' if test_database is None else '')
cf = directory / 'compose.json'
receipt_path = directory / 'ready.json'
cmd = ['docker', 'compose', '-p', project, '-f', str(cf)]
if cf.exists():
cd.require(receipt_path.exists(), 'candidate startup is unresolved; inspect its Compose project')
receipt = cd.read_json(cd.immutable_file(receipt_path))
cd.require(receipt['task'] == request['task'] and receipt['bundle'] == digest, 'candidate already holds another bundle')
attest(bundle, receipt)
return receipt
services = {}
env = {'APP_ADDR': '0.0.0.0:8080', 'TEST_WEKNORA_ENABLED': 'false', 'PP_SCAN_ENABLED': 'false',
'RELEASE_WORKER_ENABLED': 'false', 'PRODUCTION_RELEASE_REQUESTS_ENABLED': 'false',
'DOBOTAI_OPS_READ_ENABLED': 'false', 'DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED': 'false'}
if test_database is None:
password = secrets.token_hex(24)
cd.atomic_write(directory / 'postgres.env', f'POSTGRES_USER=qa\nPOSTGRES_DB=governance\nPOSTGRES_PASSWORD={password}\n'.encode())
env['DATA' + 'BASE_URL'] = f'postgres://qa:{password}@postgres:5432/governance?sslmode=disable'
services['postgres'] = {'image': 'postgres:17-alpine', 'env_file': [str(directory / 'postgres.env')],
'tmpfs': ['/var/lib/postgresql/data'],
'healthcheck': {'test': ['CMD', 'pg_isready', '-U', 'qa', '-d', 'governance'],
'interval': '2s', 'timeout': '2s', 'retries': 20}}
else:
url, cert = qa_database(test_database)
env['DATA' + 'BASE_URL'] = url
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
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}
for role, item in manifest['images'].items():
archive = bundle / f'{role}.tar'
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]}
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['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'}})
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}]}}}
if test_database is None:
# The private smoke network has no NAT. Only the web container gets an ingress network.
networks['ingress'] = {'ipam': {'config': [{'subnet': isolated_subnet([internal_subnet])}]}}
services['web']['networks'] = {'default': {}, 'ingress': {}}
cd.record(cf, {'services': services, 'networks': networks})
try:
cd.run(cmd + ['up', '-d', '--no-build', '--pull', 'never'], 'start candidate Compose project', timeout=130)
raw_ports = json.loads(cd.run(['docker', 'inspect', '--format', '{{json .NetworkSettings.Ports}}', names['web']],
'read candidate web binding'))
port = (raw_ports or {}).get('8080/tcp') or []
cd.require(len(port) == 1 and port[0].get('HostIp') == '127.0.0.1'
and re.fullmatch(r'[1-9][0-9]{0,4}', port[0].get('HostPort', '')),
'candidate web has no verified loopback binding')
receipt = {**request, 'url': f'http://127.0.0.1:{port[0]["HostPort"]}', 'containers': names,
'images': {role: image['id'] for role, image in manifest['images'].items()},
'mode': 'smoke' if test_database is None else 'acceptance'}
cd.wait_ready(lambda: attest(bundle, receipt), seconds=65)
receipt['ready_at'] = cd.stamp()
cd.record(receipt_path, receipt)
return receipt
except Exception:
cd.run(cmd + ['down', '--timeout', '3'], 'stop unsuccessful candidate Compose project', timeout=40)
raise
def attest(bundle, receipt):
cd.require(cd.hash_file(bundle / 'release.json') == receipt['bundle'], 'candidate bundle changed after deployment')
cd.attest(SimpleNamespace(sha=receipt['sha'], task=receipt['task'], directory=bundle,
test_url=receipt['url'], **receipt['containers']))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('bundle', type=Path)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='kg-candidate-smoke-') as temp:
directory = Path(temp)
try:
print(json.dumps(ready(directory, args.bundle)))
finally:
if (directory / 'compose.json').exists():
digest = cd.hash_file(args.bundle / 'release.json')
cmd = ['docker', 'compose', '-p', 'kg-batch-' + digest[:20] + '-smoke', '-f', str(directory / 'compose.json')]
cd.run(cmd + ['down', '--timeout', '3'], 'remove disposable rehearsal containers', timeout=45)
if __name__ == '__main__':
try:
main()
except (cd.CDError, qa_env.QAError, OSError, ValueError) as exc:
sys.exit(f'Candidate runtime: {exc}')
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Local build worker for authenticated Gitea candidate jobs."""
import hmac
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import sys
from urllib.error import URLError
import candidate_coordinator as coordinator
import candidate_release as candidate
import candidate_runtime as runtime
import production_cd as cd
def verify_job(run_id, plan, repo):
cd.require(isinstance(run_id, str) and run_id.isascii() and run_id.isdigit() and 0 < len(run_id) < 16,
'invalid candidate workflow run')
target = candidate.API + f'/actions/runs/{run_id}'
run = candidate.read_forge(target)
sha = run.get('head_sha')
cd.require(run.get('event') == 'workflow_dispatch' and run.get('path') == 'prepare-candidate.yml@refs/heads/main'
and run.get('status') == 'in_progress' and (run.get('actor') or {}).get('id') == 1
and cd.matches(cd.SHA, sha), 'untrusted candidate workflow run')
file = '.gitea/workflows/prepare-candidate.yml'
cd.require(candidate.git('show', f'{sha}:{file}', cwd=repo) == Path(__file__).resolve().parents[1].joinpath(file).read_text().strip(),
'candidate workflow differs from locally installed instructions')
jobs = candidate.read_forge(target + '/jobs').get('jobs', [])
guard = [job for job in jobs if job.get('name') == 'guard' and job.get('conclusion') == 'success']
cd.require(len(guard) == 1 and type(guard[0].get('id')) is int, 'candidate guard did not succeed')
# Gitea logs are plaintext and may prefix each line with a timestamp.
raw = coordinator.hfx.forge('GET', candidate.API + f'/actions/jobs/{guard[0]["id"]}/logs', raw=True)
cd.require(len(raw) <= 2**20, 'candidate guard log exceeded the read limit')
lines = raw.decode().splitlines()
cd.require(sum(line.strip().endswith(candidate.proof(plan, 'prepare')) for line in lines) == 1,
'candidate input does not match Gitea guard proof')
def main_site_sha():
raw = cd.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=6', 'weknora-test',
'docker compose -p knowledge-governance-cloud-test -f /opt/knowledge-governance/compose.json '
'exec -T api /app/api --version-record-status'], 'read main site build identity',
allowed=(0, 1), timeout=15)
sha = json.loads(raw).get('commit_sha')
cd.require(cd.matches(cd.SHA, sha), 'main site did not report a full SHA')
return sha
def prepare(payload, repo):
cd.require(isinstance(payload, dict) and set(payload) == {'run', 'plan'}, 'invalid candidate job payload')
plan = payload['plan']
candidate.check_plan(plan)
key = cd.acceptance_digest(plan)
state = coordinator.STATE
conf = Path.home() / '.config/knowledge-governance/qa.json'
with cd.deploy_lock(state / 'runtime.lock'):
cd.require(coordinator.owner_plan(plan['task']) == plan, 'release owner plan changed')
runtime.qa_database(conf)
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=repo)
verify_job(payload['run'], plan, repo)
cd.require(main_site_sha() == plan['base'], 'release baseline differs from the live main site')
directory = state / key
directory.mkdir(mode=0o700, exist_ok=True)
for existing in state.glob('*/compose.json'):
cd.require(existing.parent == directory, 'another candidate owns the acceptance slot')
candidate.build(plan, repo, directory / 'bundle')
cd.require(coordinator.owner_plan(plan['task']) == plan, 'release plan changed after candidate build')
receipt = runtime.ready(directory, directory / 'bundle', conf)
coordinator.publish_candidate(plan, receipt, payload['run'])
return receipt
def serve(repo, access):
secret = cd.immutable_file(access).read_text().strip()
cd.require(cd.matches(cd.HASH, secret), 'invalid candidate access file')
coordinator.STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def respond(self, status, body):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_POST(self):
if self.path != '/prepare' or not hmac.compare_digest(self.headers.get('Authorization', ''), 'Bearer ' + secret):
self.respond(403, {'error': 'candidate authorization refused'})
return
try:
size = int(self.headers.get('Content-Length', 0))
cd.require(0 < size <= 65536, 'invalid candidate payload size')
self.connection.settimeout(10)
payload = json.loads(self.rfile.read(size))
self.connection.settimeout(60)
receipt = prepare(payload, repo)
self.respond(200, receipt)
except (cd.CDError, runtime.qa_env.QAError) as exc:
self.respond(409, {'error': str(exc)})
except (OSError, KeyError, ValueError, URLError) as exc:
self.respond(502, {'error': f'candidate operation failed: {type(exc).__name__}'})
ThreadingHTTPServer(('127.0.0.1', 38984), Handler).serve_forever()
if __name__ == '__main__':
if len(sys.argv) != 3:
sys.exit('usage: candidate_worker.py <source repository> <private access file>')
serve(Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve())
+4 -4
View File
@@ -360,10 +360,10 @@ def cmd_internal_contracts(go: str) -> int:
cwd=ROOT).returncode
if qa_rc:
return qa_rc
cd_rc = subprocess.run(py("-m", "unittest", "discover", "-s", "scripts", "-p", "test_production_cd.py", "-v"),
cwd=ROOT).returncode
if cd_rc:
return cd_rc
for pattern in ('test_production_cd.py', 'test_candidate_release.py'):
cd_rc = subprocess.run(py('-m', 'unittest', 'discover', '-s', 'scripts', '-p', pattern, '-v'), cwd=ROOT).returncode
if cd_rc:
return cd_rc
snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode
if snapshot_rc:
return 1
+2 -2
View File
@@ -19,7 +19,7 @@ PATH = Path.home() / '.local/state/kg-hifox-release'
RUN_ID = re.compile('[1-9][0-9]{0,14}')
def forge(method, path, payload=None):
def forge(method, path, payload=None, *, raw=False):
request = Request(cd.FORGE + path, method=method,
data=json.dumps(payload).encode() if payload is not None else None)
env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0', 'GIT_ASKPASS': '/bin/false'}
@@ -31,7 +31,7 @@ def forge(method, path, payload=None):
request.add_header('Authorization', 'Basic ' + auth)
request.add_header('Content-Type', 'application/json')
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=20) as response:
return json.load(response)
return response.read(2**20 + 1) if raw else json.load(response)
def hifox(cli, *args):
+59
View File
@@ -0,0 +1,59 @@
import unittest
from types import SimpleNamespace
import candidate_release as candidate
import production_cd as cd
BASE, A, B, OTHER = [c * 40 for c in 'abcd']
TASK, QA1, QA2, OWNER = [f'{n:08d}-1111-2222-3333-444444444444' for n in range(1, 5)]
RUN = {'sha': B, 'bundle': 'e' * 64, 'ready_at': '2026-11-01T10:00:00Z', 'url': 'http://127.0.0.1:39191'}
class CandidateReleaseTest(unittest.TestCase):
def setUp(self):
self.plan = {'task': TASK, 'sha': B, 'base': BASE,
'items': [{'task': QA1, 'pr': 20}, {'task': QA2, 'pr': 21}],
'extra': []}
self.prs = {n: {'merged': True, 'base': {'ref': 'main'}, 'merge_commit_sha': sha}
for n, sha in ((20, A), (21, B))}
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': 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_pr_must_be_merged_on_main_and_match_range(self):
self.prs[20]['base']['ref'] = 'test'
with self.assertRaisesRegex(cd.CDError, 'merged into main'):
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
def test_require_all_qa_reports_and_shared_regression(self):
sources = {QA1: (self.report, self.result()), QA2: (self.report, self.result())}
with self.assertRaisesRegex(cd.CDError, 'every requirement and the release task'):
candidate.check_qa(self.plan, RUN, sources, {OWNER})
sources[TASK] = (self.report, self.result())
candidate.check_qa(self.plan, RUN, sources, {OWNER})
def test_same_candidate_and_author_required(self):
for result, author, reason in ((self.result(sha=OTHER), OWNER, 'different candidate'),
(self.result(bundle='0' * 64), OWNER, 'different candidate'),
(self.result(), QA1, 'authorized QA'),
(self.result(failed=1), OWNER, 'not passed')):
sources = {QA1: (dict(self.report, actor={'id': author}), result),
QA2: (self.report, self.result()), TASK: (self.report, self.result())}
with self.subTest(reason=reason), self.assertRaisesRegex(cd.CDError, reason):
candidate.check_qa(self.plan, RUN, sources, {OWNER})
def test_preparation_rejected_from_review_branch(self):
import json
event = {'inputs': {'mode': 'prepare', 'plan': json.dumps(self.plan)}}
env = {'GITHUB_EVENT_NAME': 'workflow_dispatch', 'GITHUB_REPOSITORY': cd.REPO,
'GITHUB_REF': 'refs/heads/feat/candidate-release-batch'}
with self.assertRaisesRegex(cd.CDError, 'workflow from main'):
candidate.event_plan(event, env)
event['inputs']['mode'] = 'verify'
self.assertEqual(candidate.event_plan(event, env), (self.plan, 'verify'))
def result(self, **extra):
return {**RUN, 'verdict': 'passed', 'required': 2, 'passed': 2, 'failed': 0, 'blocked': 0, **extra}
+3 -13
View File
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { useOptionalAuth } from './auth'
import { WeKnoraConnections } from './WeKnoraConnections'
import { fetchProductionBindingOptions, fetchProductionBindings, saveProductionBindings } from './productionBindings'
import type { ProductionBindings } from './productionBindings'
import type { KnowledgeBaseOption } from './routingBindings'
@@ -42,15 +41,9 @@ export function ProductionBindingsSection() {
const next = await saveProductionBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft })
setBindings(next)
const where = `对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}`
const frozen = next.frozen + next.retargetable > 0
? `;已冻结目标 ${next.frozen} 条(不会被改写),仍可改指向 ${next.retargetable} 条`
: ''
const replan = next.replanned || next.retired_duplicates
? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}`
: ''
setMessage(next.production_connected
? `发布目标已更新:${where}${replan}${frozen}。之后新发布的“对内/对外”内容会写入这两个生产库。`
: `发布目标已保存:${where}${replan}${frozen};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`)
? `发布目标已更新:${where}。之后新发布的“对内/对外”内容会写入这两个生产库(已发布过的条目仍回到原目标)。`
: `发布目标已保存:${where};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`)
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存生产知识库绑定失败') }
finally { setSaving(false) }
}
@@ -69,14 +62,11 @@ export function ProductionBindingsSection() {
<option value="">{placeholder}</option>
{options.map((base) => <option key={base.id} value={base.id}>{optionLabel(base)}</option>)}
</select>
: <select value="" disabled aria-label={placeholder}>
<option value="">读不到生产库列表:先在上方把生产连接测通</option>
</select>
: <input value={value} onChange={(event) => onChange(event.target.value.trim())} placeholder={`${placeholder}(输入生产知识库 ID)`} aria-label={placeholder} />
)
return <section className="settings-panel wide" id="settings-production-bindings">
<div className="settings-section-heading"><div><h2>生产知识库绑定</h2><p>发布链路的“源库 → 目标库”:新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库。留空表示未绑定,按同 ID 语义发布。</p></div><button onClick={() => void load()} disabled={loading}>{loading ? '读取中…' : '重新读取'}</button></div>
<WeKnoraConnections environment="production" title="生产 WeKnora" placeholder="http://172.29.151.11:18093" onSaved={() => void load()} />
{error ? <p className="error-message" role="alert">{error}</p> : null}
{bindings ? <div className="kb-binding-grid">
{renderSide('对内生产知识库', bindings.internal_kb_id, bindings.internal_kb_name)}
+43 -148
View File
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { useOptionalAuth } from './auth'
import { WeKnoraConnections } from './WeKnoraConnections'
import { fetchRoutingBindingOptions, fetchRoutingBindings, saveRoutingBindings } from './routingBindings'
import type { KnowledgeBaseOption, RoutingBindings } from './routingBindings'
@@ -18,171 +17,67 @@ export function RoutingBindingsSection() {
const [message, setMessage] = useState('')
const load = useCallback(async () => {
setLoading(true)
setError(null)
setLoading(true); setError(null)
try {
const next = await fetchRoutingBindings()
setBindings(next)
setInternalDraft(next.internal_bound_by_ui ? next.internal_kb_id : '')
setExternalDraft(next.external_bound_by_ui ? next.external_kb_id : '')
try {
setOptions(await fetchRoutingBindingOptions())
} catch {
setOptions([])
}
} catch (cause) {
setError(cause instanceof Error ? cause.message : '读取测试知识库绑定失败')
} finally {
setLoading(false)
}
try { setOptions(await fetchRoutingBindingOptions()) } catch { setOptions([]) }
} catch (cause) { setError(cause instanceof Error ? cause.message : '读取测试知识库绑定失败') }
finally { setLoading(false) }
}, [])
useEffect(() => {
void load()
}, [load])
useEffect(() => { void load() }, [load])
const dirty =
bindings !== null &&
(internalDraft !== (bindings.internal_bound_by_ui ? bindings.internal_kb_id : '') ||
externalDraft !== (bindings.external_bound_by_ui ? bindings.external_kb_id : ''))
const dirty = bindings !== null && (internalDraft !== (bindings.internal_bound_by_ui ? bindings.internal_kb_id : '') || externalDraft !== (bindings.external_bound_by_ui ? bindings.external_kb_id : ''))
const sameSelection = internalDraft !== '' && internalDraft === externalDraft
const save = async () => {
setSaving(true)
setError(null)
setMessage('')
setSaving(true); setError(null); setMessage('')
try {
const next = await saveRoutingBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft })
setBindings(next)
const replan =
next.replanned || next.retired_duplicates
? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}`
: ''
const fallbacks: string[] = []
if (!next.internal_bound_by_ui)
fallbacks.push(
`对内回退到部署默认库 ${next.internal_fallback_kb_id ? `${next.internal_fallback_kb_id.slice(0, 8)}…` : '(未设置)'}`
)
if (!next.external_bound_by_ui)
fallbacks.push(
`对外回退到部署默认库 ${next.external_fallback_kb_id ? `${next.external_fallback_kb_id.slice(0, 8)}…` : '(未设置)'}`
)
setMessage(
`绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}${fallbacks.length ? `;${fallbacks.join(';')}` : ''}。此后“来源与目录”的标记按新绑定路由${replan}。`
)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '保存测试知识库绑定失败')
} finally {
setSaving(false)
}
const replan = next.replanned || next.retired_duplicates
? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}`
: ''
setMessage(`绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}。此后“来源与目录”的标记按新绑定路由${replan}。`)
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存测试知识库绑定失败') }
finally { setSaving(false) }
}
const optionLabel = (base: KnowledgeBaseOption) =>
`${base.name}(${base.knowledge_count} 文档 · ${base.id.slice(0, 8)}…)`
const renderSide = (
label: string,
boundID: string,
boundName: string,
fromEnv: boolean,
boundByUI: boolean,
fallbackID = ''
) => (
const optionLabel = (base: KnowledgeBaseOption) => `${base.name}(${base.knowledge_count} 文档 · ${base.id.slice(0, 8)}…)`
const renderSide = (label: string, boundID: string, boundName: string, fromEnv: boolean, boundByUI: boolean) => (
<div className={`kb-binding-side ${boundID ? 'bound' : 'warn'}`}>
<b>{label}</b>
<span>{boundID ? boundName || `${boundID.slice(0, 8)}…` : '未绑定 · 该方向的标记会被拒绝'}</span>
<small>
{boundID
? boundByUI
? boundName
? `UI 绑定 · ${boundID.slice(0, 8)}…`
: 'UI 绑定'
: fromEnv
? `回退到部署默认库 ${fallbackID ? `${fallbackID.slice(0, 8)}…` : '(未设置)'}`
: ''
: '请绑定一个测试知识库'}
</small>
<span>{boundID ? (boundName || `${boundID.slice(0, 8)}…`) : '未绑定 · 该方向的标记会被拒绝'}</span>
<small>{boundID ? (boundByUI ? (boundName ? `UI 绑定 · ${boundID.slice(0, 8)}…` : 'UI 绑定') : fromEnv ? '来自部署默认值(env)' : '') : '请绑定一个测试知识库'}</small>
</div>
)
const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) =>
options.length > 0 ? (
<select value={value} onChange={(event) => onChange(event.target.value)} aria-label={placeholder}>
<option value="">{placeholder}</option>
{options.map((base) => (
<option key={base.id} value={base.id}>
{optionLabel(base)}
</option>
))}
</select>
) : (
<select value="" disabled aria-label={placeholder}>
<option value="">读不到测试库列表:先在上方把测试连接测通</option>
</select>
)
return (
<section className="settings-panel wide" id="settings-routing-bindings">
<div className="settings-section-heading">
<div>
<h2>测试知识库绑定</h2>
<p>
“来源与目录”里的对内 / 对外标记按这里的绑定分发到对应的测试 WeKnora
知识库;保存后立即生效,无需重启。发布写入的生产知识库见「生产知识库绑定」。
</p>
</div>
<button onClick={() => void load()} disabled={loading}>
{loading ? '读取中…' : '重新读取'}
</button>
</div>
<WeKnoraConnections
environment="test"
title="测试 WeKnora"
placeholder="http://127.0.0.1:8092"
onSaved={() => void load()}
/>
{error ? (
<p className="error-message" role="alert">
{error}
</p>
) : null}
{bindings ? (
<div className="kb-binding-grid">
{renderSide(
'对内知识库',
bindings.internal_kb_id,
bindings.internal_kb_name,
bindings.internal_env_fallback,
bindings.internal_bound_by_ui,
bindings.internal_fallback_kb_id
)}
{renderSide(
'对外知识库',
bindings.external_kb_id,
bindings.external_kb_name,
bindings.external_env_fallback,
bindings.external_bound_by_ui,
bindings.external_fallback_kb_id
)}
</div>
) : null}
{bindings && !bindings.weknora_connected ? (
<p className="hint">当前读不到 WeKnora 的库列表:先在上面的连接卡把地址与密钥配好并测通,再回来选库。</p>
) : null}
{isAdmin && bindings ? (
<div className="kb-binding-editor">
<label>对内绑定 {editorFor(internalDraft, setInternalDraft, '选择对内知识库')}</label>
<label>对外绑定 {editorFor(externalDraft, setExternalDraft, '选择对外知识库')}</label>
<p className="hint">留空 = 取消 UI 绑定,回退到部署默认值;对内与对外必须是不同的库。</p>
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的知识库</p> : null}
<button onClick={() => void save()} disabled={saving || !dirty || sameSelection}>
{saving ? '正在校验并保存…' : '保存绑定'}
</button>
{message ? (
<p className="success-message" role="status">
{message}
</p>
) : null}
</div>
) : null}
{!isAdmin ? <p className="hint">仅管理员可修改测试知识库绑定。</p> : null}
</section>
const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) => (
options.length > 0
? <select value={value} onChange={(event) => onChange(event.target.value)} aria-label={placeholder}>
<option value="">{placeholder}</option>
{options.map((base) => <option key={base.id} value={base.id}>{optionLabel(base)}</option>)}
</select>
: <input value={value} onChange={(event) => onChange(event.target.value.trim())} placeholder={`${placeholder}(输入知识库 ID)`} aria-label={placeholder} />
)
return <section className="settings-panel wide" id="settings-routing-bindings">
<div className="settings-section-heading"><div><h2>测试知识库绑定</h2><p>“来源与目录”里的对内 / 对外标记按这里的绑定分发到对应的测试 WeKnora 知识库;保存后立即生效,无需重启。发布写入的生产知识库见「生产知识库绑定」。</p></div><button onClick={() => void load()} disabled={loading}>{loading ? '读取中…' : '重新读取'}</button></div>
{error ? <p className="error-message" role="alert">{error}</p> : null}
{bindings ? <div className="kb-binding-grid">
{renderSide('对内知识库', bindings.internal_kb_id, bindings.internal_kb_name, bindings.internal_env_fallback, bindings.internal_bound_by_ui)}
{renderSide('对外知识库', bindings.external_kb_id, bindings.external_kb_name, bindings.external_env_fallback, bindings.external_bound_by_ui)}
</div> : null}
{bindings && !bindings.weknora_connected ? <p className="hint">当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。</p> : null}
{isAdmin && bindings ? <div className="kb-binding-editor">
<label>对内绑定 {editorFor(internalDraft, setInternalDraft, '选择对内知识库')}</label>
<label>对外绑定 {editorFor(externalDraft, setExternalDraft, '选择对外知识库')}</label>
<p className="hint">留空 = 取消 UI 绑定,回退到部署默认值;对内与对外必须是不同的库。</p>
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的知识库</p> : null}
<button onClick={() => void save()} disabled={saving || !dirty || sameSelection}>{saving ? '正在校验并保存…' : '保存绑定'}</button>
{message ? <p className="success-message" role="status">{message}</p> : null}
</div> : null}
{!isAdmin ? <p className="hint">仅管理员可修改测试知识库绑定。</p> : null}
</section>
}
+3 -5
View File
@@ -424,14 +424,12 @@ describe('SystemSettingsView', () => {
expect(on).toContain('测试 WeKnora')
expect(on).toContain('可达 · 可接单')
expect(on).toContain('延迟 86ms')
expect(on).toContain('生产写入:开启 · 可提交生产请求')
expect(on).toContain('已启用 · 可提交生产请求')
expect(on).toContain('生产写入:开启')
expect(on).toContain('发布目标与凭据:管理员受限配置')
const off = view(false, false)
// 连接状态与生产写入是两行:闸门关掉不代表「连接不可达」,两个事实分开说。
expect(off).toContain('连接:可达')
expect(off).toContain('未启用')
expect(off).toContain('生产写入:关闭')
expect(off).not.toContain('被阻断')
// 卡片状态由真实探测/门禁驱动,写死的“已连接 / 未连接 / 生产映射:未配置”必须消失。
for (const removed of ['本地真实连接', '生产映射:未配置']) expect(off).not.toContain(removed)
// 生产端点可达性来自真实探活,且只说真话:探活不等于验证过接单能力。
@@ -455,7 +453,7 @@ describe('SystemSettingsView', () => {
initialSection="services"
/>
)
expect(blocked).toContain('生产写入:开启 · 恢复演练未核验')
expect(blocked).toContain('已启用 · 被阻断')
// 未配置生产端点时必须显式说「未配置」,不得靠文案含糊过去。
expect(blocked).toContain('端点探测:暂无真实探测结果')
const unconfigured = renderToStaticMarkup(
+26 -23
View File
@@ -119,15 +119,6 @@ export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string
return `端点探测:${label}${detail ? `(${detail})` : ''}`
}
// 生产卡片拆两行:连接是否可达,与生产写入是否开启是两件事 —— 以前把
// 「被阻断」混进连接状态,页面会自相矛盾(端点明明可达却显示被阻断)。
const productionConnectionLine = (monitor: MonitorOverview | null): string => {
const health = findHealth(monitor, '生产 WeKnora')
if (!health) return '连接:暂无探测结果'
if (!health.configured) return '连接:未配置'
return health.liveness === 'up' ? '连接:可达' : '连接:不可达'
}
export function SystemSettingsView({
sources,
connections,
@@ -208,12 +199,6 @@ export function SystemSettingsView({
setDirty(false)
onSave(candidateInput())
}
const productionConnectionLineText = productionConnectionLine(monitor)
const productionWriteLine = !productionEnabled
? '生产写入:关闭'
: productionBackupRestoreVerified
? '生产写入:开启 · 可提交生产请求'
: '生产写入:开启 · 恢复演练未核验'
return (
<main className="page-shell system-settings">
<header className="hero compact">
@@ -293,8 +278,14 @@ export function SystemSettingsView({
</article>
<article className="production">
<b>生产 WeKnora</b>
<span>{productionConnectionLineText}</span>
<small>{`${productionWeKnoraProbe(monitor)};${productionWriteLine};发布目标与凭据:管理员受限配置,本页不可回读`}</small>
<span>
{!productionEnabled
? '未启用'
: productionBackupRestoreVerified
? '已启用 · 可提交生产请求'
: '已启用 · 被阻断'}
</span>
<small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};发布目标与凭据:管理员受限配置,本页不可回读`}</small>
</article>
</div>
<div className="safe-setting-grid production-endpoint-form">
@@ -302,11 +293,27 @@ export function SystemSettingsView({
<>
<label>
测试地址
<input value={testEndpoint || '未配置'} readOnly disabled />
<input
value={testEndpoint}
onChange={(event) => {
setTestEndpoint(event.target.value)
setDirty(true)
}}
placeholder="https://weknora.test.example"
aria-invalid={!testEndpointValid}
/>
</label>
<label>
生产地址
<input value={endpoint || '未配置'} readOnly disabled />
<input
value={endpoint}
onChange={(event) => {
setEndpoint(event.target.value)
setDirty(true)
}}
placeholder="https://weknora.prod.example"
aria-invalid={!endpointValid}
/>
</label>
<label>
生产 ID
@@ -369,10 +376,6 @@ export function SystemSettingsView({
原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora
列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。
</small>
<p className="hint">
地址已移到「测试知识库绑定 /
生产知识库绑定」分区顶部的连接卡维护(可在那里测试连接);这里是回退值,只读。
</p>
{serviceSettingsValid ? null : (
<p className="error-message" role="alert">
格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产
-183
View File
@@ -1,183 +0,0 @@
import { useCallback, useEffect, useState } from 'react'
import { PasswordInput } from './PasswordInput'
import { useOptionalAuth } from './auth'
import {
fetchWeKnoraConnections,
keyLabel,
saveWeKnoraConnection,
testWeKnoraConnection,
verificationLabel,
} from './weknoraConnections'
import type { WeKnoraConnection, WeKnoraEnvironment } from './weknoraConnections'
interface Props {
environment: WeKnoraEnvironment
title: string
placeholder: string
onSaved?: () => void
}
// 连接卡:地址 + 写-only 密钥 + 真实列库测试。它只改「连哪台实例、用哪把钥匙」,
// 不碰绑定,也不触发任何同步或发布。
export function WeKnoraConnections({ environment, title, placeholder, onSaved }: Props) {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [connection, setConnection] = useState<WeKnoraConnection | null>(null)
const [endpointDraft, setEndpointDraft] = useState('')
const [keyDraft, setKeyDraft] = useState('')
const [testing, setTesting] = useState(false)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [message, setMessage] = useState('')
const [testedEndpoint, setTestedEndpoint] = useState('')
const load = useCallback(async () => {
try {
const all = await fetchWeKnoraConnections()
const found = all.find((item) => item.environment === environment) ?? null
setConnection(found)
setEndpointDraft(found?.endpoint ?? '')
} catch (cause) {
setError(cause instanceof Error ? cause.message : '读取连接失败')
}
}, [environment])
useEffect(() => {
void load()
}, [load])
const endpoint = endpointDraft.trim()
const keyEntered = keyDraft.trim() !== ''
const endpointChanged = connection !== null && endpoint !== connection.endpoint
const canTest = endpoint !== '' && !testing && !saving
const tested = testedEndpoint !== '' && testedEndpoint === endpoint
const canSave = endpoint !== '' && !saving && !testing && (keyEntered || endpointChanged ? tested : true)
const test = async () => {
setTesting(true)
setError(null)
setMessage('')
try {
const result = await testWeKnoraConnection(environment, {
endpoint,
...(keyEntered
? { api_key: keyDraft.trim(), key_action: 'replace' as const }
: { key_action: 'keep' as const }),
})
setMessage(result.message)
setTestedEndpoint(result.outcome === 'ok' ? endpoint : '')
if (result.outcome !== 'ok') setError(result.message)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '测试连接失败')
} finally {
setTesting(false)
}
}
const save = async (action: 'keep' | 'replace' | 'clear') => {
setSaving(true)
setError(null)
try {
const next = await saveWeKnoraConnection(environment, {
endpoint,
...(action === 'replace' ? { api_key: keyDraft.trim() } : {}),
key_action: action,
base_revision: connection?.revision ?? 0,
})
setConnection(next)
setEndpointDraft(next.endpoint)
setKeyDraft('')
setTestedEndpoint('')
setMessage(`已保存:${keyLabel(next)};最近一次测试:${verificationLabel(next)}。保存未触发任何同步或发布。`)
onSaved?.()
} catch (cause) {
setError(cause instanceof Error ? cause.message : '保存连接失败')
} finally {
setSaving(false)
}
}
const clearKey = () => {
if (!window.confirm('清除后该侧将没有任何可用密钥,发布与列库都会失败。确定清除?')) return
void save('clear')
}
const saveAction = keyEntered ? 'replace' : 'keep'
return (
<div className="weknora-connection-card" id={`settings-weknora-connection-${environment}`}>
<div className="kb-binding-grid">
<div className={`kb-binding-side ${connection?.verification === 'ok' ? 'bound' : 'warn'}`}>
<b>{title}</b>
<span>连接:{verificationLabel(connection)}</span>
<small>
{connection?.endpoint
? `地址:${connection.endpoint} · 密钥:${keyLabel(connection)}`
: '还没有配置地址与密钥'}
</small>
</div>
</div>
{connection && !connection.storage_ready ? (
<p className="hint">密钥存储不可用(主密钥文件缺失或权限不是 0600):可以读取当前状态,但保存会被拒绝。</p>
) : null}
{isAdmin ? (
<div className="kb-binding-editor">
<label>
{title}地址
<input
value={endpointDraft}
onChange={(event) => {
setEndpointDraft(event.target.value)
setTestedEndpoint('')
}}
placeholder={placeholder}
aria-label={`${title}地址`}
/>
</label>
<label>
API Key
<PasswordInput
autoComplete="new-password"
value={keyDraft}
onChange={(event) => {
setKeyDraft(event.target.value)
setTestedEndpoint('')
}}
placeholder={connection?.key_configured ? '留空 = 保留原密钥' : '粘贴 API Key'}
aria-label={`${title} API Key`}
/>
</label>
<p className="hint">
「测试连接」会真实请求该实例的知识库列表,并区分地址不可达 / 密钥无效 / 无权限 /
成功;换了地址或密钥必须先测通才能保存。撤销绑定请把下方目标库留空。
</p>
<div className="kb-binding-actions">
<button onClick={() => void test()} disabled={!canTest}>
{testing ? '正在测试…' : '测试连接'}
</button>
<button onClick={() => void save(saveAction)} disabled={!canSave}>
{saving ? '正在保存…' : '保存连接'}
</button>
{connection?.key_configured ? (
<button className="danger" onClick={clearKey} disabled={saving || testing}>
清除密钥
</button>
) : null}
</div>
{error ? (
<p className="error-message" role="alert">
{error}
</p>
) : null}
{message ? (
<p className="success-message" role="status">
{message}
</p>
) : null}
</div>
) : (
<p className="hint">仅管理员可修改连接与密钥;当前密钥只显示尾 4 位,任何接口都不会回读明文。</p>
)}
</div>
)
}
-8
View File
@@ -11,10 +11,6 @@ export interface ProductionBindings {
production_base_url: string
production_connected: boolean
production_message: string
frozen: number
retargetable: number
replanned: number
retired_duplicates: number
}
const record = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
@@ -29,10 +25,6 @@ function projection(item: Record<string, unknown>): ProductionBindings {
production_base_url: typeof item.production_base_url === 'string' ? item.production_base_url : '',
production_connected: item.production_connected === true,
production_message: typeof item.production_message === 'string' ? item.production_message : '',
frozen: typeof item.frozen === 'number' ? item.frozen : 0,
retargetable: typeof item.retargetable === 'number' ? item.retargetable : 0,
replanned: typeof item.replanned === 'number' ? item.replanned : 0,
retired_duplicates: typeof item.retired_duplicates === 'number' ? item.retired_duplicates : 0,
}
}
-4
View File
@@ -5,8 +5,6 @@ export interface RoutingBindings {
external_kb_id: string
internal_env_fallback: boolean
external_env_fallback: boolean
internal_fallback_kb_id: string
external_fallback_kb_id: string
internal_bound_by_ui: boolean
external_bound_by_ui: boolean
internal_kb_name: string
@@ -32,8 +30,6 @@ function bindingProjection(item: Record<string, unknown>): RoutingBindings {
external_kb_id: typeof item.external_kb_id === 'string' ? item.external_kb_id : '',
internal_env_fallback: item.internal_env_fallback === true,
external_env_fallback: item.external_env_fallback === true,
internal_fallback_kb_id: typeof item.internal_fallback_kb_id === 'string' ? item.internal_fallback_kb_id : '',
external_fallback_kb_id: typeof item.external_fallback_kb_id === 'string' ? item.external_fallback_kb_id : '',
internal_bound_by_ui: item.internal_bound_by_ui === true,
external_bound_by_ui: item.external_bound_by_ui === true,
internal_kb_name: typeof item.internal_kb_name === 'string' ? item.internal_kb_name : '',
-26
View File
@@ -882,29 +882,3 @@ button.link {
font-size: 0.8rem;
line-height: 1.5;
}
/* 连接卡:地址 + 写-only 密钥 + 真实列库测试。它嵌在既有的「测试/生产知识库绑定」
分区里,所以只做一个轻量内框,不另起一套分区样式。 */
.weknora-connection-card {
display: grid;
gap: 8px;
margin: 10px 0 16px;
padding: 12px;
border: 1px solid var(--border-base);
border-radius: 10px;
background: var(--bg-soft);
}
.weknora-connection-card .kb-binding-grid {
margin: 0;
grid-template-columns: 1fr;
}
.kb-binding-actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.kb-binding-actions button.danger {
border-color: var(--c-fail);
background: #fff;
color: var(--c-fail);
}
-116
View File
@@ -1,116 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
fetchWeKnoraConnections,
keyLabel,
saveWeKnoraConnection,
testWeKnoraConnection,
verificationLabel,
} from './weknoraConnections'
import type { WeKnoraConnection, WeKnoraVerification } from './weknoraConnections'
const connection: WeKnoraConnection = {
environment: 'production',
endpoint: 'http://172.29.151.11:18093',
key_configured: true,
key_tail: '9f2c',
verification: 'ok',
library_count: 4,
checked_at: '2026-11-22T07:00:00Z',
updated_by: 'admin',
revision: 3,
storage_ready: true,
}
describe('WeKnora connection API', () => {
it('projects only the safe fields and never surfaces a key', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: [{ ...connection, api_key: 'placeholder-key-value', key_ciphertext: 'AAAA' }],
}),
{ status: 200 }
)
)
)
const [projected] = await fetchWeKnoraConnections()
expect(projected.key_tail).toBe('9f2c')
expect(projected).not.toHaveProperty('api_key')
expect(projected).not.toHaveProperty('key_ciphertext')
vi.unstubAllGlobals()
})
it('renders the four answers distinctly', () => {
const withVerification = (verification: WeKnoraVerification): WeKnoraConnection => ({ ...connection, verification })
expect(verificationLabel({ ...connection, library_count: 4 })).toBe('可达 · 已读到 4 个知识库')
expect(verificationLabel(withVerification('key_invalid'))).toBe('密钥无效')
expect(verificationLabel(withVerification('key_forbidden'))).toBe('密钥无权限读取知识库列表')
expect(verificationLabel(withVerification('unreachable'))).toBe('地址不可达')
expect(verificationLabel(null)).toBe('未配置')
expect(keyLabel(connection)).toBe('已配置 · 尾9f2c')
expect(keyLabel({ ...connection, key_configured: false, key_tail: '' })).toBe('未配置')
})
it('tests through the environment route and keeps the outcome', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: {
environment: 'production',
endpoint: connection.endpoint,
outcome: 'key_forbidden',
library_count: 0,
message: '密钥无权限读取知识库列表(403)',
checked_at: '2026-11-22T07:00:00Z',
},
}),
{ status: 200 }
)
)
vi.stubGlobal('fetch', fetchMock)
const result = await testWeKnoraConnection('production', {
endpoint: connection.endpoint,
api_key: 'sk-live-x',
key_action: 'replace',
})
expect(result.outcome).toBe('key_forbidden')
expect(result.message).toContain('无权限')
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/weknora-connections/production/test')
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({ key_action: 'replace' })
vi.unstubAllGlobals()
})
it('saves with the revision and an idempotency key', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: connection }), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
const saved = await saveWeKnoraConnection('production', {
endpoint: connection.endpoint,
key_action: 'keep',
base_revision: 2,
})
expect(saved.revision).toBe(3)
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('/api/v1/weknora-connections/production')
expect(init.method).toBe('PUT')
expect(init.headers['Idempotency-Key']).toBeTruthy()
expect(JSON.parse(init.body)).toMatchObject({ key_action: 'keep', base_revision: 2 })
vi.unstubAllGlobals()
})
it('surfaces the server reason when a save is refused', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ error: '请先点「测试连接」并成功,才能保存这一侧的配置' }), { status: 400 })
)
)
await expect(
saveWeKnoraConnection('test', { endpoint: 'http://127.0.0.1:8092', key_action: 'keep', base_revision: 0 })
).rejects.toThrow('测试连接')
vi.unstubAllGlobals()
})
})
-145
View File
@@ -1,145 +0,0 @@
import { newOperationID } from './operationKey'
// 连接状态:地址 + 「有没有配过密钥」+ 上一次真实列库的结论。密钥本身永远不回到
// 页面,只回显尾 4 位。
export type WeKnoraVerification = 'not_configured' | 'ok' | 'unreachable' | 'key_invalid' | 'key_forbidden'
export type WeKnoraTestOutcome = 'ok' | 'unreachable' | 'key_invalid' | 'key_forbidden'
export type WeKnoraEnvironment = 'test' | 'production'
export interface WeKnoraConnection {
environment: WeKnoraEnvironment
endpoint: string
key_configured: boolean
key_tail: string
verification: WeKnoraVerification
library_count: number
checked_at: string | null
updated_by: string
revision: number
storage_ready: boolean
}
export interface WeKnoraConnectionTestResult {
environment: WeKnoraEnvironment
endpoint: string
outcome: WeKnoraTestOutcome
library_count: number
message: string
checked_at: string
}
type KeyAction = 'keep' | 'replace' | 'clear'
const record = (value: unknown): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
const verificationOf = (value: unknown): WeKnoraVerification =>
value === 'ok' ||
value === 'unreachable' ||
value === 'key_invalid' ||
value === 'key_forbidden' ||
value === 'not_configured'
? value
: 'not_configured'
function projection(item: Record<string, unknown>): WeKnoraConnection {
const environment = item.environment === 'production' ? 'production' : 'test'
return {
environment,
endpoint: typeof item.endpoint === 'string' ? item.endpoint : '',
key_configured: item.key_configured === true,
key_tail: typeof item.key_tail === 'string' ? item.key_tail : '',
verification: verificationOf(item.verification),
library_count: typeof item.library_count === 'number' ? item.library_count : 0,
checked_at: typeof item.checked_at === 'string' ? item.checked_at : null,
updated_by: typeof item.updated_by === 'string' ? item.updated_by : '',
revision: typeof item.revision === 'number' ? item.revision : 0,
storage_ready: item.storage_ready === true,
}
}
async function reason(response: Response, fallback: string): Promise<string> {
try {
const body = (await response.json()) as unknown
if (record(body) && typeof body.error === 'string' && body.error) return body.error
} catch {
/* keep the status text */
}
return `${fallback}(HTTP ${response.status})`
}
export async function fetchWeKnoraConnections(signal?: AbortSignal): Promise<WeKnoraConnection[]> {
const response = await fetch('/api/v1/weknora-connections', { signal, headers: { Accept: 'application/json' } })
if (!response.ok) throw new Error(await reason(response, '读取 WeKnora 连接失败'))
const value = (await response.json()) as unknown
if (!record(value) || !Array.isArray(value.data)) throw new Error('WeKnora 连接响应无效')
return value.data.filter(record).map(projection)
}
export async function testWeKnoraConnection(
environment: WeKnoraEnvironment,
input: { endpoint: string; api_key?: string; key_action?: KeyAction },
signal?: AbortSignal
): Promise<WeKnoraConnectionTestResult> {
const response = await fetch(`/api/v1/weknora-connections/${environment}/test`, {
method: 'POST',
signal,
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(input),
})
if (!response.ok) throw new Error(await reason(response, '测试连接失败'))
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('测试连接响应无效')
const data = value.data
return {
environment: data.environment === 'production' ? 'production' : 'test',
endpoint: typeof data.endpoint === 'string' ? data.endpoint : input.endpoint,
outcome:
data.outcome === 'key_invalid' || data.outcome === 'key_forbidden' || data.outcome === 'unreachable'
? data.outcome
: 'ok',
library_count: typeof data.library_count === 'number' ? data.library_count : 0,
message: typeof data.message === 'string' ? data.message : '',
checked_at: typeof data.checked_at === 'string' ? data.checked_at : '',
}
}
export async function saveWeKnoraConnection(
environment: WeKnoraEnvironment,
input: { endpoint: string; api_key?: string; key_action: KeyAction; base_revision: number },
signal?: AbortSignal
): Promise<WeKnoraConnection> {
const response = await fetch(`/api/v1/weknora-connections/${environment}`, {
method: 'PUT',
signal,
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() },
body: JSON.stringify(input),
})
if (!response.ok) throw new Error(await reason(response, '保存连接失败'))
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('保存连接响应无效')
return projection(value.data)
}
// verificationLabel 是页面唯一的口径:四态说清「哪里不通」,成功时带库数量。
export function verificationLabel(connection: WeKnoraConnection | null): string {
if (!connection || !connection.endpoint) return '未配置'
switch (connection.verification) {
case 'ok':
return `可达 · 已读到 ${connection.library_count} 个知识库`
case 'key_invalid':
return '密钥无效'
case 'key_forbidden':
return '密钥无权限读取知识库列表'
case 'unreachable':
return '地址不可达'
default:
// 填了地址但还没测过:说「尚未验证」,不要谎报不可达。
return '尚未验证'
}
}
export function keyLabel(connection: WeKnoraConnection | null): string {
if (!connection || !connection.key_configured) return '未配置'
return `已配置 · 尾${connection.key_tail || '—'}`
}