Compare commits

...

15 Commits

Author SHA1 Message Date
狐友 GXXP & LEN aac8538372 fix(settings): 绑定留档名称并按旧目标重指向待入库
build / build (push) Successful in 1m48s
- 迁移 000084 保存对内/对外绑定名称快照;清除密钥后仍显示已绑定库,不再只显示裸 ID
- 测试/生产换绑只重指向同一侧的旧目标,避免测试保存误改另一环境的待入库
- 已保存连接但没有可用密钥时拒绝改绑定,禁止静默回落文件 Key
- 生产换绑返回重指向/退休数量,页面提示与测试侧一致

验证:make verify(含隔离 PostgreSQL 集成用例)15/15 通过
2026-11-23 12:47:22 +08:00
狐友 GXXP & Miku 8b900a9ffb feat(settings): 页面录入测试/生产 WeKnora 连接与密钥并收敛可达性判定
连接(地址 + 写-only 密钥)从文件引用搬进治理库:AES-GCM 密文 + 独立 0600 主密钥,
页面与接口只回显尾 4 位;测试连接真实列库并区分 地址不可达/密钥无效/无权限/成功,
换地址或换密钥必须测通才能保存(迁移 000083)。

可达性判定收敛为 weknora.HTTPAllowed,客户端与监控探活共用;新增
WEKNORA_ALLOW_PRIVATE_HTTP 只放行 RFC1918/回环/链路本地。生产绑定只保留下拉,
保存后回报冻结/未冻结条数,已冻结目标不被改写。

(cherry picked from commit ad02e8bb9c)
2026-11-23 11:50:00 +08:00
zheromiku 8c76c54d8e Merge pull request 'fix(deploy): 兼容 HiFox 确认事件跨秒写入' (#22) from fix/hifox-approval-timestamps into main
build / build (push) Successful in 1m28s
2026-11-23 03:03:32 +08:00
姚章浩 084ee1b176 fix(deploy): 兼容 HiFox 确认事件跨秒写入
build / build (push) Successful in 1m29s
任务更新时间与状态事件分别写入,允许小幅时间偏差。
仍以最近事件验证操作者,并要求验收证据早于两条时间记录。
2026-11-23 03:01:42 +08:00
zheromiku 71971e8164 Merge pull request 'feat(deploy): 接通 HiFox 待发布自动触发' (#21) from feat/hifox-release-trigger into main
build / build (push) Successful in 1m28s
2026-11-23 02:59:40 +08:00
姚章浩 47428a8b58 feat(deploy): 接通 HiFox 待发布自动触发
build / build (push) Successful in 1m27s
将发布人的状态变更与业务验收报告绑定,复用 Gitea 发布及回滚链路。
从部署回执写入运行身份、镜像及主站登录入口,避免重复调度和回写。
2026-11-23 02:57:46 +08:00
zheromiku 91988a0d3b Merge pull request 'feat(deploy): 接通云治理主站的人工确认发布流水线' (#20) from ci-trial-governance-cd into main
build / build (push) Successful in 1m29s
2026-11-23 02:26:47 +08:00
姚章浩 07a0ee2644 fix(deploy): 使用 Gitea 单次人工确认发布
build / build (push) Successful in 1m46s
2026-11-23 02:24:18 +08:00
姚章浩 0b5de6ef7e feat(deploy): 接通云治理主站的人工确认发布流水线
build / build (push) Successful in 2m0s
2026-11-23 01:35:18 +08:00
zheromiku d7d636792d Merge pull request 'feat(qa): 自动准备知识治理测试环境' (#18) from feat/qa-environment-runner into main
build / build (push) Successful in 1m28s
2026-11-22 19:37:29 +08:00
姚章浩 89c484cdc4 feat(qa): 自动准备知识治理测试环境
build / build (push) Successful in 1m29s
为 HiFox QA 检出提供环境检查、锁定依赖、专用 RDS 迁移、服务探活、测试和进程清理。已在 QA 虚拟机通过 make verify,并验证缺少 RDS 配置、错误提交和端口冲突的阻断。
2026-11-22 19:30:49 +08:00
姚章浩 5e3362e2b0 docs(dev): 补充开发与测试环境指南
build / build (push) Successful in 1m29s
从 README 提供依赖、前后端启动、测试命令和非生产 RDS 准备步骤。已在独立 QA 检出通过 make verify,Vite 健康代理和 Chromium 页面冒烟通过。
2026-11-22 19:18:48 +08:00
zheromiku edd07a65d6 Merge pull request 'docs(ops): 更新架构、平台接入及反代运维手册' (#16) from docs/governance-ops-090-main into main
build / build (push) Successful in 1m28s
2026-11-22 13:17:09 +08:00
姚章浩 7c120b3adc test(qawemail): 用绝对域名断言不可解析主机
build / build (push) Successful in 1m57s
构建机 resolv.conf 带 search 域(Tailscale tailf49802.ts.net)时,
smtp.kg-test.invalid 会被拼成 ...tailf49802.ts.net 并由 Fake-IP DNS
解析成功,断言实际测的是构建机搜索域。改成带末尾点的绝对名后与
搜索域无关,仍保持“不可解析主机必须判非法”的原意。
2026-11-22 13:14:52 +08:00
姚章浩 ea159ca2fb docs(ops): 补充治理架构、平台接入与测试反代手册
build / build (push) Failing after 1m37s
2026-11-22 13:10:44 +08:00
67 changed files with 5521 additions and 339 deletions
+6
View File
@@ -43,6 +43,12 @@ 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
+82
View File
@@ -0,0 +1,82 @@
name: deploy-production
on:
workflow_dispatch:
inputs:
action:
description: deploy 或 writeback
required: true
default: deploy
sha:
description: 验收过的完整提交 SHA
required: true
bundle:
description: release.json 的完整 SHA256
required: true
task:
description: 对应的 HiFox 任务 UUID
required: true
confirm:
description: deploy-production 或 retry-writeback
required: true
approval_event:
description: HiFox 自动触发填写的状态事件 UUID
required: false
acceptance_digest:
description: HiFox 自动触发填写的验收记录摘要
required: false
concurrency:
group: cloud-test-governance-main-production
cancel-in-progress: false
permissions:
contents: read
jobs:
guard:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: 核对手动入口及发布输入
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_REF" = refs/heads/main
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
git init -q .
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
git checkout -q --detach "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
python3 scripts/production_cd.py guard --event "$GITHUB_EVENT_PATH"
publish:
needs: [guard]
runs-on: kg-production-cd
timeout-minutes: 40
steps:
- name: 取同一提交的控制端代码
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_REF" = refs/heads/main
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
git init -q .
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
git checkout -q --detach "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
- name: 调用云主站受限发布入口并读回回执
env:
KG_CD_SSH_KEY: ${{ secrets.KG_CD_SSH_KEY }}
KG_CD_KNOWN_HOSTS: ${{ secrets.KG_CD_KNOWN_HOSTS }}
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
+11
View File
@@ -33,11 +33,22 @@
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 的降级入口;保存后回报
「已冻结目标 / 仍可改指向」条数,已冻结的执行目标不被改写。
## 开发快照(首次发布入口:同步授权、目标权威基线与维护能力)
+8
View File
@@ -27,6 +27,14 @@ BUILD_TIME ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
verify:
$(PY) scripts/ci_checks.py
.PHONY: qa qa-doctor qa-self-test
qa:
$(PY) scripts/qa_env.py run
qa-doctor:
$(PY) scripts/qa_env.py doctor
qa-self-test:
$(PY) -m unittest discover -s scripts -p test_qa_env.py -v
# 清单:哪些是必需项、在哪个档案(local / ci)下必需
list:
$(PY) scripts/ci_checks.py --list
+11 -16
View File
@@ -71,15 +71,16 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
## 访问与部署
### 已部署环境
### 运行架构与访问入口
Compose 中网页入口固定映射为 **宿主机 `8088` → Web 容器 `8080`**。网页和 `/api/` 使用同源入口。
| 组件 | 职责 | 接手时从这里看 |
|---|---|---|
| React/Vite + Web Nginx | 提供静态页面,同源转发 `/api/` 和 `/health` | [前端开发代理](web/vite.config.ts)、[Compose 的 Nginx 配置](deploy/nginx.conf) |
| Go API + 治理 PostgreSQL | 认证、角色、来源、绑定、审核、任务与发布记录。云测试使用独立逻辑库 `knowledge_governance_test` | [API](cmd/api)、[接口契约](api/openapi.yaml) |
| 普通 worker + 测试 WeKnora | worker 取件、上传、轮询并记录验收结果。WeKnora 负责解析、切片和索引 | [worker](cmd/worker)、[来源接入](docs/OPERATIONS_RUNBOOK.md#接入外部平台) |
| 发布 worker + 生产 WeKnora | 按已锁定的批次和目标执行受控发布与读回。问答端通过下游服务使用已发布知识 | [发布 worker](cmd/release-worker)、[操作手册](docs/OPERATIONS_RUNBOOK.md) |
- 本机访问:`http://127.0.0.1:8088/`
- 局域网访问:`http://<服务器内网IP>:8088/`
- 健康入口:`http://127.0.0.1:8088/health`
可以由 NAS 反向代理提供 HTTPS 域名入口,目标为平台服务器的 `8088`,保持路径原样转发。公网开放前必须验证鉴权、访问控制及转发头配置,不直接暴露数据库或内部管理接口。
从自己的电脑做系统设置验收,使用 SSH 转发后的 `http://127.0.0.1:28189/`。云测试主控制台使用受限内网入口 `http://100.85.111.121:8088/`。仓内 Compose 则将宿主 `8088` 映射到 Web 容器 `8080`。选择入口时先确认要看的部署。隧道命令、生产 `090` 服务地址和 HTTPS 反代示例见[运维手册](docs/OPERATIONS_RUNBOOK.md#入口与反向代理)。
**平台入口展示当前部署版本,不是每次 CI 的构建预览。** CI 静态预览由独立链路提供;CI 通过不会自动更新运行服务。
@@ -94,18 +95,12 @@ Compose 中网页入口固定映射为 **宿主机 `8088` → Web 容器 `8080`*
- 来源目录、spool 与运行状态挂载;按部署主机调整路径和 UID/GID。
- 测试 WeKnora 连接与对内/对外路由;生产发布按独立配置和授权接线。
准备完成后,由获授权的操作者执行:
```bash
docker compose up --build -d
```
主机需要提权时,由操作者按本机权限规则执行,不在自动化中默认使用 sudo。停止服务可用 `docker compose down`;**不要执行 `docker compose down -v`,除非明确批准删除数据库卷。**
仓内 Compose 含 `postgres` 演练服务。云测试和生产使用阿里云 RDS,部署前先核对目标逻辑库、当前迁移版本、待运行的迁移及所用的环境配置。API 和 worker 启动可执行迁移。已有环境先用 `docker compose config --services` 检查服务清单,按该环境的发布手册切换已验证的产物。前端开发可直接使用下面的 Vite 流程。
## 配置与安全边界
- 网页服务地址用于控制台探活与配置核验;真正的发布目标由受限发布运行时配置决定,两者不能混为一谈。
- 密钥通过文件或 secret 引用提供,不写入 Git、网页响应或日志。示例配置不是真实凭据。
- 测试/生产 WeKnora 的地址与 API Key 可在「系统设置 → 测试/生产知识库绑定」里录入:密钥以 AES-GCM 密文存治理库(主密钥是独立 0600 文件),页面与接口只回显尾 4 位,日志、审计与响应都不出现明文。部署期仍可用文件引用作为兜底;示例配置不是真实凭据。
- 生产请求与 Release Worker 默认关闭;启用状态必须现场确认。测试处理成功、自动审核或批次锁定都不能绕过生产门禁。
- 来源扫描与取件不应改写原始业务资料;目标知识库的发布、移除和回滚属于独立受控动作。
- 发布与恢复前必须按目标环境准备备份,并核验可恢复性。
@@ -114,7 +109,7 @@ docker compose up --build -d
## 开发与 CI
基础环境:Go 1.26、Node.js 22、npm,以及检查脚本所需的 Python 3 和工具链。依赖以仓库锁文件和实际 CI 配置为准。
本机和 QA 虚拟机的依赖安装、前后端启动、测试命令及 PostgreSQL 测试库准备见 [开发与测试指南](docs/DEVELOPMENT_AND_TESTING.md)。
```bash
make verify # 完整检查入口:本地与 CI 使用同一套规则
+162
View File
@@ -3387,6 +3387,117 @@
}
}
},
"/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": [
@@ -5676,6 +5787,57 @@
}
},
"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,
+59 -8
View File
@@ -26,6 +26,7 @@ import (
"knowledge-governance/internal/qawemail"
"knowledge-governance/internal/serviceverify"
"knowledge-governance/internal/version"
"knowledge-governance/internal/weknoraconn"
)
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
@@ -129,17 +130,26 @@ func run(ctx context.Context, getenv func(string) string) error {
}
return settings.TestWeKnoraBaseURL
}
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})
// 「连接」是页面可配的一等状态:地址 + 写-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})
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,
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,
})
// 「版本记录」:只读查询面在 API 侧接线;真正的抓取在 worker 侧(未配置来源即未接线)。
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
@@ -185,10 +195,14 @@ func run(ctx context.Context, getenv func(string) string) error {
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
RoutingBindings: postgresstore.NewStore(pool),
KnowledgeBases: knowledgeBaseLister,
KnowledgeBases: connectionAwareBases{service: connectionService, fallback: knowledgeBaseLister, allowPrivate: config.WeKnoraAllowPrivateHTTP},
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,
@@ -255,3 +269,40 @@ 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,6 +70,12 @@ 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
+131
View File
@@ -0,0 +1,131 @@
# 知识治理平台开发与测试
以下命令从仓库根目录运行。日常开发可在 Ubuntu 宿主进行,指定提交的回归在 `hifox-qa` 的独立检出中运行。部署到阿里云测试服后的验收按 [操作 Runbook](OPERATIONS_RUNBOOK.md) 和 [用户流程验收](USER_FLOWS_ACCEPTANCE.md) 执行。
## QA 虚拟机一键回归
在 `hifox-qa` 检出提测提交后,运行下列入口。将 SHA 占位值换成提测记录里的完整提交 SHA。
```bash
make qa-doctor
KG_QA_SHA='<完整提交 SHA>' make qa
```
`make qa-doctor` 检查工具链、HiFox 机器在线状态、OMP 模型调用、测试库身份和已安装的迁移。`make qa` 安装锁定依赖,在专用测试库上通过 API 初始化和迁移,随后核对完整迁移序列、API 就绪状态、Web 首页及 Vite 健康代理。通过后执行 Go 和 Vitest 测试,结束时关闭本次启动的服务。每次运行的服务日志保存在 `~/.local/state/knowledge-governance/qa/`。需要提交前完整门禁时执行 `make verify`。
初次配置由负责人在 QA 虚拟机准备 `~/.config/knowledge-governance/`。以下示例使用虚构的 RDS 主机名。
| 文件 | 内容 |
| --- | --- |
| `qa.json` | 当前用户所有、权限 `0600`,字段 `host`、`port`、`database`、`user` |
| `qa.pgpass` | 当前用户所有、权限 `0600`,填写与 `qa.json` 匹配的口令条目 |
| `rds-ca.pem` | 对应实例的 CA 证书,用于校验 RDS 主机名 |
```json
{"host":"rds.example.test","port":5432,"database":"kg_qa_app","user":"kg_qa_app"}
```
专用非生产 RDS 库和角色以 `kg_qa_` 开头,权限和网络准备见第 2 节。首次运行接受空库,后续运行接受与当前提交兼容的迁移序列。缺库、认证失败、迁移不兼容和端口冲突均会使命令非零退出。浏览器业务 E2E 和专用集成库的 Go 测试按第 4 节执行。
## 1. 检出代码与安装依赖
准备 Git、Make、Python 3、Go 1.26(含同一工具链的 `gofmt`)、Node.js 22 和 npm。数据库检查另需 PostgreSQL 客户端 `psql`。首次安装依赖需要能访问 Go 和 npm 的依赖源。
```bash
# QA 在独立克隆中拉取提测分支,使用提测记录里的完整提交 SHA
export KG_TARGET_BRANCH='<提测分支名>' KG_TARGET_SHA='<完整提交 SHA>'
git fetch origin "$KG_TARGET_BRANCH" && git switch --detach "$KG_TARGET_SHA" &&
test "$(git rev-parse HEAD)" = "$KG_TARGET_SHA" && test -z "$(git status --porcelain)"
# 上面的命令链若失败,先解决检出或工作区问题再继续
# 检查当前 shell 的工具链,非交互任务也应设置相同的 PATH
export PATH="$(go env GOROOT)/bin:$PATH"
go version
command -v gofmt
node --version
npm --version
python3 --version
make deps-install
```
`make deps-install` 通过 `go mod download` 和 `npm ci` 安装依赖。Go 依赖由 `go.mod` / `go.sum` 约束,前端由 `web/package-lock.json` 锁定。依赖安装失败时先检查工具链、依赖源和锁文件,避免临时改写清单来绕过问题。
## 2. 准备开发和测试数据库
无库检查可直接跳到第 4 节。启动 API 或执行真库测试前,由数据库管理员在**非生产 PostgreSQL RDS** 上预建专用空库和登录角色。建议分配 `kg_qa_app` 给应用冒烟,`kg_qa_it` 给 Go 集成测试,各用独立角色。开发宿主另用开发专用库,避免与 QA 共享数据。库未分配时先申请,启动流程以库已存在为前提。
| 用途 | 所需权限 | 数据初始化 |
| --- | --- | --- |
| 应用启动与 UI 冒烟 | `CONNECT`,以及目标 schema 内的 `USAGE`、`CREATE` 和对应用对象的读写权限。迁移角色须能修改自己创建的对象。 | 首次 API 启动执行仓库内嵌迁移。用户表为空时创建初始管理员,首次登录必须修改密码。初始口令通过测试环境负责人交接。 |
| Go PostgreSQL 集成测试 | `CONNECT` 和目标测试库的 `CREATE` 权限,用于建立各用例自己的 schema。 | 用例创建隔离 schema、执行迁移、写入测试数据并清理。相同测试不要并发指向同一个库,避免固定 schema 名冲突。 |
两类角色均只授予对应非生产库所需的权限。使用空库和合成数据。密码由操作者在目标机配置到权限为 `0600` 的 PostgreSQL passfile,条目按 `host:port:database:user:password` 填写。使用 RDS CA 校验证书。以下命令先读回实际数据库、角色与 TLS 状态,核对三者再启动 API 或运行真库测试。
```bash
# 用获准的 RDS 主机名、端口、库名、角色和文件路径替换示例值
export PGHOST='<非生产 RDS 主机名>' PGPORT=5432
export PGDATABASE=kg_qa_app PGUSER=kg_qa_app
export PGPASSFILE="$HOME/.config/knowledge-governance/qa.pgpass"
export PGSSLROOTCERT="$HOME/.config/knowledge-governance/rds-ca.pem"
export PGSSLMODE=verify-full PGCONNECT_TIMEOUT=5
psql -X -v ON_ERROR_STOP=1 -c \
'SELECT current_database(), current_user, ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid();'
```
如果是云厂商提供的私网地址,先确认执行机通过获准的网络路径可访问 RDS。库名、角色、TLS、连接权限或迁移权限有问题时,先交由环境负责人核对配置。实例上已有数据的库不能当作空库初始化。
## 3. 启动后端和前端
**终端 A,启动 API。** 在干净 shell 中执行第 2 节的应用库配置和连通性检查。使用独立测试配置,不加载现网 `.env`。
```bash
export DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5"
export APP_ADDR=127.0.0.1:8088
export TEST_WEKNORA_ENABLED=false PP_SCAN_ENABLED=false
export RELEASE_WORKER_ENABLED=false PRODUCTION_RELEASE_REQUESTS_ENABLED=false
export DOBOTAI_OPS_READ_ENABLED=false DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED=false
go run ./cmd/api
```
API 会在监听前连接 PostgreSQL、应用迁移并初始化管理员。Web 页面和同步 API 联调只需运行 API 与 Vite。需要验证后台队列时,另用相同的隔离应用库配置启动普通 worker(`go run ./cmd/worker`)。涉及取件或来源刷新的任务还依赖容器内 `/app/scripts` 及获准的来源接线,按部署说明准备。发布 worker 无需启动。
Vite 通过 `localhost:8088` 转发 `/api` 和健康检查。如果 `8088` 已被其他部署占用,使用端口空闲的 QA 虚拟机运行本节。仅改前端时,可复用一个获准联调的测试 API,但需要先确认 `localhost:8088/health` 可达,并核对该地址指向的环境。
**终端 B,启动 Web。**
```bash
npm --prefix web run dev -- --host 127.0.0.1 --port 5173 --strictPort
```
在运行服务的机器打开 `http://127.0.0.1:5173/`。另开终端检查 API 与前端代理,再复查迁移记录。最后一条命令需要第 2 节的应用库配置。
```bash
curl --fail --silent --show-error http://127.0.0.1:8088/health
curl --fail --silent --show-error http://127.0.0.1:5173/health
psql -X -v ON_ERROR_STOP=1 -c \
'SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1;'
```
空库首次启动后,用专用测试账号登录,按当次验收标准验证页面及接口。联调结束在两个终端按 `Ctrl+C` 停服务,数据库由环境管理员按测试数据保留规则管理。
## 4. 选择测试命令
| 目的 | 命令 |
| --- | --- |
| 查看检查及适用范围 | `make list` |
| 后端包测试 | `make tests-go` |
| 单个 Go 包及相关子包 | `go test -count=1 ./internal/httpapi/...` |
| 前端 Vitest 套件 | `make tests-web` |
| 单个前端测试文件 | `npm --prefix web test -- src/App.test.tsx` |
| 完整提交前检查,与 CI 共用入口 | `make verify` |
`make verify` 包含安装、格式、静态检查、构建、测试、版本和安全检查,并写出 `ci-report.json`。在未导入真库测试配置的 shell 中运行。若检出时用了 `--no-tags`,先执行 `git fetch --tags origin`,以便版本检查读取正式标签对应的提交。依赖安装与安全检查需要相应网络或缓存。允许跳过的外部依赖用例见 [test-scope.json](../scripts/test-scope.json),真库测试应单独执行并记录结果。
在应用冒烟之外验证真实 PostgreSQL 行为时,重新按第 2 节切换并核对 **集成测试库和角色**,然后执行目标用例。下面以 UI 设置版本切换用例为例。
```bash
TEST_DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5" \
go test -count=1 -v ./internal/platform/postgres -run '^TestUISettingsActivationRetiresPreviousRevisionIntegration$'
```
检查输出出现目标用例的 `PASS`。用例被跳过或没有匹配时,应补齐配置或纠正用例名后重跑。前端 Vitest 负责组件与业务逻辑检查,浏览器 E2E 应单独执行并按 Feature 保存证据。提测记录至少包括完整提交 SHA、执行命令、退出码,以及失败用例的日志或浏览器截图。
+85 -3
View File
@@ -3,7 +3,88 @@
按"实际干活顺序"排列的**现在的**操作流程。标注:**【新】**本期新增(含本次会话与 `f4e1ecc/6496ee3/9155bd3` 的 dws 取件)|**【变】**既有流程本期有改动|**【既有】**未变,仍照旧走。
逐条验收证据请看 `docs/USER_FLOWS_ACCEPTANCE.md`;细节规则看各自专题文档。
统一入口 **http://127.0.0.1:8088/**(测试栈,右侧面板可直接操作)。角色:管理员 / 文档工程师 / 只读。
管理员配置连接和发布授权,文档工程师维护资料,只读成员查看进度。先确定要操作的环境,再按下面的接线与验收步骤进入业务流程。
云测试治理主站自身的应用升级见[主站应用 CD](PRODUCTION_CD_RUNBOOK.md)。
## 入口与反向代理
| 请求从哪里发出 | 地址或路径 | 实际目的地 |
|---|---|---|
| 已接入内网的运维电脑 | `http://100.85.111.121:8088/` | 云测试治理主站 |
| 开发电脑的浏览器 | `http://127.0.0.1:28189/` | SSH 转发到测试机回环 `28189`,由候选 Web 提供静态资源 |
| 测试候选 Nginx(host 网络) | `/api/`、`/health` | 测试机 `127.0.0.1:18099` 候选 API |
| 同一候选 Nginx | `/api/v1/qa-ops/ai/` | 测试机 `127.0.0.1:18098` 现用治理 API,负责模型配置和连接验证 |
| 标准 Compose Web(容器网络) | `/api/`、`/health` | Docker DNS 解析 `api:8080`。静态资源和 SPA 回退由同一 Web 提供 |
**在开发电脑恢复验收入口。** 前提是 SSH 别名 `weknora-test` 能登录测试机。先查远端服务,再查本机监听。本机端口空闲且远端正常时,在独立终端运行第三条命令,保留该终端。在另一终端执行最后一条并用浏览器打开同一地址。
```bash
ssh weknora-test 'curl -fsS --max-time 5 http://127.0.0.1:28189/health'
ss -ltn 'sport = :28189'
ssh -NT -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 127.0.0.1:28189:127.0.0.1:28189 weknora-test
curl -fsS --max-time 5 http://127.0.0.1:28189/health
```
**为内网域名配置 HTTPS。** 在能访问测试主站的受信任反代机上配置证书、内部 DNS 和访问范围。以下片段放入已有 HTTPS `server`,完整保留 URI、Host 和会话 Cookie。上游应选治理 Web 入口,使 `/assets/`、`/api/`、`/health` 走同一域名。若该入口的内层代理也设置 `X-Forwarded-Proto`,联调时检查其保留受信任 TLS 终止层的协议值以及登录回调的实际 URL。
```nginx
location / {
proxy_pass http://100.85.111.121:8088;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
```
在反代机执行 `nginx -t` 校验待应用配置。入口启用后,通过该域名验证登录、一次 `/api/` 请求和首页实际引用的 JS/CSS。`index.html` 应重新校验,带哈希的资源可长期缓存,缺失的 JS 返回 404。候选切换前后分别记录通用上游和 AI 专用上游。现场可在测试机用以下只读命令查看,容器名以当时部署为准。仓内同源配置见 [deploy/nginx.conf](../deploy/nginx.conf)。
```bash
docker exec kg-test-storage-ui-6444814 nginx -T 2>&1 | grep -E 'listen .*28189|location /api/v1/qa-ops/ai/|set \$(api|health)_upstream|proxy_pass http://127[.]0[.]0[.]1:18098'
docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage-ui-6444814 kg-accept-090-api
```
**现场版本与回退。** 本次在测试机读到 Web 标签 `4b615abe534b`、API 标签 `341c3154ac91`。完整候选包的 `current` 链接位于 `/opt/knowledge-governance/acceptance/090/current`,单独切换的 Web 位于同级 `web-only/4b615abe534b/dist`,实际反代配置位于 `integration/28189.conf`。切换前记录这三处、容器标签与旧 Web 名称。静态页回退时恢复上次的 Web 资源和对应代理配置。完整候选回退按同批装配工具的 `deploy/accept-090/README.md` 执行。回退后用浏览器重新验证首页资源、模型连接和列库。数据库迁移另按备份与恢复方案处理。
本次已核实共享测试治理库到 `000082`。对内、对外独立启用的实现依赖 `000083`,待独立库联调或共享库迁移获准后,再验证单侧暂停、保存和刷新。生产 `070` 不在该套验收范围。
下文系统设置中的绑定、盘点和模型连接步骤适用于上表的测试候选版本。根据现场标签选择对应版本的代码和交付物。
## 接入外部平台
| 平台与用途 | 管理员或运维怎样接 | 接通的证据 |
|---|---|---|
| 钉钉知识库,取目录和文件 | 系统设置 → 数据源配置 → 钉钉授权。用 DWS 设备授权,以来源账号选择组织、空间和范围。API 与 worker 使用部署约定的 DWS 身份目录 | 登录后读回预期空间,选一个有权限的目录校验。登记来源、扫描完成和文件取件分别核验。 |
| AList,取工业或教育资料 | 按来源登记服务根地址和允许的目录。普通 worker 读取专用令牌文件。目录接口 `POST /api/fs/list` 使用 `X-Gateway-Token` | 在来源页扫描已知根目录,对照一个子目录和一份文件。下载遵循来源签名链接,凭据和签名 URL 仅留在受控运行环境。[目录与取件](SOURCE_CATALOG_LIVE_ROUTING_ACCEPTANCE.md) |
| PP 资料门户 | 在数据源配置填写 HTTPS 根地址和来源账号,点「测试连接」后「保存并校验」。API 和 worker 共享 `PP_AUTH_STATE_FILE` 所在目录 | 真实登录并读取一条目录记录,刷新后核对生效配置。超时或限流时查看待验证状态。 |
| WeKnora 测试 090,处理与验收 | 系统设置 → 知识库绑定 → 测试 090。当前测试 API 地址 `http://127.0.0.1:8092`,由治理服务器访问。输入该实例的专用 Key 或使用已配置凭据 | 「验证并读取知识库」能列出预期库。核对名称和 ID,为对内、对外选择不同的目标,保存后刷新读回 |
| WeKnora 生产 090,列库与映射 | 在同页切到生产 090,使用下节的转发入口与生产专用 Key。新连接的安全存储由 `WEKNORA_BINDING_MASTER_KEY_FILE` 提供 | 读取生产目录并核对两个目标 ID,保存后重新进入生产页核实。执行发布另按 §5–6 授权 |
| 问答 AI 模型 | 系统设置 → AI 模型连接,填写 OpenAI 兼容基础地址(含服务要求的 `/v1`)、模型名及专用 Key。API 与普通 worker 使用同一 `QA_AI_MASTER_KEY_FILE` | 点「测试连接」等待成功,需生效时再保存并刷新检查模型名。存储密钥、权限与 DNS 配置见 [README](../README.md#问答运营模型配置) |
**生产 090 的两段地址。** 生产机私网 IP 为 `172.29.151.11`,其 WeKnora API 对宿主回环发布 `127.0.0.1:18092`。测试治理机上已有 SSH 本地转发,治理 API 使用 host 网络,故页面的生产服务地址填写 **`http://127.0.0.1:18092`**。请求从治理 API 发出,经测试机的回环监听到生产机的回环 API。浏览器所在电脑的 `127.0.0.1:28189` 则用于打开治理页面。迁到 bridge 网络时要从新 API 容器重新验证上游可达性。
在**测试治理机**上检验已有通道。`/health` 返回 200 证明转发可用,无凭据列库返回 401 表明请求已到认证层。接着在治理页面安全输入该实例的 Key 并验证真实库列表。本次核验时,生产通道探活成功,匿名列库返回 401。带生产凭据列库和保存映射仍待验收。
```bash
ss -ltnp 'sport = :18092'
curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'health %{http_code}\n' http://127.0.0.1:18092/health
curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'catalog %{http_code}\n' http://127.0.0.1:18092/api/v1/knowledge-bases
```
## 开发测试和现场验收
1. 在开发机运行 `make list` 查看门禁,`make verify` 做整套检查。以 `ci-report.json` 的 `commit_sha` 对照 `git rev-parse HEAD`,记录失败或跳过项。前端启动和组件测试见 [开发与 CI](../README.md#开发与-ci)。
2. 针对后端改动,在独立测试逻辑库核对 `SELECT current_database(), max(version) FROM schema_migrations;` 与候选版本的迁移目录。云端多个候选可能共用治理 RDS。只改静态页面时单独切换 Web,保留原资源和代理配置供回滚。
3. 在指定入口以真实账号分别验证。来源页读取一条已知记录,模型页测试到成功终态,知识库绑定在正确环境列库,保存后刷新核对。存储页按最近批次和子库目录分别与 `du -sB1 -- <目录>` 对账。记录入口、Web/API 提交、时间和结果。
4. 候选备份页读取宿主采集的 `metadata.json`,API 只读挂载输出目录。「重新盘点」只重读文件。超过 `BACKUP_HOST_METADATA_MAX_AGE` 时,目录、占盘和预测转为未知。宿主重新采集后核对采集时间是否前进、批次是否恢复。测试现场使用按次采集、15 分钟有效期。采集脚本和挂载参数以同批测试候选交付物为准。
| 症状 | 第一步怎么查 | 如何判定 |
|---|---|---|
| 浏览器连接被拒 | 对照本机 `28189` 监听和测试机 `/health` | 远端正常、本机无监听时恢复本机 SSH 转发 |
| 页面打开,某个 API 404 或 502 | 查浏览器请求路径、Nginx 生效上游及对应 API 版本 | 404 先查路由是否存在,502 先查上游是否可达。AI 页单独核对 `18098` |
| 能探活,列库仍灰或返回 401 | 核对选中环境、凭据配置状态、容器运行 UID 与凭据文件可读性 | 用该环境的专用身份实际列库。检查过程只记录状态码和可读性 |
| 历史可读,计划或配额显示未知 | 核对快照年龄、执行主机连接与配额字段 | 盘点、SSH 计划、配额分别验证。只有主机实际读回 cron 才能报告下一次执行时间 |
---
@@ -81,8 +162,9 @@ 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 |
+53
View File
@@ -0,0 +1,53 @@
# 云测试治理主站应用 CD
正式入口为 `http://100.85.111.121:8088/`。云端 Compose 项目为 `knowledge-governance-cloud-test`,工作目录 `/opt/knowledge-governance`,当前配置链为 `compose.json`,服务为 `api`、`web`、`worker`。Web 容器提供 `8088`,通过挂载的 nginx 配置代理 API 的 `127.0.0.1:18098`。应用 CD 与知识库内容发布各自保留原有授权流程。
## 建立验收产物
1. 从干净检出的完整提交构建一次 API、worker、web 镜像。构建调用方对三个镜像都注入 `org.opencontainers.image.revision=<完整 SHA>`。API 构建身份沿用 `scripts/version.py --identity` 输出,传给 Dockerfile 的版本、提交和构建时间参数。API 与 worker 各自记录镜像 ID,即使它们来自同一个 Dockerfile。
2. 封存后用同一份归档部署到隔离验收环境。输出目录必须是新路径,父目录应已存在。三个 `--api/--web/--worker` 参数是本地镜像的完整 ID。
```bash
python3 scripts/production_cd.py pack --sha "$SHA" --task "$TASK_UUID" \
--api "$API_ID" --web "$WEB_ID" --worker "$WORKER_ID" --output "$BUNDLE_DIR"
docker load -i "$BUNDLE_DIR/api.tar"
docker load -i "$BUNDLE_DIR/web.tar"
docker load -i "$BUNDLE_DIR/worker.tar"
```
3. 用验收环境自身的 Compose 和数据库启动这些镜像。用下面的命令读回验收环境运行身份。此处三个服务参数是实际的**测试容器名**。在业务验收入口执行实际用例并将输出、结果与报告链接放在同一份验收记录里。
```bash
python3 scripts/production_cd.py attest --sha "$SHA" --task "$TASK_UUID" \
--api "$QA_API" --web "$QA_WEB" --worker "$QA_WORKER" --test-url "$QA_URL" --directory "$BUNDLE_DIR"
BUNDLE_SHA=$(sha256sum "$BUNDLE_DIR/release.json" | cut -d' ' -f1)
```
4. 由验收人使用获授权的 HiFox CLI 登记业务结论,读回任务、验收字段和状态。`cd_acceptance` 是 JSON 字符串类型的 metadata,其解析结果为 `{"verdict":"passed","sha":"…","bundle":"…","evidence":"https://…"}`。录入人应先核对真实报告与运行身份。自动发布时,`evidence` 使用同一 HiFox 任务的验收报告评论链接(带 `#comment-<UUID>`)。评论须正文包含完整提交和归档清单摘要,并在发布人确认前完成。用 `task view --output json` 核对实际任务 UUID、空间、状态和验收字段。验收登记重试复用原归档摘要与原记录。以当前版本只接受一个任务,多个任务分别验收。
5. 在首次发布前,由运维把四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
## 在 HiFox 确认发布
验收、登记、上传归档都完成后,由发布人把原任务移入「待发布」。HiFox 的「知识治理|待发布自动执行 CD」把任务 UUID 交给专用发布 Agent,Agent 调用白名单内的 `scripts/hifox_release_trigger.py`。桥接脚本读取 HiFox 时间线,校验最近一次状态变更的操作者、状态、同任务验收报告及产物摘要,随后调度 Gitea `deploy-production@main`。Gitea 仍只开放 `workflow_dispatch`。目标控制器按完整输入校验 Gitea 运行,并在切换前复查 HiFox 状态和验收摘要。
相同状态事件复用已记录的 Gitea 运行。如果调度结果未知,核查对应 Gitea 运行与本机调度记录后再处理。旧任务已处于「待发布」时,在验收登记完成后重新进入该状态可发起新确认。
也可由发布人使用 Gitea Actions 中原有人工入口应急。分支选 `main`,使用 `action=deploy`、完整 `sha`、`bundle`、任务 UUID `task` 和 `confirm=deploy-production`,仅 HiFox Agent 填写 `approval_event` 和 `acceptance_digest`。
主站侧从 Gitea 读取运行、操作者和通过的校验作业,并验证输入摘要及工作流代码。候选代码可来自仓库内的任务分支,以实际验收 SHA 为准。切换前还核验必需 CI 状态、HiFox 验收记录、三份归档、线上源代码血缘及数据库迁移账本。切换复用 `scripts/deploy-api-web.sh`,仅更换三项 Compose `image`;保留原配置字节以备回滚。切换后自动读回三镜像、API 二进制 SHA、主站健康、API readiness 及实际提供的前端资源。HiFox 回写包含原始运行 URL、完整提交、摘要、镜像 ID 及核验证据。任务评论另含主站登录地址和已核验的运行版本,带 OCI 版本标签时显示其值,其余镜像显示完整提交。
目标机已有的 `schema_migrations` 必须与候选完全相同,API 与 worker 的库连接均须核对。应用会在启动时检查迁移。新增或改变的迁移先按独立流程审查、备份、执行并复验;CD 自身只读迁移账本。发布时运营方应保留 prior tag,保障用原 Compose 字节回滚。
## 失败恢复
- `rolled_back` 表示自动恢复了原 Compose、旧的镜像 ID、API SHA 与站点健康。`rollback_failed` 或 `cutover_started` 要求巡检现场、按回执恢复并复验。目标机互斥锁覆盖切换及回写。Gitea 的取消记录只能说明流水线结束,回滚以目标机回执和运行时读回为准。
- `DEPLOYED_HIFOX_PENDING` 表示镜像切换和核验已经完成。以同一 `sha`、`bundle`、`task` 人工发起 `action=writeback`、`confirm=retry-writeback`。脚本先读原目标回执并复验仍在运行的版本,随后补写 HiFox,保留原部署链接。状态与 metadata 的当前值以 HiFox 读回为准。重复调用核对记录后结束。
- 目标回执 `/opt/knowledge-governance/cd/receipts/<bundle>.json`,镜像切换前的 Compose 保存为同名 `.compose.backup`。SSH 超时或强制中断后,先读回执和当前运行态。已存在未决或失败回执时,重复部署被拒。保留原回执作为事故证据。
## 一次性配置与权限
- 目标机安装仓库 `scripts/{production_cd.py,cd_migration_probe.py,deploy-api-web.sh,production-cd-ssh.sh}` 到 `/opt/knowledge-governance/cd/bin/`。创建私有 `receipts/`、`bundles/`、`hifox-home/`,初始化 `source.git` 为 bare Git 仓,并将 `.gitea/required-contexts.txt` 安装到该目录。仅发布运维可更新这些文件。
- 填写目标机 `/opt/knowledge-governance/cd/deploy-production.yml`,内容与 Gitea 主分支的工作流逐字节相同。控制器用 Gitea 发布人账号 ID 和只读日志验证确认。目标端 `authorized_keys` 为 CI 单独公钥设置 `restrict,command="/opt/knowledge-governance/cd/bin/production-cd-ssh.sh"`。校验云主机 SSH host key 后将其按 `kg-governance-cd` 别名写入 `KG_CD_KNOWN_HOSTS`。对应独立 SSH 私钥保存在 `KG_CD_SSH_KEY`。Runner 标签为 `kg-production-cd`,使用 `KG_CD_SSH_HOST` 和 `KG_CD_SSH_PORT` 接入批准的 Tailscale 或本机 IPv6 隧道。
- 将受控 HiFox CLI 安装至 `bin/hifox`,由账号持有人在目标主机使用 `hifox-home` 对应的私有配置目录完成登录。身份须能读取指定空间的任务、写 `cd_release` metadata 并完成对应状态迁移。状态绑定前分别读回组织状态和实际任务类型,复用原有待发布、已发布 ID,保留其余工作流配置。
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
- 常规 push CI 负责验证和静态预览。这个 workflow 的唯一事件是 `workflow_dispatch`。`make verify` 的 `contracts` 子项运行 CD 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
+1 -1
View File
@@ -3,7 +3,7 @@
> 这份文档是**破坏性变化与数据迁移步骤的落脚点**:`CHANGELOG.md` 里以 `**破坏性**` 开头的条目
> **必须**链接到本文(或本文的某个小节)。发布记录本身仍在 `CHANGELOG.md` —— 本文不维护第二份变更列表。
>
> 本仓 CI **只做 CI**:不打 tag、不发 Release、不部署。发布与部署都是**独立的人工审批动作**。
> 常规 CI 负责检查、构建与静态预览。版本 tag 与 Release 由人批准后执行。主站应用部署使用独立的[人工确认 CD](PRODUCTION_CD_RUNBOOK.md)。
## 一、正式发布(由人批准后执行)
+6
View File
@@ -260,6 +260,12 @@
- 规则:只配四项(测试地址、生产地址、生产 ID、知识库 ID);**保存时真探测**,无效才拒;凭据只写不读
- 状态:✅(见 `P41/P42` 与 `ui_settings_*` 测试)
### D1b 连接(地址 + API Key,测试 / 生产各一张)
- 入口:**系统设置 → 测试知识库绑定 / 生产知识库绑定** 分区顶部的连接卡(管理员)
- 步骤:填地址 → 粘贴 API Key(密码框)→ **测试连接** → 成功后才可 **保存连接**;换地址或换密钥必须重新测通
- 期望:密钥密文入库、页面只显示「已配置 · 尾4位」;四态文案分别是 地址不可达 / 密钥无效 / 密钥无权限读取知识库列表 / 可达(读到 N 个知识库);保存不触发任何同步或发布
- 状态:✅(`internal/weknoraconn` 单测 + `internal/httpapi/weknora_connections_test.go`;迁移 000083)
### D2 测试知识库绑定(对内 / 对外)
- 入口:**系统设置 → 测试知识库绑定** → 选库 → 保存绑定
- 期望:保存立即生效并重排"还没上传"的待入库项;对内 ≠ 对外
+43 -22
View File
@@ -31,28 +31,33 @@ type Config struct {
ProductionWeKnoraBaseURL string
ProductionWeKnoraAPIKeyFile string
ProductionWeKnoraAllowDockerHTTP 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
// 连接(地址 + 写-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
// TestAutoReviewPolicy:验收通过后是否自动批准(off|internal|all;默认 internal)。
TestAutoReviewPolicy string
// 目标库所在主机(整库逻辑备份真正执行的地方)。凭据是挂载进来的 0600 ssh
@@ -168,6 +173,7 @@ 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")),
@@ -288,6 +294,21 @@ 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,6 +138,12 @@ 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 {
+10 -2
View File
@@ -411,8 +411,16 @@ 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,
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.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,
+90 -13
View File
@@ -6,6 +6,7 @@ import (
"strings"
"time"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
@@ -15,7 +16,14 @@ import (
// such base exists on the target.
type ProductionBindingStore interface {
LoadProductionKBBindings(context.Context) (string, string, string, error)
SaveProductionKBBindings(ctx context.Context, internalID, externalID, updatedBy string, now time.Time) 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)
}
// ProductionKnowledgeBaseLister enumerates the knowledge bases of the production
@@ -33,11 +41,44 @@ 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
// operator-managed 「服务配置 · 生产地址」 first, the deployment default second.
// connection card first, the operator-managed 「服务配置 · 生产地址」 second, the
// deployment default last.
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
@@ -55,7 +96,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 {
@@ -64,21 +105,40 @@ func (config Config) productionKnowledgeBases(ctx context.Context) ([]weknora.Kn
return bases, ""
}
func (config Config) productionBindingPayload(ctx context.Context) (productionBindingView, error) {
func (config Config) productionBindingPayload(ctx context.Context, replan postgresstore.RoutingBindingReplanResult) (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: names[storedInternal], ExternalKBName: names[storedExternal],
InternalKBName: nameFor(storedInternal, storedInternalName), ExternalKBName: nameFor(storedExternal, storedExternalName),
UpdatedBy: updatedBy, ProductionBaseURL: config.productionTargetBaseURL(ctx),
ProductionConnected: message == "", ProductionMessage: message,
Frozen: frozen, Retargetable: retargetable,
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
}, nil
}
@@ -87,7 +147,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())
view, err := config.productionBindingPayload(r.Context(), postgresstore.RoutingBindingReplanResult{})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
return
@@ -137,11 +197,16 @@ func (config Config) handleSaveProductionBindings(w http.ResponseWriter, r *http
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内与对外必须绑定不同的生产知识库"})
return
}
if bases, message := config.productionKnowledgeBases(r.Context()); message == "" {
names := make(map[string]string, len(bases))
for _, base := range bases {
names[base.ID] = base.Name
}
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 internal != "" {
if _, ok := names[internal]; !ok {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内绑定的生产知识库在该 WeKnora 实例中不存在"})
@@ -155,11 +220,23 @@ func (config Config) handleSaveProductionBindings(w http.ResponseWriter, r *http
}
}
}
if err := config.ProductionBindings.SaveProductionKBBindings(r.Context(), internal, external, actorFor(r), config.Now().UTC()); err != nil {
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 {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save production bindings"})
return
}
view, err := config.productionBindingPayload(r.Context())
view, err := config.productionBindingPayload(r.Context(), replan)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
return
+51 -8
View File
@@ -11,25 +11,44 @@ import (
"time"
"knowledge-governance/internal/governance"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
type productionBindingStoreFake struct {
internal, external, saver string
savedInternal, savedExternal string
saveCallCount int
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
}
func (fake *productionBindingStoreFake) LoadProductionKBBindings(context.Context) (string, string, string, error) {
return fake.internal, fake.external, fake.saver, nil
}
func (fake *productionBindingStoreFake) SaveProductionKBBindings(_ context.Context, internal, external, updatedBy string, _ time.Time) error {
fake.savedInternal, fake.savedExternal = internal, external
fake.saver = updatedBy
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
fake.saveCallCount++
fake.internal, fake.external = internal, external
return nil
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
}
type productionListerFake struct {
@@ -113,6 +132,9 @@ 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"`
}
@@ -178,3 +200,24 @@ 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)
}
}
+47 -13
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)
SaveRoutingKBBindings(context.Context, string, string, string) error
LoadRoutingKBBindingNames(context.Context) (string, string, error)
// SaveRoutingKBBindingsWithReplan also re-points 待入库 publications that
// were still waiting for the previous knowledge base (same transaction).
SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
SaveRoutingKBBindingsWithReplan(ctx context.Context, save postgresstore.RoutingBindingSave, previous, effective postgresstore.EffectiveKBIDs, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
}
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
@@ -31,12 +31,15 @@ type routingBindingView struct {
ExternalKBID string `json:"external_kb_id"`
InternalEnvFallback bool `json:"internal_env_fallback"`
ExternalEnvFallback bool `json:"external_env_fallback"`
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"`
// 取消绑定时必须说清「回退到了哪个库」,否则「留空」等于没说。
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"`
// Replanned / RetiredDuplicates describe what THIS save did to 待入库 items
// that had not been uploaded yet. A plain read reports zeros.
Replanned int `json:"replanned"`
@@ -94,13 +97,33 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress
if err != nil {
return routingBindingView{}, err
}
internal, external := config.effectiveRoutingTargets(ctx)
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
}
return routingBindingView{
InternalKBID: internal, ExternalKBID: external,
InternalBoundByUI: storedInternal != "", ExternalBoundByUI: storedExternal != "",
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
InternalFallbackKBID: config.InternalRoutingKnowledgeBaseID, ExternalFallbackKBID: config.ExternalRoutingKnowledgeBaseID,
InternalKBName: nameFor(internal, storedInternalName), ExternalKBName: nameFor(external, storedExternalName),
UpdatedBy: updatedBy, WeKnoraConnected: connected,
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
}, nil
@@ -157,6 +180,10 @@ 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 {
@@ -182,7 +209,14 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
if effectiveExternal == "" {
effectiveExternal = config.ExternalRoutingKnowledgeBaseID
}
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), internal, external, effectiveInternal, effectiveExternal, actorFor(r), config.Now().UTC())
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())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
return
+80 -10
View File
@@ -3,6 +3,7 @@ package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
@@ -14,11 +15,14 @@ import (
)
type bindingStoreFake struct {
internal string
external string
saver string
internal string
external string
internalName string
externalName string
saver string
// replan records what the last save asked for, so tests can assert that the
// effective (env-fallback aware) targets were used.
// previous and effective (env-fallback aware) targets were used.
replanPrevious [2]string
replanEffective [2]string
replanResult postgresstore.RoutingBindingReplanResult
replanCallCount int
@@ -28,14 +32,15 @@ func (fake *bindingStoreFake) LoadRoutingKBBindings(context.Context) (string, st
return fake.internal, fake.external, fake.saver, 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) LoadRoutingKBBindingNames(context.Context) (string, string, error) {
return fake.internalName, fake.externalName, nil
}
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}
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}
fake.replanCallCount++
return fake.replanResult, nil
}
@@ -134,6 +139,9 @@ 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"`
@@ -163,3 +171,65 @@ 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")
}
}
+27 -8
View File
@@ -177,14 +177,24 @@ 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
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
ServiceTargetVerifier ServiceTargetVerifier
Now func() time.Time
RequireWeKnoraReady bool
@@ -421,6 +431,15 @@ 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
@@ -0,0 +1,153 @@
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})
}
@@ -0,0 +1,174 @@
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
+6 -1
View File
@@ -13,6 +13,7 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
)
// P10: every configured dependency reports Liveness ("process reachable") and
@@ -197,10 +198,14 @@ 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)
+6 -1
View File
@@ -50,6 +50,10 @@ 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 {
@@ -63,6 +67,7 @@ type RealProvider struct {
productionWeKnoraResolver func(ctx context.Context) string
weknoraReadiness func(ctx context.Context) error
workerStaleAfter time.Duration
allowPrivateHTTP bool
health *healthTracker
}
@@ -103,7 +108,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, 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, allowPrivateHTTP: config.AllowPrivateHTTP, health: newHealthTracker()}, nil
}
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
@@ -0,0 +1,3 @@
DROP TABLE IF EXISTS weknora_environment_connection_tests;
DROP TABLE IF EXISTS weknora_environment_connection_history;
DROP TABLE IF EXISTS weknora_environment_connections;
@@ -0,0 +1,45 @@
-- 连接是「地址 + 写-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()
);
@@ -0,0 +1,7 @@
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;
@@ -0,0 +1,10 @@
-- 「知识库绑定」保存选择时的库名快照:页面在密钥被清除或连接暂时不可达时
-- 仍要显示「对内/对外绑定的是哪个库」,不能退化成裸 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 '';
+28 -12
View File
@@ -11,51 +11,67 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 75 {
t.Fatalf("migration count = %d, want 75", len(migrations))
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)
}
// 75 允许"建立目标权威基线"作为独立业务作业,并与 sync/restore 共用写互斥。
if baseline := migrations[len(migrations)-1]; baseline.Version != 75 ||
if baseline := migrations[len(migrations)-3]; 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)-2]; executor.Version != 74 ||
if executor := migrations[len(migrations)-4]; executor.Version != 74 ||
!strings.Contains(executor.UpSQL, "library_executor_status") {
t.Fatalf("migration 74 = %#v", executor)
}
// 73 记录死信精确解除:保留上游行,只绑定指纹、重放引用与观测摘要。
if release := migrations[len(migrations)-3]; release.Version != 73 ||
if release := migrations[len(migrations)-5]; 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)-4]; instance.Version != 72 ||
if instance := migrations[len(migrations)-6]; instance.Version != 72 ||
!strings.Contains(instance.UpSQL, "library_instance_maintenance") {
t.Fatalf("migration 72 = %#v", instance)
}
// 71 让维护记录能区分实例级维护与仅治理库互斥。
if level := migrations[len(migrations)-5]; level.Version != 71 ||
if level := migrations[len(migrations)-7]; 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)-6]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
if maint := migrations[len(migrations)-8]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
t.Fatalf("migration 70 = %#v", maint)
}
if tail := migrations[len(migrations)-7]; tail.Version != 69 ||
if tail := migrations[len(migrations)-9]; tail.Version != 69 ||
!strings.Contains(tail.UpSQL, "library_jobs_write_target") {
t.Fatalf("migration 69 = %#v", tail)
}
if restore := migrations[len(migrations)-8]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
if restore := migrations[len(migrations)-10]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
t.Fatalf("migration 68 = %#v", restore)
}
if last := migrations[len(migrations)-9]; last.Version != 67 ||
if last := migrations[len(migrations)-11]; 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)-10]; flow.Version != 66 ||
if flow := migrations[len(migrations)-12]; 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,6 +3,7 @@ package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
@@ -13,43 +14,105 @@ 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
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
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) {
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
}
binding, _, err := s.loadProductionKBBinding(ctx)
if err != nil {
return "", "", "", errors.New("load production kb bindings")
return "", "", "", err
}
return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil
}
// 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 errors.New("production binding save requires a timestamp")
// 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
}
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)
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
if now.IsZero() {
return result, errors.New("production binding replan 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)
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`, internalID, externalID, updatedBy, now); err != nil {
return errors.New("save production kb bindings")
updated_at=EXCLUDED.updated_at`,
save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil {
return result, errors.New("save production kb bindings")
}
return nil
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
}
// ResolveProductionTargetKB maps a publication scope to the production base the
@@ -27,6 +27,12 @@ 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 {
@@ -39,7 +45,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
t.Fatalf("unbound resolve = %q/%v, want the tested base", target, err)
}
if err := store.SaveProductionKBBindings(ctx, "prod-internal", "prod-external", "admin", now); err != nil {
if err := save("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" {
@@ -53,7 +59,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
}
// Unbinding one side returns that side to the same-id semantics only.
if err := store.SaveProductionKBBindings(ctx, "", "prod-external", "admin", now); err != nil {
if err := save("", "prod-external", "admin", now); err != nil {
t.Fatal(err)
}
if target, err := store.ResolveProductionTargetKB(ctx, "internal", "test-kb"); err != nil || target != "test-kb" {
@@ -66,7 +72,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
if err != nil || saver != "admin" {
t.Fatalf("updated_by = %q (%v)", saver, err)
}
if err := store.SaveProductionKBBindings(ctx, "prod-internal", "", "admin", time.Time{}); err == nil {
if err := save("prod-internal", "", "admin", time.Time{}); err == nil {
t.Fatal("a save without a timestamp must be rejected")
}
}
+124 -55
View File
@@ -9,29 +9,68 @@ 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
UpdatedBy string
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
}
// 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) {
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
}
binding, _, err := s.loadRoutingKBBinding(ctx)
if err != nil {
return "", "", "", errors.New("load routing kb bindings")
return "", "", "", err
}
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 {
@@ -43,31 +82,16 @@ 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 = $3, updated_at = $3
SET superseded_at = $4, updated_at = $4
WHERE stale.superseded_at IS NULL
AND stale.test_kb_id <> $1
AND stale.test_kb_id = $3
AND stale.processing_state = 'planned'
AND stale.ingest_state = 'pending'
AND stale.knowledge_id = ''
@@ -86,9 +110,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 = $3
SET test_kb_id = $1, updated_at = $4
WHERE pending.superseded_at IS NULL
AND pending.test_kb_id <> $1
AND pending.test_kb_id = $3
AND pending.processing_state = 'planned'
AND pending.ingest_state = 'pending'
AND pending.knowledge_id = ''
@@ -102,16 +126,60 @@ 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.
//
// 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) {
// 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) {
var result RoutingBindingReplanResult
if now.IsZero() {
return result, errors.New("binding replan requires a timestamp")
@@ -121,33 +189,34 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID,
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,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4)
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)
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`, internalID, externalID, updatedBy, now); err != nil {
updated_at=EXCLUDED.updated_at`,
save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil {
return result, errors.New("save routing kb bindings")
}
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())
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 routing binding save: %w", err)
@@ -33,18 +33,21 @@ 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-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');
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-dup','item-dup','locator:r4',NULL,'unknown'),
('v-prod','item-prod','locator:r5',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-dup-new','v-dup','kb-new-internal','planned','pending','internal'),
('pub-prod','v-prod','prod-old-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 {
@@ -53,7 +56,11 @@ 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, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now)
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)
if err != nil {
t.Fatalf("SaveRoutingKBBindingsWithReplan() error = %v", err)
}
@@ -95,9 +102,39 @@ 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, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now)
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)
if err != nil {
t.Fatal(err)
}
@@ -112,4 +149,41 @@ 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,15 +52,20 @@ 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)
}
for version := latest; version > 10; version-- {
// 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
}
if err := RollbackLatestMigration(ctx, pool); err != nil {
t.Fatal(err)
}
@@ -0,0 +1,203 @@
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
}
@@ -0,0 +1,134 @@
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)
}
}
}
+49 -1
View File
@@ -48,6 +48,43 @@ 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 {
@@ -65,7 +102,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 baseURL.Scheme != "https" && !(baseURL.Scheme == "http" && (isLoopbackHost(baseURL.Hostname()) || (config.AllowDockerHTTP && isSingleLabelDockerHost(baseURL.Hostname())))) {
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
return nil, errors.New("WeKnora base URL must use HTTPS")
}
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
@@ -99,6 +136,17 @@ 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
@@ -0,0 +1,44 @@
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)
}
}
+21 -41
View File
@@ -1,55 +1,35 @@
package qaopsai
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"os"
"knowledge-governance/internal/sealedsecret"
)
// 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)
}
// 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"
func (s *Store) seal(secret string, revision int64) ([]byte, error) {
aead, err := s.aead()
key, err := sealedsecret.LoadKeyFile(s.options.KeyFile)
if err != nil {
return nil, err
}
nonce := make([]byte, aead.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return nil, ErrUnavailable
}
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) {
aead, err := s.aead()
if err != nil || len(sealed) < aead.NonceSize() {
return "", ErrUnavailable
sealed, err := sealedsecret.Seal(key, secret, sealedsecret.AAD(qaAISecretScope, s.tenant, revision))
if err != nil {
return nil, ErrUnavailable
}
raw, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision)))
return sealed, nil
}
func (s *Store) unseal(sealed []byte, revision int64) (string, error) {
key, err := sealedsecret.LoadKeyFile(s.options.KeyFile)
if err != nil {
return "", ErrUnavailable
}
return string(raw), nil
plain, err := sealedsecret.Open(key, sealed, sealedsecret.AAD(qaAISecretScope, s.tenant, revision))
if err != nil {
return "", ErrUnavailable
}
return plain, nil
}
+3 -1
View File
@@ -9,6 +9,8 @@ import (
"net/url"
"strings"
"time"
"knowledge-governance/internal/sealedsecret"
)
type Options struct {
@@ -67,7 +69,7 @@ func (s *Store) readSettings(ctx context.Context, q settingsQuery) (privateSetti
return out, ErrUnavailable
}
out.KeyConfigured = len(out.sealed) > 0
_, keyErr := s.masterKey()
_, keyErr := sealedsecret.LoadKeyFile(s.options.KeyFile)
out.StorageReady = keyErr == nil
return out, nil
}
+4 -1
View File
@@ -48,7 +48,10 @@ func TestNormalizeRefusesEnabledSettingsWithoutTransportAndBadRecipients(t *test
t.Fatalf("defaults not applied: %+v %v", good, err)
}
// 解析不了的主机名必须仍被判为非法:.invalid 是 RFC 6761 保留域,永远不解析。
if _, err := normalize(SettingsInput{Host: "smtp.kg-test.invalid", From: "kb@example.com",
// 末尾的点是必须的:构建机的 resolv.conf 可能带 search 域(本环境 Tailscale
// 的 tailf49802.ts.net),不带点就会被拼成 smtp.kg-test.invalid.<search> 并
// 由 Fake-IP DNS 解析出来,于是这条断言测的是构建机的搜索域而不是被测逻辑。
if _, err := normalize(SettingsInput{Host: "smtp.kg-test.invalid.", From: "kb@example.com",
Recipients: []string{"a@example.com"}}); err != ErrInvalid {
t.Fatalf("unresolvable host must stay invalid, got %v", err)
}
+91
View File
@@ -0,0 +1,91 @@
// 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)
}
@@ -0,0 +1,73 @@
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)
}
}
}
+19 -1
View File
@@ -13,6 +13,24 @@ 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")
@@ -21,7 +39,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.client(resolved, apiKey, verifier.config.ProductionAllowDockerHTTP)
client, err := verifier.clientWithPolicy(resolved, apiKey, verifier.config.ProductionAllowDockerHTTP, verifier.config.ProductionAllowPrivateHTTP)
if err != nil {
return nil, err
}
+41 -11
View File
@@ -40,8 +40,20 @@ type Config struct {
ProductionBaseURLFallback string
TestAllowDockerHTTP bool
ProductionAllowDockerHTTP bool
Timeout time.Duration
Now func() time.Time
// 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
}
// Verifier asks endpoints what they really hold. It is safe for concurrent use.
@@ -75,12 +87,25 @@ 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.probeEndpoint(ctx, testBaseURL, testKey, "测试地址", verifier.config.TestAllowDockerHTTP),
ProductionEndpoint: verifier.probeEndpoint(ctx, productionBaseURL, productionKey, "生产地址", verifier.config.ProductionAllowDockerHTTP),
TestEndpoint: verifier.probeEndpointWithPolicy(ctx, testBaseURL, testKey, "测试地址", verifier.config.TestAllowDockerHTTP, verifier.config.TestAllowPrivateHTTP),
ProductionEndpoint: verifier.probeEndpointWithPolicy(ctx, productionBaseURL, productionKey, "生产地址", verifier.config.ProductionAllowDockerHTTP, verifier.config.ProductionAllowPrivateHTTP),
CheckedAt: verifier.config.Now().UTC(),
}
if target.ProductionKnowledgeBaseID == "" && target.ProductionTenantID == "" {
@@ -96,7 +121,7 @@ func (verifier *Verifier) VerifyServiceTarget(ctx context.Context, target govern
verification.Message = "未核验:没有可用的生产 API Key 文件(PRODUCTION_WEKNORA_API_KEY_FILE),保存未被阻断"
return verification
}
client, err := verifier.client(productionBaseURL, productionKey, verifier.config.ProductionAllowDockerHTTP)
client, err := verifier.clientWithPolicy(productionBaseURL, productionKey, verifier.config.ProductionAllowDockerHTTP, verifier.config.ProductionAllowPrivateHTTP)
if err != nil {
verification.Status = governance.ServiceTargetCannotVerify
verification.Message = "未核验:生产地址不能作为 WeKnora 端点(" + err.Error() + "),保存未被阻断"
@@ -198,11 +223,15 @@ 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.client(baseURL, apiKey, allowDockerHTTP); err == nil {
if client, err := verifier.clientWithPolicy(baseURL, apiKey, allowDockerHTTP, allowPrivateHTTP); err == nil {
bases, listErr := client.ListKnowledgeBases(ctx)
switch {
case listErr == nil:
@@ -271,12 +300,13 @@ func (verifier *Verifier) candidateSuffix(ctx context.Context, client *weknora.C
return fmt.Sprintf(";该地址现有 %d 个知识库:%s", len(bases), strings.Join(listed, "、"))
}
func (verifier *Verifier) client(baseURL, apiKey string, allowDockerHTTP bool) (*weknora.Client, error) {
func (verifier *Verifier) clientWithPolicy(baseURL, apiKey string, allowDockerHTTP, allowPrivateHTTP bool) (*weknora.Client, error) {
return weknora.NewClient(weknora.ClientConfig{
BaseURL: baseURL,
APIKey: apiKey,
Timeout: verifier.config.Timeout,
AllowDockerHTTP: allowDockerHTTP,
BaseURL: baseURL,
APIKey: apiKey,
Timeout: verifier.config.Timeout,
AllowDockerHTTP: allowDockerHTTP,
AllowPrivateHTTP: allowPrivateHTTP,
})
}
+469
View File
@@ -0,0 +1,469 @@
// 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
@@ -0,0 +1,249 @@
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
}
+56
View File
@@ -0,0 +1,56 @@
"""Run inside a governance container. Read the real application DB ledger only."""
import json
import os
import subprocess
from urllib.parse import parse_qsl, unquote, urlsplit
def connection_env(env):
# Keep only the connection properties actually shared by libpq and pgx.
# Unknown DSN options can change the database identity or schema search path.
u = urlsplit(env['DATABASE' + '_URL'])
if u.scheme not in ('postgres', 'postgresql') or not u.hostname or not u.username or not u.path[1:] or u.fragment:
raise ValueError('invalid database URL')
query = parse_qsl(u.query, strict_parsing=True, keep_blank_values=True)
supported = {'sslmode': 'PGSSLMODE', 'sslrootcert': 'PGSSLROOTCERT', 'sslcert': 'PGSSLCERT', 'sslkey': 'PGSSLKEY'}
if len(dict(query)) != len(query) or any(key not in supported or not val for key, val in query):
raise ValueError('unknown database connection options')
safe = {'PATH': '/usr/bin:/bin', 'HOME': env.get('HOME', '/nonexistent'), 'LC_ALL': 'C',
'PGHOST': u.hostname, 'PGPORT': str(u.port or 5432), 'PGDATABASE': unquote(u.path[1:]),
'PGUSER': unquote(u.username), 'PGCONNECT_TIMEOUT': '5',
'PGOPTIONS': '-c default_transaction_read_only=on -c statement_timeout=5000'}
for name in ('PGPASSFILE', 'PGSSLMODE', 'PGSSLROOTCERT', 'PGSSLCERT', 'PGSSLKEY'):
if env.get(name):
safe[name] = env[name]
for name in env:
if name.startswith('PG') and name not in safe:
raise ValueError('unknown inherited database connection options')
safe.update({supported[key]: value for key, value in query})
if u.password:
safe['PGPASSWORD'] = unquote(u.password)
for name in ('PGDATABASE', 'PGUSER'):
if any(char in safe[name] for char in '\r\n\x00='):
raise ValueError('unsafe database identifier')
return safe
def main():
env = connection_env(os.environ)
sql = """SELECT json_build_object('database', current_database(), 'user', current_user,
'read_only', current_setting('transaction_read_only'),
'versions', (SELECT json_agg(version ORDER BY version) FROM schema_migrations));"""
p = subprocess.run(['psql', '-XAtw', '-v', 'ON_ERROR_STOP=1', '-c', sql],
env=env, capture_output=True, timeout=12)
if p.returncode:
raise ValueError('query failed')
data = json.loads(p.stdout)
if data['read_only'] != 'on' or data['database'] != env['PGDATABASE'] or data['user'] != env['PGUSER']:
raise ValueError('database identity mismatch')
print(json.dumps(data['versions']))
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, KeyError, subprocess.TimeoutExpired):
raise SystemExit('read-only migration probe failed') from None
+8
View File
@@ -356,6 +356,14 @@ def cmd_internal_web_test() -> int:
def cmd_internal_contracts(go: str) -> int:
"""版本契约:结构 + 注入身份必须**真 PASS**(SKIP 判红),
并且**开发构建不许自称正式版**(负例:标成 release ⇒ 必须红)。"""
qa_rc = subprocess.run(py("-m", "unittest", "discover", "-s", "scripts", "-p", "test_qa_env.py", "-v"),
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
snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode
if snapshot_rc:
return 1
+17 -1
View File
@@ -1,6 +1,20 @@
#!/usr/bin/env bash
# 重建并上线 governance api + web(本机 docker build 需要宿主代理 + --network host)
set -u
# Share the image-only Compose switch with CD without entering the legacy build path.
compose_up() {
"${compose[@]}" up -d --no-build --no-deps "$@"
}
if [[ "${1:-}" == --verified-compose ]]; then
[[ "$#" == 7 && "$5" == api && "$6" == web && "$7" == worker && "$4" == /* ]] || exit 2
cd -- "$2" || exit 1
compose=(docker compose -p "$3" -f "$4")
compose_up --pull never "$5" "$6" "$7"
exit $?
fi
cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1
[ -z "$(git status --porcelain --untracked-files=normal)" ] || { printf "%s\n" "REFUSED_DIRTY_SOURCE"; exit 1; }
TS=$(date +%Y%m%d-%H%M%S)
@@ -103,7 +117,9 @@ if [ "${GATES_PREV}" = "true" ] && [[ "${COMPOSE_FILES_EFFECTIVE}" != *compose.r
echo " 确实要关闸:ALLOW_GATE_OFF=1 bash scripts/deploy-api-web.sh"
exit 1
fi
docker compose ${COMPOSE_FILES_EFFECTIVE} up -d --no-build --no-deps api web || { echo "UP_FAILED"; exit 1; }
read -r -a compose_file_args <<< "$COMPOSE_FILES_EFFECTIVE"
compose=(docker compose "${compose_file_args[@]}")
compose_up api web || { echo "UP_FAILED"; exit 1; }
echo "=== 5. 状态"
docker ps --filter name=knowledge-governance-p1 --format '{{.Names}} {{.Status}} {{.Image}}'
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Submit a HiFox-approved release from the designated CD Agent host."""
import argparse
import base64
import json
import os
from pathlib import Path
import re
import sys
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener
import production_cd as cd
DISPATCH = f'/api/v1/repos/{cd.REPO}/actions/workflows/deploy-production.yml/dispatches?return_run_details=true'
PATH = Path.home() / '.local/state/kg-hifox-release'
RUN_ID = re.compile('[1-9][0-9]{0,14}')
def forge(method, path, payload=None):
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'}
fields = dict(line.split('=', 1) for line in cd.run(
['/usr/bin/git', 'credential', 'fill'], 'read Gitea credential', cwd='/', env=env,
input_data=f'url={cd.FORGE}/{cd.REPO}.git\n\n'.encode()).decode().splitlines() if '=' in line)
cd.require(fields.get('username') and fields.get('password'), 'Gitea credential unavailable')
auth = base64.b64encode(f'{fields["username"]}:{fields["password"]}'.encode()).decode()
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)
def hifox(cli, *args):
env = {'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': str(Path.home()), 'CI': '1'}
raw = cd.run([cli, '--organization-id', cd.ORG, *args, '--output', 'json'], 'read HiFox release record', env=env)
result = json.JSONDecoder().raw_decode(raw.decode().strip())[0]
cd.require(isinstance(result, (dict, list)) and (not isinstance(result, dict)
or (result.get('success') is not False and not result.get('error'))), 'HiFox record unavailable')
return result
def queue(task_id, cli, base=PATH):
cd.require(cd.matches(cd.UUID, task_id), 'use the triggering task UUID')
task = hifox(cli, 'task', 'view', task_id)
if not isinstance(task, dict) or task.get('id') != task_id or task.get('spaceId') != cd.SPACE:
raise cd.CDError('task is outside the release space')
acceptance = cd.metadata(task, 'cd_acceptance') or {}
cd.require(isinstance(acceptance, dict) and cd.matches(cd.SHA, acceptance.get('sha'))
and cd.matches(cd.HASH, acceptance.get('bundle')), 'skip: no registered candidate acceptance')
inputs = dict(action='deploy', confirm='deploy-production', sha=acceptance['sha'], bundle=acceptance['bundle'], task=task_id)
timeline = hifox(cli, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
if not isinstance(timeline, list):
raise cd.CDError('HiFox timeline unavailable')
binding, approved_at = cd.release_approval(task, timeline, inputs)
inputs.update(binding)
since = cd.immutable_file(base / 'active-since').read_text().strip()
cd.require(re.fullmatch(r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ', since) and approved_at > since,
'status approval predates activation; enter 待发布 again after acceptance')
claim = base / (binding['approval_event'] + '.json')
with cd.deploy_lock(base / 'dispatch.lock'):
if claim.exists():
result = cd.read_json(cd.immutable_file(claim))
cd.require(result.get('inputs') == inputs, 'HiFox approval already used for a different release')
cd.require(result.get('state') == 'queued', 'dispatch outcome unknown; reconcile Gitea before retry')
return result
result = {'state': 'submitting', 'inputs': inputs, 'started_at': cd.stamp()}
cd.record(claim, result)
response = forge('POST', DISPATCH, {'ref': 'main', 'inputs': inputs})
run_id = str(response.get('workflow_run_id', ''))
cd.require(cd.matches(RUN_ID, run_id), 'dispatch response has no valid run ID; reconcile before retry')
result.update(state='queued', run_id=run_id, run_url=f'{cd.FORGE}/{cd.REPO}/actions/runs/{run_id}')
cd.record(claim, result)
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('task', help='UUID of the task that entered 待发布')
args = parser.parse_args()
executable = Path.home() / '.local/bin/hifox'
try:
print(json.dumps(queue(args.task, str(executable)), ensure_ascii=False))
except HTTPError as exc:
sys.exit(f'CD: Gitea dispatch HTTP {exc.code}; reconcile before retry')
except cd.CDError as exc:
sys.exit(f'CD: {exc}')
except (OSError, KeyError, ValueError, TypeError) as exc:
sys.exit(f'CD: {type(exc).__name__}; inspect the dispatch record')
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
umask 077
[ "${SSH_ORIGINAL_COMMAND:-}" = kg-cd-v1 ] || exit 1
exec /usr/bin/env -i HOME=/opt/knowledge-governance/cd PATH=/usr/bin:/bin LANG=C.UTF-8 \
GIT_TERMINAL_PROMPT=0 /usr/bin/python3 -I /opt/knowledge-governance/cd/bin/production_cd.py serve
+857
View File
@@ -0,0 +1,857 @@
#!/usr/bin/env python3
"""Governance application CD. The installed host copy owns the release boundary."""
import argparse
from contextlib import contextmanager
import copy
from datetime import datetime, timezone
import fcntl
import hashlib
from html.parser import HTMLParser
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import sys
import tarfile
import tempfile
import time
from urllib.error import URLError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener
REPO = 'Weknora/knowledge-governance'
FORGE = 'https://gitea.zheromiku.top'
TARGET = 'cloud-test-governance-main'
ORG = '169e6f7f-e508-4a1f-9a9b-63d240439a3d'
SPACE = '106e05d1-4091-40b9-8c57-f76dc94f7825'
READY = '3e15556f-ca19-417c-8bfd-666634ea5d29'
PUBLISHED = '16185166-b8e9-4761-9926-845a1f41c96d'
RELEASE_OWNER = '39ae59fb-876c-4587-ab5d-a12a841c6c09'
LOGIN_URL = 'http://100.85.111.121:8088/'
ROLES = ('api', 'web', 'worker')
REVISION = 'org.opencontainers.image.revision'
DATA = Path('/opt/knowledge-governance/cd')
APP = DATA.parent
PROJECT = 'knowledge-governance-cloud-test'
SHA = re.compile('[0-9a-f]{40}')
HASH = re.compile('[0-9a-f]{64}')
IMAGE = re.compile('sha256:[0-9a-f]{64}')
UUID = re.compile('[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}')
GUARD_PREFIX = 'KG_CD_CONFIRM_V1 '
class CDError(RuntimeError):
pass
def require(ok, message):
if not ok:
raise CDError(message)
def stamp():
return datetime.now(timezone.utc).isoformat()
def read_json(path):
return json.loads(path.read_bytes())
def sync_dir(directory):
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def atomic_write(path, data, mode=0o600):
fd, temp = tempfile.mkstemp(dir=path.parent)
try:
with os.fdopen(fd, 'wb') as out:
os.fchmod(out.fileno(), mode)
out.write(data)
out.flush()
os.fsync(out.fileno())
os.replace(temp, path)
sync_dir(path.parent)
finally:
Path(temp).unlink(missing_ok=True)
def record(path, value):
atomic_write(path, (json.dumps(value, ensure_ascii=False, sort_keys=True) + '\n').encode())
@contextmanager
def deploy_lock(path):
fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'r+') as handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
raise CDError('deployment lock busy') from exc
yield
def matches(pattern, text):
return isinstance(text, str) and pattern.fullmatch(text) is not None
def validate_request(request):
actions = {'deploy': 'deploy-production', 'writeback': 'retry-writeback'}
action = request.get('action')
require(action in actions and request.get('confirm') == actions[action], 'explicit confirmation required')
require(matches(SHA, request.get('sha')) and matches(UUID, request.get('task'))
and matches(HASH, request.get('bundle')), 'require full SHA, bundle SHA256 and task UUID')
require(matches(re.compile('[1-9][0-9]{0,14}'), request.get('run_id')), 'invalid Gitea run ID')
event, digest = request.get('approval_event', ''), request.get('acceptance_digest', '')
require((event == '' and digest == '') or
(action == 'deploy' and matches(UUID, event) and matches(HASH, digest)),
'invalid HiFox approval binding')
def guard_proof(request, control_sha):
require(matches(SHA, control_sha), 'invalid workflow source SHA')
binding = {key: request[key] for key in ('run_id', 'action', 'confirm', 'sha', 'bundle', 'task')}
if request.get('approval_event'):
binding.update(approval_event=request['approval_event'], acceptance_digest=request['acceptance_digest'])
binding.update(repository=REPO, target=TARGET, workflow_sha=control_sha)
serialized = json.dumps(binding, sort_keys=True, separators=(',', ':')).encode()
return GUARD_PREFIX + hashlib.sha256(serialized).hexdigest()
def verify_guard_log(log, request, control_sha):
expected = guard_proof(request, control_sha)
pattern = re.compile(r'\d{4}-\d{2}-\d{2}T[0-9:.]+Z (' + GUARD_PREFIX + r'[0-9a-f]{64})')
proofs = [match.group(1) for line in log.decode().splitlines() if (match := pattern.fullmatch(line))]
require(proofs == [expected], 'Gitea guard dispatch proof missing or different')
def hash_file(path):
with path.open('rb') as src:
return hashlib.file_digest(src, 'sha256').hexdigest()
def immutable_file(path):
info = path.lstat()
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.geteuid() and not info.st_mode & 0o022,
'bundle requires regular files owned by the deployment account')
return path
def verify_bundle(directory, request, archives=True):
raw = immutable_file(directory / 'release.json').read_bytes()
require(hashlib.sha256(raw).hexdigest() == request['bundle'], 'release manifest digest mismatch')
manifest = json.loads(raw)
require(manifest.get('schema') == 1 and manifest.get('target') == TARGET
and manifest.get('sha') == request['sha'] and manifest.get('task') == request['task'],
'bundle commit, task or target mismatch')
require(set(manifest.get('images', {})) == set(ROLES), 'bundle must include API, web and worker')
for role, image in manifest['images'].items():
require(matches(IMAGE, image.get('id')) and matches(HASH, image.get('sha256')), 'invalid image record')
if archives:
archive = immutable_file(directory / (role + '.tar'))
require(hash_file(archive) == image['sha256'], f'{role} archive checksum mismatch')
versions = manifest.get('migrations')
require(isinstance(versions, list) and versions and all(type(n) is int and n > 0 for n in versions)
and versions == sorted(set(versions)), 'invalid migration ledger in manifest')
return manifest
def verify_contexts(result, contexts):
latest = {}
for item in result.get('statuses') or []:
latest.setdefault(item.get('context'), item.get('status'))
require(bool(contexts) and all(latest.get(context) == 'success' for context in contexts),
'required CI status is missing or unsuccessful')
def metadata(task, key):
value = (task.get('metadata') or {}).get(key)
return json.loads(value) if isinstance(value, str) else None
def check_task(task, request, receipt=None):
require(task.get('id') == request['task'] and task.get('spaceId') == SPACE, 'HiFox task or space mismatch')
status = (task.get('status') or {}).get('id')
same_publication = receipt and metadata(task, 'cd_release') == receipt.get('hifox')
require(status == READY or (status == PUBLISHED and same_publication), 'HiFox task is not ready for release')
evidence = metadata(task, 'cd_acceptance') or {}
url = urlsplit(evidence.get('evidence', ''))
require(evidence.get('verdict') == 'passed' and evidence.get('sha') == request['sha']
and evidence.get('bundle') == request['bundle'] and url.scheme == 'https' and url.hostname
and not (url.username or url.password or url.query)
and (not url.fragment or (url.netloc == 'app.hifox.com' and url.fragment.startswith('comment-')
and matches(UUID, url.fragment.removeprefix('comment-')))),
'missing or changed business acceptance for this commit and bundle')
return evidence
def acceptance_digest(acceptance):
return hashlib.sha256(json.dumps(acceptance, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
def release_approval(task, timeline, request):
evidence = check_task(task, request)
changes = [row for row in timeline if row.get('event') == 'status_changed']
require(bool(changes), 'missing HiFox status history')
approval = changes[-1]
approver = approval.get('actor') or {}
event_at = approval.get('createdAt') or ''
status_at = task.get('statusChangedAt') or ''
try:
difference = abs((datetime.fromisoformat(event_at.replace('Z', '+00:00'))
- datetime.fromisoformat(status_at.replace('Z', '+00:00'))).total_seconds())
except (ValueError, TypeError):
difference = float('inf')
# HiFox logs the status change after saving the task, sometimes across a second boundary.
require((approval.get('metadata') or {}).get('to') == '待发布'
and difference <= 2
and approver.get('id') == RELEASE_OWNER and approver.get('type') == 'human'
and matches(UUID, approval.get('id')), 'the latest transition must be an approval by the release owner')
task_url = task.get('url', '')
prefix = task_url + '#comment-'
require(task_url.startswith('https://app.hifox.com/') and evidence['evidence'].startswith(prefix),
'automated release requires the same-task acceptance report')
comment_id = evidence['evidence'].removeprefix(prefix)
require(matches(UUID, comment_id), 'invalid acceptance report ID')
reports = [row for row in timeline if row.get('event') == 'commented' and row.get('id') == comment_id]
require(len(reports) == 1, 'acceptance report missing from task history')
report = reports[0]
body = report.get('content') or ''
require(report.get('createdAt') and (report.get('updatedAt') or report['createdAt']) < min(event_at, status_at)
and request['sha'] in body and request['bundle'] in body,
'the unchanged report must identify the candidate and predate approval')
binding = {'approval_event': approval['id'], 'acceptance_digest': acceptance_digest(evidence)}
require(all(request.get(key, value) == value for key, value in binding.items()),
'HiFox approval or acceptance changed after dispatch')
return binding, min(event_at, status_at)
def accepted_task(host, request):
task = host.task(request['task'])
if request.get('approval_event'):
release_approval(task, host.timeline(request['task']), request)
return check_task(task, request)
def release(host, request):
validate_request(request)
path = host.receipt_path
existing = read_json(path) if path.exists() else None
if request['action'] == 'writeback':
require(existing and existing['state'] in ('deployed_hifox_pending', 'published'),
'writeback requires a verified deployment receipt')
require(all(existing[k] == request[k] for k in ('sha', 'task', 'bundle')), 'receipt binding mismatch')
manifest = verify_bundle(host.bundle_path(request), request, archives=False)
host.approve(request)
host.verify(manifest)
return writeback(host, request, existing)
require(existing is None, 'existing release receipt: use writeback or inspect interrupted/failed deployment')
host.approve(request)
manifest = verify_bundle(host.bundle_path(request), request)
host.check_ci(request)
accepted = accepted_task(host, request)
before = host.baseline()
host.pre_switch(before, manifest)
receipt = {k: request[k] for k in ('sha', 'task', 'bundle', 'run_id')}
receipt.update(state='preparing', target=TARGET, started_at=stamp(), previous=before)
record(path, receipt)
try:
host.load(host.bundle_path(request), manifest)
host.pre_switch(before, manifest)
host.approve(request)
require(accepted_task(host, request) == accepted, 'business acceptance changed before switch')
except (CDError, OSError, ValueError, KeyError) as exc:
receipt.update(state='failed_before_cutover')
record(path, receipt)
raise CDError(f'failed_before_cutover: {exc}' if isinstance(exc, CDError) else 'failed_before_cutover') from exc
receipt.update(state='cutover_started')
record(path, receipt)
try:
host.switch(before, manifest)
evidence = host.verify(manifest)
except (CDError, OSError, ValueError, KeyError) as exc:
status = 'rollback_failed'
try:
host.rollback(before)
status = 'rolled_back'
except (CDError, OSError, ValueError, KeyError):
pass
receipt.update(state=status, finished_at=stamp(), failure=str(exc) if isinstance(exc, CDError) else 'operation failed')
record(path, receipt)
raise CDError(f'{status}: deployment verification failed') from exc
receipt.update(state='deployed_hifox_pending', deployed_at=stamp(), evidence=evidence)
receipt['hifox'] = {**evidence, 'target': TARGET, 'bundle': request['bundle'], 'deployed_at': receipt['deployed_at'],
'login_url': LOGIN_URL,
'run_url': f'{FORGE}/{REPO}/actions/runs/{request["run_id"]}'}
record(path, receipt)
return writeback(host, request, receipt)
def writeback(host, request, receipt):
try:
task = host.task(request['task'])
check_task(task, request, receipt)
host.callback(request['task'], task, receipt.get('hifox'))
receipt.update(state='published')
record(host.receipt_path, receipt)
except (CDError, OSError, ValueError, KeyError) as exc:
raise CDError('DEPLOYED_HIFOX_PENDING: retry writeback for this receipt') from exc
return receipt
def with_images(config, images):
result = copy.deepcopy(config)
require(set(result['services']) == set(ROLES), 'unexpected Compose service set')
for role in ROLES:
result['services'][role]['image'] = images[role]
return result
def run(argv, purpose, *, cwd=None, input_data=None, timeout=30, allowed=(0,), env=None):
try:
result = subprocess.run(argv, cwd=cwd, input=input_data, capture_output=True, timeout=timeout, env=env)
except (OSError, subprocess.TimeoutExpired) as exc:
raise CDError(f'{purpose} unavailable or timed out') from exc
require(result.returncode in allowed, f'{purpose} failed (exit {result.returncode})')
return result.stdout
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *_args, **_kwargs):
raise CDError('unexpected HTTP redirect')
def http(url, *, direct=False, limit=2**20):
handlers = [NoRedirect()]
if direct:
handlers.append(ProxyHandler({}))
try:
with build_opener(*handlers).open(url, timeout=10) as response:
data = response.read(limit + 1)
require(len(data) <= limit, 'HTTP response exceeds limit')
return data
except (URLError, TimeoutError) as exc:
raise CDError('HTTP read failed') from exc
class Assets(HTMLParser):
def __init__(self):
super().__init__()
self.paths = []
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
path = attrs.get('src' if tag == 'script' else 'href', '')
if path and re.fullmatch(r'/assets/[A-Za-z0-9_.-]+\.(?:js|css)', path):
self.paths.append(path)
def disk_assets(html):
parser = Assets()
parser.feed(html.decode())
require(any(p.endswith('.js') for p in parser.paths), 'web index has no compiled entry point')
return sorted(set(parser.paths))
def image_inspect(image):
return json.loads(run(['docker', 'image', 'inspect', image], 'read image identity'))[0]
def inspect(name):
obj = json.loads(run(['docker', 'container', 'inspect', name], 'read running container'))[0]
require(obj['State']['Status'] == 'running' and matches(IMAGE, obj.get('Image')), 'expected container is not running')
return obj
def image_label(image):
return image_inspect(image)['Config']['Labels'].get(REVISION, '')
def api_identity(container):
raw = run(['docker', 'exec', container, '/app/api', '--version-record-status'], 'read API build identity', allowed=(0, 1))
obj = json.loads(raw)
require(matches(SHA, obj.get('commit_sha')), 'API binary has no full build identity')
return obj['commit_sha']
def migration_files(git, sha):
paths = git('ls-tree', '-r', '--name-only', sha, 'internal/platform/postgres/migrations').decode().splitlines()
return sorted(int(Path(line).name.split('_', 1)[0]) for line in paths if line.endswith('.up.sql'))
def ledger(container):
probe = Path(__file__).with_name('cd_migration_probe.py').read_text()
data = run(['docker', 'exec', container, 'python3', '-c', probe], 'read migration ledger')
result = json.loads(data)
require(isinstance(result, list) and result, 'unexpected migration ledger result')
return result
def verify_archive(archive, expected):
# docker save by ID omits mutable RepoTags. Refuse archives that could retag another app.
with tarfile.open(archive, 'r:') as t:
entry = t.getmember('manifest.json')
require(entry.isfile() and entry.size < 65536, 'unexpected Docker archive manifest')
containers = json.load(t.extractfile(entry))
require(len(containers) == 1 and not containers[0].get('RepoTags'), 'archive must contain one untagged image')
config = t.getmember(containers[0]['Config'])
require(config.isfile() and config.size < 2**20, 'unexpected Docker image config')
require('sha256:' + hashlib.sha256(t.extractfile(config).read()).hexdigest() == expected,
'archive config does not match approved image ID')
for member in t:
require((member.isdir() or member.isfile()) and not member.name.startswith('/')
and '..' not in Path(member.name).parts, 'unexpected Docker archive path')
if 'index.json' in t.getnames():
index = t.getmember('index.json')
require(index.isfile() and index.size < 65536, 'unexpected OCI archive index')
oci = json.load(t.extractfile(index))
require(len(oci.get('manifests', [])) == 1 and all(
key not in descriptor.get('annotations', {}) for descriptor in oci['manifests']
for key in ('org.opencontainers.image.ref.name', 'io.containerd.image.name')),
'archive OCI index contains a mutable name')
class LiveHost:
def __init__(self, request):
self.receipt_path = DATA / 'receipts' / (request['bundle'] + '.json')
self.compose = APP / 'compose.json'
self.git_path = DATA / 'source.git'
self.containers = {role: 'kg-cloud-' + role for role in ROLES}
self.health_url = 'http://127.0.0.1:8088'
self.request = request
def bundle_path(self, request):
return DATA / 'bundles' / request['bundle']
def git(self, *args):
return run(['git', '-C', str(self.git_path), *args], 'release source check', timeout=90)
def approve(self, request):
repo_url = f'{FORGE}/{REPO}'
run_id = request['run_id']
run_api = f'{FORGE}/api/v1/repos/{REPO}/actions/runs/{run_id}'
dispatch = json.loads(http(run_api))
control_sha = dispatch.get('head_sha')
trigger_actor = dispatch.get('trigger_actor') or dispatch.get('actor') or {}
require(str(dispatch.get('id')) == run_id and dispatch.get('event') == 'workflow_dispatch'
and dispatch.get('path') == 'deploy-production.yml@refs/heads/main'
and dispatch.get('head_branch') == 'main' and dispatch.get('status') in ('in_progress', 'running')
and (dispatch.get('actor') or {}).get('id') == 1 and trigger_actor.get('id') == 1
and matches(SHA, control_sha), 'Gitea run is not an active deployment dispatched by the release owner')
# Repo secrets can be read by other workflows. Only a completed guard from
# the installed workflow and controller may authorize the exact inputs.
try:
self.git('merge-base', '--is-ancestor', control_sha, 'refs/remotes/origin/main')
except CDError:
self.fetch_source()
self.git('merge-base', '--is-ancestor', control_sha, 'refs/remotes/origin/main')
trusted = {'scripts/production_cd.py': Path(__file__).resolve(),
'.gitea/workflows/deploy-production.yml': DATA / 'deploy-production.yml'}
for name, local in trusted.items():
require(self.git('show', f'{control_sha}:{name}') == immutable_file(local).read_bytes(),
'Gitea approval workflow differs from installed control files')
jobs = json.loads(http(run_api + '/jobs')).get('jobs') or []
guards = [job for job in jobs if job.get('name') == 'guard' and job.get('conclusion') == 'success'
and str(job.get('run_id')) == run_id and job.get('head_sha') == control_sha
and matches(re.compile('[1-9][0-9]{0,14}'), str(job.get('id')))]
require(len(guards) == 1, 'Gitea approval guard has not succeeded')
guard_id = guards[0]['id']
verify_guard_log(http(f'{repo_url}/actions/runs/{run_id}/jobs/{guard_id}/logs'), request, control_sha)
def fetch_source(self):
self.git('fetch', '--no-tags', '--prune', f'{FORGE}/{REPO}.git', '+refs/heads/*:refs/remotes/origin/*')
def check_ci(self, request):
self.fetch_source()
refs = self.git('for-each-ref', '--format=%(refname)', '--contains', request['sha'], 'refs/remotes/origin/')
require(refs.strip(), 'candidate commit is not reachable from a repository branch')
contexts = immutable_file(DATA / 'required-contexts.txt').read_text().splitlines()
verify_contexts(json.loads(http(f'{FORGE}/api/v1/repos/{REPO}/commits/{request["sha"]}/status')),
[line.strip() for line in contexts if line.strip() and not line.lstrip().startswith('#')])
def hifox(self, *args):
cli = DATA / 'bin/hifox'
env = {'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': str(DATA / 'hifox-home'), 'CI': '1'}
raw = run([str(cli), '--organization-id', ORG, *args, '--output', 'json'], 'HiFox operation', env=env)
result = json.JSONDecoder().raw_decode(raw.decode().strip())[0]
require(isinstance(result, (dict, list)) and (not isinstance(result, dict)
or (result.get('success') is not False and not result.get('error'))),
'HiFox did not return a successful result')
return result
def task(self, task):
return self.hifox('task', 'view', task)
def timeline(self, task):
return self.hifox('api', 'get', f'/rest/v1/tasks/{task}/timeline')
def comment_once(self, task, key, text):
marker = f'KG-CD {key}'
body = f'{text}\n\n`{marker}`'
def present():
return any(row.get('event') == 'commented' and row.get('content') == body
and (row.get('actor') or {}).get('id') == RELEASE_OWNER for row in self.timeline(task))
if not present():
self.hifox('task', 'comment', task, '--body', body)
require(present(), 'HiFox release comment readback mismatch')
def report_failure(self, request):
if not self.receipt_path.exists():
return
receipt = read_json(self.receipt_path)
if any(receipt.get(key) != request[key] for key in ('task', 'sha', 'bundle', 'run_id')):
return
messages = {
'failed_before_cutover': '发布检查失败,未切换主站。',
'rolled_back': '发布核验失败,已恢复原版本并复验。',
'rollback_failed': '发布核验失败,回滚未通过复验,请检查主站。',
'deployed_hifox_pending': '主站已部署并核验,HiFox 回写待完成。请重试回写。',
}
state = receipt['state']
if state in messages:
run_url = f'{FORGE}/{REPO}/actions/runs/{request["run_id"]}'
self.comment_once(request['task'], f'{state} #{request["run_id"]}',
f'{messages[state]}\n\n候选 `{request["sha"]}`\n\n[发布运行]({run_url})')
def callback(self, task_id, task, expected):
if metadata(task, 'cd_release') != expected:
self.hifox('task', 'metadata', 'set', task_id, 'cd_release', json.dumps(json.dumps(expected)))
fresh = self.task(task_id)
check_task(fresh, self.request, {'hifox': expected})
require(metadata(fresh, 'cd_release') == expected, 'HiFox release receipt readback mismatch')
images = '\n'.join(f'- {role} `{expected["images"][role]}`' for role in ROLES)
self.comment_once(task_id, f'published {expected["bundle"]}',
f'云治理主站发布完成,健康检查通过。\n\n'
f'运行版本 `{expected.get("version") or expected["sha"]}`\n\n'
f'提交 `{expected["sha"]}`\n\n{images}\n\n'
f'[登录主站]({LOGIN_URL}) · [发布运行]({expected["run_url"]})')
fresh = self.task(task_id)
check_task(fresh, self.request, {'hifox': expected})
require(metadata(fresh, 'cd_release') == expected, 'HiFox release changed during comment writeback')
if fresh['status']['id'] != PUBLISHED:
self.hifox('task', 'edit', task_id, '--status', PUBLISHED)
final = self.task(task_id)
final_status = (final.get('status') or {}).get('id')
require(final_status == PUBLISHED and metadata(final, 'cd_release') == expected, 'HiFox published readback mismatch')
def compose_cmd(self, *args):
return ['docker', 'compose', '-p', PROJECT, '-f', str(self.compose), *args]
def rendered_config(self):
raw = run(self.compose_cmd('config', '--format', 'json'), 'render Compose configuration', cwd=APP)
return json.loads(raw)['services']
def runtime(self):
rendered = self.rendered_config()
require(set(rendered) == set(ROLES), 'unexpected Compose service set')
result = {}
for role, name in self.containers.items():
c = inspect(name)
labels = c['Config']['Labels']
require(labels.get('com.docker.compose.project') == PROJECT
and labels.get('com.docker.compose.service') == role
and labels.get('com.docker.compose.project.working_dir') == str(APP)
and labels.get('com.docker.compose.project.config_files') == str(self.compose),
f'{role} does not belong to the approved Compose chain')
config = rendered[role]
image = image_inspect(c['Image'])
require(image_inspect(config['image'])['Id'] == c['Image'], f'{role} Compose image has drifted')
env = lambda entries: dict(item.split('=', 1) for item in entries or [])
expected_env = env(image['Config'].get('Env'))
expected_env.update({key: str(value) for key, value in (config.get('environment') or {}).items()
if value is not None})
require(env(c['Config'].get('Env')) == expected_env, f'{role} running environment has drifted')
expected_mounts = config.get('volumes') or []
require(all(mount['type'] == 'bind' for mount in expected_mounts), 'unexpected non-bind Compose volume')
mounts = {(v['Source'], v['Destination'], not v['RW']) for v in c.get('Mounts', []) if v['Type'] == 'bind'}
require(mounts == {(v['source'], v['target'], v.get('read_only', False)) for v in expected_mounts}
and len(mounts) == len(c.get('Mounts', [])), f'{role} running mounts have drifted')
require(not config.get('network_mode') or config['network_mode'] == c['HostConfig']['NetworkMode'],
f'{role} running network has drifted')
result[role] = c['Image']
return result
def baseline(self):
images = self.runtime()
self.probe_web()
return {'compose_sha256': hash_file(self.compose), 'images': images,
'revisions': {role: image_label(image) for role, image in images.items()}}
def pre_switch(self, previous, manifest):
require(hash_file(self.compose) == previous['compose_sha256'] and self.runtime() == previous['images'],
'target baseline changed during deployment')
for revision in set(previous['revisions'].values()):
require(matches(SHA, revision), 'running image has no source revision')
self.git('merge-base', '--is-ancestor', revision, manifest['sha'])
require(migration_files(self.git, manifest['sha']) == manifest['migrations'], 'source migration set differs from bundle')
for role in ('api', 'worker'):
require(ledger(self.containers[role]) == manifest['migrations'],
f'{role} migration ledger mismatch; verify schema changes outside CD')
def load(self, directory, manifest):
archives = {role: directory / (role + '.tar') for role in ROLES}
for role, archive in archives.items():
verify_archive(archive, manifest['images'][role]['id'])
for role, archive in archives.items():
image = manifest['images'][role]['id']
run(['docker', 'image', 'load', '-i', str(archive)], f'load {role} image', timeout=600)
require(image_inspect(image)['Id'] == image and image_label(image) == manifest['sha'],
f'{role} loaded image differs from approved build')
@property
def backup(self):
return self.receipt_path.with_suffix('.compose.backup')
def switch(self, previous, manifest):
current = self.compose.read_bytes()
require(hashlib.sha256(current).hexdigest() == previous['compose_sha256'], 'Compose changed before switch')
images = {role: manifest['images'][role]['id'] for role in ROLES}
changed = with_images(json.loads(current), images)
for role, image in previous['images'].items():
run(['docker', 'image', 'tag', image, f'knowledge-governance-cd-rollback:{self.request["bundle"]}-{role}'],
'retain rollback image')
atomic_write(self.backup, current)
atomic_write(self.compose, (json.dumps(changed, indent=2) + '\n').encode(), self.compose.stat().st_mode & 0o777)
self.recreate()
def recreate(self):
script = Path(__file__).with_name('deploy-api-web.sh')
run(['bash', str(script), '--verified-compose', str(APP), PROJECT, str(self.compose), 'api', 'web', 'worker'],
'switch governance Compose services', timeout=120)
def probe_web(self):
origin = self.health_url
require(json.loads(http(origin + '/health', direct=True)).get('status') == 'ok', 'web proxy health probe failed')
require(json.loads(http('http://127.0.0.1:18098/readyz', direct=True)).get('status') in ('ok', 'ready'),
'API readiness probe failed')
index = http(origin + '/', direct=True)
return index, {path: hashlib.sha256(http(origin + path, direct=True, limit=32 * 2**20)).hexdigest()
for path in disk_assets(index)}
def verify_web_image(self):
origin_index, assets = self.probe_web()
name = self.containers['web']
def read_asset(path):
return run(['docker', 'exec', name, 'cat', '/usr/share/nginx/html' + path], 'read running web asset')
require(origin_index == read_asset('/index.html'), 'served index differs from running web image')
for path, served_digest in assets.items():
require(hashlib.sha256(read_asset(path)).hexdigest() == served_digest, 'served asset differs from running web image')
return assets
def verify(self, manifest):
images = {role: manifest['images'][role]['id'] for role in ROLES}
def check():
require(self.runtime() == images, 'running image IDs differ from approved bundle')
require(api_identity(self.containers['api']) == manifest['sha'], 'running API SHA mismatches approval')
assets = self.verify_web_image()
version = image_inspect(images['api'])['Config']['Labels'].get('org.opencontainers.image.version')
if not isinstance(version, str) or not re.fullmatch(r'[0-9A-Za-z.+_-]{1,128}', version):
version = manifest['sha']
return {'sha': manifest['sha'], 'version': version, 'images': images, 'health': 'ok', 'asset_sha256': assets}
return wait_ready(check)
def rollback(self, previous):
if not self.backup.exists():
require(hash_file(self.compose) == previous['compose_sha256'] and self.runtime() == previous['images'],
'rollback baseline cannot be established')
self.verify_web_image()
return
original = self.backup.read_bytes()
require(hashlib.sha256(original).hexdigest() == previous['compose_sha256'], 'rollback backup checksum mismatch')
source = json.loads(original)
for role, image in previous['images'].items():
reference = source['services'][role]['image']
require(image_inspect(reference)['Id'] == image, 'rollback source tag has drifted')
atomic_write(self.compose, original, self.compose.stat().st_mode & 0o777)
self.recreate()
def check():
require(self.runtime() == previous['images'], 'rollback running images mismatch')
require(api_identity(self.containers['api']) == previous['revisions']['api'], 'rollback API SHA mismatch')
self.verify_web_image()
wait_ready(check)
def wait_ready(check, seconds=90):
deadline = time.monotonic() + seconds
while True:
try:
return check()
except (CDError, OSError, KeyError, ValueError):
if time.monotonic() >= deadline:
raise
time.sleep(3)
def event_request(event, env):
require(env.get('GITHUB_EVENT_NAME') == 'workflow_dispatch' and env.get('GITHUB_REF') == 'refs/heads/main'
and env.get('GITHUB_REPOSITORY') == REPO, 'manual dispatch from main required')
inputs = event.get('inputs') or {}
request = {name: inputs.get(name) or '' for name in
('action', 'sha', 'task', 'bundle', 'confirm', 'approval_event', 'acceptance_digest')}
request['run_id'] = env.get('GITHUB_RUN_ID', '')
validate_request(request)
return request
def pack(args):
require(matches(SHA, args.sha) and matches(UUID, args.task), 'require full SHA and task UUID')
require(not args.output.exists(), 'bundle output already exists')
source = lambda *argv: run(['git', *argv], 'read candidate source')
require(source('rev-parse', args.sha + '^{commit}').decode().strip() == args.sha, 'source commit not found')
images = {}
versions = migration_files(source, args.sha)
manifest = dict(schema=1, target=TARGET, sha=args.sha, task=args.task, images=images, migrations=versions)
with tempfile.TemporaryDirectory(dir=args.output.parent) as directory:
build = Path(directory) / "sealed"
build.mkdir(mode=0o700)
for role in ROLES:
image = image_inspect(getattr(args, role).removeprefix('sha256:'))
image_id = image['Id']
require(matches(IMAGE, image_id) and image_label(image_id) == args.sha, f'{role} source label mismatch')
archive = build / (role + '.tar')
run(['docker', 'image', 'save', '-o', str(archive), image_id], f'archive {role} image', timeout=900)
verify_archive(archive, image_id)
archive.chmod(0o600)
images[role] = {'id': image_id, 'sha256': hash_file(archive)}
record(build / 'release.json', manifest)
for item in build.iterdir():
with item.open("rb") as artifact:
os.fsync(artifact.fileno())
sync_dir(build)
build.rename(args.output)
sync_dir(args.output.parent)
print(hash_file(args.output / 'release.json'))
def attest(args):
request = {'sha': args.sha, 'task': args.task, 'bundle': hash_file(args.directory / 'release.json')}
require(matches(SHA, args.sha) and matches(UUID, args.task), 'require full SHA and task UUID')
manifest = verify_bundle(args.directory, request)
before = {role: inspect(getattr(args, role)) for role in ROLES}
for role, obj in before.items():
require(obj['Image'] == manifest['images'][role]['id'] and obj['Name'] != '/kg-cloud-' + role,
'isolated test runtime image differs from bundle')
require(api_identity(args.api) == args.sha and ledger(args.api) == manifest['migrations']
and ledger(args.worker) == manifest['migrations'], 'test runtime SHA or schema differs')
base = urlsplit(args.test_url)
require(base.scheme in ('http', 'https') and base.hostname and not (base.username or base.password or base.query or base.fragment)
and base.path in ('', '/') and base.port != 8088, 'provide isolated test endpoint')
origin = args.test_url.rstrip('/')
require(json.loads(http(origin + '/health', direct=True)).get('status') == 'ok', 'isolated test health probe failed')
index = http(origin + '/', direct=True)
require(index == run(['docker', 'exec', args.web, 'cat', '/usr/share/nginx/html/index.html'], 'read test web index'),
'test endpoint is serving another web image')
for role, obj in before.items():
require(inspect(getattr(args, role))['Id'] == obj['Id'], 'test instance changed during readback')
print(json.dumps({'sha': args.sha, 'bundle': request['bundle'], 'test_url': args.test_url,
'images': {role: obj['Image'] for role, obj in before.items()}}, sort_keys=True))
def cli():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
for command in ('guard', 'send', 'serve', 'pack', 'attest'):
sub = commands.add_parser(command)
if command in ('guard', 'send'):
sub.add_argument('--event', type=Path, required=True)
if command in ('pack', 'attest'):
sub.add_argument('--sha', required=True)
sub.add_argument('--task', required=True)
if command in ('pack', 'attest'):
for role in ROLES:
sub.add_argument('--' + role, required=True)
if command == 'pack':
sub.add_argument('--output', type=Path, required=True)
if command == 'attest':
sub.add_argument('--directory', type=Path, required=True)
sub.add_argument('--test-url', required=True)
args = parser.parse_args()
if args.command in ('guard', 'send'):
request = event_request(read_json(args.event), os.environ)
if args.command == 'guard':
print(guard_proof(request, os.environ.get('GITHUB_SHA')))
else:
send(request)
elif args.command == 'pack':
pack(args)
elif args.command == 'attest':
attest(args)
else:
raw = sys.stdin.buffer.read(8193)
require(len(raw) <= 8192, 'request exceeds size limit')
request = json.loads(raw)
validate_request(request)
with deploy_lock(DATA / 'release.lock'):
host = LiveHost(request)
for item in (DATA / 'receipts').glob('*.json'):
if read_json(item)['state'] in ('cutover_started', 'rollback_failed'):
raise CDError('previous deployment outcome requires operator reconciliation')
try:
result = release(host, request)
except (CDError, OSError, ValueError, KeyError):
try:
host.report_failure(request)
except (CDError, OSError, ValueError, KeyError):
print('CD: HiFox failure comment pending', file=sys.stderr)
raise
print(json.dumps({k: result[k] for k in ('state', 'sha', 'task', 'bundle', 'hifox')}, ensure_ascii=False))
def send(request):
key = os.environ.get('KG_CD_SSH_KEY', '')
known_hosts = os.environ.get('KG_CD_KNOWN_HOSTS', '')
host = os.environ.get('KG_CD_SSH_HOST', '')
port = os.environ.get('KG_CD_SSH_PORT', '22') or '22'
require(key.strip() and known_hosts.strip(), 'missing KG_CD_SSH_KEY or KG_CD_KNOWN_HOSTS')
require(host in ('100.85.111.121', '::1') and port.isdecimal() and 1 <= int(port) <= 65535,
'configure the direct or approved tunnel address for the target release endpoint')
with tempfile.TemporaryDirectory() as directory:
temp = Path(directory)
for filename, value in (('key', key), ('known_hosts', known_hosts)):
atomic_write(temp / filename, (value.strip() + '\n').encode())
argv = ['ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'IdentitiesOnly=yes',
'-o', 'ClearAllForwardings=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'HostKeyAlias=kg-governance-cd',
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', f'UserKnownHostsFile={temp / "known_hosts"}',
'-i', str(temp / 'key'), '-p', port, '-T', 'root@' + host, 'kg-cd-v1']
try:
result = subprocess.run(argv, input=json.dumps(request).encode(), capture_output=True, timeout=2100)
except (OSError, subprocess.TimeoutExpired) as exc:
raise CDError('target outcome unknown; inspect durable receipt before retry') from exc
if result.returncode:
error = result.stderr.decode(errors='replace')
for marker in ('DEPLOYED_HIFOX_PENDING', 'rollback_failed:', 'rolled_back:', 'failed_before_cutover:',
'target preflight rejected', 'deployment lock busy', 'writeback requires a verified deployment receipt',
'Gitea approval guard has not succeeded', 'Gitea guard dispatch proof missing or different'):
if marker in error:
raise CDError(error.strip().splitlines()[-1])
raise CDError('target rejected request or outcome unknown; inspect durable receipt')
response = json.loads(result.stdout)
require(response.get('state') == 'published' and all(response.get(k) == request[k] for k in ('sha', 'task', 'bundle')),
'invalid or unverified deployment receipt')
print(json.dumps(response, ensure_ascii=False))
if __name__ == '__main__':
try:
cli()
except CDError as error:
print(f'CD: {error}', file=sys.stderr)
sys.exit(1)
except (OSError, KeyError, ValueError, TypeError, tarfile.TarError) as error:
print(f'CD: operation could not be verified ({type(error).__name__})', file=sys.stderr)
sys.exit(1)
+374
View File
@@ -0,0 +1,374 @@
#!/usr/bin/env python3
"""Prepare and exercise an isolated Knowledge Governance QA run."""
import argparse
from contextlib import ExitStack
import fcntl
import http.client
import json
import os
from pathlib import Path
import re
import shutil
import signal
import socket
import stat
import subprocess
import sys
import tempfile
import time
ROOT = Path(__file__).resolve().parents[1]
CONFIG = Path.home() / '.config/knowledge-governance/qa.json'
API_PORT = 8088
WEB_PORT = 5173
RUNTIME_RESPONSE = 'KG_QA_RUNTIME_OK'
class QAError(RuntimeError):
pass
def report(stage, detail):
print(f'[qa:{stage}] {detail}', flush=True)
def capture(argv, stage, timeout=10, env=None):
try:
return subprocess.run(argv, cwd=ROOT, env=env, text=True, capture_output=True,
timeout=timeout, stdin=subprocess.DEVNULL)
except FileNotFoundError as exc:
raise QAError(f'{stage} 缺少命令 {argv[0]}') from exc
except subprocess.TimeoutExpired as exc:
raise QAError(f'{stage} 超过 {timeout} 秒') from exc
def private_file(path):
try:
info = path.lstat()
except FileNotFoundError as exc:
raise QAError(f'缺少测试配置文件 {path}') from exc
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o600:
raise QAError(f'{path} 必须是当前用户所有的 0600 普通文件')
def database_config(path):
private_file(path)
try:
config = json.loads(path.read_text())
except (UnicodeError, json.JSONDecodeError) as exc:
raise QAError(f'{path} 不是有效 JSON') from exc
if not isinstance(config, dict) or config.keys() != {'host', 'port', 'database', 'user'}:
raise QAError('qa.json 只接受 host、port、database、user 四个字段')
for field in ('database', 'user'):
if not re.fullmatch(r'kg_qa_[a-z0-9_]{1,56}', str(config[field])):
raise QAError(f'RDS {field} 必须以 kg_qa_ 开头并使用小写字母、数字或下划线')
host = config['host']
if not isinstance(host, str) or not re.fullmatch(r'[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+', host):
raise QAError('RDS host 必须填写证书对应的 DNS 主机名')
if type(config['port']) is not int or not 1 <= config['port'] <= 65535:
raise QAError('RDS port 必须是 1–65535 的整数')
return config
def tool_env():
allowed = ('HOME', 'PATH', 'LANG', 'TMPDIR', 'GOPROXY', 'GOSUMDB', 'GOPRIVATE', 'GONOSUMDB',
'GOMODCACHE', 'GOCACHE', 'npm_config_cache', 'npm_config_registry',
'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy')
env = {key: os.environ[key] for key in allowed if key in os.environ}
env['GOFLAGS'] = '-mod=readonly'
return env
def database_env(config, directory):
# Keep inherited PG variables and integration switches out of application children.
env = tool_env()
env.update(PGHOST=config['host'], PGPORT=str(config['port']), PGDATABASE=config['database'],
PGUSER=config['user'], PGSSLMODE='verify-full', PGCONNECT_TIMEOUT='5',
PGPASSFILE=str(directory / 'qa.pgpass'), PGSSLROOTCERT=str(directory / 'rds-ca.pem'),
PGOPTIONS='-c search_path=public', LC_ALL='C',
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')
env['APP_ADDR'] = f'127.0.0.1:{API_PORT}'
env['DATA' + 'BASE_URL'] = (
f"postgresql://{config['user']}@{config['host']}:{config['port']}/{config['database']}"
'?sslmode=verify-full&connect_timeout=5&search_path=public'
)
return env
def psql(env, sql):
result = capture(['psql', '-XAtw', '-v', 'ON_ERROR_STOP=1', '-c', sql], 'RDS 探针', env=env)
if result.returncode == 0:
return result.stdout.strip()
detail = result.stderr.lower()
hints = (
('password', '口令认证失败,检查 qa.pgpass 和登录角色'),
('certificate', 'TLS 校验失败,检查 RDS 主机名和 CA'),
('does not exist', '数据库或角色不存在,联系管理员确认专用 QA 库'),
('permission denied', 'RDS 权限不足,检查专用 QA 角色的 CONNECT、schema USAGE/CREATE 权限'),
('could not translate host name', 'RDS 主机名无法解析,检查私网 DNS'),
('timeout', '连接 RDS 超时,检查 QA 虚拟机到 RDS 的私网和安全组'),
('connection refused', 'RDS 拒绝 TCP 连接,检查主机名、端口和私网接入'),
)
hint = next((message for marker, message in hints if marker in detail), '连接或 SQL 探针失败,检查 RDS 接入和权限')
raise QAError(f'RDS {hint}(psql 退出 {result.returncode})')
def database_state(env):
identity = psql(env, """
SELECT concat_ws('|', current_database(), current_user,
COALESCE((SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()), false),
(SELECT NOT (rolsuper OR rolcreaterole OR rolcreatedb OR rolreplication OR rolbypassrls)
FROM pg_roles WHERE rolname = current_user),
(has_schema_privilege(current_user, 'public', 'USAGE') AND
has_schema_privilege(current_user, 'public', 'CREATE')),
to_regclass('public.schema_migrations') IS NOT NULL,
EXISTS (SELECT FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
WHERE n.nspname = 'public' AND c.relname <> 'schema_migrations')
OR EXISTS (SELECT FROM pg_namespace
WHERE nspname NOT IN ('public', 'information_schema') AND nspname !~ '^pg_')
OR EXISTS (SELECT FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
WHERE n.nspname = 'public'));
""")
fields = identity.split('|')
if len(fields) != 7 or fields[:4] != [env['PGDATABASE'], env['PGUSER'], 't', 't']:
raise QAError('RDS 实际库名、角色、TLS 或角色权限与 QA 配置不符')
if fields[4] != 't':
raise QAError('RDS 角色需要 public schema 的 USAGE 和 CREATE 权限')
rows = psql(env, 'SELECT version FROM public.schema_migrations ORDER BY version;') if fields[5] == 't' else ''
if any(not re.fullmatch(r'[0-9]+', row) for row in rows.splitlines()):
raise QAError('RDS 迁移记录包含无效版本')
return [int(row) for row in rows.splitlines()], fields[6] == 't'
def expected_migrations():
paths = (ROOT / 'internal/platform/postgres/migrations').glob('*.up.sql')
try:
versions = sorted(int(path.name.split('_', 1)[0]) for path in paths)
except ValueError as exc:
raise QAError('仓库存在无效的迁移文件名') from exc
if not versions or len(versions) != len(set(versions)):
raise QAError('仓库迁移文件缺失或版本重复')
return versions
def check_migrations(expected, applied, nonempty, *, complete):
if not applied and nonempty:
raise QAError('RDS 非空且缺少有效迁移记录,停止初始化')
if expected[:len(applied)] != applied:
raise QAError('RDS 迁移序列与当前提交不兼容,使用专用空库或匹配的测试库')
if complete and applied != expected:
raise QAError(f'RDS 迁移未完成,缺少版本 {expected[len(applied)]} 至 {expected[-1]}')
def check_hifox(output):
try:
state = json.loads(output)
online = state['connected'] is True and state['remoteLiveness']['status'] == 'online'
except (ValueError, KeyError, TypeError) as exc:
raise QAError('HiFox 未返回有效的在线状态,检查本机注册和接收服务') from exc
if not online:
raise QAError('HiFox 未确认测试机在线,检查本机接收服务和网络')
def check_checkout(expected):
if not re.fullmatch(r'[0-9a-f]{40}', expected):
raise QAError('设置 KG_QA_SHA 为提测的完整 40 位 Git SHA')
actual = capture(['git', 'rev-parse', 'HEAD'], 'Git 检出')
if actual.returncode or actual.stdout.strip() != expected:
raise QAError('Git 检出与提测提交不一致')
state = capture(['git', 'status', '--porcelain'], 'Git 状态')
if state.returncode or state.stdout.strip():
raise QAError('QA 需要干净的独立检出,请检查 Git 状态')
def preflight(env):
for cmd in ('git', 'make', 'go', 'node', 'npm', 'psql', 'hifox', 'omp'):
if not shutil.which(cmd, path=env.get('PATH')):
raise QAError(f'工具链缺少 {cmd},检查 QA 机器的 PATH')
go = capture(['go', 'env', 'GOROOT', 'GOVERSION'], 'Go 工具链', env=env)
fields = go.stdout.splitlines()
if go.returncode or len(fields) != 2 or not fields[1].startswith('go1.26.'):
raise QAError('QA 需要 Go 1.26 工具链')
root = Path(fields[0]) / 'bin'
if not os.access(root / 'gofmt', os.X_OK):
raise QAError('Go 工具链缺少 gofmt,请安装完整的 Go 1.26')
env['PATH'] = f"{root}:{env['PATH']}"
node = capture(['node', '--version'], 'Node.js 工具链', env=env)
if node.returncode or not node.stdout.startswith('v22.'):
raise QAError('QA 需要 Node.js 22 工具链')
report('toolchain', f'{fields[1]} / Node.js {node.stdout.strip()}')
hifox = capture(['hifox', 'computer', 'status', '--output', 'json'], 'HiFox 在线检查', timeout=15)
if hifox.returncode:
raise QAError(f'HiFox 状态命令失败(退出 {hifox.returncode})')
check_hifox(hifox.stdout)
report('machine', f'{socket.gethostname()} / HiFox online')
prompt = f'Reply with exactly {RUNTIME_RESPONSE}. Do not use tools.'
omp = capture(['omp', '--no-session', '-p', prompt], 'OMP Runtime 探针', timeout=35)
if omp.returncode or RUNTIME_RESPONSE not in {line.strip() for line in omp.stdout.splitlines()}:
raise QAError('OMP Runtime 没有返回探针结果,检查 OMP 模型配置和 Magpie 网关')
report('runtime', 'OMP 模型请求通过')
def check_ports():
for port in (API_PORT, WEB_PORT):
with socket.socket() as listener:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
listener.bind(('127.0.0.1', port))
except OSError as exc:
raise QAError(f'QA 端口 {port} 无法绑定,检查已有监听进程') from exc
def run_step(argv, stage, env, timeout):
report(stage, ' '.join(argv[:2]))
process = subprocess.Popen(argv, cwd=ROOT, env=env, stdin=subprocess.DEVNULL, start_new_session=True)
try:
code = process.wait(timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise QAError(f'{stage} 超过 {timeout} 秒') from exc
finally:
stop_process(process)
if code:
raise QAError(f'{stage} 失败(退出 {code}),查看上方命令输出')
def stop_process(process):
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
process.wait(timeout=5)
def start_service(stack, argv, env, log):
output = stack.enter_context(log.open('w', encoding='utf-8'))
process = subprocess.Popen(argv, cwd=ROOT, env=env, stdin=subprocess.DEVNULL,
stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
stack.callback(stop_process, process)
return process
def request(port, path):
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=2)
try:
connection.request('GET', path)
response = connection.getresponse()
return response.status, response.getheader('Content-Type', ''), response.read(32768)
finally:
connection.close()
def probe(port, path, expected):
try:
code, content_type, body = request(port, path)
if code != 200:
return False
if expected == 'html':
return 'text/html' in content_type and b'id="root"' in body
return 'application/json' in content_type and json.loads(body)['status'] == expected
except (OSError, http.client.HTTPException, ValueError, KeyError, TypeError):
return False
def wait_service(process, port, path, expected, log):
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
if process.poll() is not None:
raise QAError(f'服务端口 {port} 启动进程提前退出(退出 {process.returncode}),日志 {log}')
if probe(port, path, expected):
return
time.sleep(0.25)
raise QAError(f'服务探针超时 127.0.0.1:{port}{path},日志 {log}')
def qa_run(commit, env, db_env, versions, state):
with tempfile.TemporaryDirectory(prefix='run-', dir=state) as directory, ExitStack() as services:
binary = Path(directory) / 'api'
run_step(['make', 'deps-install'], 'deps', env, 300)
ldflags = f'-X knowledge-governance/internal/version.CommitSHA={commit}'
run_step(['go', 'build', '-ldflags', ldflags, '-o', str(binary), './cmd/api'], 'build-api', env, 300)
check_ports()
log_dir = Path(tempfile.mkdtemp(prefix=f'{commit[:12]}-', dir=state))
report('logs', str(log_dir))
app_env = db_env | {'PATH': env['PATH'], 'GOVERNANCE_SPOOL_ROOT': str(Path(directory) / 'spool')}
api_log = log_dir / 'api.log'
api = start_service(services, [str(binary)], app_env, api_log)
wait_service(api, API_PORT, '/readyz', 'ready', api_log)
check_migrations(versions, *database_state(db_env), complete=True)
report('migration', f'已核对全部 {len(versions)} 条迁移,最新版本 {versions[-1]}')
web_log = log_dir / 'web.log'
web = start_service(services, ['npm', '--prefix', 'web', 'run', 'dev', '--', '--host', '127.0.0.1',
'--port', str(WEB_PORT), '--strictPort'], env, web_log)
wait_service(web, WEB_PORT, '/', 'html', web_log)
wait_service(web, WEB_PORT, '/health', 'ok', web_log)
report('services', 'API /readyz、Web 首页与 Vite /health 代理通过')
run_step(['make', 'tests-go', 'tests-web'], 'tests', env, 300)
check_checkout(commit)
if api.poll() is not None or web.poll() is not None or not probe(WEB_PORT, '/health', 'ok'):
raise QAError(f'服务在测试期间失去健康状态,日志目录 {log_dir}')
report('result', f'PASS {commit},已停止本次 API 和 Web 进程')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('doctor', 'run'))
args = parser.parse_args()
env = tool_env()
try:
commit = os.environ.get('KG_QA_SHA', '')
if args.action == 'run':
check_checkout(commit)
check_ports()
preflight(env)
config_path = Path(os.environ.get('KG_QA_CONFIG', CONFIG)).expanduser().absolute()
config = database_config(config_path)
private_file(config_path.parent / 'qa.pgpass')
if not (config_path.parent / 'rds-ca.pem').is_file():
raise QAError(f'缺少 RDS CA 文件 {config_path.parent / "rds-ca.pem"}')
db_env = database_env(config, config_path.parent)
versions = expected_migrations()
if args.action == 'doctor':
applied, nonempty = database_state(db_env)
check_migrations(versions, applied, nonempty, complete=False)
report('database', f'连接与身份正常,已应用 {len(applied)}/{len(versions)} 条迁移')
return 0
state = Path.home() / '.local/state/knowledge-governance/qa'
state.mkdir(mode=0o700, parents=True, exist_ok=True)
with (state / 'run.lock').open('a') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
raise QAError('本机已有 QA 任务,等待当前任务退出') from exc
check_ports()
check_migrations(versions, *database_state(db_env), complete=False)
qa_run(commit, env, db_env, versions, state)
return 0
except (QAError, OSError, ValueError) as exc:
print(f'[qa:FAIL] {exc}', file=sys.stderr)
return 1
except KeyboardInterrupt:
print('[qa:FAIL] QA 任务中断', file=sys.stderr)
return 130
if __name__ == '__main__':
def interrupt(_signal, _frame):
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, interrupt)
sys.exit(main())
+227
View File
@@ -0,0 +1,227 @@
import hashlib
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
import production_cd as cd
import hifox_release_trigger as trigger
SHA = 'a' * 40
TASK = 'd5abdf29-d0b5-4992-8073-0cb8fffd84ed'
IMAGES = {role: 'sha256:' + str(i) * 64 for i, role in enumerate(('api', 'web', 'worker'), 1)}
CTX = 'build / build (push)'
class ProductionCD(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.request = dict(sha=SHA, task=TASK, bundle='b' * 64, confirm='deploy-production',
action='deploy', run_id='42')
self.manifest = dict(schema=1, target=cd.TARGET, sha=SHA, task=TASK, migrations=[1, 2], images={})
for role, image in IMAGES.items():
archive = self.root / (role + '.tar')
archive.write_text(role)
self.manifest['images'][role] = dict(id=image, sha256=hashlib.sha256(role.encode()).hexdigest())
data = json.dumps(self.manifest).encode()
(self.root / 'release.json').write_bytes(data)
for path in self.root.iterdir():
path.chmod(0o600)
self.request['bundle'] = hashlib.sha256(data).hexdigest()
self.acceptance = {'verdict': 'passed', 'sha': SHA, 'bundle': self.request['bundle'],
'evidence': 'https://example.test/result/42'}
self.host = Mock()
self.host.task.return_value = {'id': TASK, 'spaceId': cd.SPACE, 'status': {'id': cd.READY},
'metadata': {'cd_acceptance': json.dumps(self.acceptance)}}
self.host.baseline.return_value = {'before': 'baseline'}
self.host.pre_switch.return_value = None
self.host.verify.return_value = {'sha': SHA, 'images': IMAGES, 'health': 'ok'}
self.host.receipt_path = self.root / 'receipt.json'
self.host.bundle_path.return_value = self.root
def execute(self):
return cd.release(self.host, self.request)
def assert_no_deploy(self):
self.host.load.assert_not_called()
self.host.switch.assert_not_called()
self.host.callback.assert_not_called()
def test_no_confirmation_has_zero_side_effects(self):
self.request['confirm'] = ''
with self.assertRaisesRegex(cd.CDError, 'confirmation'):
self.execute()
self.host.assert_not_called()
self.assert_no_deploy()
def test_preconditions_prevent_loading_and_switching(self):
for mode in ('approval', 'ci', 'test', 'changed_bundle', 'tampered_archive', 'migration'):
with self.subTest(mode=mode):
self.setUp()
if mode in ('approval', 'ci', 'migration'):
step = {'approval': self.host.approve, 'ci': self.host.check_ci,
'migration': self.host.pre_switch}[mode]
step.side_effect = cd.CDError(mode)
elif mode == 'test':
self.host.task.return_value['metadata'].clear()
elif mode == 'changed_bundle':
self.request['bundle'] = 'f' * 64
else:
(self.root / 'web.tar').write_bytes(b'other image')
with self.assertRaises(cd.CDError):
self.execute()
self.assert_no_deploy()
def test_bare_ci_success_cannot_replace_required_context(self):
for statuses in ([], [{'context': 'different', 'status': 'success'}],
[{'context': CTX, 'status': 'failure'}, {'context': CTX, 'status': 'success'}]):
with self.assertRaises(cd.CDError):
cd.verify_contexts({'state': 'success', 'statuses': statuses}, [CTX])
cd.verify_contexts({'state': 'success', 'statuses': [{'context': CTX, 'status': 'success'}]}, [CTX])
def test_approval_and_acceptance_rechecked_before_switch(self):
self.host.approve.side_effect = [None, cd.CDError('revoked')]
with self.assertRaisesRegex(cd.CDError, 'revoked'):
self.execute()
self.host.switch.assert_not_called()
self.host.callback.assert_not_called()
def test_success_and_writeback_retry_do_not_switch_twice(self):
self.host.callback.side_effect = [cd.CDError('HiFox timeout'), None]
with self.assertRaisesRegex(cd.CDError, 'DEPLOYED_HIFOX_PENDING'):
self.execute()
self.assertEqual(cd.read_json(self.host.receipt_path)['state'], 'deployed_hifox_pending')
self.request.update(action='writeback', confirm='retry-writeback')
self.assertEqual(self.execute()['state'], 'published')
self.host.switch.assert_called_once()
self.host.load.assert_called_once()
self.assertEqual(self.host.verify.call_count, 2)
def test_writeback_without_receipt_refuses(self):
self.request.update(action='writeback', confirm='retry-writeback')
with self.assertRaisesRegex(cd.CDError, 'receipt'):
self.execute()
self.assert_no_deploy()
def test_failed_cutover_rolls_back_and_never_marks_published(self):
for result in ('rolled_back', 'rollback_failed'):
with self.subTest(result=result):
self.setUp()
self.host.verify.side_effect = cd.CDError('new unhealthy')
if result == 'rollback_failed':
self.host.rollback.side_effect = cd.CDError('old unhealthy')
with self.assertRaisesRegex(cd.CDError, result):
self.execute()
self.assertEqual(cd.read_json(self.host.receipt_path)['state'], result)
self.host.rollback.assert_called_once()
self.host.callback.assert_not_called()
with self.assertRaisesRegex(cd.CDError, 'receipt'):
self.execute()
self.host.switch.assert_called_once()
def test_gitea_guard_log_binds_the_exact_dispatch(self):
trusted = 'f' * 40
proof = cd.guard_proof(self.request, trusted)
log = f'2026-11-22T17:31:54.013Z {proof}\n'.encode()
cd.verify_guard_log(log, self.request, trusted)
for name, altered in (('sha', 'b' * 40), ('bundle', 'c' * 64), ('run_id', '43'),
('task', 'd5abdf29-d0b5-4992-8073-0cb8fffd84ee2'), ('confirm', 'retry-writeback')):
with self.subTest(name=name), self.assertRaisesRegex(cd.CDError, 'dispatch proof'):
cd.verify_guard_log(log, {**self.request, name: altered}, trusted)
with self.assertRaisesRegex(cd.CDError, 'dispatch proof'):
cd.verify_guard_log(log + log, self.request, trusted)
def hifox_fixture(self):
task = self.host.task.return_value
report = 'ba3ced78-e648-47de-9c17-bccb8f31f36f'
event = 'a3aa1dbe-4082-4972-8e29-ed3e39e26b30'
task.update(url='https://app.hifox.com/example/task/TEST-42', statusChangedAt='2026-11-22T18:00:00Z')
self.acceptance['evidence'] = task['url'] + '#comment-' + report
task['metadata']['cd_acceptance'] = json.dumps(self.acceptance)
timeline = [dict(id=report, event='commented', createdAt='2026-11-22T17:59:00Z',
content=f'验收通过 {SHA} {self.request["bundle"]}'),
dict(id=event, event='status_changed', createdAt=task['statusChangedAt'],
actor={'type': 'human', 'id': cd.RELEASE_OWNER}, metadata={'to': '待发布'})]
return task, timeline
def test_hifox_dispatch_claims_one_transition(self):
task, timeline = self.hifox_fixture()
timeline[-1]['createdAt'] = '2026-11-22T18:00:01Z'
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline, task, timeline]), \
patch.object(trigger, 'forge', return_value={'workflow_run_id': 42}) as dispatch:
first = trigger.queue(TASK, 'unused', self.root)
replay = trigger.queue(TASK, 'unused', self.root)
self.assertEqual(first, replay)
self.assertEqual(first['run_id'], '42')
dispatch.assert_called_once_with('POST', trigger.DISPATCH, {'ref': 'main', 'inputs': first['inputs']})
self.assertEqual(first['inputs']['approval_event'], timeline[-1]['id'])
def test_unknown_dispatch_outcome_is_held(self):
task, timeline = self.hifox_fixture()
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline, task, timeline]), \
patch.object(trigger, 'forge', side_effect=TimeoutError()) as dispatch:
with self.assertRaises(TimeoutError):
trigger.queue(TASK, 'unused', self.root)
with self.assertRaisesRegex(cd.CDError, 'outcome unknown'):
trigger.queue(TASK, 'unused', self.root)
dispatch.assert_called_once()
def test_hifox_gate_requires_owner_and_existing_candidate_report(self):
for failure in ('agent', 'other human', 'mismatched report', 'updated report', 'stale transition', 'no evidence'):
with self.subTest(failure=failure):
task, timeline = self.hifox_fixture()
if failure == 'agent':
timeline[-1]['actor']['type'] = 'agent'
if failure == 'other human':
timeline[-1]['actor']['id'] = TASK
if failure == 'mismatched report':
timeline[0]['content'] = SHA
if failure == 'updated report':
timeline[0]['updatedAt'] = '2026-11-22T19:00:00Z'
if failure == 'stale transition':
task['statusChangedAt'] = '2026-11-22T19:00:00Z'
if failure == 'no evidence':
task['metadata'] = {}
with patch.object(trigger, 'hifox', side_effect=[task, timeline]), patch.object(trigger, 'forge') as forge:
with self.assertRaises(cd.CDError):
trigger.queue(TASK, 'unused', self.root)
forge.assert_not_called()
def test_auto_approval_is_checked_again_before_switch(self):
task, timeline = self.hifox_fixture()
approval, _ = cd.release_approval(task, timeline, self.request)
self.request.update(approval)
self.host.timeline.side_effect = [timeline, timeline[:-1]]
proof = cd.guard_proof(self.request, 'f' * 40)
self.assertNotEqual(proof, cd.guard_proof({**self.request, 'acceptance_digest': 'e' * 64}, 'f' * 40))
with self.assertRaisesRegex(cd.CDError, 'status history'):
self.execute()
self.host.switch.assert_not_called()
def test_target_lock_is_exclusive(self):
path = self.root / 'lock'
with cd.deploy_lock(path):
with self.assertRaisesRegex(cd.CDError, 'deployment lock'):
with cd.deploy_lock(path):
self.fail('lock was acquired twice')
def test_persisted_compose_changes_only_images(self):
original = {'services': {role: {'image': role + ':old', 'env_file': [{'path': '/kept', 'format': 'raw'}],
'volumes': ['/kept:/run/key:ro'], 'environment': {'GATE': 'true'}}
for role in IMAGES}, 'name': 'governance'}
changed = cd.with_images(original, IMAGES)
for role, new in changed['services'].items():
self.assertEqual(new.pop('image'), IMAGES[role])
old = original['services'][role].copy()
old.pop('image')
self.assertEqual(new, old)
if __name__ == '__main__':
unittest.main()
+99
View File
@@ -0,0 +1,99 @@
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from threading import Thread
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import qa_env
class QAEnvironmentTests(unittest.TestCase):
def test_missing_approval_config_names_file(self):
with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / 'qa.json'
with self.assertRaisesRegex(qa_env.QAError, 'qa.json'):
qa_env.database_config(config)
def test_rejects_non_qa_database_before_connection(self):
with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / 'qa.json'
config.write_text(json.dumps(dict(host='rds.example.test', port=5432,
database='governance', user='kg_qa_app')))
config.chmod(0o600)
with self.assertRaisesRegex(qa_env.QAError, 'kg_qa_'):
qa_env.database_config(config)
def test_database_environment_uses_only_approved_identity(self):
settings = dict(host='rds.example.test', port=5432, database='kg_qa_app', user='kg_qa_app')
with patch.dict(os.environ, {'PGHOSTADDR': '127.0.0.1', 'PGPASSWORD': 'fixture',
'PGSERVICE': 'other', 'PRODUCTION_RELEASE_REQUESTS_ENABLED': 'true'}):
env = qa_env.database_env(settings, Path('/approved'))
self.assertEqual(env['PGHOST'], 'rds.example.test')
self.assertEqual(env['PGSSLMODE'], 'verify-full')
self.assertEqual(env['PRODUCTION_RELEASE_REQUESTS_ENABLED'], 'false')
self.assertFalse({'PGHOSTADDR', 'PGPASSWORD', 'PGSERVICE'} & env.keys())
def test_empty_database_or_known_migration_prefix_can_bootstrap(self):
for applied in ([], [1], [1, 2]):
with self.subTest(applied=applied):
qa_env.check_migrations([1, 2], applied, False, complete=False)
def test_pending_migrations_block_testing(self):
with self.assertRaisesRegex(qa_env.QAError, '迁移未完成'):
qa_env.check_migrations([1, 2], [1], False, complete=True)
def test_schema_without_ledger_is_rejected(self):
with self.assertRaisesRegex(qa_env.QAError, '非空'):
qa_env.check_migrations([1, 2], [], True, complete=False)
def test_unknown_or_missing_middle_migrations_are_rejected(self):
for applied in ([1, 3], [1, 2, 3], [2]):
with self.subTest(applied=applied), self.assertRaisesRegex(qa_env.QAError, '迁移序列'):
qa_env.check_migrations([1, 2], applied, False, complete=False)
def test_hifox_exit_zero_does_not_override_offline_state(self):
with self.assertRaisesRegex(qa_env.QAError, '在线'):
qa_env.check_hifox('{"connected":true,"remoteLiveness":{"status":"offline"}}')
qa_env.check_hifox('{"connected":true,"remoteLiveness":{"status":"online"}}')
def test_health_probe_rejects_spa_fallback(self):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(b'<html><div id="root"></div></html>')
def log_message(self, format, *args):
pass
with ThreadingHTTPServer(('127.0.0.1', 0), Handler) as server:
thread = Thread(target=server.serve_forever)
thread.start()
try:
self.assertTrue(qa_env.probe(server.server_port, '/', 'html'))
self.assertFalse(qa_env.probe(server.server_port, '/health', 'ok'))
finally:
server.shutdown()
thread.join()
def test_database_identity_mismatch_stops_before_reading_migrations(self):
env = {'PGDATABASE': 'kg_qa_app', 'PGUSER': 'kg_qa_app'}
with patch.object(qa_env, 'psql', return_value='other|kg_qa_app|t|t|t|t|t') as probe:
with self.assertRaisesRegex(qa_env.QAError, '实际库名'):
qa_env.database_state(env)
self.assertEqual(probe.call_count, 1)
def test_full_sha_mismatch_rejects_current_checkout(self):
full_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=qa_env.ROOT, text=True).strip()
wrong = ('0' if full_sha[0] != '0' else '1') + full_sha[1:]
with self.assertRaisesRegex(qa_env.QAError, '提交不一致'):
qa_env.check_checkout(wrong)
if __name__ == '__main__':
unittest.main()
+13 -3
View File
@@ -1,6 +1,7 @@
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'
@@ -41,9 +42,15 @@ 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}。之后新发布的“对内/对外”内容会写入这两个生产库(已发布过的条目仍回到原目标)。`
: `发布目标已保存:${where};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`)
? `发布目标已更新:${where}${replan}${frozen}。之后新发布的“对内/对外”内容会写入这两个生产库。`
: `发布目标已保存:${where}${replan}${frozen};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`)
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存生产知识库绑定失败') }
finally { setSaving(false) }
}
@@ -62,11 +69,14 @@ export function ProductionBindingsSection() {
<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} />
: <select value="" disabled aria-label={placeholder}>
<option value="">读不到生产库列表:先在上方把生产连接测通</option>
</select>
)
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)}
+148 -43
View File
@@ -1,6 +1,7 @@
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'
@@ -17,67 +18,171 @@ 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} 项因新库里已有同篇而被退休` : ''}`
: ''
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 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 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) => (
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 = ''
) => (
<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 ? '来自部署默认值(env)' : '') : '请绑定一个测试知识库'}</small>
<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>
</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>
: <input value={value} onChange={(event) => onChange(event.target.value.trim())} placeholder={`${placeholder}(输入知识库 ID)`} aria-label={placeholder} />
)
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>
{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>
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>
)
}
+5 -3
View File
@@ -424,12 +424,14 @@ 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)
// 生产端点可达性来自真实探活,且只说真话:探活不等于验证过接单能力。
@@ -453,7 +455,7 @@ describe('SystemSettingsView', () => {
initialSection="services"
/>
)
expect(blocked).toContain('已启用 · 被阻断')
expect(blocked).toContain('生产写入:开启 · 恢复演练未核验')
// 未配置生产端点时必须显式说「未配置」,不得靠文案含糊过去。
expect(blocked).toContain('端点探测:暂无真实探测结果')
const unconfigured = renderToStaticMarkup(
+23 -26
View File
@@ -119,6 +119,15 @@ 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,
@@ -199,6 +208,12 @@ 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">
@@ -278,14 +293,8 @@ export function SystemSettingsView({
</article>
<article className="production">
<b>生产 WeKnora</b>
<span>
{!productionEnabled
? '未启用'
: productionBackupRestoreVerified
? '已启用 · 可提交生产请求'
: '已启用 · 被阻断'}
</span>
<small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};发布目标与凭据:管理员受限配置,本页不可回读`}</small>
<span>{productionConnectionLineText}</span>
<small>{`${productionWeKnoraProbe(monitor)};${productionWriteLine};发布目标与凭据:管理员受限配置,本页不可回读`}</small>
</article>
</div>
<div className="safe-setting-grid production-endpoint-form">
@@ -293,27 +302,11 @@ export function SystemSettingsView({
<>
<label>
测试地址
<input
value={testEndpoint}
onChange={(event) => {
setTestEndpoint(event.target.value)
setDirty(true)
}}
placeholder="https://weknora.test.example"
aria-invalid={!testEndpointValid}
/>
<input value={testEndpoint || '未配置'} readOnly disabled />
</label>
<label>
生产地址
<input
value={endpoint}
onChange={(event) => {
setEndpoint(event.target.value)
setDirty(true)
}}
placeholder="https://weknora.prod.example"
aria-invalid={!endpointValid}
/>
<input value={endpoint || '未配置'} readOnly disabled />
</label>
<label>
生产 ID
@@ -376,6 +369,10 @@ export function SystemSettingsView({
原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora
列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。
</small>
<p className="hint">
地址已移到「测试知识库绑定 /
生产知识库绑定」分区顶部的连接卡维护(可在那里测试连接);这里是回退值,只读。
</p>
{serviceSettingsValid ? null : (
<p className="error-message" role="alert">
格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产
+183
View File
@@ -0,0 +1,183 @@
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,6 +11,10 @@ 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)
@@ -25,6 +29,10 @@ 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,6 +5,8 @@ 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
@@ -30,6 +32,8 @@ 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,3 +882,29 @@ 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
@@ -0,0 +1,116 @@
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
@@ -0,0 +1,145 @@
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 || '—'}`
}