Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 660320d646 | |||
| 0e33f21206 | |||
| 83bba09cde | |||
| 868924d074 | |||
| 03e622e9c7 | |||
| 9eef078ed0 | |||
| 2ca98a6a35 | |||
| 746b982c43 | |||
| 5ff6768027 | |||
| 2a639392e4 | |||
| 9cfe2114b1 | |||
| 1e7e986b70 | |||
| 8faabdcf9e | |||
| 922ff66533 | |||
| 0246db357f | |||
| 1beaa31771 | |||
| 8c76c54d8e | |||
| 084ee1b176 | |||
| 71971e8164 | |||
| 47428a8b58 | |||
| 91988a0d3b | |||
| 07a0ee2644 | |||
| 0b5de6ef7e | |||
| e892bfdd48 | |||
| d7d636792d | |||
| 89c484cdc4 | |||
| 5e3362e2b0 | |||
| 768ad53fe2 | |||
| 7d91343e5f | |||
| edd07a65d6 | |||
| 7c120b3adc | |||
| ea159ca2fb | |||
| cb026e8dd1 | |||
| 4b615abe53 | |||
| 341c3154ac | |||
| 63984dbfbe | |||
| 033f702d41 | |||
| 9eacf6473e | |||
| 6444814123 | |||
| 6ae5150fdf | |||
| 1f5bf72aec | |||
| ce2a155ebc | |||
| df69b278ce | |||
| 399b5756ea | |||
| 3da82d48d9 | |||
| afc38c921f | |||
| 0dd4ad2737 | |||
| d2f9060b33 | |||
| 3825859da6 | |||
| e0fa31c9d6 | |||
| b2cea6ed84 | |||
| 6c10f71c28 | |||
| cf65d3f363 | |||
| 8e6094e9e5 | |||
| 33afdb9f11 | |||
| 8a574903a1 | |||
| 0fb78cfe26 |
@@ -24,6 +24,11 @@ DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT=20m
|
||||
# Independent governance AI: endpoint/model/write-only API key are stored via the admin page.
|
||||
# Mount the same 32-byte regular 0600 master-key file into API and ordinary worker.
|
||||
QA_AI_MASTER_KEY_FILE=
|
||||
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP=false
|
||||
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
|
||||
QA_AI_DNS_OVER_TLS=
|
||||
# Only opt in behind an already trusted TLS-terminating same-origin reverse proxy.
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,80 @@
|
||||
name: prepare-candidate
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
plan:
|
||||
description: 'Release task UUID, exact SHA, baseline, requirement PRs and additional reviewed commits (JSON)'
|
||||
required: true
|
||||
mode:
|
||||
description: 'verify or prepare'
|
||||
required: true
|
||||
default: verify
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: knowledge-governance-candidate
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
guard:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Verify release scope and CI
|
||||
env:
|
||||
KG_CANDIDATE_READ_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
case "$GITHUB_SERVER_URL" in
|
||||
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
case "$GITHUB_REF" in refs/heads/*) ;; *) exit 1 ;; esac
|
||||
git init -q .
|
||||
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
|
||||
auth() { git -c credential.helper='!f() { printf "username=x-access-token\npassword=%s\n" "$KG_CANDIDATE_READ_TOKEN"; }; f' "$@"; }
|
||||
auth fetch -q origin "$GITHUB_REF" +refs/heads/main:refs/remotes/origin/main
|
||||
git checkout --detach -q "$GITHUB_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
export KG_CANDIDATE_FORGE="$GITHUB_SERVER_URL"
|
||||
python3 scripts/candidate_release.py guard --event "$GITHUB_EVENT_PATH" --repo .
|
||||
|
||||
prepare:
|
||||
if: ${{ inputs.mode == 'prepare' && gitea.ref == 'refs/heads/main' }}
|
||||
needs: [guard]
|
||||
runs-on: kg-candidate
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Build and deploy isolated candidate
|
||||
env:
|
||||
KG_CANDIDATE_ACCESS: ${{ secrets.KG_CANDIDATE_ACCESS }}
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REF" = refs/heads/main
|
||||
test -n "$KG_CANDIDATE_ACCESS"
|
||||
python3 - <<'PY'
|
||||
import json, os, sys
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import ProxyHandler, Request, build_opener
|
||||
with open(os.environ['GITHUB_EVENT_PATH']) as source:
|
||||
event = json.load(source)
|
||||
if event.get('inputs', {}).get('mode') != 'prepare':
|
||||
sys.exit('candidate workflow mode is not prepare')
|
||||
data = json.dumps({'run': os.environ['GITHUB_RUN_ID'], 'plan': json.loads(event['inputs']['plan'])}).encode()
|
||||
request = Request('http://127.0.0.1:38984/prepare', data=data, headers={
|
||||
'Authorization': 'Bearer ' + os.environ['KG_CANDIDATE_ACCESS'], 'Content-Type': 'application/json'})
|
||||
opener = build_opener(ProxyHandler({}))
|
||||
try:
|
||||
with opener.open(request, timeout=2540) as response:
|
||||
print(response.read(65536).decode())
|
||||
except HTTPError as exc:
|
||||
print(exc.read(4096).decode(), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
PY
|
||||
+272
-2
@@ -1,10 +1,275 @@
|
||||
# Changelog
|
||||
|
||||
## [Unreleased]
|
||||
## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **生产绑定保存重排待入库**:保存生产「知识库绑定」时,同一事务内把还没上传、
|
||||
原本瞄准旧生产目标库的待入库项改指向新库,并在保存提示里回报迁移条数;已经
|
||||
开始执行的发布项目标仍保持冻结,不会被改写。
|
||||
- **测试侧保存不再误搬生产作业**:两边共用 `test_publications` 待入库通道,重排
|
||||
现在只搬「上一次生效目标 → 新目标」成对的项;测试侧改绑不会再带走瞄准生产库的
|
||||
待入库项,生产侧也不猜「同 ID 语义」下的空目标。
|
||||
|
||||
## 开发快照 0.1.412(知识库绑定:清密钥保留名称与绑定身份)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **清除密钥保留知识库名称**:`key_action=clear` 不再把 `internal_kb_name` /
|
||||
`external_kb_name` 写成空串,改取事务内锁定行的旧值,且只在库 ID 未变时沿用
|
||||
(「同时改指向又清密钥」不会把旧库名贴到新库上);页面因此不再回落显示短 ID。
|
||||
生产侧同时保留已冻结的实例地址与租户,执行器的实例一致性检查不会把「只是没
|
||||
密钥」误判成换了实例。
|
||||
- **只填一端即可保存的存量用例对齐新语义**:留空 = 取消该方向绑定,不再断言
|
||||
`ErrInvalid`;用例改为断言保存成功、该侧为空、回退来源字段写明回退到哪、
|
||||
revision 递增,后续修订期望随之前移。
|
||||
- **清除后的真实库回归**:新增用例断言 `key_configured=false`、
|
||||
`verification=not_configured`、名称/库 ID/租户不变、`Resolve()` 失败关闭且不
|
||||
回落到部署文件里的旧 Key,历史表那一行只记布尔、不含任何密钥。该用例与既有
|
||||
集成用例一起登记进 `scripts/test-scope.json`(需显式一次性测试库,普通 CI 跳过)。
|
||||
|
||||
## 开发快照 0.1.411(知识库连接:四态验证、尾号回显与私网 http)
|
||||
|
||||
### Added
|
||||
|
||||
- **测试连接区分四态**:`POST /api/v1/kb-bindings/{environment}/catalog` 现在把
|
||||
401 与 403 分开返回「密钥无效」与「密钥无权限读取知识库列表」,与「地址不可达」
|
||||
「成功(读到 N 个库)」互不混淆,页面对应四种提示。
|
||||
- **密钥只回显尾 4 位**:绑定视图新增 `key_tail`,只用于展示;服务端不存尾号、
|
||||
不存明文,主密钥不可用时该字段为空而不是猜。
|
||||
- **清除密钥是独立动作**:`key_action=clear` 保留地址与内外库绑定,只把该侧凭据
|
||||
清空(需二次确认),消费者解析随后失败关闭,不会回落到服务器文件里的旧 Key。
|
||||
- **留空 = 取消绑定并回报回退**:视图新增 `internal_fallback` / `external_fallback`,
|
||||
测试侧回退到部署默认库、生产侧回退到「同 ID 语义」,保存提示里写明退到哪。
|
||||
- **生产绑定回报冻结计数**:`frozen` / `retargetable` 按在飞执行统计,已冻结的
|
||||
`release_item_executions.target_knowledge_base_id` 不被改写。
|
||||
|
||||
### Changed
|
||||
|
||||
- 发布管理按封存、授权、同步与查看任务切换主操作,合并重复入口;变更明细、完整性和恢复验证按需展开,维护占用与失败作业保持可见。流程说明见 [发布管理流程与页面精简](docs/release-ui-flow.md)。
|
||||
- 新增 `WEKNORA_ALLOW_PRIVATE_HTTP`:只放行 RFC1918/回环/链路本地 http,公网 http
|
||||
仍拒绝。客户端、监控探活与连接页共用 `weknora.HTTPAllowed` 这一份判定,生产
|
||||
`18093` 同网段反代因此可用,页面不再出现「卡片可达、列库失败」。
|
||||
- 私网治理台(明文 http)录入密钥改用同源校验(Origin 与 Host 完全一致),
|
||||
仍拒绝跨站与公网来源。
|
||||
|
||||
## 开发快照 0.1.410(存储页快照状态区分)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 快照超过 15 分钟后不再把目录区写成“元数据快照未接线”:按接口字段区分
|
||||
未配置、缺失、过期、无效、不完整,目录与历史分别标注真实状态。
|
||||
- 过期快照不展示旧批次路径、旧目录路径或旧容量预测;目录输入清空并提示等待宿主
|
||||
重新采集;历史区只说明过期原因,不回退冒充“没有备份”。
|
||||
- 读取源/采集时间/读回时间按同一快照状态展示:过期仍显示当时的采集时间与年龄,
|
||||
读回时间单独取 API 时间,不混用。
|
||||
- 增加过期与未配置反例回归,覆盖旧批次/旧容量不得复用。
|
||||
|
||||
## 开发快照 0.1.409(存储与备份页面显示口径修正)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 完整快照不再把宿主备份文件系统可写当成部署错误:去掉“挂载可写 / 需改 :ro”提示,
|
||||
明确备份盘由备份主机写入,API 只读元数据快照。
|
||||
- 容量已实测且完整时磁盘告警为正常,不再出现“缺主机磁盘读数”;配额相关三项仅标注
|
||||
配额字段未接线,摘要区分“磁盘项正常”与“磁盘项无法判定”。
|
||||
- 采集时间(宿主快照)与读回时间(API)分列;快照年龄/新鲜度取快照字段;
|
||||
“重新盘点”明确只重读 `metadata.json`,不会让宿主重新采集。
|
||||
- 空间预测注明以上次整批实际占盘为参考,不是接口预测。
|
||||
- 小文件不足 0.05 MiB 显示 KiB,避免非零体积被舍成 0.0 MiB。
|
||||
|
||||
## 开发快照 0.1.408(备份盘点改宿主采集器:权限失败不再产出部分字节)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复 API 以 uid 1000 遍历 root:root 0700 备份目录时 `sizes_complete=false` 但
|
||||
`Database.ActualBytes` 仍保留部分计数的问题:API 不再遍历备份目录,只读宿主快照;
|
||||
快照不完整/陈旧/缺失时批次与子库字节全部为 `null`,页面不画容量图、不使用部分字节。
|
||||
- 容量图与任何可写预测只在“快照新鲜 + 完整 + 路径校验通过 + 容量实测”时出现;
|
||||
权限失败回归覆盖采集器注入 `PermissionError` 与 API 拒绝部分字段。
|
||||
- 单库 `696320` 只作现场核对值,代码与测试不写死。
|
||||
|
||||
### Added
|
||||
|
||||
- `scripts/collect_backup_metadata.py`:宿主单次只读采集器,stat/du + MANIFEST,
|
||||
原子写 `metadata.json`,不读数据库内容、不跟随符号链接、权限失败置空字节。
|
||||
统计口径与 `du -sB1` 对齐:目录自身计入、树内硬链接按 `(dev,ino)` 去重、
|
||||
单库与整批各自独立测量;MANIFEST 只接受批次目录内常规非符号链接文件,
|
||||
打开带 `O_NOFOLLOW`。
|
||||
- `GET /api/v1/backup-schedule/inventory` 读取并校验快照:schema、root、批次/子库路径、
|
||||
采集时效、完整性;批次/子库字节可空。
|
||||
- 文档改为 28189 快照挂载、采集器安装/定时、可验证字段与写能力清单。
|
||||
|
||||
## 开发快照 0.1.407(备份盘点:只读挂载读真实批次与容量)
|
||||
|
||||
### Added
|
||||
|
||||
- `GET /api/v1/backup-schedule/inventory`:只读盘点 `rds-logical` 批次、MANIFEST 状态、每个
|
||||
子库完整主机路径、表观/实际占盘,以及只读挂载文件系统的实测容量。
|
||||
- 新包 `internal/backupinventory`:批次按目录戳倒序,`*.incomplete` 不计入;清单缺失/损坏
|
||||
逐批标注;实际占盘按 `st_blocks×512`;容量用 `statfs`,并与容器根盘比较设备号。
|
||||
- 系统设置 → 存储与备份接入盘点:整盘色带、批次列表、子库路径复制、清单失败与未接线分开;
|
||||
SSH 计划读回与文件盘点独立加载,互不掩盖失败。
|
||||
- 文档 `docs/STORAGE_BACKUP_READONLY_API.md`:28189 候选接口契约、`:ro` 最小挂载与权限要求、
|
||||
可验证字段、现有写路径与尚未实现的后端写能力。
|
||||
|
||||
### Changed
|
||||
|
||||
- 备份策略目录改为只读展示盘点到的 `host_root`;配额/预留仍无后端字段,保留占位并标未知。
|
||||
- 磁盘告警只在“挂载与容器根盘分离 + 容量实测 + 有批次占盘参考”时判定;容器根盘读数只作排障。
|
||||
|
||||
### Security
|
||||
|
||||
- 盘点不执行远端文件命令、不写备份目录;只接受只读挂载,拒绝跟随符号链接批次,扫描有上限。
|
||||
|
||||
## 开发快照 0.1.406(备份主机状态不得由历史推断)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 平台未挂载主机凭据时不再断言「定时计划不会执行」:改为无法确认当前主机计划,
|
||||
远端 cron 可能仍在执行;历史下发记录不能代替实时状态。
|
||||
- 「最后下发」明确标为历史记录,只证明当时下发过,不能代表当前主机计划或执行状态。
|
||||
- 未探测与探测失败分开:只读计划先返回时显示「尚未探测」,不误报「连接失败」;
|
||||
「与设置是否一致」只在真正读回主机计划后判定,未读到时显示无法比对。
|
||||
- 回归:无凭据但存在有效历史下发、已接线但尚未探测两例都不得出现执行断言。
|
||||
|
||||
## 开发快照 0.1.405(存储与备份:单页对齐真实接口)
|
||||
|
||||
### Added
|
||||
|
||||
- 「系统设置 → 存储与备份」按已批准交互稿落成单页:范围与读写方向、整盘占用与四项告警、
|
||||
备份策略、最近批次与子库清单、运行进度、恢复验证;立即备份按钮明确标注"整批全部业务库"。
|
||||
- 整盘色带与四项告警(磁盘不足/配额不足/两者同时/配额超出物理空闲)抽成纯函数,用隔离夹具
|
||||
覆盖正常、单项不足、同时不足与缺读数分支;生产页面在无磁盘接口时只显示"未接线"。
|
||||
- 策略区保留原型里的目录、总配额、磁盘预留位置,并逐项标注后端无对应字段、不会被保存。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「立即备份一次」不再显示成单库动作:`POST /api/v1/backup-schedule/run` 没有单库参数,
|
||||
单库按钮会触发整批,因此页面禁用单库动作并说明"范围未经证实"。
|
||||
- 备份记录只展示主机 MANIFEST 的最近一批与库名;历史批次、子库路径、恢复验证没有接口,
|
||||
保留位置并注明原因,不拼造路径或假成功。
|
||||
- 「归档占用」改名为"版本快照,不是数据库备份",与数据库整库备份分开计量,避免把两者相加。
|
||||
|
||||
## 开发快照 0.1.404(单次任务固定同一 WeKnora 连接)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 上传、轮询、验收、移除先 `BeginTask` 解析一次并核验对象租户,返回的 context 钉住同一
|
||||
不可变连接;后续上传、列库恢复、查询、chunk 读取、删除与删除后重查都复用它,不再
|
||||
各自 `Resolve`。任务开始后页面改绑实例,旧任务也不会中途切到新实例。
|
||||
- 回归:真实客户端假端点断言一次处理只解析一次且全部打到同一实例;四个 handler 用
|
||||
TaskConnector 假客户端断言所有业务调用携带同一连接令牌,含上传恢复和删除重查。
|
||||
|
||||
## 开发快照 0.1.403(实例身份约束:绑定、发布与测试对象不跨实例)
|
||||
|
||||
### Added
|
||||
|
||||
- 迁移 000082:`production_kb_bindings` 冻结每个方向核验时的实例地址与租户,
|
||||
`release_item_executions` 冻结 `target_instance_url/target_tenant_id`,
|
||||
`test_publications` 记录对象实际写入的测试实例地址/租户。
|
||||
- 文档发布执行器在 `Contract/Prepare/Activate/Restore/Compensate` 前统一核对实例身份:
|
||||
网页在实例 A 列库、执行器连实例 B 时,即使知识库 ID/租户相同也以
|
||||
`release_contract_mismatch` 失败关闭,不写目标;整库发布目标不变。
|
||||
- 测试入库的上传/轮询/验收/移除按对象记录的身份核对当前连接;改绑实例或租户后,
|
||||
旧对象不会在克隆实例上继续轮询、验收或删除。
|
||||
- 回归:实例 A/B 同名同 ID 的隔离夹具、绑定身份写入计划、四个测试 handler 的正反例。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「知识库绑定」保存必须为对内/对外各选一个库;显式“未绑定”不再回落部署默认 ID,
|
||||
避免换绑实例后把旧实例的默认库带到新实例。旧页面留下的既有绑定行保持原语义。
|
||||
|
||||
### Security
|
||||
|
||||
- 实例身份不匹配一律失败关闭;旧发布项缺少身份信息时也不再猜测,避免写错克隆实例。
|
||||
|
||||
## 开发快照 0.1.402(知识库绑定:按环境一次保存连接与内外库)
|
||||
|
||||
### Added
|
||||
|
||||
- 「系统设置 → 知识库绑定」:测试 090 / 生产 090 分环境工作区,同一时间只编辑一个环境;顶部只读显示当前生效的对内/对外库。
|
||||
- 草稿可填写本环境服务地址与 API Key;「验证并读取知识库」由服务器真实列库(分页),明确区分可读、空库、无权限、不可达。
|
||||
- 列表按「名称 + 短 ID」区分同名库;对内与对外选同一个库会被拒绝。一次保存同时写入连接与内外绑定,并回读真实生效值。
|
||||
- 新增 `GET /api/v1/kb-bindings`、`POST /api/v1/kb-bindings/{environment}/catalog`、`PUT /api/v1/kb-bindings/{environment}`;读写分离,写仅管理员。
|
||||
- 迁移 000081:`weknora_environment_bindings` 与修订历史;密钥只存 AES-256-GCM 密文,主密钥来自独立 `WEKNORA_BINDING_MASTER_KEY_FILE`。
|
||||
- 保存会校验所选库属于候选实例(同一地址与密钥读取),并在同一事务内镜像测试路由/生产文档级绑定;测试环境同时重排未上传的待入库项并回报数量。
|
||||
|
||||
### Changed
|
||||
|
||||
- 原「知识库映射 → WeKnora 连接」入口并入「知识库绑定」;探活、封存源、整库发布目标与旧文档级目标收进折叠诊断,保留入口但不再提供第二个保存路径。
|
||||
- 消费者(readiness、上传/轮询、列库、监控探活、生产列库)统一从加密存储解析当前连接;没有新行时继续使用旧部署的文件凭据与默认绑定。
|
||||
- 整库发布实际目标仍只读,并明确由部署配置决定;本页保存不触发生产写入、导入、发布或停服。
|
||||
|
||||
### Security
|
||||
|
||||
- API Key 不回显、不写日志/URL/浏览器存储;更换地址必须重新录入密钥,旧密钥不会转发到新地址,也不会跨环境取用。
|
||||
- 保存使用修订号与行锁:并发或失败时旧绑定保持不变,未保存草稿不影响当前生效值。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 生产 WeKnora 健康探活改为跟随当前有效端点(原实现绕过 resolver,改地址后仍探旧值)。
|
||||
|
||||
## 开发快照 0.1.401(AI 模型连接:当前生效 + 独立草稿)
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → AI 模型连接」按交互稿重排:顶部只读「当前生效」(模型 + 服务端真实核验态与地址),
|
||||
下方地址/模型是独立草稿;测试草稿只回显核验结果,不更新当前连接,「测试中」与「保存中」分开提示。
|
||||
- 保存成功一律用服务端响应回显当前信息;草稿改动或版本冲突(409)都会作废上一次草稿测试,
|
||||
冲突时载入最新已保存配置并要求按新版本重测。
|
||||
- 已配置密钥默认收起不回显,只有「更换密钥」或首次录入才出现输入框;更换基础地址强制重新录入密钥,
|
||||
取消更换无副作用。安全传输与独立密钥存储限制保持不变。
|
||||
- 「清除密钥并停用」收进单独折叠区,写明对问答分析与中文翻译的影响并二次确认;只提交已保存连接,
|
||||
未保存草稿不会被夹带,取消不产生任何请求。
|
||||
- 合并分区标题与组件内重复的说明文字,模型连接说明只保留一处。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 模型连接的测试/保存不再共用同一个忙碌状态,避免把草稿测试结果误当成已生效配置。
|
||||
|
||||
## 开发快照 0.1.399(系统设置分区调整:AI 模型连接 / 知识库映射)
|
||||
|
||||
### Changed
|
||||
|
||||
- 原「系统设置 → 服务配置」改名为「AI 模型连接」,只保留问答四字段分析与中文翻译共用的
|
||||
模型连接(地址、模型、密钥操作、测试连接、保存),不再混放 WeKnora 连接。
|
||||
- WeKnora 测试/生产地址、生产租户与知识库 ID 迁到「知识库映射」,与测试入库、封存源、
|
||||
生产目标同屏;两个 ID 收进「生产核验参数」,并注明只用于核验、不决定发布写入目标。
|
||||
- 连接配置在独立组件内维护自己的草稿:保存只提交连接的四项,刷新参数取服务器当前值;
|
||||
保存刷新策略也不会带上未保存的连接地址。
|
||||
- 凭据仍是服务器文件引用,连接卡只报状态,页面不提供 API Key 录入。
|
||||
- 同步更新 README、运维手册、验收清单中的入口路径。
|
||||
|
||||
## 开发快照 0.1.384(系统设置审查修复:能力心跳、封存源对照、分区合并)
|
||||
|
||||
### Added
|
||||
|
||||
- `GET /api/v1/system/worker-capabilities`:读取 worker 认领记录里的 job_types,
|
||||
页面据此显示“执行器已启用/已停用/无认领”,不再把 readiness 当成可接单。
|
||||
- 测试知识库绑定接口返回整库封存源与一致性状态,设置页同屏对照“入库目标 / 封存源”。
|
||||
|
||||
### Changed
|
||||
|
||||
- 系统设置分区合并为“知识库映射”(测试入库 + 生产目标 + 封存源对照)。
|
||||
- 服务卡片分三行:地址可达、凭据与库读取、执行器能力。
|
||||
|
||||
## 开发快照 0.1.383(发布管理精简 + 系统设置审查修复)
|
||||
|
||||
### Changed
|
||||
|
||||
- 发布管理:顶部改为「状态卡 + 下一步」,一个主按钮(启动同步/查看任务)+ 一个准备按钮
|
||||
(封存/基线/签发授权);启动条件、检查清单、恢复验证收进「发布前检查」;
|
||||
目标维护、差异明细、来源身份收进「高级与历史」。去掉重复的版本入口与说明。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 服务配置与刷新策略各自保存边界:保存一方不再夹带另一方未保存的草稿(F03)。
|
||||
- 系统设置分区独立加载:监控/目录失败不再挡住成员与备份入口;保存后重新探测服务状态(F09)。
|
||||
- 解析停滞阈值接入活动配置(worker 60 秒内生效),收尾超时仍只保存并在页面标注未接入(F02)。
|
||||
- 重置密码改为受控遮罩对话框,不再用浏览器 prompt(F11)。
|
||||
- 生产绑定:文档级旧配置收进折叠区,凭据缺失时说明不影响整库执行器(F05/F06)。
|
||||
- 备份:主机未接通时明确「当前计划不会执行」,无运行记录时失败库显示未知(F07)。
|
||||
- 文案统一:生产租户 ID、备份执行主机、收尾超时告警;技术细节不再占据主视图(F10)。
|
||||
|
||||
## 开发快照 0.1.382(采集 agent 允许显式 peer uid)
|
||||
|
||||
@@ -2361,6 +2626,11 @@
|
||||
|
||||
### Added
|
||||
|
||||
- 数据源配置新增 PP API 地址、账号与密码更新、真实登录及目录连接检查;配置校验通过才生效,临时故障保留待验证修改,扫描与取件共用生效配置。
|
||||
- 钉钉添加来源统一使用 DWS 官方授权,增加真实空间校验、中途失效恢复与账号变化保护,取消登记自动回落旧扫码侧车;认证操作接入既有审计。
|
||||
|
||||
- 数据源配置新增 DWS 登录与重新授权入口,使用钉钉官方设备授权;成功后刷新账号并独立检查目录访问权限。支持取消、过期和重试,授权仅限发起的管理员会话。[操作说明](docs/DWS_LOGIN.md)
|
||||
|
||||
- 新增解析监控统一工作台:顶部运行指标与依赖卡片、下方单一文件处理表;来源文件与目标测试库归并最新版本,动作、阶段、状态分列,后端统一筛选、计数及分页。支持单条/跨页勾选重试和版本、失败、重试详情;测试库移除重试独立核验治理规则,不误走上传流程。取消六分页和手动开始入口,生产授权仍在发布管理;本次不改变后台自动调度策略,自动处理闭环需另行端到端验收。
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
+2
-1
@@ -51,6 +51,7 @@ RUN set -eux; \
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/ /app/
|
||||
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/dws_dingtalk_scan.py \
|
||||
scripts/artifact_fetch.py scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
|
||||
scripts/pp_client.py scripts/artifact_fetch.py scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
|
||||
RUN chmod 0644 /app/scripts/*.py
|
||||
USER 65532:65532
|
||||
CMD ["/app/api"]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -52,9 +52,9 @@ Knowledge Adapter / DobotAI 网关
|
||||
|
||||
| 来源 | 当前接入方式 | 参考文档 |
|
||||
| --- | --- | --- |
|
||||
| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) |
|
||||
| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [登录授权](docs/DWS_LOGIN.md) · [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) |
|
||||
| AList | 来源目录与资料获取,依赖指定连接和凭据 | [用户操作流程](docs/OPERATIONS_RUNBOOK.md) |
|
||||
| PP(资料门户) | 本地清单、历史账本接管与只读扫描 | [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) |
|
||||
| PP(资料门户) | 页面管理 API 与认证配置;真实校验、只读扫描及取件 | [认证配置](docs/SOURCE_AUTH_CONFIGURATION.md) · [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) |
|
||||
|
||||
IT、行政等是待扩展的业务资料范围,不是已经完成的新连接器。接入敏感资料前,需要先确认 Owner、有效版本、可见范围与知识库路由。
|
||||
|
||||
@@ -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#接入外部平台)、[来源认证](docs/SOURCE_AUTH_CONFIGURATION.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,13 +95,7 @@ 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 流程。
|
||||
|
||||
## 配置与安全边界
|
||||
|
||||
@@ -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)。页面验收标准见[运维手册](docs/OPERATIONS_RUNBOOK.md#开发测试和现场验收)。
|
||||
|
||||
```bash
|
||||
make verify # 完整检查入口:本地与 CI 使用同一套规则
|
||||
@@ -127,7 +122,7 @@ make list # 查看检查清单与适用范围
|
||||
|
||||
## 问答运营模型配置
|
||||
|
||||
管理员在「系统设置 → 服务配置 → 问答评估模型」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。页面顶部显示当前已保存的模型与服务端核验结果,下方编辑的是独立草稿:测试连接只核验草稿,保存才更新当前连接,保存成功后按服务端响应回显。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显、默认收起,只有「更换密钥」或首次录入才显示输入框,更换基础地址须重新录入密钥;「清除密钥并停用」在单独折叠区里二次确认,只作用于已保存连接。录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
|
||||
API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。
|
||||
|
||||
|
||||
@@ -1972,6 +1972,29 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/backup-schedule/inventory": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getBackupScheduleInventory",
|
||||
"summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/ServiceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/backup-schedule/apply": {
|
||||
"post": {
|
||||
"tags": [
|
||||
@@ -2682,6 +2705,211 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/pp-connection": {
|
||||
"get": {
|
||||
"operationId": "getPPConnection",
|
||||
"summary": "管理员读取 PP 配置元数据及最近检查结果",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPConnectionView"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"operationId": "savePPConnection",
|
||||
"summary": "管理员保存并真实校验 PP 配置",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPConnectionView"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PPConnectionDraft"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/pp-connection/test": {
|
||||
"post": {
|
||||
"operationId": "testPPConnection",
|
||||
"summary": "管理员使用草稿真实登录并读取最小目录,不登记来源",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PPConnectionDraft"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/dingtalk-spaces/validate": {
|
||||
"post": {
|
||||
"operationId": "validateDingtalkSourceSpaces",
|
||||
"summary": "管理员用共享 DWS 身份真实检查所选空间可见性",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成"
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"urls"
|
||||
],
|
||||
"properties": {
|
||||
"urls": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/dingtalk-spaces": {
|
||||
"post": {
|
||||
"tags": [
|
||||
@@ -3434,6 +3662,26 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/system/worker-capabilities": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getWorkerCapabilities",
|
||||
"summary": "读取 worker 能力心跳(执行器是否注册上传/解析链)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/routing-bindings": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -3482,6 +3730,61 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings": {
|
||||
"get": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "getKBBindings",
|
||||
"summary": "读取测试/生产环境的 WeKnora 连接与内外库绑定(密钥不回显)",
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings/{environment}/catalog": {
|
||||
"post": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "catalogKBBindingConnection",
|
||||
"summary": "用草稿地址与密钥真实列库(管理员,只读,分页)",
|
||||
"parameters": [
|
||||
{"name": "environment", "in": "path", "required": true, "schema": {"type": "string", "enum": ["test", "production"]}}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/KBCatalogInput"}}}
|
||||
},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"409": {"$ref": "#/components/responses/Conflict"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings/{environment}": {
|
||||
"put": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "saveKBBinding",
|
||||
"summary": "一次保存当前环境的连接与内外库绑定(管理员)",
|
||||
"parameters": [
|
||||
{"name": "environment", "in": "path", "required": true, "schema": {"type": "string", "enum": ["test", "production"]}}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/KBBindingSaveInput"}}}
|
||||
},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"409": {"$ref": "#/components/responses/Conflict"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/production-kb-bindings": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -5859,6 +6162,208 @@
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"KBBindingEnvironmentView": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["environment", "revision", "base_url", "key_configured", "internal_kb_id", "external_kb_id", "verification", "storage_ready", "source"],
|
||||
"properties": {
|
||||
"environment": {"type": "string", "enum": ["test", "production"]},
|
||||
"revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_configured": {"type": "boolean"},
|
||||
"key_source": {"type": "string", "enum": ["sealed", "file", "none"]},
|
||||
"internal_kb_id": {"type": "string"},
|
||||
"internal_kb_name": {"type": "string"},
|
||||
"external_kb_id": {"type": "string"},
|
||||
"external_kb_name": {"type": "string"},
|
||||
"verification": {"type": "string"},
|
||||
"checked_at": {"type": ["string", "null"]},
|
||||
"updated_by": {"type": "string"},
|
||||
"updated_at": {"type": ["string", "null"]},
|
||||
"source": {"type": "string", "enum": ["web", "legacy"]},
|
||||
"storage_ready": {"type": "boolean"},
|
||||
"replanned": {"type": "integer", "minimum": 0},
|
||||
"retired_duplicates": {"type": "integer", "minimum": 0}
|
||||
}
|
||||
},
|
||||
"KBBindingSnapshot": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["environments", "storage_ready"],
|
||||
"properties": {
|
||||
"environments": {"type": "array", "items": {"$ref": "#/components/schemas/KBBindingEnvironmentView"}},
|
||||
"storage_ready": {"type": "boolean"}
|
||||
}
|
||||
},
|
||||
"KBCatalogInput": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["base_url", "key_action", "page", "page_size"],
|
||||
"properties": {
|
||||
"base_revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_action": {"type": "string", "enum": ["keep", "replace"]},
|
||||
"api_key": {"type": "string", "writeOnly": true, "maxLength": 4096},
|
||||
"page": {"type": "integer", "minimum": 1},
|
||||
"page_size": {"type": "integer", "minimum": 1, "maximum": 100}
|
||||
}
|
||||
},
|
||||
"KBBindingSaveInput": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["base_url", "key_action", "internal_kb_id", "external_kb_id"],
|
||||
"properties": {
|
||||
"base_revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_action": {"type": "string", "enum": ["keep", "replace"]},
|
||||
"api_key": {"type": "string", "writeOnly": true, "maxLength": 4096},
|
||||
"internal_kb_id": {"type": "string"},
|
||||
"external_kb_id": {"type": "string"}
|
||||
}
|
||||
},
|
||||
"KBCatalogOption": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"name": {"type": "string"},
|
||||
"knowledge_count": {"type": "integer"}
|
||||
}
|
||||
},
|
||||
"PPConnectionDraft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"base_url",
|
||||
"username",
|
||||
"revision"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"base_url": {
|
||||
"type": "string",
|
||||
"format": "uri",
|
||||
"description": "HTTPS API 根地址"
|
||||
},
|
||||
"username": {
|
||||
"type": "string",
|
||||
"maxLength": 255
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"writeOnly": true,
|
||||
"maxLength": 8192,
|
||||
"description": "省略或空值保留已存密码"
|
||||
},
|
||||
"revision": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"pending_id": {
|
||||
"type": "string",
|
||||
"description": "继续校验已保存的待验证修改"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPSafeMetadata": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id",
|
||||
"base_url",
|
||||
"username",
|
||||
"password_configured"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"base_url": {
|
||||
"type": "string",
|
||||
"format": "uri"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
},
|
||||
"password_configured": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPObservation": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"state",
|
||||
"message",
|
||||
"checked_at"
|
||||
],
|
||||
"properties": {
|
||||
"state": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"valid",
|
||||
"auth_failed",
|
||||
"permission_denied",
|
||||
"incomplete",
|
||||
"unavailable",
|
||||
"invalid_response"
|
||||
]
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"checked_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPConnectionView": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"revision": {
|
||||
"type": "integer"
|
||||
},
|
||||
"active": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPSafeMetadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"pending": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPSafeMetadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"observation": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"pending_observation": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"QAReportedHistoricalRate": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
|
||||
+132
-40
@@ -8,6 +8,8 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -15,12 +17,15 @@ import (
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/backuphost"
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/httpapi"
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
@@ -52,6 +57,25 @@ func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node s
|
||||
return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node)
|
||||
}
|
||||
|
||||
// 宿主快照的展示路径必须与采集 root 同一份:容器内快照路径不可给操作者复制,
|
||||
// 复制出去要在主机上能直接 cd/pg_restore。来源没配时用 target + 主机根拼。
|
||||
func backupInventoryHostRoot(config appconfig.Config) string {
|
||||
if config.BackupHostReadonlyHostPath != "" {
|
||||
return config.BackupHostReadonlyHostPath
|
||||
}
|
||||
return path.Join(config.BackupHostRoot, "rds-logical")
|
||||
}
|
||||
|
||||
func backupInventorySource(config appconfig.Config) string {
|
||||
if config.BackupHostReadonlySource != "" {
|
||||
return config.BackupHostReadonlySource
|
||||
}
|
||||
if config.BackupHostTarget == "" {
|
||||
return ""
|
||||
}
|
||||
return config.BackupHostTarget + ":" + backupInventoryHostRoot(config)
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -93,61 +117,106 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
// Production WeKnora is probed for liveness only: the console must show the
|
||||
// real state of that endpoint, while credentials and the publish target stay
|
||||
// in the release runtime config (RELEASE_CONFIG_FILE).
|
||||
// 生产 WeKnora 端点:配置入口在网页「系统设置 → 服务配置」,管理员保存的值是
|
||||
// 生产 WeKnora 端点:配置入口在网页「系统设置 → 知识库映射」,管理员保存的值是
|
||||
// 这里的真源;容器 env 只作为未在网页配置时的兜底。凭据与发布目标仍留在
|
||||
// release 运行时配置(RELEASE_CONFIG_FILE)里,不经网页也不落明文。
|
||||
actionStore := postgresstore.NewStore(pool)
|
||||
productionEndpointResolver := func(resolveCtx context.Context) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return settings.ProductionWeKnoraBaseURL
|
||||
}
|
||||
testEndpointResolver := func(resolveCtx context.Context) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return settings.TestWeKnoraBaseURL
|
||||
}
|
||||
// P10 readiness 与执行链看同一目标:网页保存的端点、当前持久化绑定、同一份
|
||||
// API Key。启动时只捕获 resolver,不捕获任何一项的值(F13:旧 env 绑定 404)。
|
||||
readinessResolver := newWeKnoraReadinessResolver(
|
||||
func(resolveCtx context.Context) string {
|
||||
if saved := testEndpointResolver(resolveCtx); saved != "" {
|
||||
return saved
|
||||
kbBindings := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: config.WeKnoraBindingMasterKeyFile,
|
||||
Timeout: 10 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP,
|
||||
kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
},
|
||||
AllowPrivateHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.WeKnoraAllowPrivateHTTP,
|
||||
kbbinding.EnvProduction: config.WeKnoraAllowPrivateHTTP,
|
||||
},
|
||||
LegacyBaseURL: func(resolveCtx context.Context, env string) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if env == kbbinding.EnvProduction {
|
||||
if value := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.ProductionWeKnoraBaseURL
|
||||
}
|
||||
if value := strings.TrimSpace(settings.TestWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
config.InternalRoutingKnowledgeBaseID,
|
||||
func(resolveCtx context.Context) (string, error) {
|
||||
internal, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
return internal, err
|
||||
LegacyKey: func(env string) (string, error) {
|
||||
path := config.TestWeKnoraAPIKeyFile
|
||||
if env == kbbinding.EnvProduction {
|
||||
path = config.ProductionWeKnoraAPIKeyFile
|
||||
}
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", nil
|
||||
}
|
||||
return weknora.ReadAPIKeyFile(path)
|
||||
},
|
||||
func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
)
|
||||
LegacyBinding: func(resolveCtx context.Context, env string) (string, string, error) {
|
||||
if env == kbbinding.EnvProduction {
|
||||
internal, external, _, err := actionStore.LoadProductionKBBindings(resolveCtx)
|
||||
return internal, external, err
|
||||
}
|
||||
internal, external, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
if internal == "" {
|
||||
internal = config.InternalRoutingKnowledgeBaseID
|
||||
}
|
||||
if external == "" {
|
||||
external = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
return internal, external, err
|
||||
},
|
||||
})
|
||||
productionEndpointResolver := func(resolveCtx context.Context) string {
|
||||
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvProduction)
|
||||
}
|
||||
testEndpointResolver := func(resolveCtx context.Context) string {
|
||||
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvTest)
|
||||
}
|
||||
// P10 readiness 与执行链看同一目标:当前持久化绑定、当前有效连接(加密存储优先、
|
||||
// 旧部署 file 凭据兜底)。任何一项读取失败都必须显式报错,不能静默退回旧值。
|
||||
readinessResolver := func(resolveCtx context.Context) (readiness.Target, error) {
|
||||
target := readiness.Target{KnowledgeBaseID: config.InternalRoutingKnowledgeBaseID}
|
||||
stored, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
if err != nil {
|
||||
return readiness.Target{}, fmt.Errorf("读取当前知识库绑定失败")
|
||||
}
|
||||
if strings.TrimSpace(stored) != "" {
|
||||
target.KnowledgeBaseID = strings.TrimSpace(stored)
|
||||
}
|
||||
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
if err != nil {
|
||||
return readiness.Target{}, fmt.Errorf("读取 WeKnora 有效连接失败:%w", err)
|
||||
}
|
||||
target.BaseURL, target.APIKey = connection.BaseURL, connection.APIKey
|
||||
return target, nil
|
||||
}
|
||||
readinessProber := readiness.Prober{
|
||||
Resolve: readinessResolver,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
Resolve: readinessResolver,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
weknoraProbe := func(probeCtx context.Context) (string, error) {
|
||||
result := readinessProber.Check(probeCtx)
|
||||
return result.Target, result.Err
|
||||
}
|
||||
knowledgeBaseLister := &weKnoraLister{
|
||||
endpoint: func(resolveCtx context.Context) string {
|
||||
if saved := testEndpointResolver(resolveCtx); saved != "" {
|
||||
return saved
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
resolve: func(resolveCtx context.Context) (string, string, error) {
|
||||
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return connection.BaseURL, connection.APIKey, err
|
||||
},
|
||||
readKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
timeout: config.TestWeKnoraHTTPTimeout,
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
timeout: config.TestWeKnoraHTTPTimeout,
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
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: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -159,6 +228,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
TestAllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
ProductionAllowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
})
|
||||
productionKnowledgeBases := &productionKnowledgeBaseLister{bindings: kbBindings, timeout: 10 * time.Second, allowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP}
|
||||
// 「版本记录」:只读查询面在 API 侧接线;真正的抓取在 worker 侧(未配置来源即未接线)。
|
||||
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
|
||||
if config.VersionHistoryGiteaBaseURL != "" {
|
||||
@@ -193,7 +263,20 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
return fmt.Errorf("快照搬运接线无效: %w", handoffErr)
|
||||
}
|
||||
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
|
||||
ppStateFile := getenv("PP_AUTH_STATE_FILE")
|
||||
if ppStateFile == "" {
|
||||
ppStateFile = "/data/source-auth/pp/settings.json"
|
||||
}
|
||||
ppPython := getenv("PP_AUTH_PYTHON")
|
||||
if ppPython == "" {
|
||||
ppPython = "/usr/bin/python3"
|
||||
}
|
||||
ppScript := getenv("PP_AUTH_CHECK_SCRIPT")
|
||||
if ppScript == "" {
|
||||
ppScript = "/app/scripts/pp_client.py"
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
PPConnection: &ppauth.Manager{Path: ppStateFile, LegacyPath: getenv("PP_LEGACY_CREDENTIALS_FILE"), Probe: ppauth.CommandProbe(ppPython, ppScript)},
|
||||
LibraryHandoffEnabled: handoffConfigured,
|
||||
QAAI: qaopsai.NewFromEnvironment(pool, getenv, config.DatabaseURL),
|
||||
QAWeeklyMail: qawemail.NewStore(pool, qaSettings.TenantKey, getenv("QA_AI_MASTER_KEY_FILE"), nil),
|
||||
@@ -213,7 +296,9 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
RoutingBindings: postgresstore.NewStore(pool),
|
||||
KnowledgeBases: knowledgeBaseLister,
|
||||
ProductionBindings: postgresstore.NewStore(pool),
|
||||
ProductionKnowledgeBases: serviceTargetVerifier,
|
||||
ProductionKnowledgeBases: productionKnowledgeBases,
|
||||
KBBindings: kbBindings,
|
||||
WeKnoraAllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL,
|
||||
ServiceTargetVerifier: serviceTargetVerifier,
|
||||
ProductionReleaseRequestsEnabled: config.ProductionReleaseRequestsEnabled,
|
||||
@@ -223,6 +308,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
ProductionReleaseAuthorizationToken: releaseAuthorizationToken,
|
||||
// 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。
|
||||
DingtalkSources: dingtalkSourceLister{},
|
||||
DWSLogin: dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{}),
|
||||
DingtalkDocuments: dingtalkSourceLister{},
|
||||
BackupSchedule: postgresstore.NewStore(pool),
|
||||
VersionHistory: versionHistoryStore,
|
||||
@@ -260,6 +346,12 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
ScriptDir: config.BackupHostScriptDir,
|
||||
Root: config.BackupHostRoot,
|
||||
}),
|
||||
BackupInventory: backupinventory.New(backupinventory.Config{
|
||||
MetadataPath: config.BackupHostMetadataPath,
|
||||
HostRoot: config.BackupHostReadonlyHostPath,
|
||||
Source: backupInventorySource(config),
|
||||
MaxAge: config.BackupHostMetadataMaxAge,
|
||||
}),
|
||||
Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour},
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
+48
-12
@@ -7,12 +7,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
)
|
||||
|
||||
// newWeKnoraReadinessResolver 把「探测目标」收敛到与业务同一组真源:
|
||||
// 端点来自网页保存的服务配置(endpoint 内部已做 env 兜底),知识库来自
|
||||
// 端点来自网页「知识库映射」保存的连接配置(endpoint 内部已做 env 兜底),知识库来自
|
||||
// 当前持久化绑定(未绑定才用 env 引导值),凭据每次重新读同一份 key 文件。
|
||||
// 任何一项读取失败都必须显式报错——静默退回旧值正是 F13 的成因。
|
||||
func newWeKnoraReadinessResolver(
|
||||
@@ -51,29 +52,64 @@ func newWeKnoraReadinessResolver(
|
||||
// weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据,
|
||||
// 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。
|
||||
type weKnoraLister struct {
|
||||
endpoint func(context.Context) string
|
||||
readKey func() (string, error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) {
|
||||
baseURL := ""
|
||||
if lister.endpoint != nil {
|
||||
baseURL = strings.TrimSpace(lister.endpoint(ctx))
|
||||
if lister.resolve == nil {
|
||||
return nil, fmt.Errorf("WeKnora 端点未配置")
|
||||
}
|
||||
baseURL, apiKey, err := lister.resolve(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
baseURL = strings.TrimSpace(baseURL)
|
||||
if baseURL == "" {
|
||||
return nil, fmt.Errorf("WeKnora 端点未配置")
|
||||
}
|
||||
apiKey, err := lister.readKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if strings.TrimSpace(apiKey) == "" {
|
||||
return nil, fmt.Errorf("WeKnora API Key 未配置")
|
||||
}
|
||||
timeout := lister.timeout
|
||||
if timeout <= 0 || timeout > 10*time.Second {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP})
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP, AllowPrivateHTTP: lister.allowPrivateHTTP})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.ListKnowledgeBases(ctx)
|
||||
}
|
||||
|
||||
// productionKnowledgeBaseLister 列生产端知识库时使用「生产环境」保存的连接
|
||||
// (加密密钥),而不是另一条文件凭据。显式传入的地址必须与已保存连接一致,
|
||||
// 防止把生产密钥发往另一个地址。
|
||||
type productionKnowledgeBaseLister struct {
|
||||
bindings *kbbinding.Store
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (lister *productionKnowledgeBaseLister) ListProductionKnowledgeBases(ctx context.Context, baseURL string) ([]weknora.KnowledgeBase, error) {
|
||||
if lister.bindings == nil {
|
||||
return nil, fmt.Errorf("生产知识库连接存储未接线")
|
||||
}
|
||||
target, err := lister.bindings.Resolve(ctx, kbbinding.EnvProduction)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if explicit := strings.TrimSpace(baseURL); explicit != "" && explicit != target.BaseURL {
|
||||
return nil, fmt.Errorf("生产地址与已保存的连接不一致:请在生产工作区重新保存连接")
|
||||
}
|
||||
timeout := lister.timeout
|
||||
if timeout <= 0 || timeout > 10*time.Second {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: target.BaseURL, APIKey: target.APIKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP, AllowPrivateHTTP: lister.allowPrivateHTTP})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -96,9 +96,8 @@ func TestKnowledgeBaseListerFollowsTheCurrentEndpoint(t *testing.T) {
|
||||
defer second.Close()
|
||||
endpoint := first.URL
|
||||
lister := &weKnoraLister{
|
||||
endpoint: func(context.Context) string { return endpoint },
|
||||
readKey: func() (string, error) { return "key-1", nil },
|
||||
timeout: time.Second,
|
||||
resolve: func(context.Context) (string, string, error) { return endpoint, "key-1", nil },
|
||||
timeout: time.Second,
|
||||
}
|
||||
bases, err := lister.ListKnowledgeBases(context.Background())
|
||||
if err != nil || len(bases) != 1 || bases[0].ID != "kb-a" {
|
||||
|
||||
@@ -163,7 +163,12 @@ func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot release
|
||||
if err != nil {
|
||||
return cleanup(errors.New("create target WeKnora verifier"))
|
||||
}
|
||||
documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier})
|
||||
documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{
|
||||
Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch,
|
||||
Objects: objectImporter, Verifier: verifier,
|
||||
TargetInstanceURL: route.Target.WeKnora.BaseURL,
|
||||
TargetTenantID: route.TenantID,
|
||||
})
|
||||
if err != nil {
|
||||
return cleanup(errors.New("create v0.7.1 document target"))
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
|
||||
VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance",
|
||||
VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"},
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), release)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("release-executor workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -74,12 +74,12 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
|
||||
TestWeKnoraEnabled: true,
|
||||
TestWeKnoraAPIKeyFile: "/nonexistent/api-key",
|
||||
}
|
||||
if _, err := workerHandlers(nil, capture); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
|
||||
if _, err := workerHandlers(nil, capture, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
|
||||
t.Fatalf("capture role must reach the test WeKnora wiring, got %v", err)
|
||||
}
|
||||
capture.TestWeKnoraEnabled = false
|
||||
capture.PPScanEnabled = false
|
||||
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture)
|
||||
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("capture workerHandlers() error = %v", err)
|
||||
}
|
||||
|
||||
+98
-14
@@ -10,6 +10,7 @@ import (
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/libraryagent"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
@@ -172,6 +174,54 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
}
|
||||
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID).
|
||||
WithRestoreDispatchEvidence(config.LibraryTargetJournalRoot)
|
||||
kbBindings := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: config.WeKnoraBindingMasterKeyFile,
|
||||
Timeout: 10 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP,
|
||||
kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
},
|
||||
LegacyBaseURL: func(resolveCtx context.Context, env string) string {
|
||||
settings, err := store.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if env == kbbinding.EnvProduction {
|
||||
if value := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.ProductionWeKnoraBaseURL
|
||||
}
|
||||
if value := strings.TrimSpace(settings.TestWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
LegacyKey: func(env string) (string, error) {
|
||||
path := config.TestWeKnoraAPIKeyFile
|
||||
if env == kbbinding.EnvProduction {
|
||||
path = config.ProductionWeKnoraAPIKeyFile
|
||||
}
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", nil
|
||||
}
|
||||
return weknora.ReadAPIKeyFile(path)
|
||||
},
|
||||
LegacyBinding: func(resolveCtx context.Context, env string) (string, string, error) {
|
||||
if env == kbbinding.EnvProduction {
|
||||
internal, external, _, err := store.LoadProductionKBBindings(resolveCtx)
|
||||
return internal, external, err
|
||||
}
|
||||
internal, external, _, err := store.LoadRoutingKBBindings(resolveCtx)
|
||||
if internal == "" {
|
||||
internal = config.InternalRoutingKnowledgeBaseID
|
||||
}
|
||||
if external == "" {
|
||||
external = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
return internal, external, err
|
||||
},
|
||||
})
|
||||
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
|
||||
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
|
||||
// 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。
|
||||
@@ -210,7 +260,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
} else if repaired > 0 {
|
||||
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
|
||||
}
|
||||
handlers, err := workerHandlers(store, config)
|
||||
handlers, err := workerHandlers(store, config, kbBindings)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -323,7 +373,7 @@ func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersiste
|
||||
return nil
|
||||
}
|
||||
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[string]jobs.Handler, error) {
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store) (map[string]jobs.Handler, error) {
|
||||
handlers := map[string]jobs.Handler{
|
||||
"demo": func(_ context.Context, job jobs.Job) error {
|
||||
log.Printf("completed demo job id=%s", job.ID)
|
||||
@@ -525,24 +575,27 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
return handlers, nil
|
||||
}
|
||||
// 启动只验证凭据“存在”(缺失像以前一样拒绝启动);具体值仍由 resolver 每次调用重读。
|
||||
if _, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); err != nil {
|
||||
return nil, fmt.Errorf("read test WeKnora API key: %w", err)
|
||||
// 启动只验证“有一条可用凭据”:旧部署是文件,新部署可以是加密存储里的连接。
|
||||
// 两者都没有时不再静默启动,仍像以前一样拒绝;具体值由 resolver 每次重读。
|
||||
storageReady := kbBindings != nil && kbBindings.StorageReady()
|
||||
if _, fileErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); fileErr != nil && !storageReady {
|
||||
return nil, fmt.Errorf("read test WeKnora API key: %w", fileErr)
|
||||
}
|
||||
// 与 API 探测共用同一有效目标:网页保存的端点优先、env 只作未配置兜底;
|
||||
// 当前持久化绑定优先、env 兜底;凭据每次调用重读同一 key 文件。
|
||||
// 与 API 探测共用同一有效目标:加密存储里的连接优先、旧部署文件/端点兜底;
|
||||
// 当前持久化绑定优先、env 兜底。
|
||||
remoteResolver := readiness.Resolver{
|
||||
Endpoint: func(resolveCtx context.Context) string {
|
||||
if settings, settingsErr := store.GetActiveUISettings(resolveCtx); settingsErr == nil && strings.TrimSpace(settings.TestWeKnoraBaseURL) != "" {
|
||||
return settings.TestWeKnoraBaseURL
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
LoadBinding: func(resolveCtx context.Context) (string, error) {
|
||||
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
|
||||
return internal, bindingErr
|
||||
},
|
||||
ReadKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
|
||||
if kbBindings == nil {
|
||||
key, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
|
||||
return config.TestWeKnoraBaseURL, key, err
|
||||
}
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
},
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
}
|
||||
client := &weknoraaccess.Client{Resolver: remoteResolver, Timeout: config.TestWeKnoraHTTPTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}
|
||||
@@ -561,6 +614,11 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
Client: client,
|
||||
PollDelay: config.TestWeKnoraPollInitial,
|
||||
StallAfter: config.TestWeKnoraStalledAfter,
|
||||
// 页面保存的停滞阈值在这里生效;每 60 秒重读一次活动配置,
|
||||
// 读失败保留上一次值,再失败才回落到启动参数。
|
||||
StallAfterSource: func() time.Duration {
|
||||
return activeStalledAfter(context.Background(), store, config.TestWeKnoraStalledAfter)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create test poll handler: %w", err)
|
||||
@@ -592,3 +650,29 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
handlers["test.remove"] = remove.Handle
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
// activeStalledAfter 读取活动 UI 配置里的解析停滞阈值(带 60 秒缓存)。
|
||||
// 页面保存后无需重启 worker 即可生效;“保存即生效”不是文案,而是这里的读取。
|
||||
var stalledAfterCache struct {
|
||||
mu sync.Mutex
|
||||
value time.Duration
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
func activeStalledAfter(ctx context.Context, store *postgresstore.Store, fallback time.Duration) time.Duration {
|
||||
stalledAfterCache.mu.Lock()
|
||||
defer stalledAfterCache.mu.Unlock()
|
||||
if time.Since(stalledAfterCache.fetchedAt) < time.Minute && stalledAfterCache.value > 0 {
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
settings, err := store.GetActiveUISettings(ctx)
|
||||
if err != nil || settings.StalledAfterSeconds <= 0 {
|
||||
if stalledAfterCache.value > 0 {
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
stalledAfterCache.value = time.Duration(settings.StalledAfterSeconds) * time.Second
|
||||
stalledAfterCache.fetchedAt = time.Now()
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestRunRequiresDatabaseURL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWorkerHandlersExcludeReleaseAndTestJobsByDefault(t *testing.T) {
|
||||
handlers, err := workerHandlers(nil, appconfig.Config{})
|
||||
handlers, err := workerHandlers(nil, appconfig.Config{}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
|
||||
PPScanLedgerPath: filepath.Join(root, "state.jsonl"),
|
||||
PPScanManifestPath: filepath.Join(root, "manifest.json"),
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
|
||||
|
||||
func TestWorkerHandlersRequireAPIKeyWhenTestWeKnoraEnabled(t *testing.T) {
|
||||
config := appconfig.Config{TestWeKnoraEnabled: true, TestWeKnoraAPIKeyFile: "/nonexistent/api-key"}
|
||||
_, err := workerHandlers(nil, config)
|
||||
_, err := workerHandlers(nil, config, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "read test WeKnora API key") {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func TestWorkerHandlersRegisterTestJobsForExplicitDockerHTTP(t *testing.T) {
|
||||
TestWeKnoraMaxUploadBytes: 1024,
|
||||
TestAcceptancePolicyVersion: "structural-v1",
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -16,9 +16,17 @@ services:
|
||||
BACKUP_HOST_TARGET: weknora-test
|
||||
BACKUP_HOST_SCRIPT_DIR: /opt/weknora-test
|
||||
BACKUP_HOST_ROOT: /srv/kb-backups
|
||||
# 只读盘点(批次/子库路径/实测容量)与上面的 SSH 计划读回独立。
|
||||
# 候选 28189 部署时按 docs/STORAGE_BACKUP_READONLY_API.md 打开:
|
||||
# 宿主采集器原子写 metadata.json,API 只读挂载输出目录(不挂备份目录):
|
||||
# BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
|
||||
# BACKUP_HOST_METADATA_MAX_AGE: 15m
|
||||
# BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
|
||||
# BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
|
||||
volumes:
|
||||
- ./secrets/release-sim:/run/release-secrets:ro
|
||||
- ./secrets/backup-host:/run/backup-host:ro
|
||||
# - /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
|
||||
|
||||
release-worker:
|
||||
environment:
|
||||
|
||||
@@ -57,6 +57,12 @@ services:
|
||||
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
|
||||
# Mount this independent master-key file read-only using the deployment overlay.
|
||||
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
|
||||
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
|
||||
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
||||
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
|
||||
# 链路本地,公网 http 仍被拒绝)。客户端、探活与连接页共用同一判定。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
|
||||
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
||||
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
|
||||
# P10 readiness probe reads the routing KB with the same scoped key.
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# 知识治理候选和批次验收
|
||||
|
||||
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
|
||||
## 发起候选
|
||||
|
||||
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
|
||||
|
||||
````markdown
|
||||
```kg-release-v1
|
||||
{"task":"<发布任务 UUID>","base":"<当前主站 SHA>","sha":"<候选 SHA>","items":[{"task":"<业务任务 UUID>","pr":123}],"extra":[]}
|
||||
```
|
||||
````
|
||||
|
||||
2. Agent 执行 `candidate_coordinator.py prepare <发布任务 UUID>`。Gitea 核对候选 SHA 的 CI、每个 PR 的落地提交和完整主干范围。需准备候选时,独立 Runner 通过回环入口调度本机执行器。执行器复查发布负责人评论、Gitea 作业证明和当前主站 SHA 后,从准确提交构建镜像并封存。
|
||||
3. 执行器在独立验收数据库上启动同份归档,核验 API 提交、三个运行镜像、迁移账本、Web 入口及归档摘要。在发布任务和业务任务回填候选版本与地址。对「待测试」业务任务,由执行器转「测试中」。本地候选地址绑定回环,验收 Agent 应和执行器同机,或使用经工程侧验证的私有转发。
|
||||
4. `candidate_coordinator.py status <发布任务 UUID>` 读取候选回执或对应 Gitea 运行链接。遇到调度结果不明,先从 Gitea 读回运行再决定恢复路径。
|
||||
|
||||
## 登记验收
|
||||
|
||||
业务验收报告分别放在原业务任务,批次共享功能回归报告放在发布任务。保持测试角色原有输出,使用获授权的验收人或测试 Agent 在对应任务评论追加以下结构化结论。报告应保留用例明细和原始证据链接。该段的 `required` 是本轮登记的必测用例数。
|
||||
|
||||
````markdown
|
||||
```kg-qa-v1
|
||||
{"sha":"<完整提交 SHA>","bundle":"<归档清单 SHA256>","url":"<候选地址>","verdict":"passed","required":3,"passed":3,"failed":0,"blocked":0}
|
||||
```
|
||||
````
|
||||
|
||||
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
|
||||
|
||||
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
|
||||
## 执行器配置
|
||||
|
||||
- 版本管理机使用 Python 3.11 及以上、Docker Compose、HiFox CLI 和已有 Gitea 凭据。候选执行器通过 `candidate_worker.py <仓库工作树> <访问文件>` 绑定 `127.0.0.1:38984`,仓库工作树允许读取 `origin/main`。执行器通过现有 Gitea 凭据读取作业与日志。运行账户需能以 `weknora-test` 执行只读版本检查。
|
||||
- 为候选执行器单独配置 `kg-candidate` Runner。作业使用同机回环网络,通过仓库 Secrets 的 `KG_CANDIDATE_ACCESS` 访问执行器。访问文件由执行器用户持有,内容为独立 64 位十六进制随机凭据。候选作业使用的容器须无宿主 Docker socket 和生产密钥挂载。
|
||||
- 业务验收使用 `~/.config/knowledge-governance/{qa.json,qa.pgpass,rds-ca.pem}`。复用 `qa_env.py` 的专用 `kg_qa_` RDS 库和角色校验。`qa.pgpass` 可包含同一端点的应用库和集成测试库条目,候选只读取 `qa.json` 指定的库和角色。验收使用专用账号与测试数据。需要验证外部系统的用例须先准备各自的隔离资源。
|
||||
- 候选执行器采用单验收槽。新批次启动前由运维确认前一批验收结束,按上一批 `ready.json` 中的容器身份停止其 Compose 项目,归档原有配置和回执后释放槽位。保留已验收的归档及审批记录。
|
||||
|
||||
## 演练和当前环境
|
||||
|
||||
`prepare-candidate.yml` 的 `verify` 模式校验 Gitea 范围与 CI。可在评审分支验证。`prepare` 模式只接受 `main` 的调度。`candidate_release.py build` 和 `candidate_runtime.py <bundle>` 可在隔离开发机演练打包及冒烟。后者使用临时 Docker 数据库,退出后停止演练容器。
|
||||
|
||||
候选提交必须位于 `main` 的第一父链,并包含主站实际运行的提交。若现场版本从独立分支发布,先通过保留提交历史的合并将现场基线纳入 `main`。现场提交本身可以位于第二父链。候选计划须覆盖 `git rev-list --first-parent <现场 SHA>..<候选 SHA>` 的每一项,包括基线合并提交和已确认随批发布的工程提交。主站数据库仅用于正式应用,业务候选使用专用 QA 库。
|
||||
@@ -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、执行命令、退出码,以及失败用例的日志或浏览器截图。
|
||||
@@ -0,0 +1,44 @@
|
||||
# DWS 登录授权
|
||||
|
||||
管理员入口:系统设置 → 数据源配置 → 钉钉账号(DWS)。
|
||||
|
||||
- 未登录时点击“登录授权”,在弹窗中打开钉钉官方授权页,由本人选择账号与组织并确认。
|
||||
- 平台等待设备授权完成。成功后自动刷新账号、组织和续期凭证有效期,并检查知识库、钉盘目录访问。
|
||||
- “重新授权”采用同一流程;授权中可取消,失败或过期后可重新发起。
|
||||
- “检查连接”只列目录与读取登录元数据,不登记来源、不扫描已有来源、不发起入库或生产发布。
|
||||
- 登录成功与目录可用分开显示;部分范围无权限时保留其他已成功范围,并展示原因。
|
||||
|
||||
## 服务端接线
|
||||
|
||||
API 直接管理 `dws auth login --device --no-browser --format json` 子进程,不复用旧浏览器扫码侧车。
|
||||
CLI 负责官方 OAuth 协议、组织 CLI 权限校验及凭据加密持久化。平台只解析官方设备授权链接、用户授权码、有效期与状态;原始输出、access token、refresh token不进入接口或日志。
|
||||
|
||||
API 与 worker 必须使用相同 UID,以及同一组可写挂载:
|
||||
|
||||
| 配置 | 用途 |
|
||||
|---|---|
|
||||
| `DWS_BIN` | 固定版本的 DWS 程序 |
|
||||
| `DWS_CONFIG_DIR` | 共享的 DWS 状态目录 |
|
||||
| `DWS_HOME` | 共享 home,包含 `.local/share/dws-cli` 文件型密钥存储 |
|
||||
| `DWS_DISABLE_KEYCHAIN=1` | 容器使用文件型凭据存储 |
|
||||
|
||||
子进程 HOME 由 DWS_HOME 指定,只透传所需环境。禁止把认证状态复制成多份,避免轮换令牌互相失效。
|
||||
|
||||
## 接口与生命周期
|
||||
|
||||
- `POST /api/v1/dws-login`:立即返回 starting,后台生成设备授权;同一浏览器管理员会话重复请求复用在途授权。
|
||||
- `GET /api/v1/dws-login/{id}`:读取本人发起的授权。
|
||||
- `DELETE /api/v1/dws-login/{id}`:取消并等待旧 CLI 退出,清除授权链接与用户码。
|
||||
- 上述接口均为管理员专用;授权绑定管理员及其登录会话,另一会话无法读取或取消。
|
||||
- 创建和取消要求同源操作意图;响应禁止缓存。仅允许 `https://login.dingtalk.com/oauth2/device/verify.htm` 官方链接。
|
||||
- 每次只运行一个授权,防止覆盖共享状态。服务重启会结束在途授权;页面提示重新发起。
|
||||
- CLI 成功退出后必须再次读到有效本地凭据才显示登录成功;真实目录访问另行检查。
|
||||
|
||||
## 添加来源
|
||||
|
||||
添加来源向导与账号卡共用官方 DWS 授权;列举、校验、登记使用同一身份。来源登记不再自动回落旧扫码侧车。保存中授权失效时保留已成功项并恢复剩余项;换账号或组织后需重新确认范围。详细交互、认证审计与 PP 接线见 [数据源认证配置](SOURCE_AUTH_CONFIGURATION.md)。
|
||||
|
||||
## 验证边界
|
||||
|
||||
自动回归覆盖授权生成、成功后状态更新、目录访问失败与部分可用、取消与进程退出、过期、重试、跨管理员/会话隔离、同源限制、官方链接校验及元数据脱敏。
|
||||
真实本人授权需要管理员在钉钉官方页面确认;自动测试与生成真实授权链接不替代本人授权,也不证明其公司目录权限。
|
||||
@@ -3,14 +3,107 @@
|
||||
按"实际干活顺序"排列的**现在的**操作流程。标注:**【新】**本期新增(含本次会话与 `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 身份目录 | 登录后读回预期空间,选一个有权限的目录校验。登记来源、扫描完成和文件取件分别核验。[授权手册](DWS_LOGIN.md) |
|
||||
| AList,取工业或教育资料 | 按来源登记服务根地址和允许的目录。普通 worker 读取专用令牌文件。目录接口 `POST /api/fs/list` 使用 `X-Gateway-Token` | 在来源页扫描已知根目录,对照一个子目录和一份文件。下载遵循来源签名链接,凭据和签名 URL 仅留在受控运行环境。[目录与取件](SOURCE_CATALOG_LIVE_ROUTING_ACCEPTANCE.md) |
|
||||
| PP 资料门户 | 在数据源配置填写 HTTPS 根地址和来源账号,点「测试连接」后「保存并校验」。API 和 worker 共享 `PP_AUTH_STATE_FILE` 所在目录 | 真实登录并读取一条目录记录,刷新后核对生效配置。超时或限流时查看待验证状态。[认证、保存与扫描契约](SOURCE_AUTH_CONFIGURATION.md) |
|
||||
| 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 容器重新验证上游可达性。
|
||||
|
||||
**直连反代(18093)与隧道(18092)二选一。** 若生产机已按前置要求提供
|
||||
`172.29.151.11:18093`(只放行测试机),页面就填 `http://172.29.151.11:18093`,并在
|
||||
部署侧设置 `WEKNORA_ALLOW_PRIVATE_HTTP=true` —— 它只放行 RFC1918/回环/链路本地
|
||||
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
|
||||
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
|
||||
|
||||
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
|
||||
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
|
||||
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
|
||||
里的旧 Key。内外库留空表示取消该方向绑定:测试侧回退到部署默认库,生产侧回退到
|
||||
「同 ID 语义」,提示里会写明。
|
||||
|
||||
在**测试治理机**上检验已有通道。`/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 分钟有效期。采集命令和挂载契约见 [备份只读接口](STORAGE_BACKUP_READONLY_API.md)。
|
||||
|
||||
| 症状 | 第一步怎么查 | 如何判定 |
|
||||
|---|---|---|
|
||||
| 浏览器连接被拒 | 对照本机 `28189` 监听和测试机 `/health` | 远端正常、本机无监听时恢复本机 SSH 转发 |
|
||||
| 页面打开,某个 API 404 或 502 | 查浏览器请求路径、Nginx 生效上游及对应 API 版本 | 404 先查路由是否存在,502 先查上游是否可达。AI 页单独核对 `18098` |
|
||||
| 能探活,列库仍灰或返回 401 | 核对选中环境、凭据配置状态、容器运行 UID 与凭据文件可读性 | 用该环境的专用身份实际列库。检查过程只记录状态码和可读性 |
|
||||
| 历史可读,计划或配额显示未知 | 核对快照年龄、执行主机连接与配额字段 | 盘点、SSH 计划、配额分别验证。只有主机实际读回 cron 才能报告下一次执行时间 |
|
||||
|
||||
---
|
||||
|
||||
## 0. 开工前:环境与凭据自检
|
||||
| 项 | 怎么做 | 成功标志 |
|
||||
|---|---|---|
|
||||
| 测试/生产 WeKnora | 系统设置 → 服务配置 | 生产端"已启用 · 可提交生产请求";测试端探测正常 |
|
||||
| 测试/生产 WeKnora | 系统设置 → 知识库绑定(选择测试 090 / 生产 090) | 生产端"已启用 · 可提交生产请求";测试端探测正常 |
|
||||
| 钉钉取件凭据 **【新】** | 容器内 `HOME=/data/home dws auth status --readonly -f json` | `authenticated:true`、`refresh_token_valid:true`(**必须带 `HOME=/data/home`,否则误报未登录**) |
|
||||
| 备份主机接线 | 系统设置 → 存储与备份 | "目标主机 weknora-test · 已连接" |
|
||||
|
||||
@@ -80,9 +173,8 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
|
||||
|
||||
| 分区 | 谁 | 现在要管什么 |
|
||||
|---|---|---|
|
||||
| 服务配置 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) |
|
||||
| 测试知识库绑定 | 管理员 | 标注往哪个测试库路由(对内 ≠ 对外) |
|
||||
| 生产知识库绑定 | 管理员 | 源库 → 目标库映射(发布写哪个生产库) |
|
||||
| 知识库绑定(测试 090 / 生产 090) | 管理员 | 每个环境:服务地址 + API Key(服务器真实列库)→ 选对外/对内库 → 一次保存;密钥不回显,换地址须重录 |
|
||||
| 绑定诊断(折叠) | 管理员 | 探活、封存源对照、整库发布目标(只读,由部署配置决定)与旧文档级目标 |
|
||||
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
|
||||
| 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) |
|
||||
| 成员与角色 | 管理员 | 成员与 viewer/engineer/admin |
|
||||
|
||||
@@ -91,13 +91,17 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
|
||||
|
||||
- 页面:系统设置 → 存储与备份(管理员可改;保存 = 写入库并立刻下发;另有"重新下发当前设置"与"立即备份一次")。
|
||||
- 接口:`GET /api/v1/backup-schedule`(不探测主机,首屏快)、`GET …/host`(SSH 读回主机 cron 与最近一次结果)、
|
||||
`GET …/inventory`(宿主采集器快照读全部批次/子库路径/实测容量,见 `docs/STORAGE_BACKUP_READONLY_API.md`)、
|
||||
`PUT`(校验时间 `HH:MM` 与 1~365 天 / 0~24 月,非法值直接 400 且不落库不下发)、`POST …/apply`、`POST …/run`。
|
||||
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
|
||||
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
|
||||
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
|
||||
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
|
||||
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
|
||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。
|
||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
|
||||
`scripts/collect_backup_metadata.py` 原子写 `metadata.json`,API 用
|
||||
`BACKUP_HOST_METADATA_PATH / BACKUP_HOST_READONLY_HOST_PATH` 只读快照,见
|
||||
`docs/STORAGE_BACKUP_READONLY_API.md`。
|
||||
- 主机状态读取只认**有 `MANIFEST.json` 的完整目录**:被中断的运行会被脚本改名 `*.incomplete`,
|
||||
所以"最近一次备份"永远不会显示一份半成品。
|
||||
- 依赖两个运行前提:运行镜像里有 `openssh-client`,且容器用户的 uid 在 `/etc/passwd` 有名字
|
||||
|
||||
@@ -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. HiFox 触发器在派发 Gitea 前自动通过执行机的 `weknora-test` SSH 通道交接四个文件,并用主站控制器校验。人工 Actions 入口仍须由运维提前将四个文件放入云主站的 `/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,cd_bundle_handoff.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
|
||||
- 常规 push CI 负责验证和静态预览。这个 workflow 的唯一事件是 `workflow_dispatch`。`make verify` 的 `contracts` 子项运行 CD 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
|
||||
@@ -3,7 +3,7 @@
|
||||
> 这份文档是**破坏性变化与数据迁移步骤的落脚点**:`CHANGELOG.md` 里以 `**破坏性**` 开头的条目
|
||||
> **必须**链接到本文(或本文的某个小节)。发布记录本身仍在 `CHANGELOG.md` —— 本文不维护第二份变更列表。
|
||||
>
|
||||
> 本仓 CI **只做 CI**:不打 tag、不发 Release、不部署。发布与部署都是**独立的人工审批动作**。
|
||||
> 常规 CI 负责检查、构建与静态预览。版本 tag 与 Release 由人批准后执行。主站应用部署使用独立的[人工确认 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
|
||||
## 一、正式发布(由人批准后执行)
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# 数据源认证配置
|
||||
|
||||
管理员入口:系统设置 → 数据源配置。PP 连接位于钉钉账号卡旁;添加来源向导使用同一组账号与配置。
|
||||
|
||||
## PP 连接
|
||||
|
||||
- API 地址填写 HTTPS 根地址;后台沿用 `/admin/login/token`、`/potal/file/back/page` 接口路径。`potal` 是上游真实路径,不能改写。
|
||||
- 账号允许修改。密码只显示已配置/未配置;点击“更新密码”录入新值。省略或留空保留既有密码,不回显原值。
|
||||
- “测试连接”使用当前表单,真实登录并读取一条目录记录;合法空目录也可通过。它不保存配置、不登记来源、不启动扫描。
|
||||
- “保存并校验”在后端重新检查本次提交。通过后切换生效;明确的认证拒绝、权限拒绝、接口不兼容阻止生效。
|
||||
- 超时、限流或服务临时故障可保存为待验证修改;缺少凭据可保存未完成配置。两者都不会替换当前生效配置;需要再次保存并校验,通过后才切换。
|
||||
- 草稿测试结果与当前生效配置状态分开;每次修改字段会使原草稿测试结果作废。检查失败时保留上次观测及时间,不能把网络失败当成退出登录。
|
||||
- 后续目录扫描和远程取件读取同一生效配置;验证过的本地文件仍按既有内容校验逻辑复用。配置保存不恢复暂停的计划、不触发入库或发布。
|
||||
|
||||
## PP 服务端接线
|
||||
|
||||
| 参数 | 默认与用途 |
|
||||
|---|---|
|
||||
| `PP_AUTH_STATE_FILE` | `/data/source-auth/pp/settings.json`;API 和 worker 必须读同一份原子配置文件 |
|
||||
| `PP_AUTH_PYTHON` | `/usr/bin/python3`;API 连接检查使用的解释器 |
|
||||
| `PP_AUTH_CHECK_SCRIPT` | `/app/scripts/pp_client.py`;与扫描、取件共享的只读协议实现 |
|
||||
| `PP_LEGACY_CREDENTIALS_FILE` | 可选,只用于首次迁移;有效状态文件存在后不再回落旧文件 |
|
||||
|
||||
配置目录及状态文件分别使用 0700 和 0600。API/worker 使用相同 UID,将宿主凭据目录挂载为共享目录,不能绑定单个文件:单文件 bind mount 会在原子 rename 后继续指向旧 inode。迁移时从目标机既有凭据文件直接读取,禁止通过聊天、命令行参数或仓库传递密码。
|
||||
|
||||
状态文件持有生效配置、待验证修改、最近检查及认证审计,包含密码,因此必须按密钥文件保护,不能进普通配置备份、版本记录或日志。更新使用跨进程文件锁、临时文件、fsync 和原子 rename。配置修订采用乐观并发控制;旧请求不能覆盖新修订。worker 的迟到检查只能更新自身生效配置 ID 对应的观测。
|
||||
|
||||
PP 检查子进程只从 stdin 接收本次凭据,stdout 只返回白名单检查结论。GET 接口仅返回配置元数据和是否存在密码;密码输入字段只可写。
|
||||
|
||||
| 接口 | 用途 |
|
||||
|---|---|
|
||||
| `GET /api/v1/pp-connection` | 管理员读取安全元数据、待验证修改与检查状态 |
|
||||
| `POST /api/v1/pp-connection/test` | 测试当前草稿,不激活 |
|
||||
| `PUT /api/v1/pp-connection` | 校验并保存;携带当前 `revision` |
|
||||
|
||||
使用已保存的待验证密码继续校验时携带 `pending_id`,避免空密码误用旧生效密码。修改请求验证管理员、同源操作意图和输入大小;响应禁止缓存。
|
||||
|
||||
## 钉钉添加向导
|
||||
|
||||
保留 类型 → 授权 → 范围 → 校验 → 保存 五步;授权步骤复用钉钉账号卡的官方 DWS 设备授权流程。
|
||||
|
||||
- 可见范围、校验和登记都使用共享 DWS 身份;登记不再自动回落旧扫码侧车。DWS 无法定位的历史空间返回明确原因。
|
||||
- `POST /api/v1/dingtalk-spaces/validate` 真实读取并检查所选空间。失败、权限不足、部分范围不完整与合法空列表分别展示。
|
||||
- 已接入空间按稳定空间身份标记,历史连接也从其存储的空间标识识别,不靠名称去重。
|
||||
- 保存中授权失效:保留已成功项及待处理项,在向导内重新授权;同账号恢复后继续剩余项,复用操作标识,首次扫描按连接身份去重。
|
||||
- 取消或失败后保留选择并停止自动提交;再次恢复失败不循环弹授权。
|
||||
- 授权后换账号/组织:重新加载范围并清除旧选择,要求重新确认。客户端提交身份指纹,后端在列举前后确认身份,变化时拒绝登记。
|
||||
- 只有已点击保存的操作才会在重新授权后继续登记;账号登录、刷新和连接检查本身不创建来源或扫描任务。
|
||||
- 登记成功和首次扫描入队分别反馈,不能用登记成功冒充扫描已运行。
|
||||
|
||||
其他历史入口若仍调用旧扫码侧车,保留其原行为;本功能不删除整个侧车服务。
|
||||
|
||||
## 审计与验证
|
||||
|
||||
PP 配置/密码更新、连接检查及 DWS 授权结果,复用现有数据源操作审计页面。凭据事件与配置在同一文件内原子提交,并与数据库原有事件按时间合并分页;不把密码写入 SQL。DWS 终态审计按授权 ID 与状态去重,轮询不刷记录。
|
||||
|
||||
回归覆盖真实协议请求、空目录、认证拒绝、权限与限流、密码保留/替换、待验证密码重校验、并发修订冲突、响应脱敏、同源及角色限制、无意外任务、审计分页、DWS 部分成功恢复与换账号保护。协议与消费者测试使用隔离的本机 HTTP 服务;运行环境可用性需另行通过真实页面检查,不能用这些用例替代。
|
||||
@@ -0,0 +1,228 @@
|
||||
# 存储与备份:宿主元数据采集器、只读接口与 28189 接线
|
||||
|
||||
「备份记录 / 整盘占用」不遍历备份目录。备份目录通常是 `root:root 0700`,API 容器
|
||||
用户 `uid 1000` 进不去;容器里遍历只会得到 permission denied 的部分字节。真实闭环是:
|
||||
|
||||
1. 备份主机上由**有读权限的宿主进程**运行 `scripts/collect_backup_metadata.py` 单次采集;
|
||||
只做 `stat`/`du` 元数据和读 `MANIFEST.json`,不读数据库内容文件。
|
||||
2. 采集器用同目录临时文件 + `fsync` + `os.replace` **原子写出** `metadata.json`。
|
||||
3. API 只读挂载这个 JSON,校验 schema、批次/子库路径、主机根、时效、完整性。
|
||||
4. 快照陈旧/缺失/不完整时,批次字节为 `null`,页面显示未知,不画容量图、不做可写预测。
|
||||
|
||||
主机 cron 计划读回仍是原来的 SSH 通道(`/host`),与快照完全独立;API 不借用 SSH
|
||||
读文件,也不获得备份目录的容器权限。
|
||||
|
||||
## 1. 采集器(宿主运行)
|
||||
|
||||
脚本:`scripts/collect_backup_metadata.py`(Python 3 标准库,无第三方依赖)
|
||||
|
||||
```sh
|
||||
python3 collect_backup_metadata.py \
|
||||
--root /srv/kb-backups/rds-logical \
|
||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||
--source weknora-test:/srv/kb-backups/rds-logical
|
||||
```
|
||||
|
||||
- 退出码:`0` 完整;`2` 已写快照但采集不完整/有错误;`1` 连快照都没写成。
|
||||
- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
|
||||
**不打开任何 `.dat/.gz` 数据文件**。
|
||||
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
|
||||
- 口径与 `du -sB1` 对齐:目录自身块计入;遍历整棵子树而非只求和文件;
|
||||
常规文件硬链接按 `(st_dev, st_ino)` 只算一次;**每个子库与整批各自独立测量**,
|
||||
所以单库字节与该子库自己的 `du` 一致、整批与整批 `du` 一致(不会把整批去重结果
|
||||
摊回单库)。
|
||||
- `MANIFEST.json` 只接受批次目录内的常规非符号链接文件;`lstat` + `O_NOFOLLOW`
|
||||
打开,符号链接/非普通文件一律 `invalid`,不会被跟随到别处。
|
||||
- 权限失败会写入 `batch.errors` 并把 `actual_bytes/apparent_bytes/file_count` 置 `null`;
|
||||
绝不把已数到的部分字节当占盘。
|
||||
|
||||
建议由宿主定时器每 5 分钟跑一次(root 或备份目录所有者;不改任何备份权限):
|
||||
|
||||
```cron
|
||||
*/5 * * * * /usr/bin/python3 /opt/knowledge-governance/collect_backup_metadata.py \
|
||||
--root /srv/kb-backups/rds-logical \
|
||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||
--source weknora-test:/srv/kb-backups/rds-logical \
|
||||
>> /var/log/knowledge-governance-backup-metadata.log 2>&1
|
||||
```
|
||||
|
||||
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
|
||||
|
||||
### 快照 schema(version 1)
|
||||
|
||||
关键字段:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `schema_version` | `1`;API 不认识就整块拒绝 |
|
||||
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
|
||||
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
|
||||
| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
|
||||
| `complete` | 全局完整;权限失败/截断/有错误时为 false |
|
||||
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
|
||||
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
|
||||
| `batches[].actual_bytes` | `st_blocks×512` 实际分配,仅完整批有值 |
|
||||
| `batches[].databases[].path` | 子库完整宿主路径,必须等于 `<batch>/<name>.dir` |
|
||||
| `batches[].manifest_state` | `ok` / `missing` / `invalid`(清单是元数据,不影响权限统计) |
|
||||
|
||||
## 2. 接口契约
|
||||
|
||||
`GET /api/v1/backup-schedule/inventory`(读者角色可看;不写任何东西)
|
||||
|
||||
始终 200 + `data`;未接线/快照缺失/陈旧/不完整/路径不一致都写在字段里。
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"wired": true,
|
||||
"metadata": {
|
||||
"configured": true, "present": true, "valid": true,
|
||||
"fresh": true, "complete": true,
|
||||
"path": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"collected_at": "2026-11-20T01:00:00Z",
|
||||
"age_seconds": 10, "max_age_seconds": 900,
|
||||
"schema_version": 1, "generation": "20261120T010000Z-abc123",
|
||||
"host": "weknora-test", "collector_version": "backup-metadata/1",
|
||||
"error": ""
|
||||
},
|
||||
"root": "/srv/kb-backups/rds-logical",
|
||||
"host_root": "/srv/kb-backups/rds-logical",
|
||||
"source": "weknora-test:/srv/kb-backups/rds-logical",
|
||||
"measurement": "host_collector",
|
||||
"mount": {
|
||||
"mount_verified": true, "read_only": false,
|
||||
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
|
||||
"evidence": "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录"
|
||||
},
|
||||
"capacity": {
|
||||
"measured": true, "total_bytes": 1000, "free_bytes": 400,
|
||||
"available_bytes": 350, "used_bytes": 600
|
||||
},
|
||||
"batches": [{
|
||||
"stamp": "20261118T193001Z",
|
||||
"path": "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
"host_path": "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
"manifest_state": "ok",
|
||||
"actual_bytes": 4096, "apparent_bytes": 300, "file_count": 3,
|
||||
"sizes_complete": true,
|
||||
"databases": [{
|
||||
"name": "weknora_v090prod",
|
||||
"path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
"host_path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
"present": true, "failed": false, "in_manifest": true,
|
||||
"actual_bytes": 4096, "apparent_bytes": 250, "file_count": 2
|
||||
}]
|
||||
}],
|
||||
"totals": {
|
||||
"batch_count": 8, "database_count": 0,
|
||||
"actual_bytes": 12000000000, "apparent_bytes": 11141651752,
|
||||
"latest_stamp": "20261118T193001Z", "latest_actual_bytes": 1500000000,
|
||||
"complete": true
|
||||
},
|
||||
"incomplete_count": 0, "skipped": [], "truncated": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 示例中的容量/字节只说明字段形状,**不是现场读数**;候选现场已核实的事实只有:
|
||||
> 8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。单库 `696320` 是现场核对值,
|
||||
> 代码与测试都不写死。
|
||||
|
||||
### 语义与页面行为
|
||||
|
||||
| 条件 | API | 页面 |
|
||||
| --- | --- | --- |
|
||||
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
|
||||
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
|
||||
| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
|
||||
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有 `*_bytes=null` | 列出路径与清单状态;占盘/容量“未知”,不画色带 |
|
||||
| 完整且新鲜 | 批次/子库字节与容量按快照 | 色带、批次、子库路径复制可用 |
|
||||
| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
|
||||
|
||||
API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
|
||||
`<batch>/<name>.dir`;重复、分隔符、`..`、`.incomplete` 一律拒绝。
|
||||
|
||||
## 3. 28189 候选 API 的最小接线
|
||||
|
||||
API 只挂**采集器输出目录**,不挂备份目录:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
api:
|
||||
environment:
|
||||
BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
|
||||
BACKUP_HOST_METADATA_MAX_AGE: 15m
|
||||
BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
|
||||
BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
|
||||
volumes:
|
||||
- /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
|
||||
```
|
||||
|
||||
- `BACKUP_HOST_METADATA_PATH` 与 `BACKUP_HOST_READONLY_HOST_PATH` 必填;`SOURCE` 可省略
|
||||
(用 target + host path 拼)。缺任一拒绝启动,避免“看起来接线”或复制猜的路径。
|
||||
- 只挂元数据目录,`uid 1000` 只需要读 `metadata.json`,**不需要**进入 root:root 0700 的备份目录。
|
||||
- 采集器由宿主 root/备份所有者运行;不新增 API SSH 权限,不改备份目录权限。
|
||||
- 主机 cron 计划仍走 `BACKUP_HOST_SSH_CONFIG/TARGET/SCRIPT_DIR`;与快照独立。
|
||||
|
||||
### 部署后核验
|
||||
|
||||
宿主:
|
||||
|
||||
```sh
|
||||
ls -l /var/lib/knowledge-governance/backup-metadata/metadata.json
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d=json.load(open('/var/lib/knowledge-governance/backup-metadata/metadata.json'))
|
||||
print(d['schema_version'], d['collected_at'], d['complete'], d['root'], len(d['batches']))
|
||||
print(d['batches'][0]['stamp'], [x['name'] for x in d['batches'][0]['databases']][:5])
|
||||
PY
|
||||
```
|
||||
|
||||
API 容器:
|
||||
|
||||
```sh
|
||||
cat /var/lib/knowledge-governance/backup-host/metadata.json >/dev/null && echo readable
|
||||
curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
|
||||
```
|
||||
|
||||
字段核对(以现场为准,示例值不写死):
|
||||
|
||||
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看占盘与容量。
|
||||
- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
|
||||
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
|
||||
`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
|
||||
- `capacity.measured=true` 且与宿主 `df -B1 /srv/kb-backups` 一致。
|
||||
- 若 `complete=false`:先看 `metadata.error` 里的 permission/遍历错误;**不要**用
|
||||
`latest_actual_bytes` 或部分 `databases[].actual_bytes` 做容量判断(它们应为 null)。
|
||||
|
||||
## 4. 与主机计划读回的关系
|
||||
|
||||
- `/host`:SSH 读 cron/脚本/计划 + MANIFEST 最近一次摘要。
|
||||
- `/inventory`:宿主快照读全部批次、子库路径、实际占盘、容量。
|
||||
|
||||
前端分别加载:快照不可用时计划区仍可显示;SSH 连不上时历史区仍可用快照。历史与子库
|
||||
路径以快照为准,SSH 的“最近一次”只作历史参考。
|
||||
|
||||
## 5. 现有写路径(本次未改)
|
||||
|
||||
| 路径 | 写什么 | 权限 |
|
||||
| --- | --- | --- |
|
||||
| `PUT /api/v1/backup-schedule` | 计划写库;`apply=true` 时 SSH 下发 cron | 管理员 |
|
||||
| `POST /api/v1/backup-schedule/apply` | SSH 重写主机 cron/计划参数 | 管理员 |
|
||||
| `POST /api/v1/backup-schedule/run` | 在主机执行 `logical-backup.sh`(写备份目录/RDS dump) | 管理员 |
|
||||
| `BackupScheduleStore.SaveBackupSchedule` | 计划落库 | 服务内部 |
|
||||
| `MarkBackupScheduleApplied` | 下发摘要回写 | 服务内部 |
|
||||
| `backuphost.Apply / RunNow` | 远端脚本执行 | 服务内部 |
|
||||
|
||||
本接口与采集器没有写备份目录、删批次、改 cron 的代码路径。
|
||||
|
||||
## 6. 还需单独确认的后端写能力
|
||||
|
||||
1. 配额 / 磁盘预留的持久化与执行(当前无字段)。
|
||||
2. 旧批次保留/删除与删除前审计、可恢复窗口。
|
||||
3. 备份目录迁移/切换。
|
||||
4. 单库备份/单库恢复(现有 run 是整批)。
|
||||
5. 恢复验证执行(`pg_restore` 演练、校验和、结果留档)。
|
||||
6. MANIFEST 修复/重建。
|
||||
7. 采集器安装/权限变更自动化(属部署与主机权限,必须人工批准)。
|
||||
8. 写操作角色细分(目前统一管理员)。
|
||||
@@ -255,20 +255,25 @@
|
||||
|
||||
## D. 系统设置
|
||||
|
||||
### D1 服务配置(测试 / 生产端点与 ID)
|
||||
- 入口:**系统设置 → 服务配置**(管理员)
|
||||
- 规则:只配四项(测试地址、生产地址、生产 ID、知识库 ID);**保存时真探测**,无效才拒;凭据只写不读
|
||||
- 状态:✅(见 `P41/P42` 与 `ui_settings_*` 测试)
|
||||
### D1 知识库绑定(测试 090 / 生产 090:连接 + 内外库)
|
||||
- 入口:**系统设置 → 知识库绑定**(管理员;普通用户只读)
|
||||
- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库;**两个方向都必须选择**)→ **保存该环境绑定**
|
||||
- 期望:一次保存同时生效连接与内外绑定;顶部「当前生效」回读服务器真实值;失败保留旧绑定,未保存草稿不影响当前值;切换环境时迟到的列库响应不串库
|
||||
- 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE`
|
||||
- 实例约束:网页在实例 A 核验的绑定会冻结地址/租户;文档发布执行器连实例 B 时,即使知识库 ID/租户相同也拒绝写入(`release_contract_mismatch`)。测试对象改绑实例/租户后,旧对象不会被轮询/验收/移除。
|
||||
- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`、`TestStartReleaseExecutionFreezesTheBindingInstanceIdentity`、`TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance`
|
||||
- 单次任务连接:`TestBeginTaskPinsOneResolvedConnectionForAllCalls`;`TestPollUsesOneVerifiedConnectionForAllCalls`、`TestValidateUsesOneVerifiedConnectionForAllCalls`、`TestRemoveUsesOneVerifiedConnectionForDeleteAndReadBack`、`TestUploadUsesOneVerifiedConnectionForWrite`、`TestUploadRecoveryUsesTheSameVerifiedConnection`
|
||||
- 状态:✅ 本地验证(未做业务验收)
|
||||
|
||||
### D2 测试知识库绑定(对内 / 对外)
|
||||
- 入口:**系统设置 → 测试知识库绑定** → 选库 → 保存绑定
|
||||
- 期望:保存立即生效并重排"还没上传"的待入库项;对内 ≠ 对外
|
||||
- 状态:✅ 本期实测
|
||||
### D2 测试知识库绑定(折叠诊断;主入口已并入 D1)
|
||||
- 入口:**系统设置 → 知识库绑定 → 连接与绑定诊断**
|
||||
- 期望:保留入库目标/封存源一致性对照与重新读取;不再提供第二个保存入口(保存统一走 D1)
|
||||
- 状态:✅ 诊断展示保留
|
||||
|
||||
### D3 生产知识库绑定(源库 → 目标库)
|
||||
- 入口:**系统设置 → 生产知识库绑定** → 对内/对外各选一个生产库
|
||||
- 期望:发布写入被冻结到该项的 `target_knowledge_base_id`;未绑定时按同 ID 语义并在契约检查处失败关闭
|
||||
- 状态:✅(`P8_PRODUCTION_KB_MAPPING_ACCEPTANCE.md`;迁移 000044)
|
||||
### D3 生产知识库绑定(折叠诊断;整库目标只读)
|
||||
- 入口:**系统设置 → 知识库绑定 → 连接与绑定诊断**
|
||||
- 期望:整库发布实际目标来自部署配置、只读;生产 090 工作区的 D1 保存只写文档级语义(源库 → 目标库),不触发整库发布或生产写入
|
||||
- 状态:✅ 诊断展示保留(`P8_PRODUCTION_KB_MAPPING_ACCEPTANCE.md`;迁移 000044)
|
||||
|
||||
### D4 存储与备份(整库逻辑备份的定时)★本期新增
|
||||
- 入口:**系统设置 → 存储与备份**(管理员)
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
# 发布管理流程与页面精简
|
||||
|
||||
## 目标与边界
|
||||
|
||||
现有整库发布页面同时呈现日常发布、维护诊断、恢复演练与历史快照,且封存操作位于页面底部,版本入口重复。此次优化聚焦 `ReleaseTargets` 的信息层级和操作位置,沿用现有 API、权限、授权绑定、维护所有者与恢复确认。
|
||||
|
||||
基线采用云测试站当前前端对应的工作树 `cbc6b98`;该提交的 web 与部署版本 `0b753e5` 相同。并行主干及其他工作树不合并、不覆盖。
|
||||
|
||||
## 操作者主流程
|
||||
|
||||
| 顺序 | 页面操作 | 后台行为 | 完成边界 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 选择对内或对外知识库 | 读取该范围 overview、快照、作业及维护窗口 | 目标身份与版本来自所选范围;读取失败不当作空库 |
|
||||
| 2 | 封存测试版本 | POST `/api/v1/library/captures`,由队列及执行器捕获测试整库版本 | 投递不等于完成,以作业与登记快照为准;此步不发布生产 |
|
||||
| 3 | 查看变更及发布条件 | 展开变更、备份与恢复验证;若缺基线或恢复证据,沿用对应管理员入口 | 逐条呈现服务端阻塞原因,不删除发布门槛 |
|
||||
| 4 | 签发同步授权 | 管理员调用 `/api/v1/library/authorizations`,绑定目标与当前快照 | 有效期内仍需单独点击启动;不自动执行同步 |
|
||||
| 5 | 启动同步 | 沿用现有同步请求与执行链:固定版本、生产预备份、同步、校验及收尾 | 只在接口条件允许时可执行;运行中主按钮改为查看任务 |
|
||||
| 6 | 查看结果 | 自动刷新作业进度,终态按真实记录呈现 | 失败显示原始原因;维护占用不被其他作业成功覆盖 |
|
||||
| 异常 | 从版本与快照选择恢复点 | 继续执行独立恢复授权、影响确认和恢复条件校验 | 恢复整套目标知识状态,不回退测试知识库 |
|
||||
|
||||
封存、签发授权、启动同步三个动作保持独立,不将其合并为一键生产写入。
|
||||
|
||||
## 页面保留规则
|
||||
|
||||
- 顶栏:唯一的「版本与快照」入口和刷新。
|
||||
- 主工作区:实际目标身份、当前生产版本、候选测试版本、紧凑变更统计、当前主动作与一份阻塞原因。
|
||||
- 已有封存时提供次级「重新封存」;运行时不提供重复封存、授权或同步入口。
|
||||
- 「查看变更明细」「发布准备与恢复验证」「封存完整性」默认折叠;原有详情和验证回调继续存在。
|
||||
- 目标维护正常时折叠,持有维护窗口时自动展开;仍按窗口持有作业展示恢复信息。
|
||||
- 最近作业仅在有记录时展示,正常完成默认折叠,失败默认展开;运行中保留主进度,分项明细按需展开。
|
||||
- 版本抽屉保留历史筛选、分页、校验记录、恢复授权和影响确认,移除重复的封存按钮。
|
||||
- 发布管理页面移除旧文档级发布及历史来源关联区域,只展示整库发布流程。
|
||||
|
||||
## 验收清单
|
||||
|
||||
- [x] 前端生产构建通过。
|
||||
- [x] 原发布、恢复、维护所有者和刷新/切库回归通过。
|
||||
- [x] 同一挂载下依次切换封存、授权、同步,点击只调用对应动作。
|
||||
- [x] 折叠与展开、打开历史不触发业务写入。
|
||||
- [x] 运行时主操作只查看任务,不调用封存、授权或同步。
|
||||
- [x] 正常维护折叠、持有时展开、释放后折叠;切库重置明细展开状态。
|
||||
- [x] 无作业不画空进度;失败原因默认可见。
|
||||
- [x] 只读角色和读取失败时禁止主动作。
|
||||
|
||||
浏览器验收使用本地候选构建,GET/HEAD 通过已有 SSH 通道读取云测试 API;代理拒绝所有写请求。界面验收与真实封存、生产同步及恢复演练分开记录;本任务不执行这些业务写入。完整仓库门禁和云端部署结论以实际运行结果为准,不用上述前端检查替代。
|
||||
@@ -47,16 +47,22 @@ type Config struct {
|
||||
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
|
||||
// WeKnoraAllowPrivateHTTP 放行同网段 http(生产 18093 反代);只接受
|
||||
// RFC1918/回环/链路本地,公网 http 仍拒绝。监控探活与列库共用同一判定。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile 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
|
||||
@@ -65,6 +71,12 @@ type Config struct {
|
||||
BackupHostTarget string
|
||||
BackupHostScriptDir string
|
||||
BackupHostRoot string
|
||||
// BackupHostMetadataPath 是容器内挂载的宿主 metadata.json(单次采集器的原子快照)。
|
||||
// 留空即"未接线";它与上面的 SSH 计划读回是两条独立通道。
|
||||
BackupHostMetadataPath string
|
||||
BackupHostMetadataMaxAge time.Duration
|
||||
BackupHostReadonlyHostPath string
|
||||
BackupHostReadonlySource string
|
||||
// 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线"
|
||||
// (页面降级展示,接口返回可用性=false)。只允许配置里批准的 origin 与仓库,
|
||||
// 不接受任何调用方传入的 URL;本功能**不使用凭据**。
|
||||
@@ -181,6 +193,10 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("LIBRARY_EMBEDDING_DIMENSION must be a positive integer")
|
||||
}
|
||||
embeddingDimension := int(embeddingDimension64)
|
||||
metadataMaxAge, err := durationOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_METADATA_MAX_AGE")), 15*time.Minute)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be a positive duration")
|
||||
}
|
||||
config := Config{
|
||||
DatabaseURL: getenv("DATABASE_URL"),
|
||||
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
|
||||
@@ -203,6 +219,7 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")),
|
||||
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
|
||||
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
|
||||
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
|
||||
GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"),
|
||||
IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")),
|
||||
ArtifactFetchMaxBytes: 200 * 1024 * 1024,
|
||||
@@ -219,6 +236,10 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
|
||||
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
|
||||
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
|
||||
BackupHostMetadataPath: strings.TrimSpace(getenv("BACKUP_HOST_METADATA_PATH")),
|
||||
BackupHostMetadataMaxAge: metadataMaxAge,
|
||||
BackupHostReadonlyHostPath: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_HOST_PATH")),
|
||||
BackupHostReadonlySource: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_SOURCE")),
|
||||
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
|
||||
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
|
||||
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
|
||||
@@ -344,6 +365,15 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE must be an absolute path")
|
||||
}
|
||||
}
|
||||
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 config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if raw := getenv("PP_SCAN_ENABLED"); raw != "" {
|
||||
config.PPScanEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
@@ -511,6 +541,28 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("TEST_AUTO_REVIEW_POLICY must be one of off, internal, all")
|
||||
}
|
||||
config.TestAutoReviewPolicy = string(normalizedPolicy)
|
||||
// 宿主采集器快照接线与生产发布开关无关:测试栈也要先读通历史批次。
|
||||
if config.BackupHostMetadataPath != "" && !filepath.IsAbs(config.BackupHostMetadataPath) {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_PATH must be an absolute path")
|
||||
}
|
||||
if config.BackupHostReadonlyHostPath != "" && !filepath.IsAbs(config.BackupHostReadonlyHostPath) {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH must be an absolute path")
|
||||
}
|
||||
if config.BackupHostMetadataPath != "" && config.BackupHostReadonlyHostPath == "" {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when metadata path is set")
|
||||
}
|
||||
if config.BackupHostMetadataPath == "" &&
|
||||
(config.BackupHostReadonlyHostPath != "" || config.BackupHostReadonlySource != "") {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_PATH is required when host path/source is set")
|
||||
}
|
||||
if config.BackupHostMetadataMaxAge <= 0 || config.BackupHostMetadataMaxAge > 24*time.Hour {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be between 1s and 24h")
|
||||
}
|
||||
for _, value := range []string{config.BackupHostReadonlyHostPath, config.BackupHostReadonlySource} {
|
||||
if strings.ContainsAny(value, "\x00\r\n") {
|
||||
return Config{}, errors.New("backup inventory display path/source contains control characters")
|
||||
}
|
||||
}
|
||||
if config.ProductionReleaseRequestsEnabled {
|
||||
// 目标主机凭据要么都给要么都不给:只给一半会把"未接线"伪装成"已接线"。
|
||||
if (config.BackupHostSSHConfig == "") != (config.BackupHostTarget == "") {
|
||||
|
||||
@@ -53,6 +53,49 @@ func TestLoadUsesSafeDefaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadValidatesBackupInventoryMount(t *testing.T) {
|
||||
base := map[string]string{"DATABASE_URL": "postgres://example"}
|
||||
load := func(extra map[string]string) (Config, error) {
|
||||
values := map[string]string{}
|
||||
for key, value := range base {
|
||||
values[key] = value
|
||||
}
|
||||
for key, value := range extra {
|
||||
values[key] = value
|
||||
}
|
||||
return Load(func(key string) string { return values[key] })
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "relative/path"}); err == nil {
|
||||
t.Fatal("relative metadata path must be rejected")
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json"}); err == nil {
|
||||
t.Fatal("metadata path without host root must be rejected (paths must not be guessed)")
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical"}); err == nil {
|
||||
t.Fatal("host path without metadata path must be rejected")
|
||||
}
|
||||
if _, err := load(map[string]string{
|
||||
"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_METADATA_MAX_AGE": "nope",
|
||||
}); err == nil {
|
||||
t.Fatal("invalid metadata max age must be rejected")
|
||||
}
|
||||
config, err := load(map[string]string{
|
||||
"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_READONLY_SOURCE": "weknora-test:/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_METADATA_MAX_AGE": "5m",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("valid inventory snapshot config rejected: %v", err)
|
||||
}
|
||||
if config.BackupHostMetadataPath == "" || config.BackupHostReadonlyHostPath == "" ||
|
||||
config.BackupHostReadonlySource == "" || config.BackupHostMetadataMaxAge != 5*time.Minute {
|
||||
t.Fatalf("inventory snapshot fields lost: %#v", config)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRequiresDatabaseURL(t *testing.T) {
|
||||
if _, err := Load(func(string) string { return "" }); err == nil {
|
||||
t.Fatal("Load() error = nil, want missing DATABASE_URL error")
|
||||
|
||||
@@ -0,0 +1,562 @@
|
||||
// Package backupinventory 读取**宿主采集器**产出的备份元数据快照。
|
||||
//
|
||||
// 为什么不在 API 里遍历备份目录:备份目录通常是 root:root 0700,API 容器用户
|
||||
// 没有进入权限;容器里遍历只能得到 permission denied 的部分字节,绝不能把部分
|
||||
// 计数当成实际占盘。这里只读宿主进程原子写出的 metadata.json,并校验 schema、
|
||||
// 批次路径、主机根、时效与完整性。API 不接触备份目录,也不借用 SSH/容器特权。
|
||||
package backupinventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
SchemaVersion = 1
|
||||
defaultMaxAge = 15 * time.Minute
|
||||
defaultMaxBytes = 16 << 20
|
||||
futureTolerance = 2 * time.Minute
|
||||
measurementLabel = "host_collector"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
// MetadataPath 是 API 容器内挂载的 metadata.json(宿主采集器原子写出)。
|
||||
MetadataPath string
|
||||
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
|
||||
HostRoot string
|
||||
// Source 是展示来源;快照里的 source 非空时以快照为准。
|
||||
Source string
|
||||
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
|
||||
MaxAge time.Duration
|
||||
// MaxBytes 防止异常大文件拖死 API。
|
||||
MaxBytes int64
|
||||
}
|
||||
|
||||
type ManifestState string
|
||||
|
||||
const (
|
||||
ManifestOK ManifestState = "ok"
|
||||
ManifestMissing ManifestState = "missing"
|
||||
ManifestInvalid ManifestState = "invalid"
|
||||
)
|
||||
|
||||
type MetadataInfo struct {
|
||||
Configured bool `json:"configured"`
|
||||
Present bool `json:"present"`
|
||||
Valid bool `json:"valid"`
|
||||
Fresh bool `json:"fresh"`
|
||||
Complete bool `json:"complete"`
|
||||
Path string `json:"path"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
AgeSeconds int64 `json:"age_seconds"`
|
||||
MaxAgeSeconds int64 `json:"max_age_seconds"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Generation string `json:"generation"`
|
||||
Host string `json:"host"`
|
||||
CollectorVersion string `json:"collector_version"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type MountInfo struct {
|
||||
ContainerRoot string `json:"container_root"`
|
||||
MountVerified bool `json:"mount_verified"`
|
||||
LivesOnContainerRoot bool `json:"lives_on_container_root"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
Evidence string `json:"evidence"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Device string `json:"device"`
|
||||
FSType string `json:"fs_type"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Capacity struct {
|
||||
Measured bool `json:"measured"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
FreeBytes int64 `json:"free_bytes"`
|
||||
AvailableBytes int64 `json:"available_bytes"`
|
||||
UsedBytes int64 `json:"used_bytes"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Database struct {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
Path string `json:"path"`
|
||||
HostPath string `json:"host_path"`
|
||||
Present bool `json:"present"`
|
||||
Failed bool `json:"failed"`
|
||||
InManifest bool `json:"in_manifest"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
}
|
||||
|
||||
type Batch struct {
|
||||
Stamp string `json:"stamp"`
|
||||
Path string `json:"path"`
|
||||
HostPath string `json:"host_path"`
|
||||
ManifestState ManifestState `json:"manifest_state"`
|
||||
ManifestPath string `json:"manifest_path"`
|
||||
ManifestError string `json:"manifest_error,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
StartedAt string `json:"started_at"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
SizesComplete bool `json:"sizes_complete"`
|
||||
SizesError string `json:"sizes_error,omitempty"`
|
||||
Databases []Database `json:"databases"`
|
||||
}
|
||||
|
||||
type Skipped struct {
|
||||
Name string `json:"name"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type Totals struct {
|
||||
BatchCount int `json:"batch_count"`
|
||||
DatabaseCount int `json:"database_count"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
LatestStamp string `json:"latest_stamp"`
|
||||
LatestActualBytes *int64 `json:"latest_actual_bytes"`
|
||||
Complete bool `json:"complete"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
Wired bool `json:"wired"`
|
||||
Metadata MetadataInfo `json:"metadata"`
|
||||
Root string `json:"root"`
|
||||
HostRoot string `json:"host_root"`
|
||||
Source string `json:"source"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Measurement string `json:"measurement"`
|
||||
Mount MountInfo `json:"mount"`
|
||||
Capacity Capacity `json:"capacity"`
|
||||
Batches []Batch `json:"batches"`
|
||||
Totals Totals `json:"totals"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
Skipped []Skipped `json:"skipped"`
|
||||
Truncated bool `json:"truncated"`
|
||||
}
|
||||
|
||||
type Reader struct {
|
||||
config Config
|
||||
now func() time.Time
|
||||
read func(string) ([]byte, error)
|
||||
}
|
||||
|
||||
func New(config Config) *Reader {
|
||||
if config.MaxAge <= 0 {
|
||||
config.MaxAge = defaultMaxAge
|
||||
}
|
||||
if config.MaxBytes <= 0 {
|
||||
config.MaxBytes = defaultMaxBytes
|
||||
}
|
||||
return &Reader{config: config, now: time.Now, read: os.ReadFile}
|
||||
}
|
||||
|
||||
func (r *Reader) Available() bool {
|
||||
return r != nil && strings.TrimSpace(r.config.MetadataPath) != ""
|
||||
}
|
||||
|
||||
// ---- 宿主快照文件(collector 的输出;只读、字段可验证) ----
|
||||
|
||||
type metadata struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
CollectorVersion string `json:"collector_version"`
|
||||
Generation string `json:"generation"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
Host string `json:"host"`
|
||||
Source string `json:"source"`
|
||||
Root string `json:"root"`
|
||||
Complete bool `json:"complete"`
|
||||
Errors []string `json:"errors"`
|
||||
Filesystem metadataFilesystem `json:"filesystem"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
Skipped []Skipped `json:"skipped"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Batches []metadataBatch `json:"batches"`
|
||||
}
|
||||
|
||||
type metadataFilesystem struct {
|
||||
MountPoint string `json:"mount_point"`
|
||||
MountSource string `json:"mount_source"`
|
||||
FSType string `json:"fs_type"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
FreeBytes int64 `json:"free_bytes"`
|
||||
AvailableBytes int64 `json:"available_bytes"`
|
||||
}
|
||||
|
||||
type metadataBatch struct {
|
||||
Stamp string `json:"stamp"`
|
||||
Path string `json:"path"`
|
||||
ManifestState string `json:"manifest_state"`
|
||||
ManifestError string `json:"manifest_error"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
StartedAt string `json:"started_at"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
|
||||
Complete bool `json:"complete"`
|
||||
Errors []string `json:"errors"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
Databases []metadataDatabase `json:"databases"`
|
||||
}
|
||||
|
||||
type metadataDatabase struct {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
Path string `json:"path"`
|
||||
Present bool `json:"present"`
|
||||
Failed bool `json:"failed"`
|
||||
InManifest bool `json:"in_manifest"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
}
|
||||
|
||||
// Snapshot 只返回可验证的事实:陈旧/缺失/不完整一律不给批次字节与容量。
|
||||
func (r *Reader) Snapshot(ctx context.Context) Snapshot {
|
||||
snapshot := Snapshot{
|
||||
Wired: r.Available(),
|
||||
Measurement: measurementLabel,
|
||||
Batches: []Batch{},
|
||||
Skipped: []Skipped{},
|
||||
ObservedAt: r.observedAt(),
|
||||
Metadata: MetadataInfo{
|
||||
Configured: r.Available(),
|
||||
MaxAgeSeconds: int64(r.config.MaxAge / time.Second),
|
||||
},
|
||||
}
|
||||
if r == nil || !r.Available() {
|
||||
snapshot.Metadata.Error = "元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)"
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
snapshot.Metadata.Path = r.config.MetadataPath
|
||||
snapshot.HostRoot = r.config.HostRoot
|
||||
snapshot.Source = r.config.Source
|
||||
if ctx.Err() != nil {
|
||||
snapshot.Metadata.Error = "读取被取消:" + ctx.Err().Error()
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
raw, err := r.read(r.config.MetadataPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
snapshot.Metadata.Error = "宿主元数据快照不存在:需要先运行 collect_backup_metadata.py"
|
||||
} else {
|
||||
snapshot.Metadata.Error = "宿主元数据快照不可读:" + err.Error()
|
||||
}
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
snapshot.Metadata.Present = true
|
||||
if int64(len(raw)) > r.config.MaxBytes {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据快照超过 %d 字节读取上限", r.config.MaxBytes))
|
||||
}
|
||||
var file metadata
|
||||
if err := json.Unmarshal(raw, &file); err != nil {
|
||||
return invalid(snapshot, "元数据快照无法解析:"+err.Error())
|
||||
}
|
||||
snapshot.Metadata.SchemaVersion = file.SchemaVersion
|
||||
snapshot.Metadata.Generation = file.Generation
|
||||
snapshot.Metadata.Host = file.Host
|
||||
snapshot.Metadata.CollectorVersion = file.CollectorVersion
|
||||
snapshot.Metadata.CollectedAt = file.CollectedAt
|
||||
snapshot.Metadata.Complete = file.Complete
|
||||
if file.Source != "" {
|
||||
snapshot.Source = file.Source
|
||||
}
|
||||
if file.SchemaVersion != SchemaVersion {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据 schema_version=%d,API 只支持 %d", file.SchemaVersion, SchemaVersion))
|
||||
}
|
||||
collectedAt, err := time.Parse(time.RFC3339, file.CollectedAt)
|
||||
if err != nil {
|
||||
return invalid(snapshot, "元数据 collected_at 非法:"+file.CollectedAt)
|
||||
}
|
||||
age := r.now().UTC().Sub(collectedAt.UTC())
|
||||
if age < -futureTolerance {
|
||||
return invalid(snapshot, "元数据 collected_at 在未来,拒绝使用")
|
||||
}
|
||||
snapshot.Metadata.AgeSeconds = int64(age / time.Second)
|
||||
if age > r.config.MaxAge {
|
||||
snapshot.Metadata.Fresh = false
|
||||
return invalid(snapshot, fmt.Sprintf("元数据已陈旧:采集于 %s,超过 %s", file.CollectedAt, r.config.MaxAge))
|
||||
}
|
||||
snapshot.Metadata.Fresh = true
|
||||
if strings.TrimSpace(r.config.HostRoot) == "" {
|
||||
return invalid(snapshot, "宿主根路径未配置:无法校验批次路径")
|
||||
}
|
||||
expectedRoot := path.Clean(strings.TrimSpace(r.config.HostRoot))
|
||||
snapshot.HostRoot = expectedRoot
|
||||
root := strings.TrimSpace(file.Root)
|
||||
if !path.IsAbs(root) || path.Clean(root) != root {
|
||||
return invalid(snapshot, "元数据 root 不是规范绝对路径:"+root)
|
||||
}
|
||||
if root != expectedRoot {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
|
||||
}
|
||||
snapshot.Root = root
|
||||
if err := validateBatches(root, file.Batches); err != nil {
|
||||
return invalid(snapshot, err.Error())
|
||||
}
|
||||
snapshot.Metadata.Valid = true
|
||||
snapshot.IncompleteCount = file.IncompleteCount
|
||||
snapshot.Skipped = append(snapshot.Skipped, file.Skipped...)
|
||||
snapshot.Truncated = file.Truncated
|
||||
snapshot.Mount = MountInfo{
|
||||
Evidence: "宿主采集器上报:" + file.Host,
|
||||
MountPoint: file.Filesystem.MountPoint,
|
||||
Device: file.Filesystem.MountSource,
|
||||
FSType: file.Filesystem.FSType,
|
||||
ReadOnly: file.Filesystem.ReadOnly,
|
||||
}
|
||||
if file.Filesystem.MountPoint == "" || !path.IsAbs(file.Filesystem.MountPoint) {
|
||||
snapshot.Mount.Error = "宿主采集器没有给出文件系统挂载点"
|
||||
} else if root != file.Filesystem.MountPoint && !strings.HasPrefix(root, strings.TrimSuffix(file.Filesystem.MountPoint, "/")+"/") {
|
||||
snapshot.Mount.Error = "批次根不在采集器上报的挂载点下"
|
||||
} else {
|
||||
snapshot.Mount.MountVerified = true
|
||||
snapshot.Mount.Evidence = fmt.Sprintf("宿主采集器:%s 挂在 %s(%s),API 不遍历备份目录",
|
||||
file.Filesystem.MountSource, file.Filesystem.MountPoint, file.Filesystem.FSType)
|
||||
}
|
||||
|
||||
// 快照不完整/截断:路径与清单状态可展示,但所有字节与容量一律未知,
|
||||
// 绝不用部分 counts 或完整批次的局部字节拼总量。
|
||||
complete := file.Complete && !file.Truncated && snapshot.Mount.MountVerified && allBatchesComplete(file.Batches)
|
||||
if !complete {
|
||||
snapshot.Metadata.Complete = false
|
||||
snapshot.Metadata.Error = incompleteReason(file)
|
||||
snapshot.Capacity = Capacity{Error: "采集快照不完整:容量与占盘未知"}
|
||||
snapshot.Mount.MountVerified = false
|
||||
snapshot.Mount.Error = "采集快照不完整,不能据此判定文件系统与占盘"
|
||||
snapshot.Batches = projectBatches(root, file.Batches, false)
|
||||
snapshot.Totals = totals(snapshot.Batches, false)
|
||||
snapshot.Error = ""
|
||||
return snapshot
|
||||
}
|
||||
|
||||
snapshot.Metadata.Complete = true
|
||||
snapshot.Capacity = projectCapacity(file.Filesystem)
|
||||
snapshot.Batches = projectBatches(root, file.Batches, true)
|
||||
snapshot.Totals = totals(snapshot.Batches, true)
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func (r *Reader) observedAt() string {
|
||||
if r == nil || r.now == nil {
|
||||
return ""
|
||||
}
|
||||
return r.now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func invalid(snapshot Snapshot, reason string) Snapshot {
|
||||
snapshot.Metadata.Valid = false
|
||||
snapshot.Metadata.Complete = false
|
||||
snapshot.Metadata.Error = reason
|
||||
snapshot.Error = reason
|
||||
snapshot.Batches = []Batch{}
|
||||
snapshot.Capacity = Capacity{Error: reason}
|
||||
snapshot.Totals = Totals{}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func incompleteReason(file metadata) string {
|
||||
if len(file.Errors) > 0 {
|
||||
return "采集不完整:" + strings.Join(limit(file.Errors, 3), ";")
|
||||
}
|
||||
for _, batch := range file.Batches {
|
||||
if len(batch.Errors) > 0 {
|
||||
return "采集不完整:" + strings.Join(limit(batch.Errors, 3), ";")
|
||||
}
|
||||
}
|
||||
return "采集不完整:存在无法遍历/统计的目录,占盘与容量未知"
|
||||
}
|
||||
|
||||
func limit(items []string, n int) []string {
|
||||
if len(items) <= n {
|
||||
return items
|
||||
}
|
||||
return items[:n]
|
||||
}
|
||||
|
||||
func allBatchesComplete(batches []metadataBatch) bool {
|
||||
for _, batch := range batches {
|
||||
if !batch.Complete || batch.ActualBytes == nil || batch.ApparentBytes == nil || batch.FileCount == nil {
|
||||
return false
|
||||
}
|
||||
for _, database := range batch.Databases {
|
||||
if database.ActualBytes == nil || database.ApparentBytes == nil || database.FileCount == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 校验的是"快照里的路径能否被安全地当成这台主机的批次/子库":
|
||||
// 根必须精确匹配配置,批次必须精确等于 root/<stamp>,子库必须精确等于
|
||||
// batch/<name>.dir,且不允许重复、分隔符、.incomplete。
|
||||
func validateBatches(root string, batches []metadataBatch) error {
|
||||
seen := map[string]bool{}
|
||||
for _, batch := range batches {
|
||||
stamp := strings.TrimSpace(batch.Stamp)
|
||||
if err := safeSegment(stamp); err != nil {
|
||||
return fmt.Errorf("批次名不合法:%q(%v)", stamp, err)
|
||||
}
|
||||
if strings.HasSuffix(stamp, ".incomplete") {
|
||||
return fmt.Errorf("批次 %q 是未完成目录,不应进入快照", stamp)
|
||||
}
|
||||
if seen[stamp] {
|
||||
return fmt.Errorf("批次 %q 重复", stamp)
|
||||
}
|
||||
seen[stamp] = true
|
||||
expected := path.Join(root, stamp)
|
||||
if batch.Path != expected || !path.IsAbs(batch.Path) {
|
||||
return fmt.Errorf("批次 %q 路径 %q 不等于 %q", stamp, batch.Path, expected)
|
||||
}
|
||||
switch ManifestState(batch.ManifestState) {
|
||||
case ManifestOK, ManifestMissing, ManifestInvalid:
|
||||
default:
|
||||
return fmt.Errorf("批次 %q 的 manifest_state 不认识:%q", stamp, batch.ManifestState)
|
||||
}
|
||||
databaseSeen := map[string]bool{}
|
||||
for _, database := range batch.Databases {
|
||||
name := strings.TrimSpace(database.Name)
|
||||
if err := safeSegment(name); err != nil {
|
||||
return fmt.Errorf("批次 %q 子库名不合法:%q", stamp, name)
|
||||
}
|
||||
if databaseSeen[name] {
|
||||
return fmt.Errorf("批次 %q 子库 %q 重复", stamp, name)
|
||||
}
|
||||
databaseSeen[name] = true
|
||||
expectedDir := path.Join(expected, name+".dir")
|
||||
if database.DirName != name+".dir" || database.Path != expectedDir || !path.IsAbs(database.Path) {
|
||||
return fmt.Errorf("批次 %q 子库 %q 路径不合法:%q", stamp, name, database.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeSegment(value string) error {
|
||||
if value == "" || value == "." || value == ".." {
|
||||
return errors.New("空值或相对路径")
|
||||
}
|
||||
for _, r := range value {
|
||||
if r == '/' || r == '\\' || r == 0 || r == '\n' || r == '\r' {
|
||||
return errors.New("包含路径分隔符或控制字符")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func projectBatches(root string, batches []metadataBatch, complete bool) []Batch {
|
||||
result := make([]Batch, 0, len(batches))
|
||||
for _, batch := range batches {
|
||||
item := Batch{
|
||||
Stamp: batch.Stamp,
|
||||
Path: path.Join(root, batch.Stamp),
|
||||
HostPath: path.Join(root, batch.Stamp),
|
||||
ManifestState: ManifestState(batch.ManifestState),
|
||||
ManifestPath: path.Join(root, batch.Stamp, "MANIFEST.json"),
|
||||
ManifestError: batch.ManifestError,
|
||||
Kind: batch.Kind,
|
||||
CreatedAt: batch.CreatedAt,
|
||||
StartedAt: batch.StartedAt,
|
||||
DurationSeconds: batch.DurationSeconds,
|
||||
SizesComplete: complete && batch.Complete,
|
||||
Databases: []Database{},
|
||||
}
|
||||
if complete && batch.Complete {
|
||||
item.ManifestTotalBytes = batch.ManifestTotalBytes
|
||||
item.ApparentBytes = batch.ApparentBytes
|
||||
item.ActualBytes = batch.ActualBytes
|
||||
item.FileCount = batch.FileCount
|
||||
}
|
||||
for _, database := range batch.Databases {
|
||||
entry := Database{
|
||||
Name: database.Name,
|
||||
DirName: database.DirName,
|
||||
Path: path.Join(root, batch.Stamp, database.DirName),
|
||||
HostPath: path.Join(root, batch.Stamp, database.DirName),
|
||||
Present: database.Present,
|
||||
Failed: database.Failed,
|
||||
InManifest: database.InManifest,
|
||||
}
|
||||
if complete && batch.Complete {
|
||||
entry.ApparentBytes = database.ApparentBytes
|
||||
entry.ActualBytes = database.ActualBytes
|
||||
entry.FileCount = database.FileCount
|
||||
}
|
||||
item.Databases = append(item.Databases, entry)
|
||||
}
|
||||
if !item.SizesComplete {
|
||||
item.SizesError = "宿主采集器该项不完整,占盘未知"
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool { return result[i].Stamp > result[j].Stamp })
|
||||
return result
|
||||
}
|
||||
|
||||
func totals(batches []Batch, complete bool) Totals {
|
||||
result := Totals{BatchCount: len(batches), Complete: complete}
|
||||
if len(batches) > 0 {
|
||||
result.LatestStamp = batches[0].Stamp
|
||||
}
|
||||
for _, batch := range batches {
|
||||
result.DatabaseCount += len(batch.Databases)
|
||||
}
|
||||
if !complete {
|
||||
return result
|
||||
}
|
||||
var apparent, actual int64
|
||||
for _, batch := range batches {
|
||||
if batch.ApparentBytes != nil {
|
||||
apparent += *batch.ApparentBytes
|
||||
}
|
||||
if batch.ActualBytes != nil {
|
||||
actual += *batch.ActualBytes
|
||||
}
|
||||
}
|
||||
result.ApparentBytes = &apparent
|
||||
result.ActualBytes = &actual
|
||||
if len(batches) > 0 {
|
||||
result.LatestActualBytes = batches[0].ActualBytes
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func projectCapacity(filesystem metadataFilesystem) Capacity {
|
||||
if filesystem.TotalBytes <= 0 {
|
||||
return Capacity{Error: "宿主采集器没有给出文件系统容量"}
|
||||
}
|
||||
used := filesystem.TotalBytes - filesystem.FreeBytes
|
||||
if used < 0 {
|
||||
used = 0
|
||||
}
|
||||
return Capacity{
|
||||
Measured: true,
|
||||
TotalBytes: filesystem.TotalBytes,
|
||||
FreeBytes: filesystem.FreeBytes,
|
||||
AvailableBytes: filesystem.AvailableBytes,
|
||||
UsedBytes: used,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package backupinventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const hostRoot = "/srv/kb-backups/rds-logical"
|
||||
|
||||
func int64p(value int64) *int64 { return &value }
|
||||
func intp(value int) *int { return &value }
|
||||
|
||||
func validMetadata() metadata {
|
||||
latest := hostRoot + "/20261118T193001Z"
|
||||
broken := hostRoot + "/20261117T193001Z"
|
||||
without := hostRoot + "/20261116T193001Z"
|
||||
return metadata{
|
||||
SchemaVersion: SchemaVersion,
|
||||
CollectorVersion: "backup-metadata/1",
|
||||
Generation: "20261120T010000Z-abc123",
|
||||
CollectedAt: "2026-11-20T01:00:00Z",
|
||||
Host: "weknora-test",
|
||||
Source: "weknora-test:" + hostRoot,
|
||||
Root: hostRoot,
|
||||
Complete: true,
|
||||
Errors: []string{},
|
||||
Filesystem: metadataFilesystem{
|
||||
MountPoint: "/srv/kb-backups",
|
||||
MountSource: "/dev/sdb1",
|
||||
FSType: "ext4",
|
||||
ReadOnly: false,
|
||||
TotalBytes: 1000,
|
||||
FreeBytes: 400,
|
||||
AvailableBytes: 350,
|
||||
},
|
||||
IncompleteCount: 1,
|
||||
Skipped: []Skipped{{Name: "notes.txt", Reason: "不是批次目录"}},
|
||||
Batches: []metadataBatch{
|
||||
{
|
||||
Stamp: "20261118T193001Z",
|
||||
Path: latest,
|
||||
ManifestState: "ok",
|
||||
Kind: "rds-logical-backup",
|
||||
CreatedAt: "20261118T193001Z",
|
||||
StartedAt: "20261118T192908Z",
|
||||
DurationSeconds: 53,
|
||||
ManifestTotalBytes: int64p(300),
|
||||
Complete: true,
|
||||
ApparentBytes: int64p(300),
|
||||
ActualBytes: int64p(4096),
|
||||
FileCount: intp(3),
|
||||
Databases: []metadataDatabase{
|
||||
{
|
||||
Name: "weknora_v090prod", DirName: "weknora_v090prod.dir",
|
||||
Path: latest + "/weknora_v090prod.dir", Present: true, InManifest: true,
|
||||
ApparentBytes: int64p(250), ActualBytes: int64p(4096), FileCount: intp(2),
|
||||
},
|
||||
{
|
||||
Name: "weknora_test", DirName: "weknora_test.dir",
|
||||
Path: latest + "/weknora_test.dir", Present: true, InManifest: true, Failed: true,
|
||||
ApparentBytes: int64p(50), ActualBytes: int64p(0), FileCount: intp(1),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Stamp: "20261117T193001Z",
|
||||
Path: broken,
|
||||
ManifestState: "invalid", ManifestError: "清单无法解析:unexpected end",
|
||||
Complete: true, ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
|
||||
Databases: []metadataDatabase{{
|
||||
Name: "weknora_prod", DirName: "weknora_prod.dir",
|
||||
Path: broken + "/weknora_prod.dir", Present: true,
|
||||
ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
|
||||
}},
|
||||
},
|
||||
{
|
||||
Stamp: "20261116T193001Z",
|
||||
Path: without,
|
||||
ManifestState: "missing",
|
||||
Complete: true, ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
|
||||
Databases: []metadataDatabase{{
|
||||
Name: "weknora_archive", DirName: "weknora_archive.dir",
|
||||
Path: without + "/weknora_archive.dir", Present: true,
|
||||
ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
|
||||
}},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func writeMetadata(t *testing.T, value metadata) string {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filename := filepath.Join(t.TempDir(), "metadata.json")
|
||||
if err := os.WriteFile(filename, raw, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return filename
|
||||
}
|
||||
|
||||
func readerAt(filename string, now time.Time) *Reader {
|
||||
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, Source: "configured", MaxAge: 15 * time.Minute})
|
||||
reader.now = func() time.Time { return now }
|
||||
return reader
|
||||
}
|
||||
|
||||
func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
|
||||
filename := writeMetadata(t, validMetadata())
|
||||
now := time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)
|
||||
snapshot := readerAt(filename, now).Snapshot(context.Background())
|
||||
if !snapshot.Wired || snapshot.Error != "" || !snapshot.Metadata.Valid || !snapshot.Metadata.Fresh || !snapshot.Metadata.Complete {
|
||||
t.Fatalf("应接受新鲜的完整快照: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || snapshot.Mount.MountPoint != "/srv/kb-backups" {
|
||||
t.Fatalf("宿主挂载判定不对: %+v", snapshot.Mount)
|
||||
}
|
||||
if !snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 1000 || snapshot.Capacity.AvailableBytes != 350 {
|
||||
t.Fatalf("容量不对: %+v", snapshot.Capacity)
|
||||
}
|
||||
if snapshot.Metadata.AgeSeconds != 300 || snapshot.Metadata.Generation == "" || snapshot.Metadata.Host != "weknora-test" {
|
||||
t.Fatalf("元数据字段不对: %+v", snapshot.Metadata)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 || len(snapshot.Skipped) != 1 {
|
||||
t.Fatalf("批次计数不对: %+v", snapshot)
|
||||
}
|
||||
latest := snapshot.Batches[0]
|
||||
if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK || latest.SizesComplete != true {
|
||||
t.Fatalf("最近批次不对: %+v", latest)
|
||||
}
|
||||
if latest.HostPath != hostRoot+"/20261118T193001Z" || latest.ManifestTotalBytes == nil || *latest.ManifestTotalBytes != 300 {
|
||||
t.Fatalf("批次路径/清单不对: %+v", latest)
|
||||
}
|
||||
prod := latest.Databases[0]
|
||||
if prod.HostPath != hostRoot+"/20261118T193001Z/weknora_v090prod.dir" || prod.ActualBytes == nil || *prod.ActualBytes != 4096 {
|
||||
t.Fatalf("子库完整路径/占盘不对: %+v", prod)
|
||||
}
|
||||
if !latest.Databases[1].Failed {
|
||||
t.Fatalf("失败库没有标记: %+v", latest.Databases[1])
|
||||
}
|
||||
if snapshot.Batches[1].ManifestState != ManifestInvalid || snapshot.Batches[1].ManifestError == "" {
|
||||
t.Fatalf("损坏清单没有如实标记: %+v", snapshot.Batches[1])
|
||||
}
|
||||
if snapshot.Batches[2].ManifestState != ManifestMissing {
|
||||
t.Fatalf("缺清单没有如实标记: %+v", snapshot.Batches[2])
|
||||
}
|
||||
if snapshot.Totals.ActualBytes == nil || *snapshot.Totals.ActualBytes != 4096+2048+1024 || !snapshot.Totals.Complete {
|
||||
t.Fatalf("汇总不对: %+v", snapshot.Totals)
|
||||
}
|
||||
if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
|
||||
t.Fatalf("来源/测量方式不对: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotStaleIsUnknown(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.CollectedAt = "2026-11-20T00:00:00Z"
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || snapshot.Metadata.Fresh || snapshot.Metadata.Complete {
|
||||
t.Fatalf("陈旧快照不能算有效: %+v", snapshot.Metadata)
|
||||
}
|
||||
if len(snapshot.Batches) != 0 || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
|
||||
t.Fatalf("陈旧快照不能给批次/容量/占盘: %+v", snapshot)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "陈旧") {
|
||||
t.Fatalf("陈旧原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotMissingMetadata(t *testing.T) {
|
||||
reader := New(Config{MetadataPath: filepath.Join(t.TempDir(), "missing.json"), HostRoot: hostRoot})
|
||||
snapshot := reader.Snapshot(context.Background())
|
||||
if !snapshot.Wired || snapshot.Metadata.Present || snapshot.Metadata.Valid {
|
||||
t.Fatalf("缺失快照不能算有效: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "不存在") {
|
||||
t.Fatalf("缺失原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotPermissionFailureNeverUsesPartialBytes(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Complete = false
|
||||
value.Errors = nil
|
||||
value.Batches[0].Complete = false
|
||||
value.Batches[0].Errors = []string{"遍历失败:PermissionError: Permission denied ('.../weknora_v090prod.dir')"}
|
||||
// 模拟采集器在权限失败前已经数到的部分字节;API 绝不能把它们当占盘。
|
||||
value.Batches[0].ActualBytes = int64p(100)
|
||||
value.Batches[0].Databases[0].ActualBytes = int64p(100)
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if !snapshot.Metadata.Valid || snapshot.Metadata.Complete {
|
||||
t.Fatalf("不完整快照应 valid=true/complete=false: %+v", snapshot.Metadata)
|
||||
}
|
||||
if snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil || snapshot.Totals.ApparentBytes != nil {
|
||||
t.Fatalf("不完整快照不能给容量/总量: %+v", snapshot)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 {
|
||||
t.Fatalf("路径仍应列出: %+v", snapshot.Batches)
|
||||
}
|
||||
latest := snapshot.Batches[0]
|
||||
if latest.ActualBytes != nil || latest.ApparentBytes != nil || latest.FileCount != nil || latest.SizesComplete {
|
||||
t.Fatalf("不完整批次不能保留部分字节: %+v", latest)
|
||||
}
|
||||
if latest.Databases[0].ActualBytes != nil || latest.Databases[0].ApparentBytes != nil {
|
||||
t.Fatalf("不完整子库不能保留部分字节: %+v", latest.Databases[0])
|
||||
}
|
||||
if !strings.Contains(snapshot.Metadata.Error, "Permission") {
|
||||
t.Fatalf("权限失败原因丢失: %q", snapshot.Metadata.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotTruncatedIsUnknown(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Truncated = true
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Complete || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
|
||||
t.Fatalf("截断快照不能算完整/容量: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRejectsPathMismatch(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Batches[0].Path = "/srv/kb-backups/rds-logical/../evil"
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || len(snapshot.Batches) != 0 {
|
||||
t.Fatalf("路径不一致必须整块拒绝: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "路径") {
|
||||
t.Fatalf("路径错误原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRejectsUnsupportedSchema(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.SchemaVersion = 99
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || !strings.Contains(snapshot.Error, "schema_version") {
|
||||
t.Fatalf("不支持的 schema 必须拒绝: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotUnconfigured(t *testing.T) {
|
||||
snapshot := New(Config{}).Snapshot(context.Background())
|
||||
if snapshot.Wired || snapshot.Error == "" || len(snapshot.Batches) != 0 {
|
||||
t.Fatalf("未接线必须给出原因且不伪造批次: %+v", snapshot)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "未接线") {
|
||||
t.Fatalf("未接线原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
// 宿主采集器的权限失败回归:self-test 用注入 walker 模拟 PermissionError,
|
||||
// 断言不完整时字节为 null 且不产生部分统计。
|
||||
func TestCollectorSelfTest(t *testing.T) {
|
||||
python, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Skip("python3 not available")
|
||||
}
|
||||
command := exec.Command(python, "../../scripts/collect_backup_metadata.py", "--self-test")
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("collector self-test failed: %v\n%s", err, output)
|
||||
}
|
||||
if !strings.Contains(string(output), "self-test ok") {
|
||||
t.Fatalf("collector self-test output unexpected: %s", output)
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,22 @@ package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// CredentialStatus contains metadata only, never credential values.
|
||||
type CredentialStatus struct {
|
||||
Identity string `json:"identity,omitempty"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at,omitempty"`
|
||||
CorpName string `json:"corp_name,omitempty"`
|
||||
UserName string `json:"user_name,omitempty"`
|
||||
StatusKnown bool `json:"status_known"`
|
||||
}
|
||||
|
||||
func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, error) {
|
||||
@@ -20,13 +26,23 @@ func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus,
|
||||
return CredentialStatus{}, errors.New("could not read DWS credential status")
|
||||
}
|
||||
var decoded struct {
|
||||
Authenticated *bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at"`
|
||||
CorpID json.RawMessage `json:"corp_id"`
|
||||
UserID json.RawMessage `json:"user_id"`
|
||||
Authenticated *bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at"`
|
||||
CorpName string `json:"corp_name"`
|
||||
UserName string `json:"user_name"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if json.Unmarshal(raw, &decoded) != nil || decoded.Authenticated == nil {
|
||||
return CredentialStatus{}, errors.New("invalid DWS credential status")
|
||||
}
|
||||
return CredentialStatus{*decoded.Authenticated, decoded.RefreshTokenValid, decoded.ExpiresAt, decoded.RefreshExpiresAt}, nil
|
||||
identity := ""
|
||||
if len(decoded.CorpID) > 0 && len(decoded.UserID) > 0 && string(decoded.CorpID) != "null" && string(decoded.UserID) != "null" {
|
||||
sum := sha256.Sum256(append(append(decoded.CorpID, 0), decoded.UserID...))
|
||||
identity = hex.EncodeToString(sum[:])
|
||||
}
|
||||
return CredentialStatus{Identity: identity, Authenticated: *decoded.Authenticated, RefreshTokenValid: decoded.RefreshTokenValid, ExpiresAt: decoded.ExpiresAt, RefreshExpiresAt: decoded.RefreshExpiresAt, CorpName: decoded.CorpName, UserName: decoded.UserName, StatusKnown: decoded.Reason == ""}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrLoginBusy = errors.New("another DWS authorization is active")
|
||||
var ErrLoginNotFound = errors.New("DWS authorization not found")
|
||||
|
||||
// DeviceLoginView contains only the user-facing challenge. Tokens remain in the
|
||||
// CLI's shared credential store; command output is never logged or returned.
|
||||
type DeviceLoginView struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
VerificationURL string `json:"verification_url,omitempty"`
|
||||
UserCode string `json:"user_code,omitempty"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type deviceLogin struct {
|
||||
view DeviceLoginView
|
||||
owner string
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
type DeviceLoginManager struct {
|
||||
ctx context.Context
|
||||
runner ExecRunner
|
||||
mu sync.Mutex
|
||||
sessions map[string]*deviceLogin
|
||||
}
|
||||
|
||||
func NewDeviceLoginManager(ctx context.Context, runner ExecRunner) *DeviceLoginManager {
|
||||
return &DeviceLoginManager{ctx: ctx, runner: runner, sessions: make(map[string]*deviceLogin)}
|
||||
}
|
||||
|
||||
func loginActive(state string) bool {
|
||||
return state == "starting" || state == "waiting" || state == "verifying"
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Start(owner string) (DeviceLoginView, error) {
|
||||
if owner == "" {
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for id, s := range m.sessions {
|
||||
if s.view.State == "cancelled" || s.view.State == "expired" {
|
||||
select {
|
||||
case <-s.done:
|
||||
default:
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
}
|
||||
if loginActive(s.view.State) {
|
||||
if s.owner == owner {
|
||||
return s.view, nil
|
||||
}
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
if time.Since(s.view.ExpiresAt) > 30*time.Minute || len(m.sessions) >= 16 {
|
||||
delete(m.sessions, id)
|
||||
}
|
||||
}
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return DeviceLoginView{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(m.ctx, 20*time.Minute)
|
||||
s := &deviceLogin{view: DeviceLoginView{ID: hex.EncodeToString(b[:]), State: "starting", ExpiresAt: time.Now().UTC().Add(20 * time.Minute)}, owner: owner, cancel: cancel, done: make(chan struct{})}
|
||||
m.sessions[s.view.ID] = s
|
||||
go m.run(ctx, s)
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Get(owner, id string) (DeviceLoginView, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s := m.sessions[id]
|
||||
if s == nil || s.owner != owner {
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
if loginActive(s.view.State) && !time.Now().Before(s.view.ExpiresAt) {
|
||||
s.cancel()
|
||||
finishLogin(s, "expired", "授权已过期,请重新发起。")
|
||||
}
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Cancel(owner, id string) (DeviceLoginView, error) {
|
||||
m.mu.Lock()
|
||||
s := m.sessions[id]
|
||||
if s == nil || s.owner != owner {
|
||||
m.mu.Unlock()
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
if loginActive(s.view.State) {
|
||||
s.cancel()
|
||||
finishLogin(s, "cancelled", "")
|
||||
}
|
||||
m.mu.Unlock()
|
||||
// Do not acknowledge cancellation while the old CLI could still write tokens.
|
||||
timer := time.NewTimer(7 * time.Second)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-s.done:
|
||||
case <-timer.C:
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func finishLogin(s *deviceLogin, state, message string) {
|
||||
s.view.State = state
|
||||
s.view.Error = message
|
||||
s.view.VerificationURL = ""
|
||||
s.view.UserCode = ""
|
||||
}
|
||||
|
||||
var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;]*[A-Za-z]`)
|
||||
var challengeCode = regexp.MustCompile(`(?:授权码|User code|User Code)\s*[::]\s*([A-Za-z0-9-]{4,32})`)
|
||||
var challengeExpiry = regexp.MustCompile(`(?:将在\s*|expires in\s*)([0-9]+)\s*(?:秒|seconds)`)
|
||||
|
||||
func safeDeviceURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && u.Scheme == "https" && u.Host == "login.dingtalk.com" && u.User == nil && u.Fragment == "" && u.Path == "/oauth2/device/verify.htm"
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) observe(s *deviceLogin, line string) {
|
||||
line = strings.TrimSpace(ansiEscape.ReplaceAllString(line, ""))
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if match := challengeCode.FindStringSubmatch(line); len(match) == 2 {
|
||||
s.view.UserCode = match[1]
|
||||
}
|
||||
if match := challengeExpiry.FindStringSubmatch(line); len(match) == 2 {
|
||||
seconds, _ := strconv.Atoi(match[1])
|
||||
if seconds > 0 && seconds <= 1800 {
|
||||
s.view.ExpiresAt = time.Now().UTC().Add(time.Duration(seconds) * time.Second)
|
||||
}
|
||||
}
|
||||
if safeDeviceURL(line) {
|
||||
u, _ := url.Parse(line)
|
||||
if s.view.VerificationURL == "" || u.Query().Get("user_code") != "" {
|
||||
s.view.VerificationURL = line
|
||||
}
|
||||
}
|
||||
if s.view.State == "starting" && s.view.UserCode != "" && s.view.VerificationURL != "" {
|
||||
s.view.State = "waiting"
|
||||
}
|
||||
if strings.Contains(line, "Step 3:") {
|
||||
s.view.State = "verifying"
|
||||
}
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) run(ctx context.Context, s *deviceLogin) {
|
||||
defer close(s.done)
|
||||
defer s.cancel()
|
||||
command, err := m.runner.command(ctx, "auth", "login", "--device", "--no-browser", "--format", "json")
|
||||
if err != nil {
|
||||
m.failed(s, "DWS 登录程序不可用,请联系管理员检查服务配置。")
|
||||
return
|
||||
}
|
||||
command.Env = append(command.Env, "DWS_LANG=zh", "NO_COLOR=1", "TERM=dumb")
|
||||
command.Stdout = io.Discard
|
||||
stderr, err := command.StderrPipe()
|
||||
if err != nil {
|
||||
m.failed(s, "无法启动 DWS 授权,请重试。")
|
||||
return
|
||||
}
|
||||
if err = command.Start(); err != nil {
|
||||
m.failed(s, "无法启动 DWS 授权,请检查凭据目录权限。")
|
||||
return
|
||||
}
|
||||
scanner := bufio.NewScanner(stderr)
|
||||
scanner.Buffer(make([]byte, 4096), 64*1024)
|
||||
for scanner.Scan() {
|
||||
m.observe(s, scanner.Text())
|
||||
}
|
||||
if scanner.Err() != nil {
|
||||
s.cancel()
|
||||
}
|
||||
err = command.Wait()
|
||||
m.mu.Lock()
|
||||
active := loginActive(s.view.State)
|
||||
m.mu.Unlock()
|
||||
if !active {
|
||||
return
|
||||
}
|
||||
if err != nil || ctx.Err() != nil {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) || !time.Now().Before(s.view.ExpiresAt) {
|
||||
finishLogin(s, "expired", "授权已过期,请重新发起。")
|
||||
} else {
|
||||
finishLogin(s, "failed", "DWS 授权未完成,请重试;若组织未开通 CLI 数据权限,请联系钉钉管理员。")
|
||||
}
|
||||
return
|
||||
}
|
||||
// A process exit alone is not proof that usable credentials were persisted.
|
||||
checkCtx, cancel := context.WithTimeout(m.ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
status, statusErr := ReadCredentialStatus(checkCtx, m.runner)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if statusErr != nil || !status.Authenticated || !status.RefreshTokenValid || !status.StatusKnown {
|
||||
finishLogin(s, "failed", "授权结束,但未读到有效 DWS 凭据,请重新授权。")
|
||||
} else {
|
||||
finishLogin(s, "succeeded", "")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) failed(s *deviceLogin, message string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if loginActive(s.view.State) {
|
||||
finishLogin(s, "failed", message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func deviceFixture(t *testing.T) (*DeviceLoginManager, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
binary := filepath.Join(root, "dws")
|
||||
script := `#!/usr/bin/env python3
|
||||
import sys,time,pathlib,json,os
|
||||
root=pathlib.Path(` + strconv.Quote(root) + `)
|
||||
a=sys.argv[1:]
|
||||
if a==['auth','login','--device','--no-browser','--format','json']:
|
||||
(root/'pid').write_text(str(os.getpid()))
|
||||
print(' 授权码: TEST-CODE',file=sys.stderr,flush=True)
|
||||
print('授权码将在 900 秒后过期。',file=sys.stderr,flush=True)
|
||||
print('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE',file=sys.stderr,flush=True)
|
||||
print('https://login.dingtalk.com/oauth2/device/verify.htm',file=sys.stderr,flush=True)
|
||||
print('never-expose-this-marker',file=sys.stderr,flush=True)
|
||||
while not (root/'finish').exists(): time.sleep(.01)
|
||||
if (root/'fail').exists(): sys.exit(1)
|
||||
elif a==['auth','status','--readonly','--format','json']:
|
||||
print(json.dumps({'authenticated':not (root/'invalid').exists(),'refresh_token_valid':True,'corp_name':'测试组织','user_name':'测试账号','access_token':'never-expose-this-marker'}))
|
||||
else: sys.exit(9)
|
||||
`
|
||||
if err := os.WriteFile(binary, []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
return NewDeviceLoginManager(ctx, ExecRunner{Binary: binary}), root
|
||||
}
|
||||
func awaitDevice(t *testing.T, m *DeviceLoginManager, id, state string) DeviceLoginView {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
v, e := m.Get("owner", id)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if v.State == state {
|
||||
return v
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
v, _ := m.Get("owner", id)
|
||||
t.Fatalf("state=%s want=%s error=%s", v.State, state, v.Error)
|
||||
return v
|
||||
}
|
||||
func TestDeviceLoginUsesOfficialChallengeAndSharedCLI(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
initial, err := m.Start("owner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if initial.State != "starting" {
|
||||
t.Fatal(initial)
|
||||
}
|
||||
waiting := awaitDevice(t, m, initial.ID, "waiting")
|
||||
if waiting.UserCode != "TEST-CODE" || !strings.Contains(waiting.VerificationURL, "user_code=TEST-CODE") {
|
||||
t.Fatal("missing complete official challenge")
|
||||
}
|
||||
if _, err = m.Start("other"); !errors.Is(err, ErrLoginBusy) {
|
||||
t.Fatal("parallel logins may overwrite shared credentials")
|
||||
}
|
||||
duplicate, _ := m.Start("owner")
|
||||
if duplicate.ID != initial.ID {
|
||||
t.Fatal("duplicate start was not idempotent")
|
||||
}
|
||||
if _, err = m.Get("other", initial.ID); !errors.Is(err, ErrLoginNotFound) {
|
||||
t.Fatal("challenge leaked to another owner")
|
||||
}
|
||||
if _, err = m.Cancel("other", initial.ID); !errors.Is(err, ErrLoginNotFound) {
|
||||
t.Fatal("foreign cancellation permitted")
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(root, "finish"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := awaitDevice(t, m, initial.ID, "succeeded")
|
||||
raw, _ := json.Marshal(done)
|
||||
if done.UserCode != "" || done.VerificationURL != "" || strings.Contains(string(raw), "never-expose") {
|
||||
t.Fatal("completed session retained sensitive output")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginCancellationClearsChallenge(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
v, _ := m.Start("owner")
|
||||
awaitDevice(t, m, v.ID, "waiting")
|
||||
closed, err := m.Cancel("owner", v.ID)
|
||||
if err != nil || closed.State != "cancelled" || closed.UserCode != "" || closed.VerificationURL != "" {
|
||||
t.Fatal(closed, err)
|
||||
}
|
||||
pidBytes, err := os.ReadFile(filepath.Join(root, "pid"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pid, _ := strconv.Atoi(string(pidBytes))
|
||||
if syscall.Kill(pid, 0) == nil {
|
||||
t.Fatal("cancel returned while credential-writing process was still running")
|
||||
}
|
||||
again, _ := m.Get("owner", v.ID)
|
||||
if again.State != "cancelled" {
|
||||
t.Fatal("late process exit overwrote cancellation")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginRejectsExitWithoutPersistedCredentials(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
os.WriteFile(filepath.Join(root, "invalid"), nil, 0600)
|
||||
os.WriteFile(filepath.Join(root, "finish"), nil, 0600)
|
||||
v, _ := m.Start("owner")
|
||||
done := awaitDevice(t, m, v.ID, "failed")
|
||||
if !strings.Contains(done.Error, "未读到有效") {
|
||||
t.Fatal("successful exit was treated as authenticated")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginFailureIsRedactedAndRetryable(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
os.WriteFile(filepath.Join(root, "fail"), nil, 0600)
|
||||
os.WriteFile(filepath.Join(root, "finish"), nil, 0600)
|
||||
v, _ := m.Start("owner")
|
||||
done := awaitDevice(t, m, v.ID, "failed")
|
||||
if strings.Contains(done.Error, "never-expose") || done.Error == "" {
|
||||
t.Fatal("raw CLI output or missing error")
|
||||
}
|
||||
retry, e := m.Start("owner")
|
||||
if e != nil || retry.ID == v.ID {
|
||||
t.Fatal("cannot retry failed authorization")
|
||||
}
|
||||
}
|
||||
func TestDeviceChallengeRejectsUntrustedLinksAndExpires(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
_ = root
|
||||
s := &deviceLogin{view: DeviceLoginView{State: "starting", ExpiresAt: time.Now().Add(time.Minute)}, cancel: func() {}}
|
||||
m.observe(s, "授权码: TEST-CODE")
|
||||
for _, link := range []string{"http://login.dingtalk.com/oauth2/device/verify.htm", "https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm", "https://user:pass@login.dingtalk.com/oauth2/device/verify.htm", "javascript:alert(1)", "https://login.dingtalk.com/other"} {
|
||||
m.observe(s, link)
|
||||
}
|
||||
if s.view.State != "starting" || s.view.VerificationURL != "" {
|
||||
t.Fatal("untrusted link accepted")
|
||||
}
|
||||
s.view.ID = "test-expired"
|
||||
s.owner = "owner"
|
||||
s.view.ExpiresAt = time.Now().Add(-time.Second)
|
||||
m.sessions[s.view.ID] = s
|
||||
got, e := m.Get("owner", s.view.ID)
|
||||
if e != nil || got.State != "expired" || got.UserCode != "" {
|
||||
t.Fatal("expired challenge retained")
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
|
||||
// KnowledgeBase 是一个钉钉知识库(wiki 空间)。URL 是 alidocs 空间链接,直接可用于登记来源。
|
||||
type KnowledgeBase struct {
|
||||
Registered bool `json:"registered"`
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
SpaceType string `json:"space_type"`
|
||||
@@ -30,6 +31,7 @@ type KnowledgeBase struct {
|
||||
|
||||
// DriveSpace 是一个钉盘空间(我的文件 = mySpace;组织空间 = orgSpace)。
|
||||
type DriveSpace struct {
|
||||
Registered bool `json:"registered"`
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
RootFolderID string `json:"root_folder_id,omitempty"`
|
||||
@@ -38,6 +40,7 @@ type DriveSpace struct {
|
||||
|
||||
// Result 是一次发现的结果。
|
||||
type Result struct {
|
||||
Identity string `json:"identity,omitempty"`
|
||||
KnowledgeBases []KnowledgeBase `json:"knowledge_bases"`
|
||||
DriveSpaces []DriveSpace `json:"drive_spaces"`
|
||||
// KnowledgeNotice / DriveNotice 说明「这一类为什么不全」:权限不足、未登录、或被上限截断。
|
||||
@@ -70,21 +73,26 @@ func SpaceListArgs(spaceType string) []string {
|
||||
// 知识库整体列不出来 → 返回 ErrUnavailable(页面必须提示「列不出来」,不能装成空列表)。
|
||||
// 单独一类失败、钉盘失败、或结果被上限截断 → 只丢那一部分,把原因写进对应的 Notice。
|
||||
func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result := Result{FetchedAt: time.Now().UTC()}
|
||||
result := Result{FetchedAt: time.Now().UTC(), KnowledgeBases: []KnowledgeBase{}, DriveSpaces: []DriveSpace{}}
|
||||
successful := 0
|
||||
causes := []error{}
|
||||
|
||||
failures := make([]string, 0, len(knowledgeSpaceTypes))
|
||||
seenKnowledge := map[string]bool{}
|
||||
for _, spaceType := range knowledgeSpaceTypes {
|
||||
raw, err := runner.RunDWS(ctx, SpaceListArgs(spaceType)...)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
failures = append(failures, describe(spaceType, failureCause(raw, err)))
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
bases, notice, err := parseKnowledgeBases(raw, spaceType)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
failures = append(failures, describe(spaceType, failureCause(raw, err)))
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
successful++
|
||||
if notice != "" {
|
||||
result.KnowledgeNotice = notice
|
||||
}
|
||||
@@ -96,9 +104,6 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result.KnowledgeBases = append(result.KnowledgeBases, base)
|
||||
}
|
||||
}
|
||||
if len(result.KnowledgeBases) == 0 && len(failures) > 0 {
|
||||
return result, fmt.Errorf("%w: %s", ErrUnavailable, strings.Join(failures, ";"))
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
result.KnowledgeNotice = strings.Join(append([]string{result.KnowledgeNotice}, failures...), ";")
|
||||
}
|
||||
@@ -107,14 +112,17 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
for _, spaceType := range []string{"mySpace", "orgSpace"} {
|
||||
raw, err := runner.RunDWS(ctx, "wiki", "space", "list", "--type", spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = err.Error()
|
||||
result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限"
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
spaces, err := parseDriveSpaces(raw, spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = err.Error()
|
||||
result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限"
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
successful++
|
||||
for _, space := range spaces {
|
||||
if seenDrive[space.SpaceType+":"+space.SpaceID] {
|
||||
continue
|
||||
@@ -123,11 +131,21 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result.DriveSpaces = append(result.DriveSpaces, space)
|
||||
}
|
||||
}
|
||||
if successful == 0 && len(causes) > 0 {
|
||||
return result, fmt.Errorf("%w: %w", ErrUnavailable, errors.Join(causes...))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func describe(scope string, err error) string {
|
||||
return scope + ":" + err.Error()
|
||||
reason := "读取失败,请重试"
|
||||
if errors.Is(err, ErrCredentials) {
|
||||
reason = "DWS 授权已失效"
|
||||
}
|
||||
if errors.Is(err, ErrPermission) {
|
||||
reason = "当前范围权限不足"
|
||||
}
|
||||
return scope + ":" + reason
|
||||
}
|
||||
|
||||
// parseKnowledgeBases 解析 `dws wiki +space-list`:
|
||||
|
||||
@@ -127,7 +127,7 @@ func TestDiscoverKeepsKnowledgeBasesWhenDriveIsDenied(t *testing.T) {
|
||||
if len(result.DriveSpaces) != 0 {
|
||||
t.Fatalf("drive spaces = %d, want 0", len(result.DriveSpaces))
|
||||
}
|
||||
if !strings.Contains(result.DriveNotice, "permission denied") {
|
||||
if !strings.Contains(result.DriveNotice, "权限") {
|
||||
t.Fatalf("drive notice = %q", result.DriveNotice)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,8 @@ type ExecRunner struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// RunDWS 运行 `dws <args…>` 并返回 stdout。
|
||||
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
|
||||
// command keeps device login and source reads on one credential environment.
|
||||
func (r ExecRunner) command(ctx context.Context, args ...string) (*exec.Cmd, error) {
|
||||
binary := r.Binary
|
||||
if binary == "" {
|
||||
binary = os.Getenv("DWS_BIN")
|
||||
@@ -32,14 +32,24 @@ func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error)
|
||||
}
|
||||
binary = found
|
||||
}
|
||||
command := exec.CommandContext(ctx, binary, args...)
|
||||
command.Env = dwsEnv()
|
||||
command.WaitDelay = 2 * time.Second
|
||||
return command, nil
|
||||
}
|
||||
|
||||
// RunDWS uses the same executable and credential environment as device login.
|
||||
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
|
||||
timeout := r.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 25 * time.Second
|
||||
}
|
||||
runCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
command := exec.CommandContext(runCtx, binary, args...)
|
||||
command.Env = dwsEnv()
|
||||
command, err := r.command(runCtx, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var stdout, stderr bytes.Buffer
|
||||
command.Stdout = &stdout
|
||||
command.Stderr = &stderr
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrCredentials = errors.New("DWS authorization required")
|
||||
var ErrPermission = errors.New("DWS directory permission denied")
|
||||
|
||||
// failureCause inspects only structured CLI errors; no upstream text is returned.
|
||||
func failureCause(raw []byte, cause error) error {
|
||||
var v struct {
|
||||
Error struct {
|
||||
Type string `json:"type"`
|
||||
Code any `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(raw, &v) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
text := strings.ToLower(v.Error.Type + " " + fmt.Sprint(v.Error.Code) + " " + v.Error.Message)
|
||||
for _, key := range []string{"permission", "forbidden", "scope", "access denied", "权限", "403"} {
|
||||
if strings.Contains(text, key) {
|
||||
return ErrPermission
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"unauth", "not_logged_in", "not logged", "login_required", "login required", "authentication", "auth_required", "credential", "token_expired", "invalid_token", "token expired", "invalid_grant", "未登录", "授权已过期", "授权失效"} {
|
||||
if strings.Contains(text, key) {
|
||||
return ErrCredentials
|
||||
}
|
||||
}
|
||||
if errors.Is(cause, ErrCredentials) || errors.Is(cause, ErrPermission) {
|
||||
return cause
|
||||
}
|
||||
return ErrUnavailable
|
||||
}
|
||||
@@ -107,6 +107,9 @@ func classifyRole(method, path string) string {
|
||||
if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") {
|
||||
return roleAdmin
|
||||
}
|
||||
if strings.HasPrefix(path, "/api/v1/dws-login") || strings.HasPrefix(path, "/api/v1/pp-connection") || strings.HasPrefix(path, "/api/v1/dingtalk-spaces") || strings.HasPrefix(path, "/api/v1/dingtalk-session") {
|
||||
return roleAdmin
|
||||
}
|
||||
if method == http.MethodGet {
|
||||
return roleViewer
|
||||
}
|
||||
@@ -138,6 +141,11 @@ func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// 「知识库绑定」saves a connection (address + key) and both bindings for one
|
||||
// environment in one write: same authority as the annotation binding.
|
||||
if strings.HasPrefix(path, "/api/v1/kb-bindings") && 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 {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
)
|
||||
|
||||
// BackupInventoryReader 读取宿主采集器写出的元数据快照。它与 SSH 主机计划读回完全独立:
|
||||
// 快照缺失/陈旧不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
|
||||
type BackupInventoryReader interface {
|
||||
Available() bool
|
||||
Snapshot(context.Context) backupinventory.Snapshot
|
||||
}
|
||||
|
||||
// handleBackupInventory 返回宿主采集器快照里的批次、子库路径与容量。
|
||||
// 未接线/快照缺失/陈旧/不完整/路径不一致都作为 200 的字段返回,由页面区分原因;
|
||||
// 只有投影本身失败才 500。
|
||||
func (config Config) handleBackupInventory(w http.ResponseWriter, r *http.Request) {
|
||||
snapshot := config.BackupInventory.Snapshot(r.Context())
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": snapshot})
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
)
|
||||
|
||||
type fakeBackupInventory struct {
|
||||
snapshot backupinventory.Snapshot
|
||||
}
|
||||
|
||||
func (fake fakeBackupInventory) Available() bool { return fake.snapshot.Wired }
|
||||
|
||||
func (fake fakeBackupInventory) Snapshot(context.Context) backupinventory.Snapshot {
|
||||
return fake.snapshot
|
||||
}
|
||||
|
||||
func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
||||
actual := int64(1024)
|
||||
databaseActual := int64(512)
|
||||
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
|
||||
Wired: true,
|
||||
Root: "/srv/kb-backups/rds-logical",
|
||||
HostRoot: "/srv/kb-backups/rds-logical",
|
||||
Source: "weknora-test:/srv/kb-backups/rds-logical",
|
||||
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
|
||||
Mount: backupinventory.MountInfo{
|
||||
MountVerified: true,
|
||||
ReadOnly: true,
|
||||
Evidence: "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4)",
|
||||
},
|
||||
Capacity: backupinventory.Capacity{Measured: true, TotalBytes: 100, FreeBytes: 40, AvailableBytes: 35, UsedBytes: 60},
|
||||
Batches: []backupinventory.Batch{{
|
||||
Stamp: "20261118T193001Z",
|
||||
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
ManifestState: backupinventory.ManifestOK,
|
||||
ActualBytes: &actual,
|
||||
Databases: []backupinventory.Database{{
|
||||
Name: "weknora_v090prod",
|
||||
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
Present: true,
|
||||
ActualBytes: &databaseActual,
|
||||
}},
|
||||
}},
|
||||
Totals: backupinventory.Totals{BatchCount: 1, ActualBytes: &actual, LatestStamp: "20261118T193001Z", Complete: true},
|
||||
}}}
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
Data backupinventory.Snapshot `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !payload.Data.Wired || !payload.Data.Mount.MountVerified || !payload.Data.Capacity.Measured {
|
||||
t.Fatalf("接线/挂载/容量字段丢失: %+v", payload.Data)
|
||||
}
|
||||
if len(payload.Data.Batches) != 1 ||
|
||||
payload.Data.Batches[0].Databases[0].HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
|
||||
t.Fatalf("批次/子库真实路径丢失: %+v", payload.Data.Batches)
|
||||
}
|
||||
if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
|
||||
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
|
||||
config := Config{BackupInventory: backupinventory.New(backupinventory.Config{})}
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("未接线不应 500: %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
Data backupinventory.Snapshot `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Data.Wired || payload.Data.Error == "" || payload.Data.Batches == nil {
|
||||
t.Fatalf("未接线必须给原因且批次为空数组: %+v", payload.Data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Credential events are committed with their secret revision in one atomic file.
|
||||
// Merge them into the existing audit view without copying secrets into SQL.
|
||||
func combinedSourceAudit(ctx context.Context, reader sourceAuditReader, manager *ppauth.Manager, limit, offset int) (postgresstore.SourceAuditPage, error) {
|
||||
if manager == nil {
|
||||
return reader.ListSourceAudit(ctx, limit, offset)
|
||||
}
|
||||
events, err := manager.Events(ctx)
|
||||
if err != nil {
|
||||
return postgresstore.SourceAuditPage{}, err
|
||||
}
|
||||
if len(events) == 0 {
|
||||
return reader.ListSourceAudit(ctx, limit, offset)
|
||||
}
|
||||
start := offset - len(events)
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
rows := make([]postgresstore.SourceAuditItem, 0, limit+len(events))
|
||||
total := 0
|
||||
for next := start; len(rows) < limit+len(events); {
|
||||
take := limit + len(events) - len(rows)
|
||||
if take > 100 {
|
||||
take = 100
|
||||
}
|
||||
page, e := reader.ListSourceAudit(ctx, take, next)
|
||||
if e != nil {
|
||||
return postgresstore.SourceAuditPage{}, e
|
||||
}
|
||||
total = page.Total
|
||||
rows = append(rows, page.Items...)
|
||||
next += len(page.Items)
|
||||
if next >= total || len(page.Items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, e := range events {
|
||||
rows = append(rows, postgresstore.SourceAuditItem{ID: e.ID, ConnectionID: "", SourceName: e.SourceName, Action: e.Action, Actor: e.Actor, CreatedAt: e.CreatedAt, Detail: e.Detail})
|
||||
}
|
||||
sort.SliceStable(rows, func(i, j int) bool {
|
||||
if rows[i].CreatedAt.Equal(rows[j].CreatedAt) {
|
||||
return rows[i].ID > rows[j].ID
|
||||
}
|
||||
return rows[i].CreatedAt.After(rows[j].CreatedAt)
|
||||
})
|
||||
skip := offset - start
|
||||
if skip > len(rows) {
|
||||
skip = len(rows)
|
||||
}
|
||||
end := skip + limit
|
||||
if end > len(rows) {
|
||||
end = len(rows)
|
||||
}
|
||||
return postgresstore.SourceAuditPage{Items: rows[skip:end], Total: total + len(events), Limit: limit, Offset: offset}, nil
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -25,25 +24,16 @@ func listDingtalkSources(w http.ResponseWriter, r *http.Request, config Config)
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
lister := config.DingtalkSources
|
||||
if lister == nil {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"})
|
||||
identity, _ := requireSessionIdentity(w, r)
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, 403, map[string]string{"error": "需要管理员身份列举数据源"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
result, err := availableDWS(ctx, config)
|
||||
if err != nil {
|
||||
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
|
||||
// 环境问题(dws 未登录 / 权限不足 / 二进制缺失):页面显示"暂时列不出来",
|
||||
// 不是平台故障,也不该把内部错误细节当 500 抛出去。
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"error": "dingtalk_discovery_unavailable",
|
||||
"hint": "dws 未登录或缺少租户目录读权限;请先刷新钉钉会话,或让管理员检查 dws 凭据。",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list dingtalk sources"})
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": result})
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestListDingtalkSourcesReportsEnvironmentProblemsAsUnavailable(t *testing.T
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("unavailable = %d, want 503 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), "dingtalk_discovery_unavailable") {
|
||||
if !strings.Contains(rec.Body.String(), "dws_unavailable") {
|
||||
t.Fatalf("body = %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,59 +2,42 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
func TestDWSNameConflictIsNotASuccessfulRegistration(t *testing.T) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: postgresstore.ErrDingtalkSpaceNameTaken}
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "wiki", SpaceID: "testspace"}}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-spaces", nil)
|
||||
registerSpaceThroughDWS(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op")
|
||||
if rec.Code != http.StatusConflict {
|
||||
req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", nil)
|
||||
registerDWSOnlySpace(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op")
|
||||
if rec.Code != 409 {
|
||||
t.Fatalf("name conflict must not claim success: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// 登记走 dws 不是侧车:解析出来的键、名称、根节点直接决定新来源的确定性 id。
|
||||
func TestResolveSpaceViaDWSUsesTheSpaceCredentialsAlreadyHeld(t *testing.T) {
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{
|
||||
KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{
|
||||
{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"},
|
||||
{Name: "视觉文档", SpaceID: "9JOGO9EEOMLMWX4Q"},
|
||||
},
|
||||
DriveSpaces: []dingtalkdiscovery.DriveSpace{
|
||||
{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a"},
|
||||
},
|
||||
}}
|
||||
rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(
|
||||
context.Background(), lister, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q"))
|
||||
if !ok || rootKey != "space-9JOGOLBQndOyaz4Q" || name != "国内技术支持管理" || rootID != "9JOGOLBQndOyaz4Q" || spaceID != "9JOGOLBQndOyaz4Q" {
|
||||
t.Fatalf("knowledge base resolved as key=%q name=%q root=%q space=%q ok=%v", rootKey, name, rootID, spaceID, ok)
|
||||
result := dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"}}, DriveSpaces: []dingtalkdiscovery.DriveSpace{{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "drive-root"}}}
|
||||
input, err := resolveDWS(result, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q"))
|
||||
if err != nil || input.RootKey != "space-9JOGOLBQndOyaz4Q" || input.Name != "国内技术支持管理" || input.RootID != "9JOGOLBQndOyaz4Q" || input.SpaceID != "9JOGOLBQndOyaz4Q" {
|
||||
t.Fatalf("wiki resolution=%+v %v", input, err)
|
||||
}
|
||||
|
||||
// 钉盘的根是 rootFolderId,不是空间 id:抓取侧按它遍历。
|
||||
rootKey, _, rootID, _, ok = resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("102571304"))
|
||||
if !ok || rootID != "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a" || rootKey != "space-102571304" {
|
||||
t.Fatalf("drive space resolved as key=%q root=%q ok=%v", rootKey, rootID, ok)
|
||||
input, err = resolveDWS(result, dingtalkdiscovery.SpaceURL("102571304"))
|
||||
if err != nil || input.RootID != "drive-root" || input.RootKey != "space-102571304" {
|
||||
t.Fatalf("drive resolution=%+v %v", input, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSpaceViaDWSLeavesUnknownSpacesToTheFallback(t *testing.T) {
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{}}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("unknownspace1")); ok {
|
||||
t.Fatal("an unknown space must not resolve")
|
||||
func TestResolveDWSRejectsUnknownAndUnwiredWithoutBrowserFallback(t *testing.T) {
|
||||
if _, err := resolveDWS(dingtalkdiscovery.Result{}, dingtalkdiscovery.SpaceURL("unknownspace1")); err == nil {
|
||||
t.Fatal("unknown space resolved")
|
||||
}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), nil, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")); ok {
|
||||
t.Fatal("without a lister nothing can resolve")
|
||||
if _, err := availableDWS(context.Background(), Config{}); err == nil {
|
||||
t.Fatal("unwired service resolved")
|
||||
}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, "not-a-space-url"); ok {
|
||||
t.Fatal("a URL without a space id must not resolve")
|
||||
if _, err := resolveDWS(dingtalkdiscovery.Result{}, "not-a-space-url"); err == nil {
|
||||
t.Fatal("invalid space resolved")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,7 @@ package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -12,10 +10,6 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// DingTalk login proxy. The scan-code login itself lives in the
|
||||
@@ -102,86 +96,15 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "url is required"})
|
||||
return
|
||||
}
|
||||
// dws 已经持有有效凭据(access 自动续期、refresh 一个月),登记也该走它:
|
||||
// 只有 dws 解析不出这个空间时,才回落到老的扫码侧车。
|
||||
if registered, ok := registerSpaceThroughDWS(w, r, config, strings.TrimSpace(input.URL), operationID); ok || registered {
|
||||
return
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"url": strings.TrimSpace(input.URL)})
|
||||
status, data := proxyDingtalk(http.MethodPost, "/spaces/add", payload)
|
||||
if status != http.StatusOK {
|
||||
if status == 0 {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "dingtalk_login_unavailable"})
|
||||
return
|
||||
}
|
||||
// Relay the sidecar's error (login_required / space_not_found /
|
||||
// name_conflict) verbatim; bodies are machine codes, no secrets.
|
||||
writeProxyResult(w, status, data)
|
||||
return
|
||||
}
|
||||
var resolved struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
Root string `json:"root"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &resolved); err != nil || resolved.Key == "" || resolved.Name == "" || resolved.Root == "" {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "invalid sidecar registration response"})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
|
||||
return
|
||||
}
|
||||
spaceID := extractDingtalkSpaceID(input.URL)
|
||||
if spaceID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid space url"})
|
||||
return
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(), Actor: actorFor(r),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_name_conflict",
|
||||
"hint": "已有同名来源仍在使用(未下架):请先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间。",
|
||||
})
|
||||
return
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_identity_conflict",
|
||||
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试;若仍失败,把该来源「去掉来源」后再登记。",
|
||||
})
|
||||
return
|
||||
case err != nil:
|
||||
// 真正的数据库/内部故障不能伪装成"冲突":换个 500 才有人去查日志。
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
|
||||
return
|
||||
}
|
||||
// First scan is enqueued right away: the new connection has no catalog
|
||||
// head yet, so the generic sources/{id}/refresh endpoint would 404 until
|
||||
// the first snapshot exists.
|
||||
if enqueuer, ok := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); ok {
|
||||
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(r.Context(), governance.CatalogSource{
|
||||
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: resolved.Name,
|
||||
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
|
||||
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
|
||||
}
|
||||
}
|
||||
log.Printf("dingtalk space %q registered as connection %s by %s", resolved.Name, connectionID, actorFor(r))
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
|
||||
"connection_id": connectionID, "name": resolved.Name,
|
||||
}})
|
||||
registerDWSOnlySpace(w, r, config, strings.TrimSpace(input.URL), operationID)
|
||||
}
|
||||
|
||||
var dingtalkSpacePattern = regexp.MustCompile(`/spaces/([A-Za-z0-9_-]+)`)
|
||||
|
||||
func extractDingtalkSpaceID(raw string) string {
|
||||
if !validDingtalkURL(raw) {
|
||||
return ""
|
||||
}
|
||||
match := dingtalkSpacePattern.FindStringSubmatch(raw)
|
||||
if len(match) == 2 {
|
||||
return match[1]
|
||||
@@ -244,76 +167,3 @@ func proxyDingtalk(method, path string, body []byte) (int, []byte) {
|
||||
}
|
||||
return resp.StatusCode, data
|
||||
}
|
||||
|
||||
// resolveSpaceViaDWS 用 dws 列举结果定位一个空间:返回确定性登记键、名称与根节点。
|
||||
// 认不出就 ok=false,调用方回落到老的扫码侧车(历史空间仍能被登记)。
|
||||
func resolveSpaceViaDWS(ctx context.Context, lister dingtalkSourcesLister, rawURL string) (rootKey, name, rootID, spaceID string, ok bool) {
|
||||
spaceID = extractDingtalkSpaceID(rawURL)
|
||||
if lister == nil || spaceID == "" {
|
||||
return "", "", "", "", false
|
||||
}
|
||||
discovered, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
return "", "", "", "", false
|
||||
}
|
||||
for _, base := range discovered.KnowledgeBases {
|
||||
if base.SpaceID == spaceID {
|
||||
// 知识库:URL 里的 id 就是空间 id,抓取侧按 spaces/<id> 匹配。
|
||||
return "space-" + spaceID, base.Name, spaceID, spaceID, true
|
||||
}
|
||||
}
|
||||
for _, space := range discovered.DriveSpaces {
|
||||
if space.SpaceID == spaceID && space.RootFolderID != "" {
|
||||
return "space-" + spaceID, space.Name, space.RootFolderID, spaceID, true
|
||||
}
|
||||
}
|
||||
return "", "", "", "", false
|
||||
}
|
||||
|
||||
// registerSpaceThroughDWS 用 dws 凭据直接登记来源,不再要求扫码会话。
|
||||
func registerSpaceThroughDWS(w http.ResponseWriter, r *http.Request, config Config, rawURL, operationID string) (bool, bool) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(ctx, config.DingtalkSources, rawURL)
|
||||
if !ok {
|
||||
return false, false
|
||||
}
|
||||
store, wired := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !wired {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
|
||||
return true, false
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(ctx, postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: rootKey, Name: name, SpaceID: spaceID, RootID: rootID, Now: config.Now(), Actor: actorFor(r),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源,但空间标识不一致;请核对已有来源,不能按名称判定添加成功。"})
|
||||
return true, false
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_identity_conflict",
|
||||
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试。",
|
||||
})
|
||||
return true, false
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
|
||||
return true, false
|
||||
}
|
||||
if enqueuer, wired := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); wired {
|
||||
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{
|
||||
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: name,
|
||||
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
|
||||
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
|
||||
}
|
||||
}
|
||||
log.Printf("dingtalk space %q registered as connection %s by %s (dws)", name, connectionID, actorFor(r))
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
|
||||
"connection_id": connectionID, "name": name,
|
||||
}})
|
||||
return true, true
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
@@ -123,7 +124,7 @@ func TestDingtalkSpaceRegistrationErrorClassification(t *testing.T) {
|
||||
|
||||
call := func(storeErr error) (int, string) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: storeErr}
|
||||
handler, err := NewHandler(Config{Store: store})
|
||||
handler, err := NewHandler(Config{Store: store, DingtalkSources: fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "公司级技术支持知识库", SpaceID: "9JOK9EEOMLMWX4Q"}}}}})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHandler() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
func registerDWSLoginRoutes(mux *http.ServeMux, config Config) {
|
||||
mux.HandleFunc("POST /api/v1/dws-login", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "start") })
|
||||
mux.HandleFunc("GET /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "get") })
|
||||
mux.HandleFunc("DELETE /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "cancel") })
|
||||
}
|
||||
|
||||
func handleDWSLogin(w http.ResponseWriter, r *http.Request, config Config, action string) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "需要管理员身份才能管理 DWS 授权"})
|
||||
return
|
||||
}
|
||||
if action != "get" {
|
||||
originOK := true
|
||||
if raw := r.Header.Get("Origin"); raw != "" {
|
||||
origin, err := url.Parse(raw)
|
||||
originOK = err == nil && origin.Host == r.Host && (origin.Scheme == "http" || origin.Scheme == "https")
|
||||
}
|
||||
if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != "dws-login" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "请从本平台的数据源配置页发起授权"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if config.DWSLogin == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "DWS 登录服务未接通,请联系管理员"})
|
||||
return
|
||||
}
|
||||
// Bind the challenge to this authenticated administrator and browser session.
|
||||
owner := identity.UserID + "/" + identity.SessionID
|
||||
var view dingtalkdiscovery.DeviceLoginView
|
||||
var err error
|
||||
switch action {
|
||||
case "start":
|
||||
view, err = config.DWSLogin.Start(owner)
|
||||
case "get":
|
||||
view, err = config.DWSLogin.Get(owner, r.PathValue("id"))
|
||||
case "cancel":
|
||||
view, err = config.DWSLogin.Cancel(owner, r.PathValue("id"))
|
||||
}
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, dingtalkdiscovery.ErrLoginNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "授权会话已结束或服务已重启,请重新发起"})
|
||||
case errors.Is(err, dingtalkdiscovery.ErrLoginBusy):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "另一位管理员正在授权,请稍后再试"})
|
||||
default:
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "无法发起 DWS 授权,请重试"})
|
||||
}
|
||||
return
|
||||
}
|
||||
if config.PPConnection != nil && (action != "get" || view.State == "succeeded" || view.State == "failed" || view.State == "expired") {
|
||||
if err := config.PPConnection.AuditOnce(r.Context(), "dws-"+view.ID+"-"+string(view.State), "钉钉账号(DWS)", "dws_authorization", identity.Username, "DWS 授权状态:"+string(view.State)); err != nil {
|
||||
if action == "start" {
|
||||
_, _ = config.DWSLogin.Cancel(owner, view.ID)
|
||||
}
|
||||
writeJSON(w, 503, map[string]string{"error": "授权审计写入失败,请重试"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if action != "get" {
|
||||
log.Printf("DWS authorization action=%s id=%s actor=%s", action, view.ID, identity.Username)
|
||||
}
|
||||
status := http.StatusOK
|
||||
if action == "start" {
|
||||
status = http.StatusAccepted
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"data": view})
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDWSLoginHTTPAuthenticationOwnershipAndOrigin(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
manager := dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{Binary: "/nonexistent/dws"})
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, DWSLogin: manager})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(method, path, role, session, origin, intent string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
if role != "" {
|
||||
r = r.WithContext(context.WithValue(r.Context(), sessionKey{}, sessionIdentity{UserID: "admin-user", Username: "tester", Role: role, SessionID: session}))
|
||||
}
|
||||
r.Header.Set("Origin", origin)
|
||||
r.Header.Set("X-Governance-Action", intent)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
for _, role := range []string{"", roleViewer, roleEngineer} {
|
||||
w := call("POST", "/api/v1/dws-login", role, "s1", "", "dws-login")
|
||||
if w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("role=%q status=%d", role, w.Code)
|
||||
}
|
||||
}
|
||||
for _, input := range [][2]string{{"", ""}, {"https://foreign.invalid", "dws-login"}} {
|
||||
w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", input[0], input[1])
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("origin/intent not enforced: %d", w.Code)
|
||||
}
|
||||
}
|
||||
w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", "", "dws-login")
|
||||
if w.Code != 202 || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("start=%d body=%s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Data dingtalkdiscovery.DeviceLoginView `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Data.ID == "" {
|
||||
t.Fatal("missing session", err)
|
||||
}
|
||||
path := "/api/v1/dws-login/" + body.Data.ID
|
||||
for _, method := range []string{"GET", "DELETE"} {
|
||||
w = call(method, path, roleAdmin, "other-session", "", "dws-login")
|
||||
if w.Code != 404 {
|
||||
t.Fatalf("foreign session %s=%d", method, w.Code)
|
||||
}
|
||||
w = call(method, path, roleEngineer, "s1", "", "dws-login")
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("engineer %s=%d", method, w.Code)
|
||||
}
|
||||
}
|
||||
w = call("GET", path, roleAdmin, "s1", "", "")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("get=%d", w.Code)
|
||||
}
|
||||
w = call("DELETE", path, roleAdmin, "s1", "", "dws-login")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("cancel=%d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDWSLoginRoutesAreAdminOnly(t *testing.T) {
|
||||
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
|
||||
for _, path := range []string{"/api/v1/dws-login", "/api/v1/dws-login/session-id"} {
|
||||
if got := classifyRole(method, path); got != roleAdmin {
|
||||
t.Errorf("%s %s role=%s; authorization artifacts must be admin-only", method, path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dwsSourceError struct {
|
||||
Status int
|
||||
Code, Hint string
|
||||
}
|
||||
|
||||
func (e *dwsSourceError) Error() string { return e.Hint }
|
||||
func writeDWSSourceError(w http.ResponseWriter, err error) {
|
||||
var e *dwsSourceError
|
||||
if errors.As(err, &e) {
|
||||
writeJSON(w, e.Status, map[string]string{"error": e.Code, "hint": e.Hint})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 500, map[string]string{"error": "dws_source_failed", "hint": "读取钉钉来源失败,请重试"})
|
||||
}
|
||||
func availableDWS(ctx context.Context, config Config) (dingtalkdiscovery.Result, error) {
|
||||
identity := ""
|
||||
if config.DingtalkSources == nil {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{501, "dws_unwired", "DWS 来源服务未接通"}
|
||||
}
|
||||
if reader, ok := config.DingtalkSources.(interface {
|
||||
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
|
||||
}); ok {
|
||||
status, err := reader.ReadDWSMetadata(ctx)
|
||||
if err != nil || !status.StatusKnown {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{503, "dws_status_unavailable", "暂时无法读取 DWS 授权状态,请重试"}
|
||||
}
|
||||
identity = status.Identity
|
||||
if !status.Authenticated && !status.RefreshTokenValid {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{401, "dws_login_required", "DWS 未登录或授权已失效,请重新授权"}
|
||||
}
|
||||
}
|
||||
result, err := config.DingtalkSources.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, dingtalkdiscovery.ErrCredentials) {
|
||||
return result, &dwsSourceError{401, "dws_login_required", "DWS 授权已失效,请重新授权"}
|
||||
}
|
||||
if errors.Is(err, dingtalkdiscovery.ErrPermission) {
|
||||
return result, &dwsSourceError{403, "dws_permission_denied", "当前 DWS 账号缺少目录读取权限"}
|
||||
}
|
||||
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
|
||||
return result, &dwsSourceError{503, "dws_unavailable", "DWS 目录暂时无法读取,请检查连接后重试"}
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
if identity != "" {
|
||||
reader := config.DingtalkSources.(interface {
|
||||
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
|
||||
})
|
||||
fresh, e := reader.ReadDWSMetadata(ctx)
|
||||
if e != nil {
|
||||
return result, &dwsSourceError{503, "dws_status_unavailable", "无法确认当前账号,请重试"}
|
||||
}
|
||||
if fresh.Identity != identity {
|
||||
return result, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"}
|
||||
}
|
||||
}
|
||||
result.Identity = identity
|
||||
if config.Store != nil {
|
||||
if page, e := config.Store.ListSourceConnections(ctx); e == nil {
|
||||
seen := map[string]bool{}
|
||||
for _, c := range page.Items {
|
||||
seen[c.ID] = true
|
||||
}
|
||||
for i, kb := range result.KnowledgeBases {
|
||||
in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + kb.SpaceID}
|
||||
result.KnowledgeBases[i].Registered = seen[in.ConnectionID()]
|
||||
}
|
||||
for i, space := range result.DriveSpaces {
|
||||
in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + space.SpaceID}
|
||||
result.DriveSpaces[i].Registered = seen[in.ConnectionID()]
|
||||
}
|
||||
}
|
||||
}
|
||||
if registry, ok := config.Store.(interface {
|
||||
RegisteredDingtalkSpaceIDs(context.Context) (map[string]bool, error)
|
||||
}); ok {
|
||||
ids, e := registry.RegisteredDingtalkSpaceIDs(ctx)
|
||||
if e != nil {
|
||||
return result, &dwsSourceError{503, "dws_registration_state_unavailable", "无法核对已接入空间,请重试"}
|
||||
}
|
||||
for i, kb := range result.KnowledgeBases {
|
||||
result.KnowledgeBases[i].Registered = ids[kb.SpaceID]
|
||||
}
|
||||
for i, space := range result.DriveSpaces {
|
||||
result.DriveSpaces[i].Registered = ids[space.SpaceID]
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func resolveDWS(result dingtalkdiscovery.Result, raw string) (postgresstore.RegisterDingtalkSpaceInput, error) {
|
||||
spaceID := extractDingtalkSpaceID(raw)
|
||||
if spaceID == "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"}
|
||||
}
|
||||
for _, base := range result.KnowledgeBases {
|
||||
if base.SpaceID == spaceID {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: base.Name, RootID: spaceID, SpaceID: spaceID}, nil
|
||||
}
|
||||
}
|
||||
for _, space := range result.DriveSpaces {
|
||||
if space.SpaceID == spaceID && space.RootFolderID != "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: space.Name, RootID: space.RootFolderID, SpaceID: spaceID}, nil
|
||||
}
|
||||
}
|
||||
if result.KnowledgeNotice != "" || result.DriveNotice != "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{503, "dws_scope_incomplete", "当前目录结果不完整,无法确认所选空间;请检查相应目录权限后重试"}
|
||||
}
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{409, "dws_space_not_visible", "当前 DWS 账号已看不到所选空间,请刷新范围或核对账号权限"}
|
||||
}
|
||||
func registerDWSOnlySpace(w http.ResponseWriter, r *http.Request, config Config, raw, operationID string) {
|
||||
if extractDingtalkSpaceID(raw) == "" {
|
||||
writeDWSSourceError(w, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := availableDWS(ctx, config)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity {
|
||||
writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"})
|
||||
return
|
||||
}
|
||||
input, err := resolveDWS(result, raw)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
input.Now = config.Now()
|
||||
input.Actor = actorFor(r)
|
||||
store, ok := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !ok {
|
||||
writeJSON(w, 503, map[string]string{"error": "registration_unavailable"})
|
||||
return
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(ctx, input)
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, 409, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源仍在使用:请核对空间身份,必要时先移除旧连接(原去掉来源操作)"})
|
||||
return
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, 409, map[string]string{"error": "space_identity_conflict", "hint": "登记键已指向另一个空间,请刷新后核对来源"})
|
||||
return
|
||||
case err != nil:
|
||||
writeJSON(w, 500, map[string]string{"error": "space_registration_failed"})
|
||||
return
|
||||
}
|
||||
queued := false
|
||||
if queue, ok := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); ok {
|
||||
_, _, err = queue.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: input.Name}, "dws-source-first:"+connectionID, config.Now().UTC())
|
||||
queued = err == nil
|
||||
}
|
||||
writeJSON(w, 201, map[string]any{"data": map[string]any{"connection_id": connectionID, "name": input.Name, "first_scan_queued": queued}})
|
||||
}
|
||||
func validateDWSSpace(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !credentialAdmin(w, r, "dingtalk-space") {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
URLs []string `json:"urls"`
|
||||
}
|
||||
if decodeJSONStrict(r, &input) != nil || len(input.URLs) == 0 || len(input.URLs) > 100 {
|
||||
writeJSON(w, 400, map[string]string{"error": "请选择有效的空间范围"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := availableDWS(ctx, config)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity {
|
||||
writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"})
|
||||
return
|
||||
}
|
||||
for _, raw := range input.URLs {
|
||||
if _, err := resolveDWS(result, raw); err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": map[string]any{"valid": true, "checked_at": config.Now().UTC(), "count": len(input.URLs)}})
|
||||
}
|
||||
func validDingtalkURL(raw string) bool {
|
||||
if !strings.Contains(raw, "://") {
|
||||
return true
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && u.Scheme == "https" && u.Host == "alidocs.dingtalk.com" && u.User == nil && u.Fragment == ""
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDWSRegistrationNeverFallsBackToBrowserSession(t *testing.T) {
|
||||
calls := 0
|
||||
sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(401) }))
|
||||
defer sidecar.Close()
|
||||
t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL)
|
||||
h, err := NewHandler(Config{Store: &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}}, DingtalkSources: fakeDingtalkSources{err: dingtalkdiscovery.ErrUnavailable}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", strings.NewReader(`{"url":"https://alidocs.dingtalk.com/i/spaces/valid-space-id/overview"}`))
|
||||
req.Header.Set("Idempotency-Key", "op-dws-only")
|
||||
req.Header.Set("X-Governance-Action", "dingtalk-space")
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if calls != 0 || rec.Code != 503 || !strings.Contains(rec.Body.String(), "dws_unavailable") {
|
||||
t.Fatalf("DWS failed: legacy calls=%d status=%d body=%s", calls, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
)
|
||||
|
||||
// KBBindingStore is the environment-scoped 「知识库绑定」capability. Save does
|
||||
// the real candidate read itself, so the HTTP layer decides no policy beyond
|
||||
// status/role.
|
||||
type KBBindingStore interface {
|
||||
List(context.Context) ([]kbbinding.View, error)
|
||||
Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error)
|
||||
Save(context.Context, string, kbbinding.SaveInput, string, time.Time) (kbbinding.View, error)
|
||||
ResolveBaseURL(context.Context, string) string
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
views, err := config.KBBindings.List(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load knowledge base bindings"})
|
||||
return
|
||||
}
|
||||
storageReady := false
|
||||
for _, view := range views {
|
||||
storageReady = storageReady || view.StorageReady
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "kb-bindings" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"})
|
||||
return
|
||||
}
|
||||
env := r.PathValue("environment")
|
||||
if !kbbinding.ValidEnvironment(env) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"})
|
||||
return
|
||||
}
|
||||
var input kbbinding.CatalogInput
|
||||
if err := decodeJSONStrict(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
catalog, err := config.KBBindings.Catalog(r.Context(), env, input)
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": catalog})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "kb-bindings" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"})
|
||||
return
|
||||
}
|
||||
env := r.PathValue("environment")
|
||||
if !kbbinding.ValidEnvironment(env) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"})
|
||||
return
|
||||
}
|
||||
var input kbbinding.SaveInput
|
||||
if err := decodeJSONStrict(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view, "operation": "saved"})
|
||||
}
|
||||
|
||||
func writeKBBindingError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, kbbinding.ErrInvalid):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "绑定参数不合法:请检查地址、密钥与内外库选择"})
|
||||
case errors.Is(err, kbbinding.ErrConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "该环境的绑定已被其他保存更新;草稿未写入,旧绑定保持不变,请重新读取后再试"})
|
||||
case errors.Is(err, kbbinding.ErrKeyForwarding):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址"})
|
||||
case errors.Is(err, kbbinding.ErrNotConfigured):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "这个地址还没有可用 API Key:请输入密钥或先选择已配置的连接"})
|
||||
case errors.Is(err, kbbinding.ErrStorage):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "独立安全存储未就绪(WEKNORA_BINDING_MASTER_KEY_FILE);未写入任何绑定"})
|
||||
case errors.Is(err, kbbinding.ErrRejected):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrRejected.Error()+":")})
|
||||
case errors.Is(err, kbbinding.ErrUnreachable):
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrUnreachable.Error()+":")})
|
||||
default:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
)
|
||||
|
||||
type fakeKBBindings struct {
|
||||
views []kbbinding.View
|
||||
catalog kbbinding.Catalog
|
||||
saveErr error
|
||||
catalogErr error
|
||||
lastSave kbbinding.SaveInput
|
||||
lastActor string
|
||||
}
|
||||
|
||||
func (fake *fakeKBBindings) List(context.Context) ([]kbbinding.View, error) {
|
||||
return fake.views, nil
|
||||
}
|
||||
func (fake *fakeKBBindings) Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error) {
|
||||
return fake.catalog, fake.catalogErr
|
||||
}
|
||||
func (fake *fakeKBBindings) Save(_ context.Context, _ string, input kbbinding.SaveInput, actor string, _ time.Time) (kbbinding.View, error) {
|
||||
fake.lastSave = input
|
||||
fake.lastActor = actor
|
||||
if fake.saveErr != nil {
|
||||
return kbbinding.View{}, fake.saveErr
|
||||
}
|
||||
return fake.views[0], nil
|
||||
}
|
||||
func (fake *fakeKBBindings) ResolveBaseURL(context.Context, string) string { return "" }
|
||||
|
||||
func kbBindingHandler(t *testing.T, store KBBindingStore) *Config {
|
||||
t.Helper()
|
||||
config := &Config{KBBindings: store, Now: func() time.Time { return time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) }}
|
||||
return config
|
||||
}
|
||||
|
||||
func TestKBBindingsReadNeverEchoesSecretsAndWriteRequiresIntent(t *testing.T) {
|
||||
store := &fakeKBBindings{views: []kbbinding.View{{
|
||||
Environment: kbbinding.EnvTest, Revision: 2, BaseURL: "https://weknora.test.example",
|
||||
KeyConfigured: true, KeySource: "sealed", InternalKBID: "kb-in", InternalKBName: "内部",
|
||||
ExternalKBID: "kb-out", ExternalKBName: "对外", Source: "web", StorageReady: true,
|
||||
}}}
|
||||
config := kbBindingHandler(t, store)
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindings(response, httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
body := response.Body.String()
|
||||
for _, forbidden := range []string{"api_key", "key_ciphertext", "sealed-key-value"} {
|
||||
if strings.Contains(body, forbidden) {
|
||||
t.Fatalf("read response exposes %q: %s", forbidden, body)
|
||||
}
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
|
||||
request.SetPathValue("environment", "test")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("save without intent status = %d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
|
||||
store := &fakeKBBindings{
|
||||
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}},
|
||||
saveErr: kbbinding.ErrConflict,
|
||||
}
|
||||
config := kbBindingHandler(t, store)
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "旧绑定保持不变") {
|
||||
t.Fatalf("conflict status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) {
|
||||
store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}}
|
||||
config := kbBindingHandler(t, store)
|
||||
body := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
|
||||
request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "HTTPS") {
|
||||
t.Fatalf("plain HTTP key entry status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("loopback catalog status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "typed-key") {
|
||||
t.Fatal("catalog response echoed the typed key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
||||
for _, path := range []string{"/api/v1/kb-bindings/test", "/api/v1/kb-bindings/test/catalog"} {
|
||||
if role := classifyRole(http.MethodPut, path); role != roleAdmin {
|
||||
t.Fatalf("PUT %s role = %s, want admin", path, role)
|
||||
}
|
||||
if role := classifyRole(http.MethodGet, "/api/v1/kb-bindings"); role != roleViewer {
|
||||
t.Fatalf("GET bindings role = %s, want viewer", role)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) {
|
||||
switch value := node.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range value {
|
||||
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" {
|
||||
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" && path != "components.schemas.KBBindingEnvironmentView.properties" && path != "components.schemas.KBCatalogInput.properties" && path != "components.schemas.KBBindingSaveInput.properties" {
|
||||
t.Fatalf("unapproved endpoint exposure at %s", path)
|
||||
}
|
||||
next := key
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
func credentialAdmin(w http.ResponseWriter, r *http.Request, action string) bool {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, 403, map[string]string{"error": "需要管理员身份管理来源凭据"})
|
||||
return false
|
||||
}
|
||||
if r.Method != "GET" {
|
||||
originOK := true
|
||||
if raw := r.Header.Get("Origin"); raw != "" {
|
||||
u, err := url.Parse(raw)
|
||||
originOK = err == nil && u.Host == r.Host && (u.Scheme == "http" || u.Scheme == "https")
|
||||
}
|
||||
if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != action {
|
||||
writeJSON(w, 403, map[string]string{"error": "请从本平台的数据源配置页操作"})
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func writePPError(w http.ResponseWriter, err error) {
|
||||
status := http.StatusBadRequest
|
||||
if errors.Is(err, ppauth.ErrConflict) {
|
||||
status = http.StatusConflict
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": err.Error()})
|
||||
}
|
||||
|
||||
func registerPPConnectionRoutes(mux *http.ServeMux, config Config) {
|
||||
for _, pattern := range []string{"GET /api/v1/pp-connection", "PUT /api/v1/pp-connection", "POST /api/v1/pp-connection/test"} {
|
||||
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !credentialAdmin(w, r, "pp-connection") {
|
||||
return
|
||||
}
|
||||
if config.PPConnection == nil {
|
||||
writeJSON(w, 503, map[string]string{"error": "PP 配置服务未接通,请联系管理员"})
|
||||
return
|
||||
}
|
||||
if r.Method == "GET" {
|
||||
v, err := config.PPConnection.View()
|
||||
if err != nil {
|
||||
writeJSON(w, 503, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": v})
|
||||
return
|
||||
}
|
||||
var draft ppauth.Draft
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 16384)
|
||||
if decodeJSONStrict(r, &draft) != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "PP 配置请求格式不正确"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second)
|
||||
defer cancel()
|
||||
if r.Method == "POST" {
|
||||
result, err := config.PPConnection.Test(ctx, draft, actorFor(r))
|
||||
if err != nil {
|
||||
writePPError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
return
|
||||
}
|
||||
result, err := config.PPConnection.Save(ctx, draft, actorFor(r))
|
||||
if err != nil {
|
||||
status := 400
|
||||
if errors.Is(err, ppauth.ErrConflict) {
|
||||
status = 409
|
||||
}
|
||||
if errors.Is(err, ppauth.ErrRejected) {
|
||||
status = 422
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"error": err.Error(), "data": result})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type noPPJobStore struct {
|
||||
*fakeJobStore
|
||||
queued int
|
||||
}
|
||||
|
||||
func (s *noPPJobStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) {
|
||||
s.queued++
|
||||
return s.fakeJobStore.Enqueue(ctx, request, now)
|
||||
}
|
||||
func TestPPHTTPRoundTripRechecksSaveAndNeverEnqueues(t *testing.T) {
|
||||
probes := 0
|
||||
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c ppauth.Credentials) ppauth.Observation {
|
||||
probes++
|
||||
return ppauth.Observation{State: "valid", Message: "认证有效 · 目录可读"}
|
||||
}}
|
||||
store := &noPPJobStore{fakeJobStore: &fakeJobStore{}}
|
||||
h, err := NewHandler(Config{Store: store, PPConnection: m})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(method, path, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("X-Governance-Action", "pp-connection")
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
draft := `{"base_url":"https://api.example.invalid","username":"example","password":"example-private","revision":0}`
|
||||
for _, op := range [][2]string{{"POST", "/api/v1/pp-connection/test"}, {"PUT", "/api/v1/pp-connection"}, {"GET", "/api/v1/pp-connection"}} {
|
||||
rec := call(op[0], op[1], draft)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%s status=%d body=%s", op[0], rec.Code, rec.Body)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "example-private") || strings.Contains(rec.Body.String(), `"password":`) {
|
||||
t.Fatal("credential leaked through response")
|
||||
}
|
||||
}
|
||||
if probes != 2 || store.queued != 0 {
|
||||
t.Fatalf("save must recheck and must not enqueue: checks=%d jobs=%d", probes, store.queued)
|
||||
}
|
||||
rec := call("PUT", "/api/v1/pp-connection", draft)
|
||||
if rec.Code != 409 {
|
||||
t.Fatalf("stale revision accepted: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
func TestPPHTTPRefusesCrossOriginBeforeProbe(t *testing.T) {
|
||||
probes := 0
|
||||
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, _ ppauth.Credentials) ppauth.Observation {
|
||||
probes++
|
||||
return ppauth.Observation{State: "valid"}
|
||||
}}
|
||||
h, _ := NewHandler(Config{Store: &fakeJobStore{}, PPConnection: m})
|
||||
req := httptest.NewRequest("POST", "/api/v1/pp-connection/test", strings.NewReader(`{}`))
|
||||
req.Header.Set("Origin", "https://foreign.example.invalid")
|
||||
req.Header.Set("X-Governance-Action", "pp-connection")
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 403 || probes != 0 {
|
||||
t.Fatal("cross-origin request reached credential probe")
|
||||
}
|
||||
}
|
||||
|
||||
type combinedAuditStore struct {
|
||||
*fakeJobStore
|
||||
items []postgresstore.SourceAuditItem
|
||||
}
|
||||
|
||||
func (s *combinedAuditStore) ListSourceAudit(_ context.Context, limit, offset int) (postgresstore.SourceAuditPage, error) {
|
||||
start := offset
|
||||
if start > len(s.items) {
|
||||
start = len(s.items)
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(s.items) {
|
||||
end = len(s.items)
|
||||
}
|
||||
return postgresstore.SourceAuditPage{Items: s.items[start:end], Total: len(s.items), Limit: limit, Offset: offset}, nil
|
||||
}
|
||||
func TestPPSourceAuditSharesTheExistingPagedView(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json"}
|
||||
if err := os.Mkdir(filepath.Dir(m.Path), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
store := &combinedAuditStore{fakeJobStore: &fakeJobStore{}}
|
||||
expected := []postgresstore.SourceAuditItem{}
|
||||
for i := 0; i < 8; i++ {
|
||||
item := postgresstore.SourceAuditItem{ID: fmt.Sprintf("db-%02d", i), CreatedAt: now.Add(-time.Duration(i*2) * time.Minute), SourceName: "existing source"}
|
||||
store.items = append(store.items, item)
|
||||
expected = append(expected, item)
|
||||
}
|
||||
state := ppauth.State{}
|
||||
for i := 0; i < 4; i++ {
|
||||
event := ppauth.AuditEvent{ID: fmt.Sprintf("auth-%02d", i), CreatedAt: now.Add(-time.Duration(i*2+1) * time.Minute), SourceName: "PP", Action: "credential_test", Actor: "tester", Detail: "只读连接检查"}
|
||||
state.Audit = append(state.Audit, event)
|
||||
expected = append(expected, postgresstore.SourceAuditItem{ID: event.ID, CreatedAt: event.CreatedAt, SourceName: event.SourceName})
|
||||
}
|
||||
raw, _ := json.Marshal(state)
|
||||
if err := os.WriteFile(m.Path, raw, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sort.Slice(expected, func(i, j int) bool { return expected[i].CreatedAt.After(expected[j].CreatedAt) })
|
||||
for offset := 0; offset <= len(expected); offset++ {
|
||||
page, err := combinedSourceAudit(ctx, store, m, 3, offset)
|
||||
if err != nil || page.Total != len(expected) {
|
||||
t.Fatalf("offset=%d total=%d err=%v", offset, page.Total, err)
|
||||
}
|
||||
end := offset + 3
|
||||
if end > len(expected) {
|
||||
end = len(expected)
|
||||
}
|
||||
if len(page.Items) != end-offset {
|
||||
t.Fatalf("wrong page length at %d", offset)
|
||||
}
|
||||
for i, item := range page.Items {
|
||||
if item.ID != expected[offset+i].ID {
|
||||
t.Fatalf("audit order mismatch at offset %d", offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPPAuthRoutesRequireAdminAndFailClosedWhenUnwired(t *testing.T) {
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, method := range []string{"GET", "PUT", "POST"} {
|
||||
path := "/api/v1/pp-connection"
|
||||
if method == "POST" {
|
||||
path += "/test"
|
||||
}
|
||||
for _, role := range []string{"", roleViewer, roleEngineer, roleAdmin} {
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
if role != "" {
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{UserID: "admin", Username: "tester", Role: role, SessionID: "session"}))
|
||||
}
|
||||
req.Header.Set("X-Governance-Action", "pp-connection")
|
||||
res := httptest.NewRecorder()
|
||||
h.ServeHTTP(res, req)
|
||||
want := 403
|
||||
if role == "" {
|
||||
want = 401
|
||||
}
|
||||
if role == roleAdmin {
|
||||
want = 503
|
||||
}
|
||||
if res.Code != want {
|
||||
t.Errorf("%s role=%q status=%d want=%d", method, role, res.Code, want)
|
||||
}
|
||||
}
|
||||
if got := classifyRole(method, path); got != roleAdmin {
|
||||
t.Errorf("%s classified=%q; credential metadata and tests must be admin only", method, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/pgdsn"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
@@ -88,6 +89,11 @@ func (config Config) libraryPublishTarget() libraryPublishTargetView {
|
||||
// productionTargetBaseURL is the production endpoint the picker reads from: the
|
||||
// operator-managed 「服务配置 · 生产地址」 first, the deployment default second.
|
||||
func (config Config) productionTargetBaseURL(ctx context.Context) string {
|
||||
if config.KBBindings != nil {
|
||||
if resolved := strings.TrimSpace(config.KBBindings.ResolveBaseURL(ctx, kbbinding.EnvProduction)); resolved != "" {
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
if settings, err := config.Store.GetActiveUISettings(ctx); err == nil {
|
||||
if resolved := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); resolved != "" {
|
||||
return resolved
|
||||
|
||||
@@ -2,11 +2,9 @@ package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
)
|
||||
|
||||
func qaAIError(w http.ResponseWriter, err error) {
|
||||
@@ -42,24 +40,7 @@ func qaAIReady(w http.ResponseWriter, r *http.Request, c Config) bool {
|
||||
return true
|
||||
}
|
||||
func qaAISecretTransport(r *http.Request, c Config) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
host := r.Host
|
||||
if parsed, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = parsed
|
||||
}
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
return true
|
||||
}
|
||||
if c.QAAITrustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
|
||||
origin, err := url.Parse(r.Header.Get("Origin"))
|
||||
return err == nil && origin.Scheme == "https"
|
||||
}
|
||||
return false
|
||||
return secretTransportAllowed(r, c.QAAITrustTLSProxy)
|
||||
}
|
||||
func registerQAAIRoutes(mux *http.ServeMux, c Config) {
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -17,7 +17,7 @@ type RoutingBindingStore interface {
|
||||
SaveRoutingKBBindings(context.Context, string, string, string) error
|
||||
// SaveRoutingKBBindingsWithReplan also re-points 待入库 publications that
|
||||
// were still waiting for the previous knowledge base (same transaction).
|
||||
SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
|
||||
SaveRoutingKBBindingsWithReplan(ctx context.Context, save postgresstore.RoutingBindingSave, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
|
||||
}
|
||||
|
||||
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
|
||||
@@ -41,6 +41,24 @@ type routingBindingView struct {
|
||||
// that had not been uploaded yet. A plain read reports zeros.
|
||||
Replanned int `json:"replanned"`
|
||||
RetiredDuplicates int `json:"retired_duplicates"`
|
||||
// 整库封存源(LIBRARY_SOURCE_KB_*)与“测试入库绑定”是两套配置:
|
||||
// 页面必须同时给出两者,并标明是否一致,避免改绑后名字变了、封存还是旧库。
|
||||
LibrarySourceInternalKB string `json:"library_source_internal_kb"`
|
||||
LibrarySourceExternalKB string `json:"library_source_external_kb"`
|
||||
InternalSourceState string `json:"internal_source_state"`
|
||||
ExternalSourceState string `json:"external_source_state"`
|
||||
}
|
||||
|
||||
// sourceState 只回答“入库目标与封存源是不是同一个库”。
|
||||
func sourceState(binding, source string) string {
|
||||
switch {
|
||||
case source == "":
|
||||
return "unconfigured"
|
||||
case binding == source:
|
||||
return "consistent"
|
||||
default:
|
||||
return "mismatch"
|
||||
}
|
||||
}
|
||||
|
||||
type routingKnowledgeBaseOption struct {
|
||||
@@ -101,7 +119,11 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress
|
||||
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
|
||||
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
|
||||
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
|
||||
UpdatedBy: updatedBy, WeKnoraConnected: connected,
|
||||
LibrarySourceInternalKB: config.LibrarySourceInternalKB,
|
||||
LibrarySourceExternalKB: config.LibrarySourceExternalKB,
|
||||
InternalSourceState: sourceState(internal, config.LibrarySourceInternalKB),
|
||||
ExternalSourceState: sourceState(external, config.LibrarySourceExternalKB),
|
||||
UpdatedBy: updatedBy, WeKnoraConnected: connected,
|
||||
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
|
||||
}, nil
|
||||
}
|
||||
@@ -174,6 +196,9 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
|
||||
// The saved binding re-routes FUTURE annotations; pending 待入库 items that
|
||||
// have never been uploaded are re-pointed in the same transaction, otherwise
|
||||
// they would keep aiming at the previous (possibly removed) knowledge base.
|
||||
// Only items aimed at the PREVIOUS effective target of this side move, so a
|
||||
// test-side save cannot carry off production-side pending work.
|
||||
previousInternal, previousExternal := config.effectiveRoutingTargets(r.Context())
|
||||
effectiveInternal := internal
|
||||
if effectiveInternal == "" {
|
||||
effectiveInternal = config.InternalRoutingKnowledgeBaseID
|
||||
@@ -182,7 +207,12 @@ 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())
|
||||
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), postgresstore.RoutingBindingSave{
|
||||
InternalID: internal, ExternalID: external,
|
||||
Previous: postgresstore.EffectiveKBIDs{Internal: previousInternal, External: previousExternal},
|
||||
Effective: postgresstore.EffectiveKBIDs{Internal: effectiveInternal, External: effectiveExternal},
|
||||
UpdatedBy: actorFor(r),
|
||||
}, config.Now().UTC())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
|
||||
return
|
||||
|
||||
@@ -18,7 +18,8 @@ type bindingStoreFake struct {
|
||||
external string
|
||||
saver string
|
||||
// replan records what the last save asked for, so tests can assert that the
|
||||
// effective (env-fallback aware) targets were used.
|
||||
// effective (env-fallback aware) targets and the previous pair were used.
|
||||
replanPrevious [2]string
|
||||
replanEffective [2]string
|
||||
replanResult postgresstore.RoutingBindingReplanResult
|
||||
replanCallCount int
|
||||
@@ -33,9 +34,10 @@ func (fake *bindingStoreFake) SaveRoutingKBBindings(_ context.Context, internal,
|
||||
return 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, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
|
||||
fake.internal, fake.external, fake.saver = save.InternalID, save.ExternalID, save.UpdatedBy
|
||||
fake.replanPrevious = [2]string{save.Previous.Internal, save.Previous.External}
|
||||
fake.replanEffective = [2]string{save.Effective.Internal, save.Effective.External}
|
||||
fake.replanCallCount++
|
||||
return fake.replanResult, nil
|
||||
}
|
||||
@@ -134,6 +136,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"`
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// secretTransportAllowed is the single rule for typing a secret into the
|
||||
// console: a real TLS connection, a loopback request, or a same-origin HTTPS
|
||||
// request that a trusted reverse proxy forwarded. The browser's origin scheme
|
||||
// must agree, so a plain-HTTP page behind a misconfigured proxy cannot submit
|
||||
// a key even if it spoofs X-Forwarded-Proto.
|
||||
func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
host := r.Host
|
||||
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = parsedHost
|
||||
}
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
return true
|
||||
}
|
||||
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
|
||||
origin, err := url.Parse(r.Header.Get("Origin"))
|
||||
return err == nil && origin.Scheme == "https"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
|
||||
// fetch from the operator console itself when it is served over plain http on a
|
||||
// private address. That is the only non-TLS shape this deployment needs, and it
|
||||
// still requires an exact Origin/Host match.
|
||||
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
|
||||
if secretTransportAllowed(r, trustTLSProxy) {
|
||||
return true
|
||||
}
|
||||
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
|
||||
return false
|
||||
}
|
||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Host, r.Host) {
|
||||
return false
|
||||
}
|
||||
host := parsed.Hostname()
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
return strings.EqualFold(host, "localhost")
|
||||
}
|
||||
@@ -15,10 +15,13 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/backuphost"
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
@@ -135,6 +138,13 @@ type Config struct {
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
RoutingBindings RoutingBindingStore
|
||||
KnowledgeBases KnowledgeBaseLister
|
||||
// KBBindings is the environment-scoped 「知识库绑定」store: connection +
|
||||
// internal/external bindings saved together. Nil keeps the page read-only
|
||||
// and reports unavailable, never a fake success.
|
||||
KBBindings KBBindingStore
|
||||
// WeKnoraAllowPrivateHTTP 允许在私网治理台(明文 http)上录入 WeKnora API Key;
|
||||
// 同时决定客户端/探活是否放行同网段 http(生产 18093 反代)。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
|
||||
// enumerates the production-side bases the operator can bind.
|
||||
// BackupSchedule 是「系统设置 → 存储与备份」的计划存储;BackupHost 负责在目标库
|
||||
@@ -192,10 +202,13 @@ 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
|
||||
LibraryRetentionVersions int
|
||||
LibraryRetentionDays int
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
// BackupInventory 读的是只读挂载的 rds-logical 目录(批次/子库/实测容量)。
|
||||
// 与 BackupHost 的 SSH 计划读回分离,任一侧失败都不能影响另一侧。
|
||||
BackupInventory BackupInventoryReader
|
||||
BackupRuns *BackupRunTracker
|
||||
ProductionBindings ProductionBindingStore
|
||||
ProductionKnowledgeBases ProductionKnowledgeBaseLister
|
||||
@@ -222,6 +235,8 @@ type Config struct {
|
||||
DingtalkSources dingtalkSourcesLister
|
||||
// DingtalkDocuments 列在线文档/表格并校验可读(只读,dws)。
|
||||
DingtalkDocuments dingtalkDocLister
|
||||
DWSLogin *dingtalkdiscovery.DeviceLoginManager
|
||||
PPConnection *ppauth.Manager
|
||||
NewID func() (string, error)
|
||||
Auth *AuthConfig
|
||||
}
|
||||
@@ -243,6 +258,10 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
// 未挂载主机凭据:Available()=false,页面显示"未接线"而不是 500。
|
||||
config.BackupHost = backuphost.New(backuphost.Config{})
|
||||
}
|
||||
if config.BackupInventory == nil {
|
||||
// 未挂载只读备份目录:批次/容量显示"未接线",独立于 SSH 计划读回。
|
||||
config.BackupInventory = backupinventory.New(backupinventory.Config{})
|
||||
}
|
||||
for _, knowledgeBaseID := range []string{config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID} {
|
||||
if knowledgeBaseID != "" && !validCatalogID(knowledgeBaseID) {
|
||||
return nil, errors.New("routing knowledge base ID is invalid")
|
||||
@@ -256,6 +275,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
config.NewID = newID
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
registerDWSLoginRoutes(mux, config)
|
||||
registerPPConnectionRoutes(mux, config)
|
||||
mux.HandleFunc("POST /api/v1/dingtalk-spaces/validate", func(w http.ResponseWriter, r *http.Request) { validateDWSSpace(w, r, config) })
|
||||
registerQAAIRoutes(mux, config)
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })
|
||||
@@ -377,6 +399,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
internal, external := config.effectiveRoutingTargets(r.Context())
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"internal_enabled": internal != "", "external_enabled": external != ""}})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/system/worker-capabilities", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleWorkerCapabilities(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/routing-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.RoutingBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "routing bindings storage unavailable"})
|
||||
@@ -394,6 +419,15 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.handleSaveRoutingBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/kb-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/kb-bindings/{environment}/catalog", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindingCatalog(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/kb-bindings/{environment}", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindingSave(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.BackupSchedule == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"})
|
||||
@@ -408,6 +442,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.handleBackupScheduleHost(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/backup-schedule/inventory", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleBackupInventory(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.BackupSchedule == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"})
|
||||
|
||||
@@ -35,7 +35,7 @@ func listSourceAudit(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, 501, map[string]string{"error": "audit not configured"})
|
||||
return
|
||||
}
|
||||
page, err := reader.ListSourceAudit(r.Context(), limit, offset)
|
||||
page, err := combinedSourceAudit(r.Context(), reader, config.PPConnection, limit, offset)
|
||||
if err != nil {
|
||||
writeJSON(w, 500, map[string]string{"error": "无法读取数据源操作记录"})
|
||||
return
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// workerHeartbeatStore 是队列存活记录的只读视图。页面要回答“执行器在不在”,
|
||||
// 只能看 worker 认领任务时自己写下的 job_types;readiness 只证明接口可达。
|
||||
type workerHeartbeatStore interface {
|
||||
ListWorkerHeartbeats(context.Context) ([]postgresstore.WorkerHeartbeat, error)
|
||||
}
|
||||
|
||||
type workerCapabilityView struct {
|
||||
WorkerID string `json:"worker_id"`
|
||||
JobTypes []string `json:"job_types"`
|
||||
Alive bool `json:"alive"`
|
||||
LastSeenAt string `json:"last_seen_at"`
|
||||
}
|
||||
|
||||
type testUploadCapability struct {
|
||||
State string `json:"state"`
|
||||
Consumers int `json:"consumers"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
// 与 qaopsmirror 的工作就绪判定同一个窗口:2 分钟没有认领记录就当作不在线。
|
||||
const workerHeartbeatTTL = 2 * time.Minute
|
||||
|
||||
const testUploadJobType = "test.upload"
|
||||
|
||||
func testUploadCapabilityOf(workers []postgresstore.WorkerHeartbeat, now time.Time) testUploadCapability {
|
||||
alive, consumers := 0, 0
|
||||
for _, worker := range workers {
|
||||
if now.Sub(worker.LastSeenAt) > workerHeartbeatTTL {
|
||||
continue
|
||||
}
|
||||
alive++
|
||||
if slices.Contains(worker.JobTypes, testUploadJobType) {
|
||||
consumers++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case consumers > 0:
|
||||
return testUploadCapability{State: "enabled", Consumers: consumers,
|
||||
Detail: "上传/解析执行器已注册(认领过 test.upload)"}
|
||||
case alive > 0:
|
||||
return testUploadCapability{State: "disabled", Consumers: 0,
|
||||
Detail: "worker 在线但没有注册 test.upload:上传/解析任务不会被消费"}
|
||||
default:
|
||||
return testUploadCapability{State: "stale", Consumers: 0,
|
||||
Detail: "没有有效的 worker 认领记录:执行器未运行,或从未接单"}
|
||||
}
|
||||
}
|
||||
|
||||
func (config Config) handleWorkerCapabilities(w http.ResponseWriter, r *http.Request) {
|
||||
store, ok := config.Store.(workerHeartbeatStore)
|
||||
if !ok || store == nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"test_upload": testUploadCapability{State: "unknown", Detail: "worker 存活记录不可用"},
|
||||
"workers": []workerCapabilityView{},
|
||||
}})
|
||||
return
|
||||
}
|
||||
workers, err := store.ListWorkerHeartbeats(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"test_upload": testUploadCapability{State: "unknown", Detail: "读取 worker 存活记录失败"},
|
||||
"workers": []workerCapabilityView{},
|
||||
}})
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
views := make([]workerCapabilityView, 0, len(workers))
|
||||
for _, worker := range workers {
|
||||
views = append(views, workerCapabilityView{
|
||||
WorkerID: worker.WorkerID,
|
||||
JobTypes: worker.JobTypes,
|
||||
Alive: now.Sub(worker.LastSeenAt) <= workerHeartbeatTTL,
|
||||
LastSeenAt: worker.LastSeenAt.UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"test_upload": testUploadCapabilityOf(workers, now),
|
||||
"workers": views,
|
||||
}})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
func TestTestUploadCapabilityReflectsWorkerHeartbeats(t *testing.T) {
|
||||
now := time.Date(2026, time.November, 17, 7, 0, 0, 0, time.UTC)
|
||||
fresh := now.Add(-10 * time.Second)
|
||||
stale := now.Add(-5 * time.Minute)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
workers []postgresstore.WorkerHeartbeat
|
||||
state string
|
||||
consume int
|
||||
}{
|
||||
{"no heartbeats", nil, "stale", 0},
|
||||
{"heartbeat too old", []postgresstore.WorkerHeartbeat{{LastSeenAt: stale, JobTypes: []string{"test.upload"}}}, "stale", 0},
|
||||
{"worker online without upload chain", []postgresstore.WorkerHeartbeat{{LastSeenAt: fresh, JobTypes: []string{"source.scan.dingtalk"}}}, "disabled", 0},
|
||||
{"enabled consumer", []postgresstore.WorkerHeartbeat{{LastSeenAt: fresh, JobTypes: []string{"test.upload", "test.poll"}}}, "enabled", 1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := testUploadCapabilityOf(tc.workers, now)
|
||||
if got.State != tc.state || got.Consumers != tc.consume {
|
||||
t.Fatalf("%s: got state=%s consumers=%d, want %s/%d", tc.name, got.State, got.Consumers, tc.state, tc.consume)
|
||||
}
|
||||
if got.Detail == "" {
|
||||
t.Fatalf("%s: detail must explain the state", tc.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
// Package kbbinding 是「知识库绑定」的唯一服务端入口:按环境保存连接
|
||||
// (地址 + 加密后的 API Key)和对内/对外知识库绑定,并提供候选人列库、
|
||||
// 选库归属校验与消费者解析。旧的部署文件凭据/默认绑定在没有任何新行时
|
||||
// 继续生效,所以升级不需要回填数据。
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
const (
|
||||
EnvTest = "test"
|
||||
EnvProduction = "production"
|
||||
)
|
||||
|
||||
func Environments() []string { return []string{EnvTest, EnvProduction} }
|
||||
|
||||
func ValidEnvironment(value string) bool {
|
||||
return value == EnvTest || value == EnvProduction
|
||||
}
|
||||
|
||||
func EnvironmentLabel(value string) string {
|
||||
if value == EnvProduction {
|
||||
return "生产 090"
|
||||
}
|
||||
return "测试 090"
|
||||
}
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("invalid knowledge base binding")
|
||||
ErrConflict = errors.New("knowledge base binding revision conflict")
|
||||
ErrKeyForwarding = errors.New("old key must not follow a new address")
|
||||
ErrNotConfigured = errors.New("weknora connection is not configured")
|
||||
ErrStorage = errors.New("secure binding storage is not ready")
|
||||
ErrRejected = errors.New("weknora rejected the candidate connection")
|
||||
ErrUnreachable = errors.New("weknora candidate connection is unreachable")
|
||||
)
|
||||
|
||||
// View is the public projection. It never carries a key, ciphertext or any
|
||||
// value derived from the key beyond "configured or not".
|
||||
type View struct {
|
||||
Environment string `json:"environment"`
|
||||
Revision int64 `json:"revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyConfigured bool `json:"key_configured"`
|
||||
KeySource string `json:"key_source"`
|
||||
// KeyTail is the only part of the key the page may show. It is derived at
|
||||
// read time and never stored, so a rotated master key cannot resurrect it.
|
||||
KeyTail string `json:"key_tail"`
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
InternalKBName string `json:"internal_kb_name"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
ExternalKBName string `json:"external_kb_name"`
|
||||
Verification string `json:"verification"`
|
||||
CheckedAt *time.Time `json:"checked_at"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
// Source says where this effective configuration comes from: a row saved on
|
||||
// this page, or the pre-existing deployment file/default binding.
|
||||
Source string `json:"source"`
|
||||
StorageReady bool `json:"storage_ready"`
|
||||
// Replanned / RetiredDuplicates only report what a save just did to 待入库
|
||||
// rows that had never been uploaded; a plain read reports zeros.
|
||||
Replanned int `json:"replanned"`
|
||||
RetiredDuplicates int `json:"retired_duplicates"`
|
||||
// 留空绑定 = 取消绑定,页面必须说清回退到了哪里:测试侧回退到部署默认库,
|
||||
// 生产侧回退到「同 ID 语义」。空串表示该方向仍有显式绑定。
|
||||
InternalFallback string `json:"internal_fallback"`
|
||||
ExternalFallback string `json:"external_fallback"`
|
||||
// 生产侧冻结计数:执行已开始的发布项目标已钉死,保存绑定不会改写它们。
|
||||
Frozen int `json:"frozen"`
|
||||
Retargetable int `json:"retargetable"`
|
||||
}
|
||||
|
||||
type Option struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
}
|
||||
|
||||
type Catalog struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int64 `json:"total"`
|
||||
Options []Option `json:"options"`
|
||||
}
|
||||
|
||||
type CatalogInput struct {
|
||||
BaseRevision int64 `json:"base_revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyAction string `json:"key_action"`
|
||||
APIKey string `json:"api_key"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type SaveInput struct {
|
||||
BaseRevision int64 `json:"base_revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyAction string `json:"key_action"`
|
||||
APIKey string `json:"api_key"`
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
}
|
||||
|
||||
// Target is what consumers (readiness, upload, listing, monitoring) need to
|
||||
// reach the effective instance. It never leaves the server.
|
||||
type Target struct {
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Revision int64
|
||||
Source string
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
MasterKeyFile string
|
||||
Timeout time.Duration
|
||||
// AllowDockerHTTP mirrors the per-environment client policy (a single-label
|
||||
// docker host may be reached over plain HTTP in the internal network).
|
||||
AllowDockerHTTP map[string]bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses
|
||||
// (production 18093 reverse proxy). Public http stays refused.
|
||||
AllowPrivateHTTP map[string]bool
|
||||
// LegacyBaseURL resolves the pre-existing endpoint (web setting first, then
|
||||
// the deployment env value). It is only consulted when no row exists.
|
||||
LegacyBaseURL func(context.Context, string) string
|
||||
// LegacyKey reads the deployment credential file. It is only consulted when
|
||||
// no row exists, or when a keep action targets exactly that legacy address.
|
||||
LegacyKey func(string) (string, error)
|
||||
// LegacyBinding resolves the pre-existing internal/external binding ids.
|
||||
LegacyBinding func(context.Context, string) (string, string, error)
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type DB interface {
|
||||
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
|
||||
Begin(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db DB
|
||||
options Options
|
||||
}
|
||||
|
||||
func New(db DB, options Options) *Store {
|
||||
if options.Timeout <= 0 {
|
||||
options.Timeout = 10 * time.Second
|
||||
}
|
||||
if options.Now == nil {
|
||||
options.Now = time.Now
|
||||
}
|
||||
return &Store{db: db, options: options}
|
||||
}
|
||||
|
||||
type stored struct {
|
||||
Environment string
|
||||
Revision int64
|
||||
BaseURL string
|
||||
KeyCiphertext []byte
|
||||
InternalKBID string
|
||||
ExternalKBID string
|
||||
InternalKBName string
|
||||
ExternalKBName string
|
||||
Verification string
|
||||
CheckedAt *time.Time
|
||||
UpdatedBy string
|
||||
UpdatedAt *time.Time
|
||||
}
|
||||
|
||||
const bindingColumns = `environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at`
|
||||
|
||||
func scanStored(row pgx.Row) (stored, bool, error) {
|
||||
var value stored
|
||||
err := row.Scan(&value.Environment, &value.Revision, &value.BaseURL, &value.KeyCiphertext,
|
||||
&value.InternalKBID, &value.ExternalKBID, &value.InternalKBName, &value.ExternalKBName,
|
||||
&value.Verification, &value.CheckedAt, &value.UpdatedBy, &value.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return stored{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return stored{}, false, err
|
||||
}
|
||||
return value, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) load(ctx context.Context, env string) (stored, bool, error) {
|
||||
if !ValidEnvironment(env) {
|
||||
return stored{}, false, ErrInvalid
|
||||
}
|
||||
return scanStored(s.db.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1`, env))
|
||||
}
|
||||
|
||||
func (s *Store) StorageReady() bool {
|
||||
return s.loadBox() != nil
|
||||
}
|
||||
|
||||
func (s *Store) loadBox() *secretbox.Box {
|
||||
box, err := secretbox.Load(s.options.MasterKeyFile)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return box
|
||||
}
|
||||
|
||||
func (s *Store) legacyBaseURL(ctx context.Context, env string) string {
|
||||
if s.options.LegacyBaseURL == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(s.options.LegacyBaseURL(ctx, env))
|
||||
}
|
||||
|
||||
func (s *Store) legacyKey(env string) (string, error) {
|
||||
if s.options.LegacyKey == nil {
|
||||
return "", nil
|
||||
}
|
||||
value, err := s.options.LegacyKey(env)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(value), nil
|
||||
}
|
||||
|
||||
// List returns both environments' effective views for the page header and the
|
||||
// environment switch. Names are best-effort: an unreachable instance yields
|
||||
// short ids instead of hiding the binding.
|
||||
func (s *Store) List(ctx context.Context) ([]View, error) {
|
||||
views := make([]View, 0, 2)
|
||||
for _, env := range Environments() {
|
||||
view, err := s.Get(ctx, env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
return views, nil
|
||||
}
|
||||
|
||||
func (s *Store) Get(ctx context.Context, env string) (View, error) {
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
view := View{Environment: env, StorageReady: s.StorageReady(), Source: "legacy"}
|
||||
if found {
|
||||
view.Revision = saved.Revision
|
||||
view.BaseURL = saved.BaseURL
|
||||
view.KeyConfigured = len(saved.KeyCiphertext) > 0
|
||||
view.KeySource = keySource(view.KeyConfigured)
|
||||
view.InternalKBID = saved.InternalKBID
|
||||
view.InternalKBName = saved.InternalKBName
|
||||
view.ExternalKBID = saved.ExternalKBID
|
||||
view.ExternalKBName = saved.ExternalKBName
|
||||
view.Verification = saved.Verification
|
||||
view.CheckedAt = saved.CheckedAt
|
||||
view.UpdatedBy = saved.UpdatedBy
|
||||
view.UpdatedAt = saved.UpdatedAt
|
||||
view.Source = "web"
|
||||
if s.options.MasterKeyFile != "" {
|
||||
if tail, ok := s.keyTail(saved, env); ok {
|
||||
view.KeyTail = tail
|
||||
}
|
||||
}
|
||||
s.fillFallbacks(ctx, env, &view)
|
||||
s.fillExecutionCounts(ctx, env, &view)
|
||||
return view, nil
|
||||
}
|
||||
// Legacy fallback: exactly what the consumers use before any page save.
|
||||
view.BaseURL = s.legacyBaseURL(ctx, env)
|
||||
if key, keyErr := s.legacyKey(env); keyErr == nil && key != "" {
|
||||
view.KeyConfigured = true
|
||||
view.KeySource = "file"
|
||||
}
|
||||
if s.options.LegacyBinding != nil {
|
||||
internal, external, bindErr := s.options.LegacyBinding(ctx, env)
|
||||
if bindErr != nil {
|
||||
return View{}, bindErr
|
||||
}
|
||||
view.InternalKBID = internal
|
||||
view.ExternalKBID = external
|
||||
}
|
||||
view.Verification = "legacy"
|
||||
s.fillFallbacks(ctx, env, &view)
|
||||
s.fillExecutionCounts(ctx, env, &view)
|
||||
s.fillNames(ctx, &view)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// keyTail decrypts only to keep the last four characters. It never returns the
|
||||
// key and never writes the tail anywhere.
|
||||
func (s *Store) keyTail(saved stored, env string) (string, bool) {
|
||||
box := s.loadBox()
|
||||
if box == nil || len(saved.KeyCiphertext) == 0 {
|
||||
return "", false
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
runes := []rune(string(raw))
|
||||
if len(runes) <= 4 {
|
||||
return string(runes), true
|
||||
}
|
||||
return string(runes[len(runes)-4:]), true
|
||||
}
|
||||
|
||||
// fillFallbacks explains where an unbound direction routes to. Without this the
|
||||
// page could only say 「留空」without saying what 「空」means.
|
||||
func (s *Store) fillFallbacks(ctx context.Context, env string, view *View) {
|
||||
if view.InternalKBID != "" && view.ExternalKBID != "" {
|
||||
return
|
||||
}
|
||||
if env == EnvProduction {
|
||||
if view.InternalKBID == "" {
|
||||
view.InternalFallback = "same-id"
|
||||
}
|
||||
if view.ExternalKBID == "" {
|
||||
view.ExternalFallback = "same-id"
|
||||
}
|
||||
return
|
||||
}
|
||||
if s.options.LegacyBinding == nil {
|
||||
return
|
||||
}
|
||||
internal, external, err := s.options.LegacyBinding(ctx, env)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if view.InternalKBID == "" && strings.TrimSpace(internal) != "" {
|
||||
view.InternalFallback = strings.TrimSpace(internal)
|
||||
}
|
||||
if view.ExternalKBID == "" && strings.TrimSpace(external) != "" {
|
||||
view.ExternalFallback = strings.TrimSpace(external)
|
||||
}
|
||||
}
|
||||
|
||||
// fillExecutionCounts reports how many in-flight release items already have a
|
||||
// frozen production target. Completed executions are history, not something a
|
||||
// binding change could still move.
|
||||
func (s *Store) fillExecutionCounts(ctx context.Context, env string, view *View) {
|
||||
if env != EnvProduction {
|
||||
return
|
||||
}
|
||||
var frozen, retargetable int
|
||||
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)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
view.Frozen, view.Retargetable = frozen, retargetable
|
||||
}
|
||||
|
||||
func keySource(configured bool) string {
|
||||
if configured {
|
||||
return "sealed"
|
||||
}
|
||||
return "none"
|
||||
}
|
||||
|
||||
// fillNames reads names from the effective instance for the legacy view. A
|
||||
// failure leaves names empty; ids still identify the binding.
|
||||
func (s *Store) fillNames(ctx context.Context, view *View) {
|
||||
if view.BaseURL == "" || (view.InternalKBID == "" && view.ExternalKBID == "") {
|
||||
return
|
||||
}
|
||||
// 只是把 ID 换成名字:不能让一次不可达的旧实例拖住整个页面读取。
|
||||
namesCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
key, err := s.legacyKey(view.Environment)
|
||||
if err != nil || key == "" {
|
||||
return
|
||||
}
|
||||
client, err := s.client(view.BaseURL, key, view.Environment)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
names := map[string]string{}
|
||||
page := 1
|
||||
for page <= 20 {
|
||||
result, err := client.ListKnowledgeBasesPage(namesCtx, page, 100)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
for _, base := range result.Items {
|
||||
names[base.ID] = base.Name
|
||||
}
|
||||
if result.Total <= int64(page*100) || len(result.Items) < 100 {
|
||||
break
|
||||
}
|
||||
page++
|
||||
}
|
||||
view.InternalKBName = names[view.InternalKBID]
|
||||
view.ExternalKBName = names[view.ExternalKBID]
|
||||
}
|
||||
|
||||
// Resolve returns the effective connection consumers must use. A saved row is
|
||||
// authoritative: if its key cannot be opened we fail closed instead of falling
|
||||
// back to the file credential (that would send the old key to a new address).
|
||||
func (s *Store) Resolve(ctx context.Context, env string) (Target, error) {
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return Target{}, err
|
||||
}
|
||||
if found {
|
||||
if saved.BaseURL == "" {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
if len(saved.KeyCiphertext) == 0 {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return Target{}, ErrStorage
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return Target{}, ErrStorage
|
||||
}
|
||||
return Target{BaseURL: saved.BaseURL, APIKey: string(raw), Revision: saved.Revision, Source: "web"}, nil
|
||||
}
|
||||
baseURL := s.legacyBaseURL(ctx, env)
|
||||
key, err := s.legacyKey(env)
|
||||
if err != nil {
|
||||
return Target{}, err
|
||||
}
|
||||
if baseURL == "" || key == "" {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
return Target{BaseURL: baseURL, APIKey: key, Source: "legacy"}, nil
|
||||
}
|
||||
|
||||
// ResolveBaseURL is for health probes that only need the endpoint (no key).
|
||||
func (s *Store) ResolveBaseURL(ctx context.Context, env string) string {
|
||||
if saved, found, err := s.load(ctx, env); err == nil && found && saved.BaseURL != "" {
|
||||
return saved.BaseURL
|
||||
}
|
||||
return s.legacyBaseURL(ctx, env)
|
||||
}
|
||||
|
||||
func (s *Store) keyFor(ctx context.Context, env string, action, baseURL, apiKey string, saved stored, found bool) (string, error) {
|
||||
switch action {
|
||||
case "keep":
|
||||
if apiKey != "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if found {
|
||||
if saved.BaseURL != baseURL {
|
||||
return "", ErrKeyForwarding
|
||||
}
|
||||
if len(saved.KeyCiphertext) == 0 {
|
||||
return "", ErrNotConfigured
|
||||
}
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return "", ErrStorage
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return "", ErrStorage
|
||||
}
|
||||
return string(raw), nil
|
||||
}
|
||||
// First save on an upgraded deployment: keeping the deployment file key
|
||||
// is allowed only for exactly that legacy address.
|
||||
if s.legacyBaseURL(ctx, env) != baseURL {
|
||||
return "", ErrKeyForwarding
|
||||
}
|
||||
return s.legacyKey(env)
|
||||
case "replace":
|
||||
if !validAPIKey(apiKey) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return apiKey, nil
|
||||
case "clear":
|
||||
// 清除密钥是独立动作:留下地址与绑定,只是这一侧不再有可用凭据,
|
||||
// 消费者解析会失败关闭(不会悄悄回落到部署文件里的旧 Key)。
|
||||
if apiKey != "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return "", nil
|
||||
default:
|
||||
return "", ErrInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func validAPIKey(value string) bool {
|
||||
return value != "" && len(value) <= 4096 && strings.TrimSpace(value) == value && !strings.ContainsAny(value, "\r\n\x00")
|
||||
}
|
||||
|
||||
func (s *Store) client(baseURL, apiKey, env string) (*weknora.Client, error) {
|
||||
return weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: baseURL,
|
||||
APIKey: apiKey,
|
||||
Timeout: s.options.Timeout,
|
||||
AllowDockerHTTP: s.options.AllowDockerHTTP[env],
|
||||
AllowPrivateHTTP: s.options.AllowPrivateHTTP[env],
|
||||
})
|
||||
}
|
||||
|
||||
func keyAAD(env string, revision int64) string {
|
||||
return "weknora-binding:" + env + ":" + strconv.FormatInt(revision, 10)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
type emptyDB struct{}
|
||||
|
||||
func (emptyDB) QueryRow(context.Context, string, ...any) pgx.Row { return emptyRow{} }
|
||||
func (emptyDB) Begin(context.Context) (pgx.Tx, error) {
|
||||
return nil, errors.New("no transaction in unit test")
|
||||
}
|
||||
|
||||
type emptyRow struct{}
|
||||
|
||||
func (emptyRow) Scan(...any) error { return pgx.ErrNoRows }
|
||||
|
||||
// fakeWeKnora serves the two reads the candidate validation makes: one page of
|
||||
// knowledge bases and a single base by id.
|
||||
func fakeWeKnora(t *testing.T, wantKey string, bases []struct{ id, name string }, total int64) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("X-API-Key"); got != wantKey {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/knowledge-bases" {
|
||||
items := make([]string, 0, len(bases))
|
||||
for _, base := range bases {
|
||||
items = append(items, `{"id":"`+base.id+`","name":"`+base.name+`","knowledge_count":2}`)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[` + strings.Join(items, ",") + `],"total":` + strconv.FormatInt(total, 10) + `}`))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/knowledge-bases/") {
|
||||
id := strings.TrimPrefix(r.URL.Path, "/api/v1/knowledge-bases/")
|
||||
for _, base := range bases {
|
||||
if base.id == id {
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"` + base.id + `","name":"` + base.name + `"}}`))
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
func TestCatalogDistinguishesEmptyFromPermissionFromUnreachable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}})
|
||||
|
||||
empty := fakeWeKnora(t, "key-1", nil, 0)
|
||||
catalog, err := store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: empty.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusEmpty || catalog.Total != 0 {
|
||||
t.Fatalf("empty catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
|
||||
denied := fakeWeKnora(t, "another-key", nil, 0)
|
||||
catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: denied.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusKeyInvalid {
|
||||
t.Fatalf("denied catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
|
||||
down := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
downURL := down.URL
|
||||
down.Close()
|
||||
catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: downURL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusUnreachable {
|
||||
t.Fatalf("unreachable catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogPaginatesAndReturnsNamesWithShortIDsAreStable(t *testing.T) {
|
||||
server := fakeWeKnora(t, "key-1", []struct{ id, name string }{{"kb-1", "技术资料"}}, 1)
|
||||
store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}})
|
||||
catalog, err := store.Catalog(context.Background(), EnvTest, CatalogInput{
|
||||
BaseURL: server.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusOK || len(catalog.Options) != 1 || catalog.Options[0].Name != "技术资料" {
|
||||
t.Fatalf("catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyActionRulesRejectForwardingAndInvalidInput(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{})
|
||||
saved := stored{Environment: EnvTest, Revision: 1, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://new.example", "", saved, true); !errors.Is(err, ErrKeyForwarding) {
|
||||
t.Fatalf("keep with a new address = %v, want ErrKeyForwarding", err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("keep with a typed key = %v, want ErrInvalid", err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "replace", "https://new.example", " ", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("replace with blank key = %v, want ErrInvalid", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
|
||||
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
|
||||
store := New(emptyDB{}, Options{Now: func() time.Time { return now }})
|
||||
for _, input := range []SaveInput{
|
||||
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"},
|
||||
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"},
|
||||
{BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"},
|
||||
} {
|
||||
if _, err := store.Save(context.Background(), EnvTest, input, "admin", now); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("input %#v error = %v, want ErrInvalid", input, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogDistinguishesInvalidKeyFromForbiddenKey(t *testing.T) {
|
||||
invalid := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusUnauthorized})
|
||||
if invalid.Status != "key_invalid" || !strings.Contains(invalid.Message, "密钥无效") {
|
||||
t.Fatalf("401 -> %+v", invalid)
|
||||
}
|
||||
forbidden := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusForbidden})
|
||||
if forbidden.Status != "key_forbidden" || !strings.Contains(forbidden.Message, "无权限") {
|
||||
t.Fatalf("403 -> %+v", forbidden)
|
||||
}
|
||||
dead := catalogFailure(context.DeadlineExceeded)
|
||||
if dead.Status != "unreachable" || !(strings.Contains(dead.Message, "超时") || strings.Contains(dead.Message, "不可达")) {
|
||||
t.Fatalf("timeout -> %+v", dead)
|
||||
}
|
||||
if dead.Status == invalid.Status || invalid.Status == forbidden.Status {
|
||||
t.Fatal("the three outcomes must stay distinguishable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearKeyIsASeparateAction(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{})
|
||||
saved := stored{Environment: EnvTest, Revision: 2, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")}
|
||||
key, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "", saved, true)
|
||||
if err != nil || key != "" {
|
||||
t.Fatalf("clear = %q, %v", key, err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("clear with a typed key = %v, want ErrInvalid", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyTailShowsOnlyFourCharacters(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "master.key")
|
||||
if err := os.WriteFile(path, bytes.Repeat([]byte{7}, 32), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
box, err := secretbox.Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("secretbox.Load: %v", err)
|
||||
}
|
||||
sealed, err := box.Seal([]byte("sk-live-abcd"), keyAAD(EnvTest, 3))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := New(emptyDB{}, Options{MasterKeyFile: path})
|
||||
tail, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 3}, EnvTest)
|
||||
if !ok || tail != "abcd" {
|
||||
t.Fatalf("tail = %q %v", tail, ok)
|
||||
}
|
||||
// A different revision must not open — the tail must never leak from a
|
||||
// ciphertext that no longer matches the row.
|
||||
if _, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 4}, EnvTest); ok {
|
||||
t.Fatal("tail opened with the wrong revision")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{LegacyBinding: func(context.Context, string) (string, string, error) {
|
||||
return "legacy-in-0001", "legacy-out-0001", nil
|
||||
}})
|
||||
view := View{Environment: EnvTest}
|
||||
store.fillFallbacks(context.Background(), EnvTest, &view)
|
||||
if view.InternalFallback != "legacy-in-0001" || view.ExternalFallback != "legacy-out-0001" {
|
||||
t.Fatalf("test fallbacks = %+v", view)
|
||||
}
|
||||
production := View{Environment: EnvProduction}
|
||||
store.fillFallbacks(context.Background(), EnvProduction, &production)
|
||||
if production.InternalFallback != "same-id" || production.ExternalFallback != "same-id" {
|
||||
t.Fatalf("production fallbacks = %+v", production)
|
||||
}
|
||||
bound := View{Environment: EnvTest, InternalKBID: "a", ExternalKBID: "b"}
|
||||
store.fillFallbacks(context.Background(), EnvTest, &bound)
|
||||
if bound.InternalFallback != "" || bound.ExternalFallback != "" {
|
||||
t.Fatalf("bound view must not claim a fallback: %+v", bound)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
package kbbinding_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/postgres/pgtest"
|
||||
)
|
||||
|
||||
// testSecret() 在运行时拼出测试夹具密钥,避免把任何字面量误当成真实凭据入库。
|
||||
func testSecret() string { return "fixture-" + strings.Repeat("k", 24) }
|
||||
|
||||
func fakeCandidate(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-Key") != testSecret() {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/knowledge-bases":
|
||||
_, _ = w.Write([]byte(`{"success":true,"total":5,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4},{"id":"p-internal","name":"生产内部资料","knowledge_count":5},{"id":"p-external","name":"生产客户手册","knowledge_count":6},{"id":"p-new-internal","name":"生产内部资料新版","knowledge_count":0}]}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/kb-in":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料","tenant_id":10000}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册","tenant_id":10000}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/p-internal":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-internal","name":"生产内部资料","tenant_id":10000}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/p-external":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-external","name":"生产客户手册","tenant_id":10000}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/p-new-internal":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-new-internal","name":"生产内部资料新版","tenant_id":10000}}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
func masterKey(t *testing.T) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "binding-master.key")
|
||||
if err := os.WriteFile(path, []byte(strings.Repeat("k", 32)), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction(t *testing.T) {
|
||||
databaseURL := pgtest.IsolatedDatabaseURL(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 := postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-kbb','manual','KBB',true);
|
||||
INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,title,item_type,revision,visibility,visibility_origin) VALUES
|
||||
('item-kbb','conn-kbb','n-kbb',repeat('c',64),'docs/kbb.docx','kbb.docx','document','locator:r1','internal','configured_scope'),
|
||||
('item-prod-kbb','conn-kbb','n-prod-kbb',repeat('d',64),'docs/prod-kbb.docx','prod-kbb.docx','document','locator:r2','internal','configured_scope');
|
||||
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
||||
('version-kbb','item-kbb','locator:r1',NULL,'unknown'),
|
||||
('version-prod-kbb','item-prod-kbb','locator:r2',NULL,'unknown');
|
||||
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
||||
('pub-kbb','version-kbb','kb-legacy-in','planned','pending','internal'),
|
||||
('pub-prod-kbb','version-prod-kbb','p-internal','planned','pending','internal');
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := fakeCandidate(t)
|
||||
store := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: masterKey(t),
|
||||
Timeout: 2 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true},
|
||||
// 留空的一侧回退到部署默认绑定:用例必须能断言回退来源写了什么。
|
||||
LegacyBinding: func(context.Context, string) (string, string, error) {
|
||||
return "kb-legacy-in", "kb-legacy-out", nil
|
||||
},
|
||||
})
|
||||
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
|
||||
// 留空 = 取消该方向绑定,不再报 ErrInvalid:只填对内也要能保存,
|
||||
// 对外回退到部署默认库,响应里必须写明回退来源。
|
||||
internalOnly, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("save with an unbound side = %v, want success", err)
|
||||
}
|
||||
if internalOnly.Revision != 1 || !internalOnly.KeyConfigured ||
|
||||
internalOnly.InternalKBID != "kb-in" || internalOnly.InternalKBName != "内部技术资料" ||
|
||||
internalOnly.ExternalKBID != "" || internalOnly.ExternalKBName != "" ||
|
||||
internalOnly.ExternalFallback != "kb-legacy-out" || internalOnly.InternalFallback != "" {
|
||||
t.Fatalf("internal-only view = %#v", internalOnly)
|
||||
}
|
||||
// 只填对内也要把未上传的待入库项改指向对内库。
|
||||
if internalOnly.Replanned != 1 {
|
||||
t.Fatalf("internal-only replanned = %d, want 1", internalOnly.Replanned)
|
||||
}
|
||||
view, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 1, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("Save() error = %v", err)
|
||||
}
|
||||
if view.Revision != 2 || !view.KeyConfigured || view.InternalKBName != "内部技术资料" || view.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("view = %#v", view)
|
||||
}
|
||||
// 待入库项在第一次保存时已经指向 kb-in:这次补上对外绑定不再移动任何行。
|
||||
if view.Replanned != 0 {
|
||||
t.Fatalf("second save replanned = %d, want 0", view.Replanned)
|
||||
}
|
||||
target, err := store.Resolve(ctx, kbbinding.EnvTest)
|
||||
if err != nil || target.BaseURL != server.URL || target.APIKey != testSecret() || target.Revision != 2 {
|
||||
t.Fatalf("Resolve() = %#v, %v", target, err)
|
||||
}
|
||||
var routingInternal, routingExternal string
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal, &routingExternal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if routingInternal != "kb-in" || routingExternal != "kb-out" {
|
||||
t.Fatalf("routing binding = %s/%s", routingInternal, routingExternal)
|
||||
}
|
||||
var pendingKB string
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-kbb'`).Scan(&pendingKB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pendingKB != "kb-in" {
|
||||
t.Fatalf("pending publication target = %s, want kb-in", pendingKB)
|
||||
}
|
||||
// A save on the test card must not carry off pending work that already aims
|
||||
// at the production binding: the two environments share test_publications.
|
||||
var productionPending string
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod-kbb'`).Scan(&productionPending); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if productionPending != "p-internal" {
|
||||
t.Fatalf("test-side save moved a production pending item to %s", productionPending)
|
||||
}
|
||||
|
||||
// A stale revision must not overwrite the saved connection or re-point work.
|
||||
_, err = store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 1, BaseURL: server.URL, KeyAction: "keep",
|
||||
InternalKBID: "kb-out", ExternalKBID: "kb-in",
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if !errors.Is(err, kbbinding.ErrConflict) {
|
||||
t.Fatalf("stale save error = %v, want ErrConflict", err)
|
||||
}
|
||||
unchanged, err := store.Resolve(ctx, kbbinding.EnvTest)
|
||||
if err != nil || unchanged.APIKey != testSecret() {
|
||||
t.Fatalf("connection changed after conflict: %#v, %v", unchanged, err)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if routingInternal != "kb-in" {
|
||||
t.Fatalf("routing binding changed after conflict: %s", routingInternal)
|
||||
}
|
||||
|
||||
// A base from another instance (404 here) must be refused and leave no row
|
||||
// for a different environment.
|
||||
if _, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "not-there", ExternalKBID: "kb-out",
|
||||
}, "admin", now); !errors.Is(err, kbbinding.ErrRejected) {
|
||||
t.Fatalf("unknown base error = %v, want ErrRejected", err)
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM weknora_environment_bindings WHERE environment='production'`).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("failed production save wrote %d rows", count)
|
||||
}
|
||||
|
||||
// The old key must never be forwarded: keep is only legal for the saved URL.
|
||||
if _, err := store.Catalog(ctx, kbbinding.EnvTest, kbbinding.CatalogInput{
|
||||
BaseURL: "https://another.example", KeyAction: "keep", Page: 1, PageSize: 20,
|
||||
}); !errors.Is(err, kbbinding.ErrKeyForwarding) {
|
||||
t.Fatalf("keep with another address = %v, want ErrKeyForwarding", err)
|
||||
}
|
||||
|
||||
prodView, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "p-internal", ExternalKBID: "p-external",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("production Save() error = %v", err)
|
||||
}
|
||||
if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 || prodView.Replanned != 0 {
|
||||
t.Fatalf("production view = %#v", prodView)
|
||||
}
|
||||
// Changing the production internal base must re-point pending 待入库 items
|
||||
// that were waiting for p-internal (the C-006 failure), and must leave the
|
||||
// test-lane publication on its own target.
|
||||
prodMoved, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: prodView.Revision, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "p-new-internal", ExternalKBID: "p-external",
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("production retarget Save() error = %v", err)
|
||||
}
|
||||
if prodMoved.Replanned != 1 || prodMoved.RetiredDuplicates != 0 {
|
||||
t.Fatalf("production replan = %d/%d, want 1 moved / 0 retired", prodMoved.Replanned, prodMoved.RetiredDuplicates)
|
||||
}
|
||||
var movedProduction, stillTest string
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod-kbb'`).Scan(&movedProduction); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if movedProduction != "p-new-internal" {
|
||||
t.Fatalf("production pending target = %s, want p-new-internal", movedProduction)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-kbb'`).Scan(&stillTest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stillTest != "kb-in" {
|
||||
t.Fatalf("test publication moved by a production save: %s", stillTest)
|
||||
}
|
||||
var productionInternal, productionURL string
|
||||
var productionTenant uint64
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id, internal_instance_url, internal_tenant_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal, &productionURL, &productionTenant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if productionInternal != "p-new-internal" || productionURL != server.URL || productionTenant != 10000 {
|
||||
t.Fatalf("production binding = %s / %s / %d", productionInternal, productionURL, productionTenant)
|
||||
}
|
||||
}
|
||||
|
||||
// 清除密钥只清凭据:名称、库 ID、绑定、实例身份全部保留,消费者必须失败关闭
|
||||
// (绝不回落到部署文件里的旧 Key),历史表只记「是否配置」而不含任何密钥。
|
||||
func TestClearKeyKeepsNamesIDsAndFrozenIdentity(t *testing.T) {
|
||||
databaseURL := pgtest.IsolatedDatabaseURL(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 := postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := fakeCandidate(t)
|
||||
store := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: masterKey(t),
|
||||
Timeout: 2 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true},
|
||||
// 部署文件里仍留着旧 Key:清除之后解析必须 ErrNotConfigured,不能悄悄用它。
|
||||
LegacyKey: func(string) (string, error) { return testSecret(), nil },
|
||||
})
|
||||
now := time.Date(2026, 11, 20, 8, 0, 0, 0, time.UTC)
|
||||
|
||||
saved, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("seed Save() error = %v", err)
|
||||
}
|
||||
if saved.Revision != 1 || saved.InternalKBName != "内部技术资料" || saved.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("seed view = %#v", saved)
|
||||
}
|
||||
|
||||
cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear",
|
||||
InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID,
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("clear Save() error = %v", err)
|
||||
}
|
||||
if cleared.Revision != 2 || cleared.KeyConfigured || cleared.KeyTail != "" {
|
||||
t.Fatalf("cleared view = %#v", cleared)
|
||||
}
|
||||
if cleared.Verification != "not_configured" {
|
||||
t.Fatalf("verification = %q, want not_configured", cleared.Verification)
|
||||
}
|
||||
if cleared.InternalKBID != "kb-in" || cleared.ExternalKBID != "kb-out" ||
|
||||
cleared.InternalKBName != "内部技术资料" || cleared.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("clear dropped the binding or its names: %#v", cleared)
|
||||
}
|
||||
if _, err := store.Resolve(ctx, kbbinding.EnvTest); !errors.Is(err, kbbinding.ErrNotConfigured) {
|
||||
t.Fatalf("Resolve() after clear = %v, want ErrNotConfigured", err)
|
||||
}
|
||||
|
||||
// 「同时改指向又清密钥」:改过的一侧不能沿用旧库名(否则新库顶着旧名字),
|
||||
// 没动的一侧仍然保留原名称。
|
||||
retargeted, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: cleared.Revision, BaseURL: server.URL, KeyAction: "clear",
|
||||
InternalKBID: "kb-new", ExternalKBID: "kb-out",
|
||||
}, "admin", now.Add(2*time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("retarget+clear Save() error = %v", err)
|
||||
}
|
||||
if retargeted.Revision != 3 || retargeted.InternalKBID != "kb-new" || retargeted.InternalKBName != "" ||
|
||||
retargeted.ExternalKBID != "kb-out" || retargeted.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("retarget+clear view = %#v", retargeted)
|
||||
}
|
||||
|
||||
// 生产侧同一口径:租户与实例地址是执行器的一致性凭据,清密钥不能把它们清零。
|
||||
prodSaved, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("production seed Save() error = %v", err)
|
||||
}
|
||||
prodCleared, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: prodSaved.Revision, BaseURL: server.URL, KeyAction: "clear",
|
||||
InternalKBID: prodSaved.InternalKBID, ExternalKBID: prodSaved.ExternalKBID,
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("production clear Save() error = %v", err)
|
||||
}
|
||||
if prodCleared.Revision != 2 || prodCleared.KeyConfigured || prodCleared.Verification != "not_configured" ||
|
||||
prodCleared.InternalKBName != "内部技术资料" || prodCleared.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("production cleared view = %#v", prodCleared)
|
||||
}
|
||||
var prodInternal, prodExternal, prodInternalURL, prodExternalURL string
|
||||
var prodInternalTenant, prodExternalTenant uint64
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT internal_kb_id,external_kb_id,internal_instance_url,external_instance_url,internal_tenant_id,external_tenant_id
|
||||
FROM production_kb_bindings WHERE id='active'`).
|
||||
Scan(&prodInternal, &prodExternal, &prodInternalURL, &prodExternalURL, &prodInternalTenant, &prodExternalTenant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if prodInternal != "kb-in" || prodExternal != "kb-out" || prodInternalURL != server.URL || prodExternalURL != server.URL ||
|
||||
prodInternalTenant != 10000 || prodExternalTenant != 10000 {
|
||||
t.Fatalf("production identity after clear = %s/%s %s/%s %d/%d",
|
||||
prodInternal, prodExternal, prodInternalURL, prodExternalURL, prodInternalTenant, prodExternalTenant)
|
||||
}
|
||||
if _, err := store.Resolve(ctx, kbbinding.EnvProduction); !errors.Is(err, kbbinding.ErrNotConfigured) {
|
||||
t.Fatalf("production Resolve() after clear = %v, want ErrNotConfigured", err)
|
||||
}
|
||||
|
||||
// 历史表只记布尔:既没有密钥列,也不含密钥明文。
|
||||
var keyConfigured bool
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT key_configured FROM weknora_environment_binding_history
|
||||
WHERE environment='test' AND revision=2`).Scan(&keyConfigured); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if keyConfigured {
|
||||
t.Fatal("history still says the cleared key is configured")
|
||||
}
|
||||
var secretColumns int
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema=current_schema() AND table_name='weknora_environment_binding_history'
|
||||
AND column_name IN ('key_ciphertext','api_key','key')`).Scan(&secretColumns); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if secretColumns != 0 {
|
||||
t.Fatalf("history table has %d key columns", secretColumns)
|
||||
}
|
||||
var leaked int
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM weknora_environment_binding_history
|
||||
WHERE base_url LIKE $1 OR internal_kb_id LIKE $1 OR external_kb_id LIKE $1 OR actor LIKE $1 OR verification LIKE $1`,
|
||||
"%"+testSecret()+"%").Scan(&leaked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if leaked != 0 {
|
||||
t.Fatalf("history contains the key plaintext in %d rows", leaked)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
const (
|
||||
statusOK = "ok"
|
||||
statusEmpty = "empty"
|
||||
statusKeyInvalid = "key_invalid"
|
||||
statusKeyForbidden = "key_forbidden"
|
||||
statusUnreachable = "unreachable"
|
||||
statusUnsupported = "unsupported"
|
||||
)
|
||||
|
||||
// Catalog validates a draft connection for real and returns one page of the
|
||||
// knowledge bases that key can read. It never writes anything and never echoes
|
||||
// the key.
|
||||
func (s *Store) Catalog(ctx context.Context, env string, input CatalogInput) (Catalog, error) {
|
||||
if !ValidEnvironment(env) {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
baseURL := strings.TrimSpace(input.BaseURL)
|
||||
if baseURL == "" || baseURL != input.BaseURL || len(baseURL) > 300 {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
page, pageSize := input.Page, input.PageSize
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
key, err := s.keyFor(ctx, env, input.KeyAction, baseURL, input.APIKey, saved, found)
|
||||
if err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
client, err := s.client(baseURL, key, env)
|
||||
if err != nil {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
result, err := client.ListKnowledgeBasesPage(ctx, page, pageSize)
|
||||
if err != nil {
|
||||
return catalogFailure(err), nil
|
||||
}
|
||||
options := make([]Option, 0, len(result.Items))
|
||||
for _, base := range result.Items {
|
||||
options = append(options, Option{ID: base.ID, Name: base.Name, KnowledgeCount: base.KnowledgeCount})
|
||||
}
|
||||
status := statusOK
|
||||
message := fmt.Sprintf("已读取 %d 个知识库", result.Total)
|
||||
if result.Total == 0 {
|
||||
status = statusEmpty
|
||||
message = "连接可用,但这个实例还没有可读的知识库"
|
||||
}
|
||||
return Catalog{Status: status, Message: message, Page: page, PageSize: pageSize, Total: result.Total, Options: options}, nil
|
||||
}
|
||||
|
||||
// catalogFailure turns a transport/permission failure into a distinguishable
|
||||
// answer: "empty" must never be shown for "could not ask".
|
||||
func catalogFailure(err error) Catalog {
|
||||
var httpErr *weknora.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
switch httpErr.StatusCode {
|
||||
case http.StatusUnauthorized:
|
||||
return Catalog{Status: statusKeyInvalid, Message: "密钥无效:该实例拒绝了这把 API Key(401)"}
|
||||
case http.StatusForbidden:
|
||||
return Catalog{Status: statusKeyForbidden, Message: "密钥无权限读取知识库列表(403)"}
|
||||
case http.StatusNotFound:
|
||||
return Catalog{Status: statusUnsupported, Message: "该地址没有知识库列表接口(HTTP 404):确认填的是 WeKnora 服务地址"}
|
||||
default:
|
||||
return Catalog{Status: statusUnreachable, Message: fmt.Sprintf("实例返回 HTTP %d,无法确认连接", httpErr.StatusCode)}
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return Catalog{Status: statusUnreachable, Message: "连接超时:检查地址、网络与防火墙"}
|
||||
}
|
||||
return Catalog{Status: statusUnreachable, Message: "服务不可达:检查地址、网络与证书"}
|
||||
}
|
||||
|
||||
// Save writes the environment's connection and both bindings in ONE
|
||||
// transaction. The candidate instance is asked first; nothing is written when
|
||||
// either selected base does not belong to it. A stale base_revision returns
|
||||
// ErrConflict and leaves the previous binding untouched.
|
||||
func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor string, now time.Time) (View, error) {
|
||||
if !ValidEnvironment(env) || strings.TrimSpace(actor) == "" || now.IsZero() {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
baseURL := strings.TrimSpace(input.BaseURL)
|
||||
internal := strings.TrimSpace(input.InternalKBID)
|
||||
external := strings.TrimSpace(input.ExternalKBID)
|
||||
if baseURL == "" || baseURL != input.BaseURL || len(baseURL) > 300 ||
|
||||
internal != input.InternalKBID || external != input.ExternalKBID ||
|
||||
len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
// 留空 = 取消该方向绑定:测试侧回退到部署默认库,生产侧回退到「同 ID 语义」,
|
||||
// 响应里会写明回退到哪(InternalFallback / ExternalFallback)。
|
||||
if internal != "" && internal == external {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
key, err := s.keyFor(ctx, env, input.KeyAction, baseURL, input.APIKey, saved, found)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
selected := map[string]selectedBase{}
|
||||
cleared := key == "" && input.KeyAction == "clear"
|
||||
if !cleared {
|
||||
client, clientErr := s.client(baseURL, key, env)
|
||||
if clientErr != nil {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
selected, err = s.verifySelection(ctx, client, internal, external)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
}
|
||||
revision := saved.Revision + 1
|
||||
if !found {
|
||||
revision = 1
|
||||
}
|
||||
sealed := []byte{}
|
||||
if !cleared {
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
sealed, err = box.Seal([]byte(key), keyAAD(env, revision))
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
}
|
||||
verification := "verified"
|
||||
if cleared {
|
||||
verification = "not_configured"
|
||||
}
|
||||
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,42))`, "weknora-binding:"+env); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
locked, lockedFound, err := scanStored(tx.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1 FOR UPDATE`, env))
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
lockedRevision := int64(0)
|
||||
if lockedFound {
|
||||
lockedRevision = locked.Revision
|
||||
}
|
||||
if lockedRevision != input.BaseRevision {
|
||||
return View{}, ErrConflict
|
||||
}
|
||||
// 清除密钥只清这一侧的凭据:名称、库 ID、绑定都保留。verified 分支里名称
|
||||
// 来自候选实例的实时读取;clear 不访问实例,所以名称必须取锁定行的旧值,
|
||||
// 否则 upsert 会用空串覆盖掉表里已有的 internal_kb_name / external_kb_name,
|
||||
// 页面只能回落显示短 ID。只在 ID 未变时沿用,避免「同时改指向又清密钥」把
|
||||
// 旧库名贴到新库上。
|
||||
internalName := selected[internal].Name
|
||||
externalName := selected[external].Name
|
||||
if cleared && lockedFound {
|
||||
if internal == locked.InternalKBID {
|
||||
internalName = locked.InternalKBName
|
||||
}
|
||||
if external == locked.ExternalKBID {
|
||||
externalName = locked.ExternalKBName
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO weknora_environment_bindings(
|
||||
environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id,
|
||||
internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$10)
|
||||
ON CONFLICT(environment) DO UPDATE SET
|
||||
revision=EXCLUDED.revision,base_url=EXCLUDED.base_url,key_ciphertext=EXCLUDED.key_ciphertext,
|
||||
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,
|
||||
verification=EXCLUDED.verification,checked_at=EXCLUDED.checked_at,
|
||||
updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`,
|
||||
env, revision, baseURL, sealed, internal, external, internalName, externalName, verification, now.UTC(), actor); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO weknora_environment_binding_history(
|
||||
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
||||
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC()); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
replan := postgresstore.RoutingBindingReplanResult{}
|
||||
if env == EnvTest {
|
||||
// 只搬「上一次生效目标」下的待入库:路由行没有值的一侧由部署默认绑定
|
||||
// 补齐(与 effectiveRoutingTargets 同一口径);两边都空就不要猜。
|
||||
previous := postgresstore.EffectiveKBIDs{}
|
||||
rowErr := tx.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id FROM routing_kb_bindings WHERE id='active' FOR UPDATE`).
|
||||
Scan(&previous.Internal, &previous.External)
|
||||
if rowErr != nil && !errors.Is(rowErr, pgx.ErrNoRows) {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
if (previous.Internal == "" || previous.External == "") && s.options.LegacyBinding != nil {
|
||||
legacyInternal, legacyExternal, legacyErr := s.options.LegacyBinding(ctx, EnvTest)
|
||||
if legacyErr != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
if previous.Internal == "" {
|
||||
previous.Internal = legacyInternal
|
||||
}
|
||||
if previous.External == "" {
|
||||
previous.External = legacyExternal
|
||||
}
|
||||
}
|
||||
if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, previous,
|
||||
postgresstore.EffectiveKBIDs{Internal: internal, External: external}, now.UTC())
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
} else {
|
||||
// 生产页只改「文档级发布」的目标映射;整库发布目标仍由部署配置决定,
|
||||
// 本保存不写它。同时冻结候选实例地址与租户,执行器写入前必须与自己的
|
||||
// 目标一致;执行已开始的项目标不会被重排改写。
|
||||
var previous postgresstore.EffectiveKBIDs
|
||||
var priorInternalTenant, priorExternalTenant uint64
|
||||
rowErr := tx.QueryRow(ctx, `
|
||||
SELECT internal_kb_id,external_kb_id,internal_tenant_id,external_tenant_id
|
||||
FROM production_kb_bindings WHERE id='active' FOR UPDATE`).
|
||||
Scan(&previous.Internal, &previous.External, &priorInternalTenant, &priorExternalTenant)
|
||||
if rowErr != nil && !errors.Is(rowErr, pgx.ErrNoRows) {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
internalTenant := selected[internal].TenantID
|
||||
externalTenant := selected[external].TenantID
|
||||
if cleared {
|
||||
// 同一条「只清密钥」口径:clear 不访问实例,租户不能被写成 0,
|
||||
// 否则执行器的实例一致性检查会把「只是没密钥」误判成换了实例。
|
||||
// 仍然只在 ID 未变时沿用。
|
||||
if internal == previous.Internal {
|
||||
internalTenant = priorInternalTenant
|
||||
}
|
||||
if external == previous.External {
|
||||
externalTenant = priorExternalTenant
|
||||
}
|
||||
}
|
||||
if err := postgresstore.SaveProductionKBBindingsWithIdentityTx(ctx, tx,
|
||||
internal, external, baseURL, baseURL,
|
||||
internalTenant, externalTenant, actor, now.UTC()); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
// 生产页保存也要让「还没上传、原本瞄准旧生产库」的待入库项改指向新库;
|
||||
// 只在国内/国外旧目标存在时搬,空的一侧是「同 ID 语义」,不能猜。
|
||||
replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, previous,
|
||||
postgresstore.EffectiveKBIDs{Internal: internal, External: external}, now.UTC())
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
view, err := s.Get(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
view.Replanned = replan.Replanned
|
||||
view.RetiredDuplicates = replan.RetiredDuplicates
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// verifySelection proves both chosen bases belong to THIS candidate instance by
|
||||
// reading them with the draft credential. An empty selection still probes the
|
||||
// list endpoint, so a save cannot store a connection nobody verified.
|
||||
type selectedBase struct {
|
||||
Name string
|
||||
TenantID uint64
|
||||
}
|
||||
|
||||
func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]selectedBase, error) {
|
||||
selected := map[string]selectedBase{}
|
||||
if internal == "" && external == "" {
|
||||
if _, err := client.ListKnowledgeBasesPage(ctx, 1, 1); err != nil {
|
||||
return nil, selectionError(err, "无法确认候选连接")
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
for _, id := range []string{internal, external} {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
base, err := client.GetKnowledgeBase(ctx, id)
|
||||
if err != nil {
|
||||
return nil, selectionError(err, fmt.Sprintf("知识库 %s 不属于该连接实例或不可读", shortID(id)))
|
||||
}
|
||||
if base.ID != id {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
selected[id] = selectedBase{Name: base.Name, TenantID: base.TenantID}
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
|
||||
func selectionError(err error, message string) error {
|
||||
var httpErr *weknora.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
if httpErr.StatusCode == http.StatusUnauthorized || httpErr.StatusCode == http.StatusForbidden {
|
||||
return fmt.Errorf("%w:密钥被实例拒绝(HTTP %d)", ErrRejected, httpErr.StatusCode)
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%w:连接超时", ErrUnreachable)
|
||||
}
|
||||
if _, ok := err.(*weknora.HTTPError); ok {
|
||||
return fmt.Errorf("%w:%s", ErrRejected, message)
|
||||
}
|
||||
if errors.Is(err, ErrInvalid) || errors.Is(err, ErrRejected) || errors.Is(err, ErrUnreachable) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w:%s", ErrUnreachable, message)
|
||||
}
|
||||
|
||||
func validBaseID(value string) bool {
|
||||
return !strings.ContainsAny(value, "\x00\r\n\t /?#\\")
|
||||
}
|
||||
|
||||
func shortID(value string) string {
|
||||
if len(value) > 8 {
|
||||
return value[:8]
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// P10: every configured dependency reports Liveness ("process reachable") and
|
||||
@@ -200,10 +201,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)
|
||||
|
||||
@@ -31,7 +31,7 @@ type RealProviderConfig struct {
|
||||
WeKnoraBaseURL string
|
||||
MinerUBaseURL string
|
||||
// TestWeKnoraResolver reads the test endpoint an admin saved in the web
|
||||
// settings, so 「服务配置」is the single place the console probes. The env
|
||||
// settings, so 「知识库映射 → WeKnora 连接」is the single place the console probes. The env
|
||||
// value above stays the bootstrap fallback for containers wired before the
|
||||
// UI existed.
|
||||
TestWeKnoraResolver func(ctx context.Context) string
|
||||
@@ -50,6 +50,10 @@ type RealProviderConfig struct {
|
||||
// WorkerStaleAfter bounds how long a missing worker heartbeat still counts
|
||||
// as alive (P10).
|
||||
WorkerStaleAfter time.Duration
|
||||
// AllowPrivateHTTP lets the console probe a same-LAN http endpoint — the
|
||||
// same judgement the WeKnora client uses, so a card can never say 「可达」
|
||||
// while the client refuses that URL.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
type RealProvider struct {
|
||||
@@ -63,6 +67,7 @@ type RealProvider struct {
|
||||
productionWeKnoraResolver func(ctx context.Context) string
|
||||
weknoraReadiness func(ctx context.Context) (string, 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) {
|
||||
@@ -114,7 +119,7 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
overview.Health = provider.Services(ctx)
|
||||
overview.Services = append(overview.Services,
|
||||
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.resolveTestWeKnoraBaseURL(ctx), now),
|
||||
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.productionWeKnoraBaseURL, now),
|
||||
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.resolveProductionWeKnoraBaseURL(ctx), now),
|
||||
governance.MonitorService{Key: "embedding", Name: "Embedding模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
|
||||
governance.MonitorService{Key: "llm", Name: "LLM模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
|
||||
provider.httpHealth(ctx, "mineru", "MinerU", provider.minerUBaseURL, now),
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RegisteredDingtalkSpaceIDs also covers historical connections whose root key
|
||||
// predates DWS; a source name is never an identity.
|
||||
func (s *Store) RegisteredDingtalkSpaceIDs(ctx context.Context) (map[string]bool, error) {
|
||||
rows, err := s.db.Query(ctx, "SELECT base_url FROM source_connections WHERE source_type='dingtalk' AND archived_at IS NULL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := map[string]bool{}
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
space := u.Query().Get("space")
|
||||
if space == "" && strings.HasPrefix(u.Path, "spaces/") {
|
||||
space = strings.TrimPrefix(u.Path, "spaces/")
|
||||
}
|
||||
if space != "" {
|
||||
result[space] = true
|
||||
}
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
-- 回滚只删本迁移新增的审计与配置表;旧部署的 file 凭据/绑定表不受影响。
|
||||
DROP TABLE IF EXISTS weknora_environment_binding_history;
|
||||
DROP TABLE IF EXISTS weknora_environment_bindings;
|
||||
@@ -0,0 +1,36 @@
|
||||
-- 「知识库绑定」按环境保存一组连接与内外库绑定:测试与生产各自一行,
|
||||
-- 一次保存同时写连接(地址 + 加密密钥)与对内/对外目标。没有行时消费者
|
||||
-- 继续使用旧部署的文件凭据/默认绑定,所以升级不需要回填。
|
||||
--
|
||||
-- key_ciphertext 只存密文;主密钥在独立文件里(WEKNORA_BINDING_MASTER_KEY_FILE),
|
||||
-- 不进库、不进备份、不经页面回显。verification 记录最近一次真实列库/选库核验。
|
||||
CREATE TABLE weknora_environment_bindings (
|
||||
environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')),
|
||||
revision BIGINT NOT NULL CHECK (revision > 0),
|
||||
base_url TEXT NOT NULL DEFAULT '',
|
||||
key_ciphertext BYTEA NOT NULL DEFAULT ''::bytea,
|
||||
internal_kb_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
external_kb_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
internal_kb_name TEXT NOT NULL DEFAULT '',
|
||||
external_kb_name TEXT NOT NULL DEFAULT '',
|
||||
verification TEXT NOT NULL DEFAULT 'not_configured'
|
||||
CHECK (verification IN ('not_configured','verified','empty','unreachable','rejected')),
|
||||
checked_at TIMESTAMPTZ,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- 修订历史只记录“是否配置了密钥”,绝不复制密文或明文,供审计回答谁在何时
|
||||
-- 把哪个环境指向了哪里。
|
||||
CREATE TABLE weknora_environment_binding_history (
|
||||
environment VARCHAR(16) NOT NULL,
|
||||
revision BIGINT NOT NULL,
|
||||
base_url TEXT NOT NULL,
|
||||
key_configured BOOLEAN NOT NULL,
|
||||
internal_kb_id VARCHAR(128) NOT NULL,
|
||||
external_kb_id VARCHAR(128) NOT NULL,
|
||||
verification TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (environment, revision)
|
||||
);
|
||||
@@ -0,0 +1,13 @@
|
||||
ALTER TABLE test_publications
|
||||
DROP COLUMN IF EXISTS test_instance_tenant,
|
||||
DROP COLUMN IF EXISTS test_instance_url;
|
||||
|
||||
ALTER TABLE release_item_executions
|
||||
DROP COLUMN IF EXISTS target_tenant_id,
|
||||
DROP COLUMN IF EXISTS target_instance_url;
|
||||
|
||||
ALTER TABLE production_kb_bindings
|
||||
DROP COLUMN IF EXISTS external_tenant_id,
|
||||
DROP COLUMN IF EXISTS internal_tenant_id,
|
||||
DROP COLUMN IF EXISTS external_instance_url,
|
||||
DROP COLUMN IF EXISTS internal_instance_url;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- 实例身份约束:网页(kbbinding)在实例 A 上列库/选库,而文档发布执行器可能
|
||||
-- 连的是实例 B。同名/同 ID 的知识库在克隆实例里完全可能存在,所以 ID 本身
|
||||
-- 不能证明“写的是网页看到的那个实例”。这里把候选连接地址与租户随绑定冻结到
|
||||
-- 每个发布项,执行器在写入前用自己的目标地址/租户核对;不一致即失败关闭。
|
||||
--
|
||||
-- 同时给测试入库的发布项记录“对象实际写入的测试实例地址/租户”:
|
||||
-- 改绑实例或租户后,旧对象不能在克隆实例上继续轮询/验收/移除。
|
||||
ALTER TABLE production_kb_bindings
|
||||
ADD COLUMN IF NOT EXISTS internal_instance_url TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS external_instance_url TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS internal_tenant_id BIGINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS external_tenant_id BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE release_item_executions
|
||||
ADD COLUMN IF NOT EXISTS target_instance_url TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS target_tenant_id BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE test_publications
|
||||
ADD COLUMN IF NOT EXISTS test_instance_url TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS test_instance_tenant BIGINT NOT NULL DEFAULT 0;
|
||||
@@ -11,8 +11,23 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 80 {
|
||||
t.Fatalf("migration count = %d, want 80", len(migrations))
|
||||
if len(migrations) != 82 {
|
||||
t.Fatalf("migration count = %d, want 82", len(migrations))
|
||||
}
|
||||
// 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
|
||||
// 实际实例身份;克隆实例同名/同 ID 不能冒充。
|
||||
if identity := migrations[81]; identity.Version != 82 ||
|
||||
!strings.Contains(identity.UpSQL, "target_instance_url") ||
|
||||
!strings.Contains(identity.UpSQL, "test_instance_url") ||
|
||||
!strings.Contains(identity.UpSQL, "internal_tenant_id") {
|
||||
t.Fatalf("migration 82 = %#v", identity)
|
||||
}
|
||||
// 81 是环境级「知识库绑定」:连接密文与内外库同表同事务,历史只记是否配置密钥。
|
||||
if binding := migrations[80]; binding.Version != 81 ||
|
||||
!strings.Contains(binding.UpSQL, "weknora_environment_bindings") ||
|
||||
!strings.Contains(binding.UpSQL, "key_ciphertext") ||
|
||||
!strings.Contains(binding.DownSQL, "DROP TABLE IF EXISTS weknora_environment_bindings") {
|
||||
t.Fatalf("migration 81 = %#v", binding)
|
||||
}
|
||||
// 79 是恢复验证:verify 成为独立业务作业并与写作业共用互斥,
|
||||
// 证据按 target_id 落库(换目标旧证据自动失效)。
|
||||
|
||||
@@ -39,14 +39,48 @@ func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, extern
|
||||
if now.IsZero() {
|
||||
return errors.New("production binding save requires a timestamp")
|
||||
}
|
||||
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)
|
||||
// 旧入口没有实例身份可写:显式清空身份列,执行器随后会失败关闭,
|
||||
// 而不是沿用上一条(可能属于另一个实例的)地址/租户。
|
||||
if _, err := s.db.Exec(ctx, productionBindingIdentityUpsertSQL,
|
||||
internalID, externalID, updatedBy, now, "", "", 0, 0); err != nil {
|
||||
return errors.New("save production kb bindings")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// productionBindingIdentityUpsertSQL freezes the instance identity the console
|
||||
// verified each side on. An empty URL keeps the legacy same-id behaviour for
|
||||
// old callers; the executor then cannot prove the instance and refuses a mapped
|
||||
// write instead of guessing.
|
||||
const productionBindingIdentityUpsertSQL = `
|
||||
INSERT INTO production_kb_bindings(
|
||||
id,internal_kb_id,external_kb_id,updated_by,updated_at,
|
||||
internal_instance_url,external_instance_url,internal_tenant_id,external_tenant_id)
|
||||
VALUES('active',$1,$2,$3,$4,$5,$6,$7,$8)
|
||||
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=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
|
||||
updated_at=EXCLUDED.updated_at,
|
||||
internal_instance_url=EXCLUDED.internal_instance_url,
|
||||
external_instance_url=EXCLUDED.external_instance_url,
|
||||
internal_tenant_id=EXCLUDED.internal_tenant_id,
|
||||
external_tenant_id=EXCLUDED.external_tenant_id`
|
||||
|
||||
// SaveProductionKBBindingsTx lets the environment-scoped 「知识库绑定」save
|
||||
// update the same row inside its own transaction, so connection and bindings
|
||||
// cannot be half-written.
|
||||
func SaveProductionKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
|
||||
return SaveProductionKBBindingsWithIdentityTx(ctx, tx, internalID, externalID, "", "", 0, 0, updatedBy, now)
|
||||
}
|
||||
|
||||
// SaveProductionKBBindingsWithIdentityTx is used by the environment-scoped
|
||||
// 「知识库绑定」save: it stores which instance/tenant each side was verified on,
|
||||
// so the release executor can refuse a cloned instance with the same base id.
|
||||
func SaveProductionKBBindingsWithIdentityTx(ctx context.Context, tx pgx.Tx, internalID, externalID, internalURL, externalURL string, internalTenant, externalTenant uint64, updatedBy string, now time.Time) error {
|
||||
if _, err := tx.Exec(ctx, productionBindingIdentityUpsertSQL,
|
||||
internalID, externalID, updatedBy, now,
|
||||
internalURL, externalURL, internalTenant, externalTenant); err != nil {
|
||||
return errors.New("save production kb bindings")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -11,19 +11,22 @@ import (
|
||||
)
|
||||
|
||||
type PublicationForRemoval struct {
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
RetrievalState governance.RetrievalState
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
TestInstanceURL string
|
||||
TestInstanceTenant uint64
|
||||
RetrievalState governance.RetrievalState
|
||||
}
|
||||
|
||||
func (s *Store) LoadPublicationForRemoval(ctx context.Context, publicationID string) (PublicationForRemoval, error) {
|
||||
var candidate PublicationForRemoval
|
||||
var retrievalState string
|
||||
err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,retrieval_state
|
||||
err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,test_instance_url,test_instance_tenant,retrieval_state
|
||||
FROM test_publications
|
||||
WHERE id=$1 AND knowledge_id<>'' AND retrieval_state='disabling'`, publicationID).Scan(
|
||||
&candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID, &retrievalState,
|
||||
&candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID,
|
||||
&candidate.TestInstanceURL, &candidate.TestInstanceTenant, &retrievalState,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return PublicationForRemoval{}, ErrPublicationStateConflict
|
||||
|
||||
@@ -75,13 +75,32 @@ execution_gate AS (
|
||||
WHEN 'internal' THEN binding.internal_kb_id
|
||||
WHEN 'external' THEN binding.external_kb_id
|
||||
END, ''),
|
||||
publication.test_kb_id) AS target_kb_id
|
||||
publication.test_kb_id) AS target_kb_id,
|
||||
-- 身份必须与 target_kb_id 来自同一来源:重试/回滚沿用的旧目标若
|
||||
-- 没有身份(迁移前),不能拿当前绑定去补,否则会把旧项写到新实例;
|
||||
-- 这种情况留空,由执行器失败关闭。
|
||||
CASE
|
||||
WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL
|
||||
THEN COALESCE(prior_item.target_instance_url, '')
|
||||
ELSE COALESCE(NULLIF(CASE publication.target_scope
|
||||
WHEN 'internal' THEN binding.internal_instance_url
|
||||
WHEN 'external' THEN binding.external_instance_url
|
||||
END, ''), '')
|
||||
END AS target_instance_url,
|
||||
CASE
|
||||
WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL
|
||||
THEN COALESCE(prior_item.target_tenant_id, 0)
|
||||
ELSE COALESCE(NULLIF(CASE publication.target_scope
|
||||
WHEN 'internal' THEN binding.internal_tenant_id
|
||||
WHEN 'external' THEN binding.external_tenant_id
|
||||
END, 0), 0)
|
||||
END AS target_tenant_id
|
||||
FROM started
|
||||
JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id
|
||||
JOIN test_publications AS publication ON publication.id = item.publication_id
|
||||
LEFT JOIN production_kb_bindings AS binding ON binding.id = 'active'
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT candidate.target_knowledge_base_id
|
||||
SELECT candidate.target_knowledge_base_id, candidate.target_instance_url, candidate.target_tenant_id
|
||||
FROM release_item_executions AS candidate
|
||||
JOIN release_executions AS candidate_execution ON candidate_execution.id = candidate.release_execution_id
|
||||
WHERE candidate.publication_id = item.publication_id
|
||||
@@ -94,11 +113,14 @@ execution_gate AS (
|
||||
) AS prior_item ON TRUE
|
||||
), seeded AS (
|
||||
INSERT INTO release_item_executions (
|
||||
id, release_execution_id, publication_id, action, state, created_at, updated_at, target_knowledge_base_id
|
||||
id, release_execution_id, publication_id, action, state, created_at, updated_at,
|
||||
target_knowledge_base_id, target_instance_url, target_tenant_id
|
||||
)
|
||||
SELECT 'ri-' || SUBSTR(MD5(started.id || ':' || item.publication_id), 1, 32),
|
||||
started.id, item.publication_id, item.action, 'pending', $4::TIMESTAMPTZ, $4::TIMESTAMPTZ,
|
||||
COALESCE(target_base.target_kb_id, '')
|
||||
COALESCE(target_base.target_kb_id, ''),
|
||||
COALESCE(target_base.target_instance_url, ''),
|
||||
COALESCE(target_base.target_tenant_id, 0)
|
||||
FROM started
|
||||
JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id
|
||||
LEFT JOIN target_base ON target_base.publication_id = item.publication_id
|
||||
@@ -129,6 +151,8 @@ execution_gate AS (
|
||||
item.review_id AS release_revision,
|
||||
publication.test_kb_id,
|
||||
COALESCE(target_base.target_kb_id, '') AS target_kb_id,
|
||||
COALESCE(target_base.target_instance_url, '') AS target_instance_url,
|
||||
COALESCE(target_base.target_tenant_id, 0) AS target_tenant_id,
|
||||
publication.knowledge_id,
|
||||
item.decided_visibility,
|
||||
COALESCE(previous.production_revision, '') AS previous_production_revision
|
||||
@@ -180,6 +204,8 @@ SELECT COUNT(DISTINCT started.id)::INTEGER,
|
||||
'release_revision', plan.release_revision,
|
||||
'test_knowledge_base_id', plan.test_kb_id,
|
||||
'target_knowledge_base_id', plan.target_kb_id,
|
||||
'target_instance_url', plan.target_instance_url,
|
||||
'target_tenant_id', plan.target_tenant_id,
|
||||
'knowledge_id', plan.knowledge_id,
|
||||
'decided_visibility', plan.decided_visibility,
|
||||
'previous_production_revision', plan.previous_production_revision
|
||||
@@ -307,7 +333,8 @@ func (s *Store) StartExecution(ctx context.Context, request releaseworkflow.Star
|
||||
if !validShortID(item.PublicationID) || !validShortID(item.SourceItemVersionID) ||
|
||||
!validRemoteIdentifier(item.TestKnowledgeBaseID) || !validRemoteIdentifier(item.TargetKnowledgeBaseID) || !validRemoteIdentifier(item.KnowledgeID) ||
|
||||
(item.DecidedVisibility != governance.VisibilityInternal && item.DecidedVisibility != governance.VisibilityExternal) ||
|
||||
len(item.PreviousProductionRevision) > 128 {
|
||||
len(item.PreviousProductionRevision) > 128 || len(item.TargetInstanceURL) > 300 ||
|
||||
strings.ContainsAny(item.TargetInstanceURL, " \r\n\x00") {
|
||||
return nil, errors.New("invalid release execution plan")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T) {
|
||||
payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]`
|
||||
payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","target_instance_url":"https://instance-a.weknora.example","target_tenant_id":10000,"knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]`
|
||||
db := &recordingDB{row: startExecutionRow{executionCount: 1, payload: []byte(payload)}}
|
||||
items, err := NewStore(db).StartExecution(context.Background(), releaseworkflow.StartExecutionRequest{
|
||||
ExecutionID: "rx-safe", JobID: "job-safe", Operation: "publish", Now: time.Now(),
|
||||
@@ -24,7 +24,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T)
|
||||
if len(items) != 1 || items[0].PublicationID != "tp-safe" || items[0].Action != "delete" || items[0].KnowledgeID != "knowledge-safe" || items[0].PreviousProductionRevision != "prod-old" {
|
||||
t.Fatalf("items=%#v", items)
|
||||
}
|
||||
if items[0].TargetBase() != "prod-kb" {
|
||||
if items[0].TargetBase() != "prod-kb" || items[0].TargetInstanceURL != "https://instance-a.weknora.example" || items[0].TargetTenantID != 10000 {
|
||||
t.Fatalf("target base=%q, want the mapped 源库 → 目标库 target", items[0].TargetBase())
|
||||
}
|
||||
sql := strings.ToLower(db.queryRowSQL)
|
||||
@@ -39,6 +39,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T)
|
||||
"release_delete_ready", "item.action = 'delete'", "execution_gate.valid_items = execution_gate.item_count",
|
||||
// the 源库 → 目标库 mapping is resolved into the plan and frozen per item
|
||||
"production_kb_bindings", "target_knowledge_base_id", "target_base.target_kb_id",
|
||||
"target_instance_url", "target_tenant_id", "internal_instance_url", "internal_tenant_id",
|
||||
} {
|
||||
if !strings.Contains(sql, required) {
|
||||
t.Fatalf("start execution SQL missing %q", required)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
releaseworkflow "knowledge-governance/internal/workflows/release"
|
||||
)
|
||||
|
||||
// The console verified the production binding on instance A. The release plan
|
||||
// must freeze that instance identity with each item; the executor later compares
|
||||
// it with its own route target before writing. Same knowledge-base id/tenant on
|
||||
// a cloned instance is not enough.
|
||||
func TestStartReleaseExecutionFreezesTheBindingInstanceIdentity(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.Fatal(err)
|
||||
}
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO source_connections (id, source_type, name) VALUES ('conn-manual', 'manual', 'Manual')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publicationID := "tp-identity-e2e"
|
||||
insertReviewFixture(t, ctx, pool, 9, publicationID, now)
|
||||
if _, err := store.ReviewPublication(ctx, governance.ReviewPublicationRequest{PublicationID: publicationID, Decision: governance.ReviewApproved, DecidedVisibility: governance.VisibilityInternal, ReviewerRef: "engineer-1", DecisionCode: "approved_for_release", Now: now.Add(time.Minute)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
batch, err := store.CreateReleaseBatch(ctx, governance.CreateReleaseBatchRequest{Name: "Identity publish", CreatedBy: "engineer-1", PublicationIDs: []string{publicationID}, Now: now.Add(2 * time.Minute)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.SealReleaseBatch(ctx, governance.SealReleaseBatchRequest{BatchID: batch.ID, SealedBy: "engineer-2", Now: now.Add(3 * time.Minute)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
execution, err := store.AuthorizeReleaseBatch(ctx, governance.AuthorizeReleaseBatchRequest{BatchID: batch.ID, AuthorizedBy: "release-owner", AuthorizationCode: "production_release_authorized", Now: now.Add(4 * time.Minute)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveProductionKBBindingsWithIdentityTx(ctx, tx, "test-kb", "test-kb", "https://instance-a.weknora.example", "https://instance-a.weknora.example", 10000, 10000, "admin", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plan, err := store.StartExecution(ctx, releaseworkflow.StartExecutionRequest{ExecutionID: execution.ID, JobID: execution.JobID, Operation: governance.ReleaseOperationPublish, Now: now.Add(5 * time.Minute)})
|
||||
if err != nil || len(plan) != 1 {
|
||||
t.Fatalf("plan=%#v error=%v", plan, err)
|
||||
}
|
||||
if plan[0].TargetKnowledgeBaseID != "test-kb" || plan[0].TargetInstanceURL != "https://instance-a.weknora.example" || plan[0].TargetTenantID != 10000 {
|
||||
t.Fatalf("plan identity = %s / %s / %d", plan[0].TargetKnowledgeBaseID, plan[0].TargetInstanceURL, plan[0].TargetTenantID)
|
||||
}
|
||||
}
|
||||
@@ -60,14 +60,33 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
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.
|
||||
// EffectiveKBIDs is the pair of knowledge base ids consumers actually route to:
|
||||
// the UI binding where it is set, the deployment default otherwise. A save must
|
||||
// name both the pair it replaces and the pair it establishes, so re-planning
|
||||
// only moves work that was aimed at THIS environment's previous target.
|
||||
type EffectiveKBIDs struct {
|
||||
Internal string
|
||||
External string
|
||||
}
|
||||
|
||||
// RoutingBindingSave is one binding change: the ids to persist plus the
|
||||
// effective routing before and after it.
|
||||
type RoutingBindingSave struct {
|
||||
InternalID string
|
||||
ExternalID string
|
||||
Previous EffectiveKBIDs
|
||||
Effective EffectiveKBIDs
|
||||
UpdatedBy string
|
||||
}
|
||||
|
||||
// replanRetireDuplicatesSQL retires a pending publication aimed at the previous
|
||||
// target 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.
|
||||
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 = $1
|
||||
AND stale.processing_state = 'planned'
|
||||
AND stale.ingest_state = 'pending'
|
||||
AND stale.knowledge_id = ''
|
||||
@@ -77,7 +96,7 @@ WHERE stale.superseded_at IS NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM test_publications twin
|
||||
WHERE twin.source_item_version_id = stale.source_item_version_id
|
||||
AND twin.test_kb_id = $1
|
||||
AND twin.test_kb_id = $3
|
||||
AND twin.superseded_at IS NULL)
|
||||
`
|
||||
|
||||
@@ -86,9 +105,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 = $3, test_instance_url = '', test_instance_tenant = 0, updated_at = $4
|
||||
WHERE pending.superseded_at IS NULL
|
||||
AND pending.test_kb_id <> $1
|
||||
AND pending.test_kb_id = $1
|
||||
AND pending.processing_state = 'planned'
|
||||
AND pending.ingest_state = 'pending'
|
||||
AND pending.knowledge_id = ''
|
||||
@@ -98,20 +117,20 @@ WHERE pending.superseded_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM test_publications twin
|
||||
WHERE twin.source_item_version_id = pending.source_item_version_id
|
||||
AND twin.test_kb_id = $1
|
||||
AND twin.test_kb_id = $3
|
||||
AND twin.superseded_at IS NULL)
|
||||
`
|
||||
|
||||
// SaveRoutingKBBindingsWithReplan saves the binding and, in the SAME
|
||||
// transaction, re-points 待入库 items that were still waiting for the old
|
||||
// SaveRoutingKBBindingsWithReplan saves the test-side binding and, in the SAME
|
||||
// transaction, re-points 待入库 items that were still waiting for the previous
|
||||
// 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) {
|
||||
// save.Previous is the effective pair before the change (stored binding, or the
|
||||
// deployment default where a side was unbound); an empty or unchanged side is
|
||||
// not guessed at.
|
||||
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, save RoutingBindingSave, now time.Time) (RoutingBindingReplanResult, error) {
|
||||
var result RoutingBindingReplanResult
|
||||
if now.IsZero() {
|
||||
return result, errors.New("binding replan requires a timestamp")
|
||||
@@ -121,6 +140,22 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID,
|
||||
return result, fmt.Errorf("begin routing binding save: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err := SaveRoutingKBBindingsTx(ctx, tx, save.InternalID, save.ExternalID, save.UpdatedBy, now); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result, err = ReplanPendingPublicationsTx(ctx, tx, save.Previous, save.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)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SaveRoutingKBBindingsTx is the binding upsert, shared by the settings page and
|
||||
// the environment-scoped 「知识库绑定」save so the two entries cannot drift.
|
||||
func SaveRoutingKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
|
||||
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)
|
||||
@@ -129,28 +164,37 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
external_kb_id=EXCLUDED.external_kb_id,
|
||||
updated_by=EXCLUDED.updated_by,
|
||||
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
|
||||
return result, errors.New("save routing kb bindings")
|
||||
return errors.New("save routing kb bindings")
|
||||
}
|
||||
for _, scope := range []struct{ name, kbID string }{
|
||||
{"internal", effectiveInternal},
|
||||
{"external", effectiveExternal},
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplanPendingPublicationsTx re-points untouched 待入库 rows from the previous
|
||||
// effective targets to the new ones inside the caller's transaction. It only
|
||||
// moves rows that were never uploaded anywhere AND were aimed at the previous
|
||||
// target: that target check is what keeps one environment's save from carrying
|
||||
// off pending work belonging to the other environment (both envs share the
|
||||
// test_publications lane until an item is executed). Anything already in flight
|
||||
// keeps its frozen target.
|
||||
func ReplanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
|
||||
var result RoutingBindingReplanResult
|
||||
for _, scope := range []struct{ name, from, to string }{
|
||||
{"internal", previous.Internal, effective.Internal},
|
||||
{"external", previous.External, effective.External},
|
||||
} {
|
||||
if scope.kbID == "" {
|
||||
if scope.from == "" || scope.to == "" || scope.from == scope.to {
|
||||
continue
|
||||
}
|
||||
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.kbID, scope.name, now)
|
||||
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.from, scope.name, scope.to, 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)
|
||||
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.from, scope.name, scope.to, now)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("replan pending publications: %w", err)
|
||||
}
|
||||
result.RetiredDuplicates += int(retired.RowsAffected())
|
||||
result.Replanned += int(moved.RowsAffected())
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return result, fmt.Errorf("commit routing binding save: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -33,16 +33,19 @@ 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-prod','conn-replan','n-prod',repeat('b',64),'docs/prod.docx','prod.docx','document','locator:r5','internal','configured_scope'),
|
||||
('item-dup','conn-replan','n-dup',repeat('b',64),'docs/dup.docx','dup.docx','document','locator:r4','internal','configured_scope');
|
||||
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
||||
('v-in','item-in','locator:r1',NULL,'unknown'),
|
||||
('v-ext','item-ext','locator:r2',NULL,'unknown'),
|
||||
('v-sent','item-sent','locator:r3',NULL,'unknown'),
|
||||
('v-prod','item-prod','locator:r5',NULL,'unknown'),
|
||||
('v-dup','item-dup','locator:r4',NULL,'unknown');
|
||||
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
||||
('pub-in','v-in','kb-old-internal','planned','pending','internal'),
|
||||
('pub-ext','v-ext','kb-old-external','planned','pending','external'),
|
||||
('pub-sent','v-sent','kb-old-internal','pending','uploaded','internal'),
|
||||
('pub-prod','v-prod','p-internal','planned','pending','internal'),
|
||||
('pub-dup-old','v-dup','kb-old-internal','planned','pending','internal'),
|
||||
('pub-dup-new','v-dup','kb-new-internal','planned','pending','internal');
|
||||
INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
|
||||
@@ -53,12 +56,19 @@ 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",
|
||||
Previous: EffectiveKBIDs{Internal: "kb-old-internal", External: "kb-old-external"},
|
||||
Effective: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||
UpdatedBy: "tester",
|
||||
}, now)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveRoutingKBBindingsWithReplan() error = %v", err)
|
||||
}
|
||||
// pub-in and pub-ext move; pub-sent already has an upload job (untouched);
|
||||
// pub-dup-old already has a twin for the new KB so it is retired instead.
|
||||
// pub-dup-old already has a twin for the new KB so it is retired instead;
|
||||
// pub-prod aims at the production binding and must not be carried off by a
|
||||
// test-side save.
|
||||
if result.Replanned != 2 || result.RetiredDuplicates != 1 {
|
||||
t.Fatalf("replan result = %#v, want 2 moved / 1 retired", result)
|
||||
}
|
||||
@@ -95,9 +105,17 @@ 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"])
|
||||
}
|
||||
if states["pub-prod"].kb != "p-internal" || states["pub-prod"].superseded {
|
||||
t.Fatalf("a pending item aimed at another environment's target must stay put: %#v", states["pub-prod"])
|
||||
}
|
||||
|
||||
// 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",
|
||||
Previous: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||
Effective: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||
UpdatedBy: "tester",
|
||||
}, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -29,22 +29,27 @@ type PublicationForUpload struct {
|
||||
SourceItemVersionID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
IngestState governance.IngestState
|
||||
ProcessingState governance.ProcessingState
|
||||
TargetScope governance.Visibility
|
||||
ContentObjectID string
|
||||
SHA256 string
|
||||
SizeBytes int64
|
||||
MIME string
|
||||
ValidatedFormat string
|
||||
LocalSpoolRef string
|
||||
Title string
|
||||
// 对象实际写入的测试实例身份;空 = 迁移前的旧行,无法证明归属。
|
||||
TestInstanceURL string
|
||||
TestInstanceTenant uint64
|
||||
IngestState governance.IngestState
|
||||
ProcessingState governance.ProcessingState
|
||||
TargetScope governance.Visibility
|
||||
ContentObjectID string
|
||||
SHA256 string
|
||||
SizeBytes int64
|
||||
MIME string
|
||||
ValidatedFormat string
|
||||
LocalSpoolRef string
|
||||
Title string
|
||||
}
|
||||
|
||||
type PublicationForPoll struct {
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
TestInstanceURL string
|
||||
TestInstanceTenant uint64
|
||||
ProcessingState governance.ProcessingState
|
||||
PollSequence int
|
||||
LastRemoteStatus string
|
||||
@@ -55,9 +60,11 @@ type PublicationForPoll struct {
|
||||
}
|
||||
|
||||
type PublicationForValidation struct {
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
TestInstanceURL string
|
||||
TestInstanceTenant uint64
|
||||
// TargetScope 决定这条知识发到哪个生产库(对内/对外)。自动批准策略依赖它:
|
||||
// 默认只自动批准"对内","对外"仍要人工。
|
||||
TargetScope string
|
||||
@@ -71,6 +78,7 @@ type LegacyVerificationCandidate struct {
|
||||
|
||||
const loadPublicationForUploadSQL = `
|
||||
SELECT p.id, p.source_item_version_id, p.test_kb_id, p.knowledge_id,
|
||||
p.test_instance_url, p.test_instance_tenant,
|
||||
p.ingest_state, p.processing_state, p.target_scope,
|
||||
co.id, co.sha256, co.size_bytes, co.mime, co.validated_format,
|
||||
co.local_spool_ref, si.title
|
||||
@@ -89,7 +97,8 @@ WHERE p.id = $1
|
||||
`
|
||||
|
||||
const loadPublicationForPollSQL = `
|
||||
SELECT id, test_kb_id, knowledge_id, processing_state, poll_sequence,
|
||||
SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant,
|
||||
processing_state, poll_sequence,
|
||||
last_remote_status, last_remote_updated_at, processing_started_at,
|
||||
last_observed_at, updated_at
|
||||
FROM test_publications
|
||||
@@ -97,7 +106,7 @@ WHERE id = $1
|
||||
`
|
||||
|
||||
const loadPublicationForValidationSQL = `
|
||||
SELECT id, test_kb_id, knowledge_id, target_scope
|
||||
SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant, target_scope
|
||||
FROM test_publications
|
||||
WHERE id = $1
|
||||
AND ingest_state = 'uploaded'
|
||||
@@ -223,8 +232,10 @@ ON CONFLICT (idempotency_key) DO NOTHING
|
||||
const markUploadingSQL = `
|
||||
UPDATE test_publications
|
||||
SET ingest_state = 'uploading',
|
||||
test_instance_url = $2,
|
||||
test_instance_tenant = $3,
|
||||
last_error = '',
|
||||
updated_at = $2
|
||||
updated_at = $4
|
||||
WHERE id = $1
|
||||
AND ingest_state IN ('pending', 'uploading')
|
||||
AND processing_state = 'pending'
|
||||
@@ -393,6 +404,8 @@ func (s *Store) LoadPublicationForUpload(ctx context.Context, publicationID stri
|
||||
&candidate.SourceItemVersionID,
|
||||
&candidate.TestKBID,
|
||||
&candidate.KnowledgeID,
|
||||
&candidate.TestInstanceURL,
|
||||
&candidate.TestInstanceTenant,
|
||||
&ingestState,
|
||||
&processingState,
|
||||
&candidate.TargetScope,
|
||||
@@ -422,6 +435,8 @@ func (s *Store) LoadPublicationForPoll(ctx context.Context, publicationID string
|
||||
&publication.ID,
|
||||
&publication.TestKBID,
|
||||
&publication.KnowledgeID,
|
||||
&publication.TestInstanceURL,
|
||||
&publication.TestInstanceTenant,
|
||||
&processingState,
|
||||
&publication.PollSequence,
|
||||
&publication.LastRemoteStatus,
|
||||
@@ -446,6 +461,8 @@ func (s *Store) LoadPublicationForValidation(ctx context.Context, publicationID
|
||||
&publication.ID,
|
||||
&publication.TestKBID,
|
||||
&publication.KnowledgeID,
|
||||
&publication.TestInstanceURL,
|
||||
&publication.TestInstanceTenant,
|
||||
&publication.TargetScope,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -594,8 +611,8 @@ func (s *Store) RetryPublication(ctx context.Context, publicationID string, now
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) MarkUploading(ctx context.Context, publicationID string, now time.Time) error {
|
||||
tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, now)
|
||||
func (s *Store) MarkUploading(ctx context.Context, publicationID, instanceURL string, instanceTenant uint64, now time.Time) error {
|
||||
tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, instanceURL, instanceTenant, now)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark test publication uploading: %w", err)
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ func TestPublicationOrchestrationIsAtomicAndRejectsStaleTransitions(t *testing.T
|
||||
if _, err := store.LoadPublicationForUpload(ctx, "publication-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.MarkUploading(ctx, "publication-1", now); err != nil {
|
||||
if err := store.MarkUploading(ctx, "publication-1", "", 0, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
|
||||
|
||||
@@ -39,7 +39,7 @@ func TestLoadPublicationForUploadMapsVerifiedCandidate(t *testing.T) {
|
||||
|
||||
func TestMarkUploadingRejectsStalePublicationState(t *testing.T) {
|
||||
db := &recordingDB{commandTag: pgconn.NewCommandTag("UPDATE 0")}
|
||||
err := NewStore(db).MarkUploading(context.Background(), "publication-1", time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC))
|
||||
err := NewStore(db).MarkUploading(context.Background(), "publication-1", "", 0, time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC))
|
||||
if !errors.Is(err, ErrPublicationStateConflict) {
|
||||
t.Fatalf("MarkUploading() error = %v, want ErrPublicationStateConflict", err)
|
||||
}
|
||||
@@ -380,6 +380,8 @@ func (publicationValidationRow) Scan(dest ...any) error {
|
||||
*(dest[0].(*string)) = "publication-1"
|
||||
*(dest[1].(*string)) = "kb-1"
|
||||
*(dest[2].(*string)) = "knowledge-1"
|
||||
*(dest[3].(*string)) = ""
|
||||
*(dest[4].(*uint64)) = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -547,13 +549,15 @@ func (row publicationPollRow) Scan(dest ...any) error {
|
||||
*(dest[0].(*string)) = "publication-1"
|
||||
*(dest[1].(*string)) = "kb-1"
|
||||
*(dest[2].(*string)) = "knowledge-1"
|
||||
*(dest[3].(*string)) = string(governance.ProcessingProcessing)
|
||||
*(dest[4].(*int)) = 2
|
||||
*(dest[5].(*string)) = "processing"
|
||||
*(dest[6].(**time.Time)) = &row.now
|
||||
*(dest[7].(**time.Time)) = &row.now
|
||||
*(dest[3].(*string)) = ""
|
||||
*(dest[4].(*uint64)) = 0
|
||||
*(dest[5].(*string)) = string(governance.ProcessingProcessing)
|
||||
*(dest[6].(*int)) = 2
|
||||
*(dest[7].(*string)) = "processing"
|
||||
*(dest[8].(**time.Time)) = &row.now
|
||||
*(dest[9].(**time.Time)) = &row.now
|
||||
*(dest[10].(**time.Time)) = &row.now
|
||||
*(dest[11].(**time.Time)) = &row.now
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -572,6 +576,8 @@ func (publicationUploadRow) Scan(dest ...any) error {
|
||||
"version-1",
|
||||
"kb-1",
|
||||
"",
|
||||
"", // test_instance_url
|
||||
uint64(0),
|
||||
string(governance.IngestPending),
|
||||
string(governance.ProcessingPending),
|
||||
"internal",
|
||||
@@ -589,6 +595,8 @@ func (publicationUploadRow) Scan(dest ...any) error {
|
||||
*target = value.(string)
|
||||
case *int64:
|
||||
*target = value.(int64)
|
||||
case *uint64:
|
||||
*target = value.(uint64)
|
||||
case *governance.Visibility:
|
||||
*target = governance.Visibility(value.(string))
|
||||
case nil:
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// WorkerHeartbeat 是队列认领时顺手写下的存活记录(P10)。
|
||||
// 它本来就带 job_types:页面用它判断“这个 worker 有没有注册上传/解析链”,
|
||||
// 不需要再开一张表,也不该拿 readiness 或 env 去猜。
|
||||
type WorkerHeartbeat struct {
|
||||
WorkerID string
|
||||
JobTypes []string
|
||||
StartedAt time.Time
|
||||
LastSeenAt time.Time
|
||||
}
|
||||
|
||||
func (s *Store) ListWorkerHeartbeats(ctx context.Context) ([]WorkerHeartbeat, error) {
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT worker_id, job_types, started_at, last_seen_at
|
||||
FROM worker_heartbeats ORDER BY last_seen_at DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []WorkerHeartbeat
|
||||
for rows.Next() {
|
||||
var hb WorkerHeartbeat
|
||||
var types string
|
||||
if err := rows.Scan(&hb.WorkerID, &types, &hb.StartedAt, &hb.LastSeenAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if types != "" {
|
||||
hb.JobTypes = strings.Split(types, ",")
|
||||
}
|
||||
out = append(out, hb)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -48,6 +48,53 @@ type ClientConfig struct {
|
||||
Timeout time.Duration
|
||||
MaxResponseBytes int64
|
||||
AllowDockerHTTP bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for RFC1918 / link-local
|
||||
// literals, because the production instance is only reachable as a same-LAN
|
||||
// http reverse proxy. Public http hosts stay refused.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
// HTTPPolicy is the single reachability judgement shared by the WeKnora client,
|
||||
// the console probes and the binding page: 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 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
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
@@ -65,7 +112,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, "/")
|
||||
@@ -234,6 +281,31 @@ func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBasesPage reads one page. The console must show every readable
|
||||
// base without pretending the first page is the whole set, so the total is
|
||||
// carried through whenever the instance reports one.
|
||||
func (c *Client) ListKnowledgeBasesPage(ctx context.Context, page, pageSize int) (KnowledgeBasePage, error) {
|
||||
if !validPage(page, pageSize) {
|
||||
return KnowledgeBasePage{}, errors.New("invalid knowledge base list request")
|
||||
}
|
||||
query := url.Values{}
|
||||
query.Set("page", fmt.Sprint(page))
|
||||
query.Set("page_size", fmt.Sprint(pageSize))
|
||||
var response knowledgeBaseListResponse
|
||||
if err := c.doJSONQuery(ctx, http.MethodGet, "/api/v1/knowledge-bases", query, nil, &response); err != nil {
|
||||
return KnowledgeBasePage{}, err
|
||||
}
|
||||
if !response.Success {
|
||||
return KnowledgeBasePage{}, errors.New("WeKnora returned an unsuccessful knowledge base list")
|
||||
}
|
||||
total := response.Total
|
||||
totalKnown := total > 0 || (len(response.Data) == 0 && response.Page > 0)
|
||||
if !totalKnown {
|
||||
total = int64(len(response.Data))
|
||||
}
|
||||
return KnowledgeBasePage{Items: response.Data, Total: total, Page: page, PageSize: pageSize, TotalKnown: totalKnown}, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeBase reads a single knowledge base by id. A knowledge base that is
|
||||
// not there surfaces as *HTTPError with status 404, so a caller can tell
|
||||
// "definitely absent" from "could not ask".
|
||||
|
||||
@@ -2,6 +2,8 @@ package weknora
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -76,8 +78,21 @@ type KnowledgeBase struct {
|
||||
}
|
||||
|
||||
type knowledgeBaseListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []KnowledgeBase `json:"data"`
|
||||
Success bool `json:"success"`
|
||||
Data []KnowledgeBase `json:"data"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
// KnowledgeBasePage is one page of the readable knowledge bases. TotalKnown is
|
||||
// false when the instance did not report a total; callers must not invent one.
|
||||
type KnowledgeBasePage struct {
|
||||
Items []KnowledgeBase
|
||||
Total int64
|
||||
Page int
|
||||
PageSize int
|
||||
TotalKnown bool
|
||||
}
|
||||
|
||||
type knowledgeBaseResponse struct {
|
||||
@@ -85,6 +100,34 @@ type knowledgeBaseResponse struct {
|
||||
Data KnowledgeBase `json:"data"`
|
||||
}
|
||||
|
||||
// InstanceIdentity is the verifiable identity of the WeKnora instance a call
|
||||
// actually reached: the normalized service address plus the tenant that owns
|
||||
// the knowledge base. Knowledge base ids alone cannot distinguish a cloned
|
||||
// instance, so workflows that stored an object must compare this before using
|
||||
// the object again.
|
||||
type InstanceIdentity struct {
|
||||
BaseURL string
|
||||
TenantID uint64
|
||||
}
|
||||
|
||||
// NormalizeInstanceURL is the single comparison form for service addresses:
|
||||
// scheme/host are case-insensitive and a trailing slash is not a different
|
||||
// instance. Userinfo/query/fragment never reach storage (endpoints are
|
||||
// validated as bare origins), so they are deliberately dropped here.
|
||||
func NormalizeInstanceURL(raw string) string {
|
||||
parsed, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || parsed.Host == "" {
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
parsed.Scheme = strings.ToLower(parsed.Scheme)
|
||||
parsed.Host = strings.ToLower(parsed.Host)
|
||||
parsed.Path = strings.TrimRight(parsed.Path, "/")
|
||||
parsed.User = nil
|
||||
parsed.RawQuery = ""
|
||||
parsed.Fragment = ""
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
type chunkListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []Chunk `json:"data"`
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Credentials struct {
|
||||
ID string `json:"id"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
type Draft struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password,omitempty"`
|
||||
PendingID string `json:"pending_id,omitempty"`
|
||||
Revision int `json:"revision"`
|
||||
}
|
||||
type Observation struct {
|
||||
State string `json:"state"`
|
||||
Message string `json:"message"`
|
||||
CheckedAt string `json:"checked_at"`
|
||||
Previous *Observation `json:"previous,omitempty"`
|
||||
}
|
||||
type Metadata struct {
|
||||
ID string `json:"id"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
PasswordConfigured bool `json:"password_configured"`
|
||||
}
|
||||
type View struct {
|
||||
Revision int `json:"revision"`
|
||||
Active *Metadata `json:"active"`
|
||||
Pending *Metadata `json:"pending"`
|
||||
Observation *Observation `json:"observation"`
|
||||
PendingObservation *Observation `json:"pending_observation"`
|
||||
}
|
||||
type AuditEvent struct {
|
||||
ID string `json:"id"`
|
||||
SourceName string `json:"source_name"`
|
||||
Action string `json:"action"`
|
||||
Actor string `json:"actor"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
type State struct {
|
||||
Revision int `json:"revision"`
|
||||
Active *Credentials `json:"active"`
|
||||
Pending *Credentials `json:"pending"`
|
||||
Observation *Observation `json:"observation"`
|
||||
PendingObservation *Observation `json:"pending_observation"`
|
||||
Audit []AuditEvent `json:"audit"`
|
||||
}
|
||||
type Manager struct {
|
||||
Path string
|
||||
LegacyPath string
|
||||
Probe func(context.Context, Credentials) Observation
|
||||
}
|
||||
|
||||
var ErrRejected = errors.New("PP 配置校验未通过,原配置保留")
|
||||
var ErrInvalid = errors.New("API 地址必须为 HTTPS 根地址,且不能包含凭据、查询参数或片段")
|
||||
var ErrConflict = errors.New("配置已被更新,请刷新后重新提交")
|
||||
|
||||
func ValidateBaseURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && len(raw) <= 300 && strings.TrimSpace(raw) == raw && u.Scheme == "https" && u.Host != "" && u.Hostname() != "" && u.Opaque == "" && u.User == nil && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.Contains(raw, "#") && (u.Path == "" || u.Path == "/")
|
||||
}
|
||||
func metadata(c *Credentials) *Metadata {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &Metadata{ID: c.ID, BaseURL: c.BaseURL, Username: c.Username, PasswordConfigured: c.Password != ""}
|
||||
}
|
||||
func view(s State) View {
|
||||
return View{Revision: s.Revision, Active: metadata(s.Active), Pending: metadata(s.Pending), Observation: s.Observation, PendingObservation: s.PendingObservation}
|
||||
}
|
||||
func randomID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic("secure random unavailable")
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
func (m *Manager) locked(ctx context.Context, fn func(*State) (bool, error)) error {
|
||||
if !filepath.IsAbs(m.Path) {
|
||||
return errors.New("PP credential storage path is invalid")
|
||||
}
|
||||
dir := filepath.Dir(m.Path)
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
return errors.New("PP 配置存储不可用")
|
||||
}
|
||||
info, err := os.Lstat(dir)
|
||||
if err != nil || !info.IsDir() || info.Mode().Perm()&0077 != 0 {
|
||||
return errors.New("PP 配置目录权限必须为 0700")
|
||||
}
|
||||
lockPath := m.Path + ".lock"
|
||||
if info, e := os.Lstat(lockPath); e == nil && (info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0077 != 0) {
|
||||
return errors.New("PP 配置锁权限不安全")
|
||||
}
|
||||
lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return errors.New("PP 配置存储不可用")
|
||||
}
|
||||
defer lock.Close()
|
||||
for {
|
||||
err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if err != syscall.EWOULDBLOCK {
|
||||
return errors.New("PP 配置锁不可用")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
|
||||
var s State
|
||||
info, err = os.Lstat(m.Path)
|
||||
if err == nil {
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > 16<<20 {
|
||||
return errors.New("PP 凭据文件权限或格式不安全")
|
||||
}
|
||||
raw, e := os.ReadFile(m.Path)
|
||||
if e != nil || json.Unmarshal(raw, &s) != nil {
|
||||
return errors.New("无法读取 PP 配置")
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return errors.New("无法读取 PP 配置")
|
||||
} else if m.LegacyPath != "" {
|
||||
raw, e := os.ReadFile(m.LegacyPath)
|
||||
if e == nil {
|
||||
var c Credentials
|
||||
if json.Unmarshal(raw, &c) != nil {
|
||||
return errors.New("旧 PP 配置格式不正确")
|
||||
}
|
||||
if c.BaseURL == "" {
|
||||
c.BaseURL = "https://api.dobot.cn"
|
||||
}
|
||||
c.ID = "legacy"
|
||||
s.Active = &c
|
||||
} else if !errors.Is(e, os.ErrNotExist) {
|
||||
return errors.New("无法读取旧 PP 配置")
|
||||
}
|
||||
}
|
||||
changed, err := fn(&s)
|
||||
if err != nil || !changed {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".pp-next-")
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
tmp := f.Name()
|
||||
defer os.Remove(tmp)
|
||||
if err = f.Chmod(0600); err == nil {
|
||||
_, err = f.Write(raw)
|
||||
}
|
||||
if err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
closeErr := f.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp, m.Path)
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
d, e := os.Open(dir)
|
||||
if e != nil {
|
||||
return errors.New("PP 配置持久化未确认")
|
||||
}
|
||||
defer d.Close()
|
||||
if d.Sync() != nil {
|
||||
return errors.New("PP 配置持久化未确认")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m *Manager) View() (v View, err error) {
|
||||
err = m.locked(context.Background(), func(s *State) (bool, error) { v = view(*s); return false, nil })
|
||||
return
|
||||
}
|
||||
func (m *Manager) snapshot(ctx context.Context) (s State, err error) {
|
||||
err = m.locked(ctx, func(state *State) (bool, error) { s = *state; return false, nil })
|
||||
return
|
||||
}
|
||||
func candidate(s State, d Draft) (Credentials, error) {
|
||||
if !ValidateBaseURL(d.BaseURL) {
|
||||
return Credentials{}, ErrInvalid
|
||||
}
|
||||
if len(d.Username) > 255 || strings.ContainsAny(d.Username, "\n\r\x00") || len(d.Password) > 8192 {
|
||||
return Credentials{}, errors.New("账号或密码格式不正确")
|
||||
}
|
||||
c := Credentials{ID: randomID(), BaseURL: strings.TrimRight(d.BaseURL, "/"), Username: strings.TrimSpace(d.Username), Password: d.Password}
|
||||
if c.Password == "" && d.PendingID != "" {
|
||||
if s.Pending == nil || s.Pending.ID != d.PendingID {
|
||||
return Credentials{}, ErrConflict
|
||||
}
|
||||
c.Password = s.Pending.Password
|
||||
} else if c.Password == "" && s.Active != nil {
|
||||
c.Password = s.Active.Password
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
func same(a, b *Credentials) bool {
|
||||
return a != nil && b != nil && a.BaseURL == b.BaseURL && a.Username == b.Username && a.Password == b.Password
|
||||
}
|
||||
func (m *Manager) probe(ctx context.Context, c Credentials) Observation {
|
||||
o := Observation{State: "incomplete", Message: "配置未完成,请填写账号和密码"}
|
||||
if c.Username != "" && c.Password != "" {
|
||||
if m.Probe == nil {
|
||||
o = Observation{State: "unavailable", Message: "PP 检查服务未接通"}
|
||||
} else {
|
||||
o = m.Probe(ctx, c)
|
||||
}
|
||||
}
|
||||
switch o.State {
|
||||
case "valid", "auth_failed", "permission_denied", "incomplete", "unavailable", "invalid_response":
|
||||
default:
|
||||
o = Observation{State: "unavailable", Message: "检查结果不可识别,请重试"}
|
||||
}
|
||||
if o.CheckedAt == "" {
|
||||
o.CheckedAt = time.Now().UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
return o
|
||||
}
|
||||
func addAudit(s *State, source, action, actor, detail string) {
|
||||
s.Audit = append(s.Audit, AuditEvent{ID: "auth-" + randomID(), SourceName: source, Action: action, Actor: actor, CreatedAt: time.Now().UTC(), Detail: detail})
|
||||
}
|
||||
func retainObservation(old *Observation, next Observation) *Observation {
|
||||
if next.State == "unavailable" && old != nil {
|
||||
if old.State == "unavailable" && old.Previous != nil {
|
||||
next.Previous = old.Previous
|
||||
} else {
|
||||
next.Previous = old
|
||||
}
|
||||
}
|
||||
return &next
|
||||
}
|
||||
func (m *Manager) Save(ctx context.Context, d Draft, actor string) (v View, err error) {
|
||||
s, err := m.snapshot(ctx)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if s.Revision != d.Revision {
|
||||
return v, ErrConflict
|
||||
}
|
||||
c, err := candidate(s, d)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
o := m.probe(ctx, c)
|
||||
rejected := o.State == "auth_failed" || o.State == "permission_denied" || o.State == "invalid_response"
|
||||
err = m.locked(ctx, func(current *State) (bool, error) {
|
||||
if current.Revision != s.Revision {
|
||||
return false, ErrConflict
|
||||
}
|
||||
if rejected {
|
||||
if same(current.Active, &c) {
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_rejected", actor, o.Message)
|
||||
v = view(*current)
|
||||
return true, nil
|
||||
}
|
||||
current.Revision++
|
||||
if o.State == "valid" {
|
||||
current.Active = &c
|
||||
current.Pending = nil
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
current.PendingObservation = nil
|
||||
} else {
|
||||
current.Pending = &c
|
||||
current.PendingObservation = &o
|
||||
}
|
||||
detail := "认证配置已保存并生效"
|
||||
if o.State != "valid" {
|
||||
detail = "修改已保存为待验证,未替换生效配置"
|
||||
}
|
||||
if d.Password != "" {
|
||||
detail += ";密码已更新"
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_configured", actor, detail)
|
||||
v = view(*current)
|
||||
return true, nil
|
||||
})
|
||||
if err == nil && rejected {
|
||||
err = fmt.Errorf("%w:%s", ErrRejected, o.Message)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (m *Manager) Test(ctx context.Context, d Draft, actor string) (o Observation, err error) {
|
||||
s, err := m.snapshot(ctx)
|
||||
if err != nil {
|
||||
return o, err
|
||||
}
|
||||
if s.Revision != d.Revision {
|
||||
return o, ErrConflict
|
||||
}
|
||||
c, err := candidate(s, d)
|
||||
if err != nil {
|
||||
return o, err
|
||||
}
|
||||
o = m.probe(ctx, c)
|
||||
err = m.locked(ctx, func(current *State) (bool, error) {
|
||||
if current.Revision != s.Revision {
|
||||
return false, ErrConflict
|
||||
}
|
||||
if same(current.Active, &c) {
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_test", actor, o.Message)
|
||||
return true, nil
|
||||
})
|
||||
return
|
||||
}
|
||||
func (m *Manager) Audit(ctx context.Context, source, action, actor, detail string) error {
|
||||
return m.locked(ctx, func(s *State) (bool, error) { addAudit(s, source, action, actor, detail); return true, nil })
|
||||
}
|
||||
func (m *Manager) AuditOnce(ctx context.Context, id, source, action, actor, detail string) error {
|
||||
return m.locked(ctx, func(s *State) (bool, error) {
|
||||
for _, e := range s.Audit {
|
||||
if e.ID == id {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
addAudit(s, source, action, actor, detail)
|
||||
s.Audit[len(s.Audit)-1].ID = id
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
func (m *Manager) Events(ctx context.Context) (events []AuditEvent, err error) {
|
||||
err = m.locked(ctx, func(s *State) (bool, error) { events = append(events, s.Audit...); return false, nil })
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSaveValidatesBeforeActivationAndTransientKeepsActive(t *testing.T) {
|
||||
state := "valid"
|
||||
seen := ""
|
||||
manager := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
seen = c.Password
|
||||
return Observation{State: state, Message: state}
|
||||
}}
|
||||
view, err := manager.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-password", Revision: 0}, "tester")
|
||||
if err != nil || view.Active == nil || view.Active.Username != "example" || !view.Active.PasswordConfigured || seen != "example-password" {
|
||||
t.Fatalf("validated save did not activate: %+v %v", view, err)
|
||||
}
|
||||
activeID := view.Active.ID
|
||||
state = "unavailable"
|
||||
view, err = manager.Save(context.Background(), Draft{BaseURL: "https://changed.example.invalid", Username: "changed", Revision: view.Revision}, "tester")
|
||||
if err != nil || view.Active == nil || view.Active.ID != activeID || view.Pending == nil || view.Pending.Username != "changed" || seen != "example-password" {
|
||||
t.Fatalf("transient save replaced active or lost password: %+v %v", view, err)
|
||||
}
|
||||
state = "auth_failed"
|
||||
_, err = manager.Save(context.Background(), Draft{BaseURL: "https://changed.example.invalid", Username: "changed", Password: "bad-example", Revision: view.Revision}, "tester")
|
||||
if !errors.Is(err, ErrRejected) {
|
||||
t.Fatalf("explicit rejection allowed activation: %v", err)
|
||||
}
|
||||
after, _ := manager.View()
|
||||
if after.Active.ID != activeID {
|
||||
t.Fatal("rejection changed active config")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPendingPasswordSurvivesRevalidationWithoutReturningSecrets(t *testing.T) {
|
||||
state := "valid"
|
||||
seen := ""
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
seen = c.Password
|
||||
return Observation{State: state, Message: state}
|
||||
}}
|
||||
v, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-old"}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state = "unavailable"
|
||||
v, err = m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-new", Revision: v.Revision}, "tester")
|
||||
if err != nil || v.Pending == nil {
|
||||
t.Fatalf("pending save: %v", err)
|
||||
}
|
||||
state = "valid"
|
||||
v, err = m.Save(context.Background(), Draft{BaseURL: v.Pending.BaseURL, Username: v.Pending.Username, PendingID: v.Pending.ID, Revision: v.Revision}, "tester")
|
||||
if err != nil || seen != "example-new" || v.Pending != nil {
|
||||
t.Fatal("saved pending password was not reused")
|
||||
}
|
||||
raw, _ := json.Marshal(v)
|
||||
if strings.Contains(string(raw), "example-new") || strings.Contains(string(raw), `"password":`) {
|
||||
t.Fatal("metadata leaked secret")
|
||||
}
|
||||
info, err := os.Stat(m.Path)
|
||||
if err != nil || info.Mode().Perm() != 0600 {
|
||||
t.Fatal("secret file not mode 0600")
|
||||
}
|
||||
}
|
||||
func TestConcurrentSavesCannotOverwriteANewerRevision(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
barrier := make(chan struct{})
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
if calls.Add(1) == 2 {
|
||||
close(barrier)
|
||||
}
|
||||
<-barrier
|
||||
return Observation{State: "valid", Message: "valid"}
|
||||
}}
|
||||
outcomes := make(chan error, 2)
|
||||
var wg sync.WaitGroup
|
||||
for _, name := range []string{"example-one", "example-two"} {
|
||||
wg.Add(1)
|
||||
go func(user string) {
|
||||
defer wg.Done()
|
||||
_, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: user, Password: "example-password"}, "tester")
|
||||
outcomes <- err
|
||||
}(name)
|
||||
}
|
||||
wg.Wait()
|
||||
close(outcomes)
|
||||
success, conflict := 0, 0
|
||||
for err := range outcomes {
|
||||
if err == nil {
|
||||
success++
|
||||
} else if errors.Is(err, ErrConflict) {
|
||||
conflict++
|
||||
} else {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if success != 1 || conflict != 1 {
|
||||
t.Fatalf("success=%d conflict=%d", success, conflict)
|
||||
}
|
||||
}
|
||||
func TestFailedObservationRetainsPreviousSuccess(t *testing.T) {
|
||||
state := "valid"
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation { return Observation{State: state, Message: state} }}
|
||||
v, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-password"}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state = "unavailable"
|
||||
_, err = m.Test(context.Background(), Draft{BaseURL: v.Active.BaseURL, Username: v.Active.Username, Revision: v.Revision}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, err = m.View()
|
||||
if err != nil || v.Observation.Previous == nil || v.Observation.Previous.State != "valid" {
|
||||
t.Fatal("failed check erased previous successful observation")
|
||||
}
|
||||
}
|
||||
func TestPPPythonProtocolAndConfigurationConsumers(t *testing.T) {
|
||||
command := exec.Command("python3", "-m", "unittest", "discover", "-s", "../../scripts", "-p", "test_pp_client.py", "-v")
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("PP protocol regression: %v\n%s", err, output)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CommandProbe reuses the worker's read-only PP adapter; secrets travel on stdin.
|
||||
func CommandProbe(python, script string) func(context.Context, Credentials) Observation {
|
||||
return func(ctx context.Context, c Credentials) Observation {
|
||||
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
raw, _ := json.Marshal(c)
|
||||
command := exec.CommandContext(ctx, python, script)
|
||||
command.Stdin = bytes.NewReader(raw)
|
||||
command.Env = []string{"PATH=" + os.Getenv("PATH"), "PYTHONUNBUFFERED=1"}
|
||||
out, err := command.Output()
|
||||
if err != nil || len(out) > 8192 {
|
||||
return Observation{State: "unavailable", Message: "PP 检查服务暂不可用,请重试"}
|
||||
}
|
||||
var o Observation
|
||||
if json.Unmarshal(out, &o) != nil {
|
||||
return Observation{State: "unavailable", Message: "PP 检查结果不可识别"}
|
||||
}
|
||||
return o
|
||||
}
|
||||
}
|
||||
+21
-32
@@ -1,53 +1,42 @@
|
||||
package qaopsai
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
// The independently provisioned master key never lives in source, settings JSON or database backups.
|
||||
func (s *Store) box() (*secretbox.Box, error) {
|
||||
box, err := secretbox.Load(s.options.KeyFile)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return box, nil
|
||||
}
|
||||
|
||||
// masterKey 保留给调用方判断“存储是否就绪”;实际加解密统一走 secretbox。
|
||||
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 {
|
||||
if _, err := s.box(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
return []byte{1}, nil
|
||||
}
|
||||
|
||||
func (s *Store) seal(secret string, revision int64) ([]byte, error) {
|
||||
aead, err := s.aead()
|
||||
box, err := s.box()
|
||||
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
|
||||
return box.Seal([]byte(secret), fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))
|
||||
}
|
||||
|
||||
func (s *Store) unseal(sealed []byte, revision int64) (string, error) {
|
||||
aead, err := s.aead()
|
||||
if err != nil || len(sealed) < aead.NonceSize() {
|
||||
return "", ErrUnavailable
|
||||
box, err := s.box()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
raw, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision)))
|
||||
raw, err := box.Open(sealed, fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))
|
||||
if err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -45,6 +45,9 @@ type Resolver struct {
|
||||
LoadBinding func(context.Context) (string, error)
|
||||
ReadKey func() (string, error)
|
||||
DefaultKB string
|
||||
// ResolveConnection 可选:一次解析端点与凭据(例如来自加密存储)。
|
||||
// 提供时优先于 Endpoint + ReadKey,因为密钥解密需要请求上下文。
|
||||
ResolveConnection func(context.Context) (baseURL, apiKey string, err error)
|
||||
}
|
||||
|
||||
func (resolver Resolver) Resolve(ctx context.Context) (Target, error) {
|
||||
@@ -58,25 +61,35 @@ func (resolver Resolver) Resolve(ctx context.Context) (Target, error) {
|
||||
knowledgeBaseID = stored
|
||||
}
|
||||
}
|
||||
apiKey := ""
|
||||
if resolver.ReadKey != nil {
|
||||
value, err := resolver.ReadKey()
|
||||
baseURL, apiKey := "", ""
|
||||
if resolver.ResolveConnection != nil {
|
||||
var err error
|
||||
baseURL, apiKey, err = resolver.ResolveConnection(ctx)
|
||||
if err != nil {
|
||||
return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败")
|
||||
return Target{}, fmt.Errorf("读取 WeKnora 有效连接失败:%w", err)
|
||||
}
|
||||
} else {
|
||||
if resolver.ReadKey != nil {
|
||||
value, err := resolver.ReadKey()
|
||||
if err != nil {
|
||||
return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败")
|
||||
}
|
||||
apiKey = strings.TrimSpace(value)
|
||||
}
|
||||
if resolver.Endpoint != nil {
|
||||
baseURL = strings.TrimSpace(resolver.Endpoint(ctx))
|
||||
}
|
||||
apiKey = strings.TrimSpace(value)
|
||||
}
|
||||
baseURL := ""
|
||||
if resolver.Endpoint != nil {
|
||||
baseURL = strings.TrimSpace(resolver.Endpoint(ctx))
|
||||
}
|
||||
return Target{BaseURL: baseURL, KnowledgeBaseID: knowledgeBaseID, APIKey: apiKey}, nil
|
||||
return Target{BaseURL: strings.TrimSpace(baseURL), KnowledgeBaseID: knowledgeBaseID, APIKey: strings.TrimSpace(apiKey)}, nil
|
||||
}
|
||||
|
||||
type Prober struct {
|
||||
Resolve func(context.Context) (Target, error)
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses, the
|
||||
// same judgement the binding store and the client use.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (prober Prober) Check(ctx context.Context) Result {
|
||||
@@ -96,10 +109,11 @@ func (prober Prober) Check(ctx context.Context) Result {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: prober.AllowDockerHTTP,
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: prober.AllowDockerHTTP,
|
||||
AllowPrivateHTTP: prober.AllowPrivateHTTP,
|
||||
})
|
||||
if err != nil {
|
||||
return Result{Target: described, Err: err}
|
||||
|
||||
@@ -151,5 +151,5 @@ func testDocumentBundle(t *testing.T) *DocumentBundle {
|
||||
func fixedArchiveTime() time.Time { return time.Date(2026, 9, 6, 11, 0, 0, 0, time.UTC) }
|
||||
|
||||
func releasePlanForArchive() releaseworkflow.PlanItem {
|
||||
return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"}
|
||||
return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ package v071
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/releasebundle"
|
||||
releaseworkflow "knowledge-governance/internal/workflows/release"
|
||||
)
|
||||
@@ -49,6 +51,11 @@ type DocumentTargetConfig struct {
|
||||
Search searchDocumentTarget
|
||||
Objects objectDocumentTarget
|
||||
Verifier ProductionVerifier
|
||||
// TargetInstanceURL/TargetTenantID are the executor's own route target. The
|
||||
// console freezes the instance it verified the binding on; this side must
|
||||
// match before any document write/restore.
|
||||
TargetInstanceURL string
|
||||
TargetTenantID uint64
|
||||
}
|
||||
|
||||
type DocumentTarget struct {
|
||||
@@ -63,6 +70,9 @@ func NewDocumentTarget(config DocumentTargetConfig) (*DocumentTarget, error) {
|
||||
}
|
||||
|
||||
func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow.PlanItem) (releasebundle.TargetContract, error) {
|
||||
if err := target.checkInstance(item); err != nil {
|
||||
return releasebundle.TargetContract{}, err
|
||||
}
|
||||
contract, err := target.config.Contract.Contract(ctx, item)
|
||||
if err != nil {
|
||||
return releasebundle.TargetContract{}, errors.New("inspect target release contract")
|
||||
@@ -75,6 +85,9 @@ func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow
|
||||
// same target base. The archive itself keeps the canonical source-form bundle:
|
||||
// the remap is deterministic, so a rollback re-derives the same target form.
|
||||
func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision string) (*DocumentBundle, error) {
|
||||
if err := target.checkInstance(item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bundle, err := target.config.Archive.Load(revision)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -86,6 +99,9 @@ func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision
|
||||
}
|
||||
|
||||
func (target *DocumentTarget) Prepare(ctx context.Context, item releaseworkflow.PlanItem, exported releaseworkflow.ExportedBundle) (releaseworkflow.PreparedChange, error) {
|
||||
if err := target.checkInstance(item); err != nil {
|
||||
return releaseworkflow.PreparedChange{}, err
|
||||
}
|
||||
bundle, ok := exported.(*DocumentBundle)
|
||||
if !ok || validateDocumentBundle(bundle) != nil || bundle.Manifest.ReleaseRevision != item.ReleaseRevision {
|
||||
return releaseworkflow.PreparedChange{}, errors.New("invalid v0.7.1 target bundle")
|
||||
@@ -219,6 +235,30 @@ func (target *DocumentTarget) VerifyRestored(ctx context.Context, item releasewo
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkInstance is the single instance-identity boundary for the document
|
||||
// release path. Empty identity means a pre-identity binding: the executor
|
||||
// cannot prove which instance it is, so it fails closed instead of writing to a
|
||||
// cloned instance that happens to expose the same knowledge base id.
|
||||
func (target *DocumentTarget) checkInstance(item releaseworkflow.PlanItem) error {
|
||||
if item.TargetInstanceURL == "" || item.TargetTenantID == 0 {
|
||||
return fmt.Errorf("%w: binding has no verified instance identity", releaseworkflow.ErrTargetInstanceMismatch)
|
||||
}
|
||||
if target.config.TargetInstanceURL == "" || target.config.TargetTenantID == 0 {
|
||||
return fmt.Errorf("%w: executor target identity is not configured", releaseworkflow.ErrTargetInstanceMismatch)
|
||||
}
|
||||
if weknora.NormalizeInstanceURL(item.TargetInstanceURL) != weknora.NormalizeInstanceURL(target.config.TargetInstanceURL) {
|
||||
return fmt.Errorf("%w: binding verified on %s, executor writes %s",
|
||||
releaseworkflow.ErrTargetInstanceMismatch,
|
||||
weknora.NormalizeInstanceURL(item.TargetInstanceURL),
|
||||
weknora.NormalizeInstanceURL(target.config.TargetInstanceURL))
|
||||
}
|
||||
if item.TargetTenantID != target.config.TargetTenantID {
|
||||
return fmt.Errorf("%w: binding tenant %d, executor tenant %d",
|
||||
releaseworkflow.ErrTargetInstanceMismatch, item.TargetTenantID, target.config.TargetTenantID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (target *DocumentTarget) restoreBundle(ctx context.Context, item releaseworkflow.PlanItem, revision string) error {
|
||||
bundle, err := target.loadBundle(item, revision)
|
||||
if err != nil {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user