Compare commits

..

97 Commits

Author SHA1 Message Date
姚章浩 868924d074 fix(cd): 核验容器引擎使用的镜像清单摘要
build / build (push) Successful in 1m53s
2026-11-23 21:46:03 +08:00
姚章浩 03e622e9c7 fix(cd): 派发前交接并核验主站候选归档
build / build (push) Successful in 2m10s
2026-11-23 21:10:50 +08:00
zheromiku 9eef078ed0 Merge pull request 'fix(settings): CYWL-4 知识库绑定与主站基线对齐' (#23) from hifox-agent/len/CYWL-4-fix into main
build / build (push) Successful in 1m56s
Reviewed-on: #23
2026-11-23 14:32:01 +08:00
姚章浩 2ca98a6a35 fix(settings): 将 CYWL-4 对齐主站源码基线
build / build (push) Successful in 1m50s
2026-11-23 14:26:53 +08:00
zheromiku 746b982c43 Merge pull request 'chore(repo): 纳入云治理主站运行基线' (#27) from integrate/cloud-main-baseline into main
build / build (push) Successful in 1m54s
2026-11-23 14:23:57 +08:00
姚章浩 5ff6768027 chore(repo): 同步主干候选发布校验
build / build (push) Successful in 1m46s
2026-11-23 14:20:48 +08:00
zheromiku 2a639392e4 Merge pull request 'fix(cd): 支持已合入主干的现场基线' (#26) from fix/candidate-merged-baseline into main
build / build (push) Successful in 1m29s
2026-11-23 14:19:47 +08:00
姚章浩 9cfe2114b1 fix(cd): 兼容应用与集成测试共用的 QA 凭据文件
build / build (push) Successful in 1m32s
2026-11-23 13:54:07 +08:00
姚章浩 1e7e986b70 chore(repo): 纳入云治理主站运行基线
build / build (push) Successful in 1m47s
2026-11-23 13:50:49 +08:00
姚章浩 8faabdcf9e fix(cd): 支持已合入主干的现场基线
build / build (push) Successful in 1m40s
2026-11-23 13:48:07 +08:00
zheromiku 922ff66533 Merge pull request 'feat(cd): 接入候选构建与批次验收' (#25) from feat/candidate-release-batch into main
build / build (push) Successful in 1m25s
2026-11-23 13:31:41 +08:00
姚章浩 0246db357f fix(cd): 校验候选部署入口并隔离凭据
build / build (push) Successful in 1m30s
2026-11-23 13:28:40 +08:00
姚章浩 1beaa31771 feat(cd): 接入候选构建与批次验收
build / build (push) Successful in 1m30s
2026-11-23 13:20:25 +08:00
zheromiku 8c76c54d8e Merge pull request 'fix(deploy): 兼容 HiFox 确认事件跨秒写入' (#22) from fix/hifox-approval-timestamps into main
build / build (push) Successful in 1m28s
2026-11-23 03:03:32 +08:00
姚章浩 084ee1b176 fix(deploy): 兼容 HiFox 确认事件跨秒写入
build / build (push) Successful in 1m29s
任务更新时间与状态事件分别写入,允许小幅时间偏差。
仍以最近事件验证操作者,并要求验收证据早于两条时间记录。
2026-11-23 03:01:42 +08:00
zheromiku 71971e8164 Merge pull request 'feat(deploy): 接通 HiFox 待发布自动触发' (#21) from feat/hifox-release-trigger into main
build / build (push) Successful in 1m28s
2026-11-23 02:59:40 +08:00
姚章浩 47428a8b58 feat(deploy): 接通 HiFox 待发布自动触发
build / build (push) Successful in 1m27s
将发布人的状态变更与业务验收报告绑定,复用 Gitea 发布及回滚链路。
从部署回执写入运行身份、镜像及主站登录入口,避免重复调度和回写。
2026-11-23 02:57:46 +08:00
zheromiku 91988a0d3b Merge pull request 'feat(deploy): 接通云治理主站的人工确认发布流水线' (#20) from ci-trial-governance-cd into main
build / build (push) Successful in 1m29s
2026-11-23 02:26:47 +08:00
姚章浩 07a0ee2644 fix(deploy): 使用 Gitea 单次人工确认发布
build / build (push) Successful in 1m46s
2026-11-23 02:24:18 +08:00
姚章浩 0b5de6ef7e feat(deploy): 接通云治理主站的人工确认发布流水线
build / build (push) Successful in 2m0s
2026-11-23 01:35:18 +08:00
狐友 GXXP & LEN e892bfdd48 fix(kbbinding): 生产保存重排待入库并按环境配对
build / build (push) Successful in 2m20s
- 生产页保存对内/对外库时,在同一事务内把还没上传、原本瞄准旧生产库的待入库项改指向新库,并在保存提示里回报迁移条数;执行已开始的项目标保持冻结。
- 重排改为「上一次生效目标 → 新目标」成对过滤:测试与生产共用 test_publications,测试侧保存不再带走瞄准生产库的待入库(验收附带发现)。
- 用例补生产重排、测试侧保存不误搬生产作业、生产保存不动测试作业三组断言。
2026-11-22 23:31:41 +08:00
zheromiku d7d636792d Merge pull request 'feat(qa): 自动准备知识治理测试环境' (#18) from feat/qa-environment-runner into main
build / build (push) Successful in 1m28s
2026-11-22 19:37:29 +08:00
姚章浩 89c484cdc4 feat(qa): 自动准备知识治理测试环境
build / build (push) Successful in 1m29s
为 HiFox QA 检出提供环境检查、锁定依赖、专用 RDS 迁移、服务探活、测试和进程清理。已在 QA 虚拟机通过 make verify,并验证缺少 RDS 配置、错误提交和端口冲突的阻断。
2026-11-22 19:30:49 +08:00
姚章浩 5e3362e2b0 docs(dev): 补充开发与测试环境指南
build / build (push) Successful in 1m29s
从 README 提供依赖、前后端启动、测试命令和非生产 RDS 准备步骤。已在独立 QA 检出通过 make verify,Vite 健康代理和 Chromium 页面冒烟通过。
2026-11-22 19:18:48 +08:00
狐友 GXXP & Miku 768ad53fe2 fix(kbbinding): 清除密钥保留知识库名称与绑定身份
build / build (push) Successful in 1m49s
- clear 不再把 internal_kb_name / external_kb_name 写成空串:改取事务内锁定行的
  旧值,且只在库 ID 未变时沿用(同时改指向又清密钥不会把旧库名贴到新库上);
  生产侧一并保留已冻结的实例地址与租户,执行器的实例一致性检查不会把「只是没
  密钥」误判成换了实例
- 存量集成用例对齐「留空 = 取消绑定」新语义:只填一端保存成功、该侧为空、回退
  来源字段写明回退到哪、revision 递增,后续修订期望随之前移
- 新增真实库用例:clear 后 key_configured=false、verification=not_configured、
  名称/库 ID/租户不变、Resolve() 返回 ErrNotConfigured、历史表只记布尔无密钥
- 前端清密钥用例补充断言:请求带当前库 ID,页面仍显示名称而不回落短 ID
2026-11-22 16:35:32 +08:00
狐友 GXXP & Miku 7d91343e5f feat(binding): 连接四态验证、密钥尾号与私网 http 放行
build / build (push) Successful in 1m45s
在既有 kbbinding(迁移 000081)上补齐任务要求,不另建表、不另起路由:
- 测试连接区分 401/403(密钥无效 / 无权限)与不可达、成功四态;
- 视图回显密钥尾 4 位(服务端不存、不回读明文);
- key_action=clear 作为独立动作,清除后解析失败关闭、不回落文件旧 Key;
- 内外库留空 = 取消绑定,回报回退来源(测试侧部署默认库 / 生产侧同 ID 语义);
- 生产绑定回报在飞执行的冻结/仍可改指向条数,已冻结目标不被改写;
- 新增 WEKNORA_ALLOW_PRIVATE_HTTP:客户端/探活/连接页共用 HTTPAllowed,
  只放行 RFC1918/回环/链路本地 http,生产 18093 同网段反代因此可用。
2026-11-22 15:46:13 +08:00
zheromiku edd07a65d6 Merge pull request 'docs(ops): 更新架构、平台接入及反代运维手册' (#16) from docs/governance-ops-090-main into main
build / build (push) Successful in 1m28s
2026-11-22 13:17:09 +08:00
姚章浩 7c120b3adc test(qawemail): 用绝对域名断言不可解析主机
build / build (push) Successful in 1m57s
构建机 resolv.conf 带 search 域(Tailscale tailf49802.ts.net)时,
smtp.kg-test.invalid 会被拼成 ...tailf49802.ts.net 并由 Fake-IP DNS
解析成功,断言实际测的是构建机搜索域。改成带末尾点的绝对名后与
搜索域无关,仍保持“不可解析主机必须判非法”的原意。
2026-11-22 13:14:52 +08:00
姚章浩 ea159ca2fb docs(ops): 补充治理架构、平台接入与测试反代手册
build / build (push) Failing after 1m37s
2026-11-22 13:10:44 +08:00
姚章浩 cb026e8dd1 docs(ops): 补充治理架构、平台接入与测试反代手册 2026-11-22 11:47:33 +08:00
姚章浩 4b615abe53 fix(settings): 区分快照过期与未配置 2026-11-20 02:10:07 +08:00
姚章浩 341c3154ac fix(settings): 存储页区分宿主可写盘与配额未知
完整快照不再提示挂载可写或需改 :ro;容量可信时磁盘告警正常,仅配额相关三项标注未接线。采集时间取宿主快照、读回时间取 API 并分列;“重新盘点”明确只重读 metadata.json。空间预测注明上次整批实际占盘仅供参考;小文件不足 0.05 MiB 显示 KiB,不再舍成 0.0 MiB。
2026-11-20 01:56:02 +08:00
姚章浩 63984dbfbe fix(backup): 宿主采集器按 du 口径去重硬链接并拒绝清单符号链接
备份目录 root:root 0700,API 不再遍历;宿主采集器只读 stat/du,原子写快照。统计包含目录自身、树内 (dev,ino) 硬链接去重,单库与整批各自独立与 du -sB1 对齐;MANIFEST 仅接受目录内常规非符号链接文件并 O_NOFOLLOW 打开。快照缺失/陈旧/不完整时批次与子库字节为 null,页面不画容量图、不使用部分字节。
2026-11-20 01:41:28 +08:00
姚章浩 033f702d41 feat(backup): 只读盘点真实批次、子库路径与容量
为什么:28189 验收里历史批次/子库路径/容量都没有真实接口,页面只能占位;
用户要求修实际接口而不是继续改文案,同时不得写主机或触发备份。

怎么改:新增 GET /api/v1/backup-schedule/inventory,只读盘点 statfs 实测容量、
st_blocks 实际占盘、全部批次与 MANIFEST 状态、每个子库完整主机路径。目录必须
只读挂载;用设备号区分挂载文件系统与容器根盘,同设备时不给主机容量。清单
missing/invalid、未接线、不可读分别展示。SSH 计划读回与盘点独立加载。
前端消费该接口:整盘色带、批次列表、子库路径复制、清单失败与容器根盘提示。

怎么验:Go 单测覆盖清单/占盘/符号链接/容器根盘;handler 契约;appconfig 接线校验;
vitest 627 项、tsc、vite build、prettier 通过;本地页面夹具核对 8 批与路径复制,
1440/1024/768 无横向溢出。未连接真实主机、未执行备份、未改真实计划。
2026-11-20 01:05:24 +08:00
姚章浩 9eacf6473e fix(settings): 备份主机状态不得由历史下发推断
为什么:host_configured=false 时页面宣称"定时计划不会执行",但平台只是没挂载
主机凭据,远端既有 cron 可能仍在跑;最后下发是历史记录,也不能证明当前计划。

怎么改:无凭据时改为"无法确认当前主机计划/远端 cron 可能仍在执行";最后下发标为
历史并注明不能代表当前状态;未探测与探测失败分开;"与设置是否一致"只在真正读回
主机计划后判定。

怎么验:新增无凭据 + 有效历史下发、已接线未探测两例回归,断言不出现"不会执行";
vitest 619 项、tsc、prettier 通过;本地页面夹具 C 面板核对文案。
2026-11-19 23:45:15 +08:00
姚章浩 6444814123 feat(settings): 存储与备份单页对齐真实接口
为什么:原型里的单库立备、示例容量、历史批次与目录检查在本仓接口中都不存在;
把整批 run 包装成单库按钮会误触发整批,填示例读数会把演示值当产品事实。

怎么改:按真实契约重排单页——范围/读写方向、四项告警、策略、最近批次、运行进度与
恢复验证。立即备份明确标注整批并禁用单库动作;目录/配额/预留、子库路径、历史批次、
恢复验证保留原型位置并注明未接线;归档与数据库备份分开计量。整盘色带与告警抽成
纯函数,用隔离夹具覆盖正常/不足/缺读数分支。

怎么验:tsc、vitest 618 项、vite build、prettier 通过;本地页面夹具在 1440/1024/768
无横向溢出,未接线与夹具读数两种形态均按预期渲染。
2026-11-19 23:31:16 +08:00
姚章浩 6ae5150fdf fix(worker): 单次任务固定同一 WeKnora 连接
TargetIdentity 与业务调用原先各自 Resolve:身份核验通过后,上传/轮询/验收/
移除的后续调用仍可能在下一次解析时切到新实例。现在 BeginTask 只解析一次,
用同一连接读取对象租户并把该不可变连接钉进返回 context;后续上传、列库恢复、
查询、chunk 读取、删除与删除后重查全部复用它。

TaskConnector 优先于 IdentityProvider;仅实现 TargetIdentity 的窄假客户端仍可
工作,生产路径不会走双解析。新增假端点测试断言一次处理只解析一次、绑定后改
当前实例仍全部打到原实例;四个 handler 的 TaskConnector 假客户端断言所有业务
调用携带同一连接令牌,覆盖上传恢复和删除重查。
2026-11-19 15:33:40 +08:00
姚章浩 1f5bf72aec fix(release): 以实例身份阻断绑定与发布跨实例
网页可能在实例 A 上列库并保存生产绑定,而文档发布执行器实际连实例 B。
克隆实例可以有相同知识库 ID、名称甚至租户,单靠 ID 无法证明写的是同一个
目标。现在绑定保存会冻结候选实例地址/租户,发布计划把身份冻结到每个项,
执行器在 Contract/Prepare/Activate/Restore/Compensate 前核对;不一致以
release_contract_mismatch 非重试失败关闭,不写目标。整库发布目标不变。

测试入库对象在上传前记录实际实例地址/租户;轮询、验收、移除先核对当前
连接,改绑实例或租户后旧对象不会被克隆实例接管。旧行没有身份时失败关闭。

「知识库绑定」保存要求对内/对外各选一个库,不再把显式未绑定回落到部署
默认 ID,避免换绑实例后带过去旧对象的默认库。

验证:隔离 PostgreSQL 覆盖绑定身份落库与发布计划冻结;v071 用同 ID/同租户
的 A/B 实例做正反例;四个测试 handler 的实例错配负例;前端 607 项通过。
2026-11-19 15:19:51 +08:00
姚章浩 ce2a155ebc feat(settings): 知识库绑定按环境一次保存连接与内外库
原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥,
也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址
与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与
绑定,回读真实生效值。

服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件
凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥
不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储
解析当前连接,避免只保存了页面数据。

验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错;
make verify 在本提交上执行(结果见交付说明)。
2026-11-19 14:51:47 +08:00
姚章浩 df69b278ce feat(settings): AI 模型连接改为当前生效与独立草稿编辑
为什么:交互稿要求顶部只读已保存模型与真实核验态,下方编辑独立草稿;测试草稿
不得改写当前连接,保存一律回显服务端结果,草稿变动或配置被他人改动后旧测试失效。
原来只有一张表单和一个 busy 状态,测试与保存无法区分,清除密钥也与保存混在一起。

改了什么:QAModelSettings 拆成 saved / draft 两层;已配置密钥默认收起,仅更换或
首次录入展示输入框,换地址强制重新录入;清除并停用收进折叠区、二次确认且只提交
已保存连接;409 冲突重新拉取已保存配置并作废草稿测试。样式迁到 systemSettings.css,
删除 qaOps.css 里同名残留;合并分区与组件内重复说明。

怎么验的:npm test 119 文件 600 例全过(新增 mounted 交互回归 5 例);npm run build
通过;make verify 全量门禁 17 项 success(identity 本地 skipped)。未推送、未部署。
2026-11-19 12:21:54 +08:00
dev 399b5756ea fix(ci): 依赖漏洞例外可追溯到链底公告,picomatch ReDoS 记账
build / build (push) Successful in 2m25s
- check_deps_vuln: 包因依赖有洞被标记时,via 只有依赖名,原实现取不到 GHSA;
  改为沿 via 追到链底公告,fdir/tinyglobby/vite/vitest 与 picomatch 都记同一编号。
- 例外表:GHSA-fc5q-39xc-vjpf 在 npm 上范围 <=4.0.7、4.0.7 已是最新,没有修复版本;
  仅开发依赖、只解析本仓 glob,按策略记例外(到期 2027-02-15)。
2026-11-18 17:57:26 +08:00
姚章浩 3da82d48d9 feat(settings): 服务配置拆为 AI 模型连接,WeKnora 连接并入知识库映射
build / build (push) Failing after 2m22s
- 原「服务配置」更名为「AI 模型连接」,只保留问答分析与中文翻译共用的模型连接
- 测试/生产 WeKnora 地址、生产租户与知识库 ID 迁入「知识库映射」,与入库/封存/生产目标同屏
- 连接配置独立草稿与独立保存,刷新策略不夹带未保存地址
- 同步 README、运维手册、验收清单入口路径
2026-11-18 15:15:13 +08:00
姚章浩 afc38c921f style(settings): 为 DWS 账号补齐与 PP 一致的卡片边框
build / build (push) Successful in 1m49s
DWS 账号区使用与 PP 相同的边框、圆角、内边距、外边距及背景。
仅调整现有 CSS,保留账号信息、授权按钮和检查连接交互。

验证:Prettier 通过;DWS 现有 7 项回归通过;TypeScript/Vite 构建与 git diff --check 通过。
2026-11-17 20:36:08 +08:00
姚章浩 0dd4ad2737 fix(settings): 兼容 PP 目录接口的字符串总数
build / build (push) Successful in 1m46s
真实 PP 登录正常,目录接口将 Java Long 总数序列化为十进制字符串;新客户端的纯整数判断误报不兼容。
接受规范的非负十进制字符串,并保留对负数、布尔、小数和非规范字符串的拒绝。

验证:新增用例先复现 invalid_response,再完成 9 项 PP 回归;make verify 退出 0。
候选代码在测试站 API 和 worker 容器中均真实登录并读取目录成功,确认消费同一配置。
2026-11-17 20:01:44 +08:00
姚章浩 d2f9060b33 fix(settings): 禁止 PP 隐式回落旧凭据配置
build / build (push) Successful in 1m58s
生效状态文件缺失时,扫描与取件仅在显式配置迁移路径时读取旧凭据;默认未配置状态与 API 一致。
新增缺失状态文件的回归,先复现旧凭据被隐式启用,再验证修复。

验证:PP 客户端 7 项隔离服务/配置回归通过;完整 make verify 退出 0,全部本地必需门禁通过。
2026-11-17 19:32:17 +08:00
姚章浩 3825859da6 feat(settings): 打通 PP 认证配置并统一 DWS 来源授权
build / build (push) Successful in 2m20s
PP 增加受控凭据更新、真实登录与目录检查,待验证修改不会替换生效配置;扫描与取件共享生效修订。
钉钉来源向导、校验与登记共用 DWS 授权,支持中途恢复与换账号保护,取消旧扫码自动回落。
认证审计复用已有来源审计页,配置响应不回传密码;补齐运行镜像脚本与权限。

验证:make verify 退出 0;PP/DWS/httpapi 目标 race 回归通过;隔离 HTTP 服务验证 PP 协议及扫描/取件消费者。
尚未部署;真实 PP 凭据与目录可用性在测试站部署后验证。
2026-11-17 19:08:46 +08:00
姚章浩 e0fa31c9d6 fix(settings): 目录鉴权失败提示登录授权入口
build / build (push) Successful in 1m51s
目录检查不可用时给出 DWS 登录与权限检查说明,避免直接展示机器错误码。
新增真实 Response 回归已先失败复现,修复后完整 make verify 通过。
2026-11-17 17:17:42 +08:00
姚章浩 b2cea6ed84 feat(settings): 新增 DWS 设备登录与目录连接检查
build / build (push) Successful in 1m52s
数据源配置可发起钉钉官方设备授权、重新授权和取消,完成后刷新共享账号状态并独立检查目录权限。
授权会话限定发起的管理员登录会话,令牌由现有 CLI 存储,取消等待子进程退出。

验证:完整 make verify 通过;前端 582 项、Go 1545 项通过,487 项声明的可选集成未运行。
授权处理器与 HTTP 边界通过 race 检查;本人钉钉授权仍由管理员在官方页面完成。
2026-11-17 16:59:47 +08:00
dev 6c10f71c28 fix(settings): 数据源显示上次更新/下次计划;归档注记统一术语
build / build (push) Successful in 1m54s
2026-11-17 16:14:05 +08:00
dev cf65d3f363 fix(settings): 生产凭据缺失说明准确化;存储页保留策略收进折叠并统一术语
build / build (push) Successful in 1m49s
2026-11-17 16:08:54 +08:00
dev 8e6094e9e5 feat(settings): worker 能力心跳读取 + 封存源对照 + 知识库映射合并
build / build (push) Successful in 2m6s
F01:新增 /api/v1/system/worker-capabilities,按 job_types 判定 test.upload 执行器是否注册,
服务卡片分「地址可达 / 凭据与库读取 / 执行器能力」三行。
F04:routing-bindings 返回 LIBRARY_SOURCE_KB_* 与一致性,设置页同屏显示入库目标与封存源。
结构:测试绑定与生产目标合并为「知识库映射」。
2026-11-17 16:04:00 +08:00
dev 33afdb9f11 test(web): 保存边界回归(F03):分区提交载荷互不夹带
build / build (push) Successful in 1m51s
2026-11-17 15:34:31 +08:00
dev 8a574903a1 fix(web): 测试 WeKnora 卡片不承诺可接单,技术说明折叠
build / build (push) Successful in 1m49s
2026-11-17 15:30:13 +08:00
dev 0fb78cfe26 feat(web): 发布管理界面精简 + 系统设置审查修复
build / build (push) Successful in 1m51s
发布管理:状态卡 + 一个主按钮,准备动作与检查项分层次收纳,去掉重复入口。
系统设置:F02 停滞阈值接入活动配置;F03 分区保存边界;F05/F06 生产绑定分层与凭据说明;
F07 备份未接主机/未知证据如实显示;F09 分区独立加载与保存后重探;F10 文案精简;F11 重置密码对话框。
2026-11-17 15:23:29 +08:00
dev cbc6b981c6 fix(library): 0.9.0 索引写入/归属校验不补 tenant_id,冲突可定位
build / build (push) Successful in 1m56s
- SearchIdentity 增加 NoTenantField,按目标 profile 决定是否注入 tenant_id
  (写入、归属预检、恢复搬运三条路径)
- 归属冲突与写集合不匹配写明具体字段,排查不用再猜
- 网关侧 acquire 冲突打印 plan/claim/owner 三项
2026-11-17 11:59:45 +08:00
dev ecf518e3bb fix(library): 基线/索引按 0.9.0 profile 校验,不再写死 74 与 tenant_id
build / build (push) Successful in 2m5s
- OpenBaselineStack 用目标库解析出的 profile 校验 schema(134 合法),
  contract.WeKnoraVersion 取 profile 值
- no-gate 维护参数(IngressMode/IngressAck/HealthURL)从配置透传,
  否则 0.9.0 目标会被当成缺闸门拒绝
- 索引写入与校验按 profile 决定是否补 tenant_id(0.9.0 索引无该字段)
2026-11-17 11:43:02 +08:00
姚章浩 0b753e550e feat(libraryagent): 允许显式 peer uid 连接
build / build (push) Successful in 1m54s
容器里的治理进程以固定非 root 用户运行,agent 原先只接受与自身同 uid 的连接,
socket 挂进容器后一律被拒(peer uid is not allowed)。新增 --allow-peer-uid,
默认仍只允许同 uid,放行清单只能由部署参数给出,避免"挂上就能连"。
2026-11-16 23:15:34 +08:00
姚章浩 2066bedbbe feat(library): 维护窗口支持显式 no-gate 测试栈
build / build (push) Successful in 2m2s
0.9.0 测试栈没有入口闸门容器(只有 app/frontend/docreader/es/redis),
实例级维护窗口因此开不了。新增 LIBRARY_TARGET_INGRESS_MODE=none,
必须同时给 LIBRARY_NO_INGRESS_ACK=test-only 且不得声明半套闸门;
默认仍是 gate,行为与文案不变。

no-gate 下不调用任何闸门动作,改为要求 LIBRARY_TARGET_HEALTH_URL 并在
恢复后探测 200;维护记录、冻结日志与快照写入 ingress_mode/ingress_ack,
gate 证据位置如实写“无闸门(测试模式)”,不伪装“入口已排空”。
2026-11-16 22:58:37 +08:00
姚章浩 5f1a8f565c fix(libraryctl): 只读会话在 RDS 上强制生效
build / build (push) Successful in 1m46s
托管实例(RDS)上角色级设置会覆盖启动参数,SHOW
default_transaction_read_only 实测为 off;而池里每条连接是独立会话,
对单条连接 SET 管不到其他连接。改为 AfterConnect 给每条连接显式置
只读,并把"连不上"与"连上但可写"分开报,避免一句泛化失败掩盖真实原因。
2026-11-16 21:26:50 +08:00
姚章浩 4fce49478f fix(library): 采集绑定允许对外库未配置
build / build (push) Successful in 1m48s
routing_kb_bindings 在 0.9.0 迁移后只剩 id='active' 一行且两列都是 NULL。
解析要求两者都非空,于是 status/preflight 一律报 read routing bindings failed,
测不出真实原因;而平台侧约定对外库没有对应目标时留空。

- 读取 SQL 对两列 COALESCE,NULL 与空串同等处理:容器模式与文件模式
  (governance DSN)从此共用同一条查询与同一份解析语义。
- internal_kb_id 必填,为空报「对内知识库未绑定(...internal_kb_id 为空)」;
  空输出(无生效绑定行)归入同一说法。
- external_kb_id 允许为空:绑定仍有效,status 与 -scope internal 照常;
  -scope external 明确失败并报「对外知识库未配置(...external_kb_id 为空)」,
  不回退到对内库。
- preflight/capture/dead-letters 在连源库、开维护窗口之前定住 scope 目标库,
  缺绑定不再退化成 knowledge base not found in source。

测试:新增绑定解析与 scope 目标解析用例(internal 空拒绝并点名、external 空
解析成功且 external 被拒、两列都有原行为不变),以及一条不连库的查询形状断言。
开发快照 0.1.380。
2026-11-16 21:21:29 +08:00
姚章浩 4d2cb13b0e test(library): 夹具口令改为运行时拼装
build / build (push) Successful in 1m42s
ci 档案的密钥扫描按被跟踪文件判定,测试夹具里的赋值型/URL 型口令字面量
会被当成真泄漏;这类必然是假值,写在源码里只会淹没真信号。改为运行时
拼接,断言仍引用同一变量,验证“错误里不含口令”的原意不变。
2026-11-16 21:03:18 +08:00
姚章浩 0aa9f273e6 feat(library): 采集接入 RDS 型 0.9.0 栈
build / build (push) Failing after 1m33s
为什么:测试 0.9.0 栈(Compose 项目 weknora-v090)没有源库容器,治理库也不在
容器里,两者都是 RDS。旧实现用 -source-pg/-governance-pg 的容器地址拼 DSN、
用 docker exec psql 读路由绑定,在这类栈上采集根本起不来——不是权限问题,是
地址解析方式错了。

怎么改:
- 新增 internal/librarydsn 收敛"这次 DSN 从哪来":容器模式保持原形状
  (sslmode=disable,目标不变);-source-pg 为空时改用源应用容器 env 的 DB_*
  直连托管实例,TLS 取 LIBRARY_SOURCE_DB_SSLMODE(默认 require,prefer/allow
  这类会静默降级的取值直接拒);-governance-pg 为空时从
  LIBRARY_GOVERNANCE_DSN_FILE 的 0600 文件读 DSN(复用 dobotaiops.ReadDSNFile,
  不另写一份同义实现)。两条路径都不进日志/错误/describe,错误只点名缺哪个变量、
  缺哪个文件。
- libraryctl 的路由绑定读取按模式分派,只共用行解析;外部路径用只读会话。
  libraryagent 的 identity/health 增报 source_db/governance_db 模式;-describe
  只打这两项,不再 dump 配置。
- 新增 scripts/library-capture-v090.sh:weknora-v090 的唯一写入者 app + 逐个
  声明的 non-writers,两个 -pg 传空走外部模式,归档根可环境变量覆盖,
  LIBRARYCTL_BIN 缺失即失败;0.7.1 入口脚本一字未动。

怎么验:internal/librarydsn 三条路径(容器/RDS/文件)各有用例,缺变量、缺文件、
0644 文件、非 PostgreSQL 内容均失败关闭且断言错误不含口令;cmd/libraryctl 侧
钉住文件模式接线与"错误不带地址";v090 脚本进 CI 做 bash -n 加标志/服务声明
断言,并拒绝 0.7.1 容器名出现在新入口。make verify 17 项全绿。

未做:真实采集、生产 executor、Key/KB 绑定。
2026-11-16 20:53:40 +08:00
姚章浩 fba2713b4e feat(library): 发布写入支持 WeKnora 0.9.0 schema 134
build / build (push) Successful in 1m54s
整库发布写入路径原先按 0.7.1 的固定表集合工作:0.9.0 没有 wiki_log_entries,
Current/清理/编目/整实例指纹都会在不存在表上失败,跨版本闸门也因快照丢掉
SchemaVersion 而失效(未知版本被当作 74)。

改为在装配时解析目标 profile,表集合与清理顺序按解析结果;快照复制与范围改写
带上 SchemaVersion/Profile;跨版本发布显式拒绝并同时点名两个版本。单文档发布包
仍只支持 0.7.1,但改为明确拒绝并说明原因。

本机隔离验证:真实 0.9.0 schema 源库→导出→封存→写入干净 134 目标→逐表核对→
写前镜像回滚;74→134 拒绝与 134 缺表不报错两个负例通过。make verify 17 项全绿。
2026-11-16 20:42:23 +08:00
姚章浩 10568943af test(qawemail): 用绝对域名断言不可解析主机
build / build (push) Successful in 1m48s
构建机 resolv.conf 带 search 域(Tailscale tailf49802.ts.net)时,
smtp.kg-test.invalid 会被拼成 ...tailf49802.ts.net 并由 Fake-IP DNS
解析成功,断言实际测的是构建机搜索域。改成带末尾点的绝对名后与
搜索域无关,仍保持“不可解析主机必须判非法”的原意。
2026-11-16 20:27:25 +08:00
姚章浩 3f2626f621 feat(library): 整库发布支持 WeKnora 0.9.0 schema 134
build / build (push) Failing after 1m32s
按 schema 版本选 profile 并以 information_schema 能力探测放行,取代写死的
version==74;未知版本、脏库、缺表缺列、跨版本搬运一律拒绝并点名原因。
0.9.0 的索引名改从部署配置解析,wiki_log_entries 按 profile 变为可选,
归档部件集合随之一致。
2026-11-16 20:22:29 +08:00
姚章浩 e8bfdbbc06 docs(changelog): 记录工作台界面优化开发快照 0.1.375
build / build (push) Failing after 1m41s
为什么:本仓每个面向使用者的变更都要在 CHANGELOG 留开发快照段,版本号按
基线 tag 后的提交数推导(5e850e9 为 0.1.369,本轮 6 个提交后为 0.1.375)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:10:28 +08:00
姚章浩 ef3c1fbf84 fix(web): 侧栏环境标注改为云测试环境
为什么:平台已迁到云测试主机,侧栏底部仍硬编码「本地治理环境」,会让人误以为
操作的是本机旧栈。

改了什么:文案改为「云测试环境」,用例同时断言不再出现旧文案。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:09:43 +08:00
姚章浩 2da96da592 feat(web): 问答流水立即同步改为次按钮并对齐页面边距
为什么:「立即同步」会让后台入队写同步作业,却与只读的「查询」同为蓝色实心主按钮,
容易误点;问答页左边缘比其他模块多缩进 8px,切换页面时标题会跳。

改了什么(同步的启用条件、调用与状态提示不变):
- 「查询」用全站主按钮色;「立即同步」加 qa-sync-action,改为白底钴蓝描边次按钮;
  「本周」悬停不再被主按钮悬停规则染色。
- 查询区、结果区改为与其他模块一致的圆角卡片 + 极轻投影;焦点改为统一光晕。
- 页头改用共享 .page-header(h2→h1,每页一个 h1);横向边距统一 24px,
  纵向保留原有紧凑密度;删掉被后文覆盖、从未生效的重复 padding/gap。
- 问答区硬编码蓝/灰映射回令牌;修正从未定义的 --danger-ink。

验证:typecheck、vitest 全量通过(含 96px 按钮宽度断言);浏览器只读核对
查询=实心钴蓝、立即同步=白底描边,执行一次查询(GET)台账正常;未点击立即同步。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:09:43 +08:00
姚章浩 10182b027e feat(web): 来源与目录批量条按选中高亮并换用线性图标
为什么:「对内/对外/禁止导入」是三块实心色按钮挤在右上角,「已选 N 项」缩在
禁止导入下面;没选中时整条也一样抢眼,📁/📄 emoji 与工作台风格不协调。

改了什么(策略按钮的启用条件、调用与确认不变):
- 批量条:「全选当前页」后紧跟「已选 N 项」,策略按钮归入一组(role=group);
  只有选中后整条才浅钴蓝高亮。
- 策略按钮改为浅底语义色描边,与表格内策略徽标同色同形。
- 📁/📄 换成 CSS mask 线性图标;文件夹名改为深色正文、悬停变钴蓝。
- 表头/单元格字号统一(11→12.5px),行悬停底色;页头接入共享 .page-header。
- 删除重复的列宽规则与被后文覆盖的禁止导入样式(同一含义只留一份),
  目录区硬编码蓝/灰映射回令牌。

验证:typecheck、vitest 全量通过(App 用例按新 h1 标记更新);浏览器只读核对
勾选→高亮/已选 1 项、取消→恢复中性、文件格式筛选展开;未点击任何策略按钮。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:09:43 +08:00
姚章浩 060872a144 feat(web): 解析监控标明筛选范围并收拢筛选与批量条
为什么:顶部「失败 35」是全部任务口径,下方表格默认只看「未结束」,常常为空;
两者范围不同却没有任何提示,「已选 0 项」的批量条也常亮蓝色,像有待办动作。

改了什么(筛选项、接口参数、重试权限与确认流程均不变):
- 指标卡口径(全部任务口径/最近 1 小时/当前)改成徽标;文件处理标题旁显示
  「当前筛选 N 项 · 本页 M 项」,分页写明「当前筛选共 N 项」「第 x / y 页」。
- 「清除筛选(N)」显示已生效筛选数(默认的未结束也算一项),无筛选时禁用;
  「仅当前绑定」改为可见按下态的切换片;时间范围展开为浮层,不再挤乱筛选行。
- 批量条只有选中后才高亮;禁用的主按钮改为中性灰,不再像"加载中"。
- 表格行距收紧、状态改为圆点徽标、选中行左侧标记;来源名限两行并保留完整 title;
  页头接入共享 .page-header。

验证:typecheck、vitest 全量通过;浏览器只读核对范围说明与分页总数一致、
时间浮层、详情抽屉 Esc 关闭、服务状态展开、1920/1024/390 宽度无横向溢出,
全程浏览器侧拦截非 GET 请求(0 条)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:08:49 +08:00
姚章浩 0f7b8987b4 feat(web): 全站改用越疆配色并统一模块页头
为什么:测试机工作台要长时间盯着看。原配色是深色侧栏 + 三种"主按钮"
(全局深藏青、监控页蓝、问答页黑),各模块页头字号/边距/是否装卡片各不相同;
另有一处真缺陷:全局 button:hover:not(:disabled) 特异性高于 .nav-item:hover,
悬停导航时被刷成白底,选中项文字几乎看不见。

改了什么:
- 色板改取越疆官网 dobot.cn:品牌钴蓝 #0039C8 为全站唯一强调/主操作色,
  文字与底色改为不带蓝紫偏色的中性灰(用户反馈紫色费眼);卡片细边 + 极轻投影。
- 侧栏改为明亮底,选中项浅钴蓝底 + 钴蓝字;悬停规则补 :not(:disabled) 修复白底。
  导航字号/点击区保持 16px / 44px(沿用 8d44d54 的放大决定)。
- 新增唯一一份 .page-header / .page-title / .page-subtitle;版本记录、系统设置、
  发布管理接入(版本记录页头不再装卡片),删掉各自重复的标题字号规则;
  page-shell 改为 max-width,模块自己的 1800/1500 上限终于生效。
- 版本记录、系统设置、问答同步状态里的硬编码蓝/石板灰映射回令牌;顺带修正
  6 个从未定义的变量(--border/--card/--accent/--brand 等)——它们此前只靠
  回退值或干脆不生效。

不改业务语义、权限、确认流程与接口调用。
验证:npm run typecheck、vitest 全量(110 文件 / 568 用例)通过;浏览器只读核对
导航悬停色、六个模块页头左缘/字号/字重一致。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:07:44 +08:00
姚章浩 5e850e96f5 fix(qa-weekly-mail): 修复发送记录读回并区分未知投递
build / build (push) Successful in 2m18s
1) 发送记录读回(确定性回归):Sends() 的 SELECT 只有 6 列,Scan 却收 7 个字段(多出
message_id)。只要历史里存在任意一条发送记录,整个列表就返回 ErrUnavailable —— 发送
成功后页面刷新、以及“完成读真实发送记录”都会失败。改为查询带 message_id,并检查
rows.Err(),不把截断的列表当成完整历史。

2) 未知投递不再当成可重试失败:DATA 已提交但没收到最终 250(连接中断/超时)时,邮件可能
已被服务器接受;旧实现记 failed 并允许下一分钟重发,会重复投递。现在由 SMTPMailer 在
writer.Close() 失败处抛出窄类型 unknownDeliveryError,deliver 保留 sending 并记录原因,
自动/手动路径都不再重发(手动返回 ERRDeliveryUnknown,HTTP 409 说明原因)。连接建立前
失败、STARTTLS/AUTH/MAIL/RCPT/DATA 命令被拒、正文写入失败仍是确定失败,可如实 failed 并
重试一次。

3) SMTP 交互加有限期限:整体 90 秒(随请求 ctx 收紧),并用 context.AfterFunc 在取消时打断
阻塞读写,避免服务器接受 DATA 后不响应时挂死 worker 与发送行。

验证:真实隔离 PG 先 RED 后 GREEN(非空 sent+failed 历史读回成功并带真实 message_id;
HTTP GET /weekly-mail/sends 非空历史 200);本机 TLS SMTP 桩 + 真实 SMTPMailer 覆盖成功、
RCPT 550、DATA 后丢最终 250、DATA 阶段卡死(ctx 800ms 内返回)四类;真实 deliver 在未知
结果时留 sending 且不重发,在明确拒绝时 failed 并可重试一次成功。make verify 17 项全绿。
2026-11-09 01:06:09 +08:00
姚章浩 719876d039 fix(qa-weekly-mail): 修复周日发送窗口并提供正式补发
build / build (push) Successful in 3m5s
根因:SendDue 同时要求“已到配置时段”与“该周已结束(下周一00:00)”。周日23点的时段
只在周内存在,当周周报永远不满足“已结束”,于是 11/08 23:00 只报 nothing_confirmed、
11/09 00:00 又已成 not_due —— 邮件从未尝试发送,与 SMTP 凭据/网络无关。

改法(最小、不碰历史发布模块):
1. 由发送窗口反推要发的周:周日窗口发当天结束的那一周,其它工作日仍发上一完整周
   (周一09:00 语义不变)。自动发送只处理这一周,不再按“所有已结束的周”回填。
2. 认领改为只重认 failed(或首次)记录:sent 幂等返回真实 message_id;sending 视为
   结果未知,拒绝盲重发并提示核对邮箱。自动与手工共用同一条渲染/认领/投递路径,
   并发或重复点击只投递一次;失败如实写 failed,不假写 sent。
3. 新增管理员正式补发(页面按钮 + GET 预览 + POST /weekly-mail/send/{week}):精确指定
   周、已确认版本与正文 hash,必须同源操作意图;未来周拒绝,当前周须到设定时点,
   已结束周可显式补发。正文/看板图片/主送/抄送与自动发送一致,结果写入正式发送记录。
   这不是“发送测试邮件”(只发 review 地址、不登记)。

验证:真实隔离 PostgreSQL(kg-pgtest-writeset 上的独立一次性库)先 RED(旧实现真实
复现 nothing_confirmed)后 GREEN;覆盖到点前/未来周/未确认/正文变化、周一语义保持、
手工补发一次并读回 message_id、并发只投递一次、结果未知不重发、失败可重试一次。
HTTP 与前端解析用例通过;make verify 17 项全绿。
2026-11-09 00:48:33 +08:00
姚章浩 9d445f4953 test(ci): 声明两个隔离PG纵向用例为可选未运行
build / build (push) Successful in 1m53s
2026-11-06 11:04:07 +08:00
姚章浩 2eff9447e1 fix(library): 修正启动收敛误判并提供精确核对
build / build (push) Failing after 1m20s
ReconcileLibraryJobs 不再把 completed capture queue 当成不存在,保留待核对
pending 封存作业;failed/cancelled/missing 仍按真实队列状态处置。管理员核对
入口只允许精确的启动误判形态,并要求 completed queue、export succeeded、
唯一 test_sealed 版本、来源身份与完整归档复核。新增 library_job_repairs
不可变审计表,在同一事务内 CAS 保存原 state/stage/error/recovery/finished_at
及本次 actor/原因/证据后修复;真实失败/取消不开放。

验证:真实隔离 PostgreSQL 启动收敛 RED/GREEN、启动→handler 纵向 pending 与
系统误判 failed、审计保留/幂等、负例;真实 Go 全量与 make verify 17 项通过。
2026-11-06 10:51:21 +08:00
姚章浩 146ac832a2 fix(library): 修复封存终态回写并增加精确核对
build / build (push) Successful in 2m9s
修复 varchar 状态参数在 AdvanceLibraryJob 的 42P08;worker 开始/终态写入失败
不再吞掉。新增管理员核对路由,仅在 completed capture queue、export succeeded、
精确 test_sealed 版本、来源身份和归档复核一致时,以条件更新修复仍为
pending/running 的同一作业;已有不同快照或并发失败/取消行拒绝覆盖。保留
第一因与历史记录,不重新封存、不产生快照、不写源或目标知识。

验证:真实 varchar DDL PG 路径、handler 负例/幂等、worker 注入、web 组件;
umask022 与真实隔离 kg_library_test_* 下 Go 全量与 make verify 17 项通过。
2026-11-06 10:04:19 +08:00
姚章浩 77bbc3ac6b fix(worker): 恢复保留错误的第一因分类
build / build (push) Successful in 1m38s
恢复 terminalLibraryCaptureError,但仅限仍存在的 missing library generated
question index 和 empty library index content;已恢复写入者时走
jobs.Permanent(validation_failed),保留原消息。已取消的正文索引覆盖 marker
和网络超时仍重试。部署脚本另以新包提供旧基线稳定性采样;不恢复 R3f 已取消
的正文索引/父类型规则。

验证:worker 保留错误 RED→GREEN、v071、Go 全量、make verify 17 项。
2026-11-05 18:48:53 +08:00
姚章浩 eaa388f76b fix(release): 取消封存正文索引与父类型推断规则
build / build (push) Successful in 1m42s
按用户明确要求,治理封存不再替 WeKnora 判断正文块“应该”有独立索引:
删除 status/chunk_type/parent/mixed/flat 推导的 needOriginal、mixedDocs
及覆盖门槛;删除 parent 类型搭配限制,仅保留父引用存在与同 knowledge。
capture/preflight/archive/load/replay/writeset 共用校验同步更新,移除已无
用途的 worker 永久失败分类。

保留真实导出范围、PG/ES 原始正文/问题 metadata/vector、tenant/KB/
knowledge/chunk 身份、清单摘要、资源字节、Wiki/问题索引 source_id 及真实
悬空引用等完整性检查;不修改源端,不补数据/索引。旧测试改为原样捕获正例,
新增 status0/2 缺正文索引和父类型不匹配的接受回归,以及 archive/readback
逐行/逐记录比对。

验证:v071、cmd/worker、Go 全量、make verify 17 项。
2026-11-05 18:24:36 +08:00
姚章浩 cf11343cf4 fix(release): 适配原生 parent-child 索引覆盖选择
build / build (push) Successful in 2m0s
治理候选封存现在解析 chunks.parent_chunk_id,并按 knowledge 区分源端
v0.7.1 的原生索引选择:mixed 文档只要求有 parent 的 text 原文索引,
flat 文档仍要求全部 text;parent_text 仅作上下文;status=2 缺失仍拒绝。
问题索引仍按 source_id 精确核对,不把问题记录当正文索引。

非空 parent_chunk_id 必须指向同一 knowledge 的真实 parent_text;standalone
空字段不强制关联,不被其他文档的 parent 豁免。归档与解档复用同一校验;
合成夹具证明 PG 全部 4 个 chunk 与 2 条 ES 原始记录读回保留。

验证:真实 ArchiveLibraryCandidate RED→GREEN、v071 全量、Go 全量、
make verify 17 项。源 WeKnora 未修改,不补父关联/索引,不重解析。
2026-11-05 16:18:20 +08:00
姚章浩 7511c59987 fix(release): 修复封存阶段真源与精确验证列表
build / build (push) Successful in 1m56s
F02:测试封存作业只展示只读导出测试版本,不再套用备份生产/同步 Wiki/
生产验证/生产生效,也不再写目标维护;运行和失败终态都保留真实 export
状态。同一挂载覆盖 running→failed。

F03:版本列表按每个 snapshot_id 精确查询恢复验证记录,与详情使用同一
endpoint;同 scope 最新 passed 不再给其他快照染色,未演练与读取失败分开。

封存失败:已恢复写入者且确定不可重试的捕获校验错误使用永久失败,避免
第二次 attempt 的 already exists 覆盖第一因;业务 job 的 error 在失败重试
中保留第一条,成功时清除。瞬时不可达/超时仍保留重试。

验证:Go/前端全量、隔离 PG 精确快照与首因测试、临时独立 ES 的
Current→Prepare→Verify PASS、make verify 17 项。host libraryctl 仍是旧
f9c15a8f...dirty,360 镜像未替换 host 工具,本轮只单独准备包不切换。
2026-11-05 14:05:13 +08:00
姚章浩 b81fcd07e3 fix(release): 修复tableState文本身份与快照统计归属
build / build (push) Successful in 1m57s
tableState 非 resources 分支恢复直接扫描 text 身份,避免 queryRows 把普通
doc id/UUID/复合键/数字 id 当 JSON canonical 校验而失败;resources 仍使用
F01 精确引用闭包。隔离 PG 覆盖字符串、UUID、复合键与数字 ID。

F11:快照 HTTP 投影补 bindings/wiki_log_entries;作业统计按本作业
target_snapshot_id/snapshot_id 取对应快照,取不到显示未知,不借最新封存;
running/pending/failed/unknown 不再在无 detail 时显示完成。

F03:verifications 支持 snapshot_id 精确查询,返回 snapshot_latest 并只按
该快照回答 verified;抽屉“查看校验记录”按选中快照加载,不借用最新记录。

F08:显示主机探测时间;无真实 next-run 时说明尚未核验下一次执行;最近成功
单列未知,不以最近运行冒充。

验证:Go/前端全量、隔离 PG tableState/F01 对拍与 make verify 17 项通过。
实际 Current→Prepare→Verify ES 集成被共享 ES 磁盘 watermark 阻塞,未冒充。
2026-11-05 13:19:27 +08:00
姚章浩 1a0f99e346 fix(release): 修复发布管理F01-F11资源闭包与状态呈现
build / build (push) Successful in 1m44s
F01:捕获、写前镜像、指纹和恢复后内容校验共用按目标精确绑定的资源闭包:
从已限定范围的 resource_bindings 与正文 handle 一次提取,再按索引取资源,
不再对每个租户资源扫描全部正文表。无绑定正文引用仍保留,缺失资源仍失败。

F02/F03:恢复验证使用 capture/verify/canary/restore/finalize 自己的阶段,登记
证据不再叫新版本生效;顶部优先在飞作业;已验证且 API reason 为空时不再同屏
显示未读到状态,报告可展开。

F04-F11:显示实际目标实例/项目/库;运行中主按钮查看当前任务并禁止重复启动;
快照历史默认已登记、可筛选分页并定位所选;无真实下次计划时显示未读取;各
scope 独立 overview;新操作清旧通知;存储行按文档/分块/资源/绑定及 Wiki
页面/目录/日志分项。高影响恢复验证/恢复增加一次影响确认。

验证:隔离 PG 20k 无关资源夹具旧扫描 683ms→新导出 41ms,资源 ID 闭包相等;
Go/前端全量及 make verify 17 项通过。未部署、未做 8088 UI 验收。
2026-11-05 12:50:11 +08:00
姚章浩 7675e2cd88 fix(ui): 保留业务HTTP配置超时
build / build (push) Successful in 1m33s
F13 动态客户端原先把 TEST_WEKNORA_HTTP_TIMEOUT(默认 60s)强制截成 10s,
与 readiness 探针上限混用,导致上传/轮询等业务请求 10s 即超时。

现在显式正超时原样传入;未配置/非正值回落到 appconfig 的 60s 默认。
readiness 探测自己的 10s 上限不变。

新增本地 httptest:60s 配置下 11s 响应成功,显式 50ms 短超时仍生效;
端点/凭据/绑定动态解析回归保持通过。make verify 17 项通过。
2026-11-05 12:03:42 +08:00
姚章浩 5bf4aae30e fix(ui): 接通取件后自动解析与一次性定位
build / build (push) Successful in 1m42s
F17:MarkArtifactFetched 与已验证内容复用都在同一事务内经过策略、来源启用、
过滤、superseded 和当前绑定的复核后,自动把 planned 转 pending 并入队唯一
test.upload;确认与作业幂等,失败整笔回滚。356 已卡记录可对同一文件再次保存
当前策略,经同一路径恢复,不做全库补扫或手工补队列。来源页提示改为自动接续。

F14:来源→监控定位清空未结束/动作/阶段/时间筛选;来源目录定位改为一次性请求
并由父消费,revision/sources 重载不再重放旧请求,手工换目录保持。

F13:抽出 readiness.Resolver 作为端点/绑定/凭据唯一来源;worker 上传/轮询/
校验/移除改用动态客户端,每次调用重读有效配置,不再固化启动 env 客户端。

验证:隔离 PG 的 F17 正负例与恢复用例、前端挂载定位回归、全量 Go/前端测试
及 make verify 17 项通过。未部署、未做 8088 UI 验收。
2026-11-05 11:46:42 +08:00
姚章浩 1c80b07f2c fix(ui): 修复F12-F16入口与追溯缺陷
build / build (push) Successful in 1m59s
Dockerfile 运行阶段补齐 dws_dingtalk_scan(F12),并新增 runtime-scripts 门禁
做脚本依赖闭包正负例;就绪探测每次解析当前端点/绑定/凭据并区分 404、未配置、
不可达(F13);路由写入来源路径与父目录,历史空值仅按同连接同 item 的意图读时
补齐(F14);目标筛选显示短 ID 与当前绑定/历史并提供快捷筛选(F15);刷新终态
移除后台运行、展示失败时间/旧快照/脱敏原因/作业 ID 与重试(F16)。

验证:make verify 17 项全过(identity 本地按设计 skipped);一次性 schema 的
Monitor 目录/路由集成用例通过;8088 部署与真实 UI 验收仍由父会话执行。
2026-11-05 10:38:26 +08:00
姚章浩 dfbf3336b2 docs(version): 修正0.1.28同号说明归属
build / build (push) Successful in 1m29s
f33730ed 按第一父真实边界说明开发版本历史修复并标注QA分支为集成。
保留另一0.1.28提交自身说明;新增同号不同SHA选择回归。
2026-11-04 17:05:51 +08:00
姚章浩 600cca02e5 docs(version): 修订历史说明 merge 与 rename 统计
build / build (push) Successful in 1m30s
0.1.207/0.1.35 按真实第一父 diff 重写范围与功能摘要。
0.1.340 修正为 +2485/-336 并补 rename 测试文件变更。
0.1.28 正文保留,仅补目标提交;新增合并说明回归断言。
2026-11-04 16:34:21 +08:00
姚章浩 e735ae603d docs(version): 补齐270条历史开发版本说明
build / build (push) Successful in 1m29s
按权威 version→commit 映射,为缺失开发版本增加 exact-SHA CHANGELOG 块。
正文采用该提交新增 CHANGELOG 或真实 commit body/diff 归纳,已有82条不改。
新增270条绑定验收与错SHA拒绝测试,不改变版本计算与同步实现。
2026-11-04 16:20:09 +08:00
姚章浩 2a2e98bd8e fix(version): 兼容开发快照版本标题
build / build (push) Successful in 1m41s
识别“## 开发快照 <version>(说明)”并保留旧 snapshot/v 格式。
版本号精确匹配、不跨二级标题、空正文不返回,archive 精确 SHA 绑定不变。
2026-11-04 15:57:53 +08:00
姚章浩 92684c6f60 fix(index): 预检使用目标映射 ID
build / build (push) Successful in 1m45s
PlanWriteSet 的 index preflight 改用与 plan/Apply 一致的目标物理 _id。
保留 tenant/KB 归属、完整 _mget 与并发版本校验;legacy 路径不映射。
负例:映射后 ID 被占、legacy 源 ID 冲突仍拒绝。
2026-11-04 15:12:08 +08:00
姚章浩 537a6df46d fix(library): 首次同步可复用同租户已存在资源
build / build (push) Successful in 1m39s
取消资源复用必须属于本目标历史成功同步/预备份的自加门槛。
仍要求目标行逐列一致与实际对象字节一致;旧库资源行/绑定/对象不删不改。
新增 reuse evidence v3:无 provenance,保留行摘要与逐对象字节证据。
2026-11-04 14:22:51 +08:00
姚章浩 0d9091e464 fix(library): 目标隔离映射兼容旧计划与真实回归
build / build (push) Successful in 1m41s
空 mode 计划不映射;索引 source_id 按语义映射;relation 按字段表解析。
隔离回归按持久映射 ID 断言,DS02 故障注入真实命中。
2026-11-04 12:40:12 +08:00
姚章浩 e0fc2c32b8 feat(library): 目标库隔离 ID 映射并保留旧库
build / build (push) Successful in 2m11s
同实例第二个目标 KB 与旧库共享源 UUID 时,计划/写入/校验/恢复按目标范围派生稳定身份;
计划持久化 target_id_mode,旧计划与写前镜像不二次映射;资源保持共享 ID。
2026-11-04 12:07:27 +08:00
姚章浩 6042955498 fix(objectgateway): 入口测试夹具改用无口令 PG URL
build / build (push) Successful in 1m59s
现象:CI run 347 / job 362 在 security-secrets 失败,指向
cmd/object-gateway/main_test.go:30 的 pg-url 类别。

根因:该 DSN 只用于 127.0.0.1:1 故意不可达连接,验证启动能越过
配置阶段到达 journal/后端准入,本身不需要任何口令,却写成了带口令形式。

取舍:直接换成合法无口令 URL,不拆秘密字符串隐藏检测、不改扫描器/基线/
必需项范围。产品代码与测试行为不变。

证据:check_secrets.py 由 exit 1(指向该行)转为 exit 0;go test
./cmd/object-gateway 通过;umask 022 下 make verify 16 项本地必需全 success。
2026-11-04 09:52:00 +08:00
姚章浩 a55319d972 fix(objectgateway): 取消整桶独占前置并按维护停写更新
build / build (push) Failing after 2m29s
现象:共享桶部署下网关启动即报 gateway_auditor_key_required,残留过期
审计文件则每次 Execute 报 gateway_exclusive_writer_evidence_unverified;
用户已改为“停目标写入容器→更新→启动”的维护式更新。

根因:Gateway.Ready 强制 Isolation.Verify,main 强制 Ed25519 公钥,等于
把整桶独占证明当作发布前置;这与共享桶、沿用原 AK 的实际部署矛盾。

取舍:删除审计校验与相关 env 依赖,保留 journal、治理 PG 只读 authority、
plan/owner/attempt/epoch 绑定、intent-before-send、单次写与精确版本回滚。
create 仅在精确版本读回且仍为 current 时提交;发现外部 latest 只返回冲突,
不在 confirm 阶段删除(journal create intent 已提交,删除会变成无 delete
intent/receipt 的未记账副作用并让 intent 永久 held)。同 key 不自动合并。

证据:真实二进制无审计/残留审计两环境通过;kg-pgtest-writeset 一次性库 +
随机 MinIO 桶跑 14 个网关用例(含共享桶共存写者、同 key 既有对象拒绝、
精确回滚)全过;umask 022 下 make verify 本地必需项全 success。
2026-11-04 09:45:47 +08:00
姚章浩 017765763a fix(library): 维护卡只展示 owner_job_id 匹配的作业详情
build / build (push) Successful in 1m45s
问题:维护窗口 record.owner_job_id 指向失败/待恢复的作业 A,但页面把同 scope
最新作业(更新的成功封存 B)当窗口进度,needs_restore 被显示成“导出 · 已完成”,
需要处理的原窗口因此看起来已经结束。

改法:
- maintenanceSummary 只接受“按 owner_job_id 读到的持有作业”,id 不一致一律按
  未读取处理;进度/错误/恢复说明只来自该作业,不拿最新作业兜底。
- 新增 fetchLibraryJobDetail 读取既有只读接口 GET /api/v1/library/jobs/{id},
  明确区分 loaded / missing(404) / error(非2xx、结构不符、id 串包) / unread,
  不把读取失败吞成“不存在”。
- 恢复可用性只由“维护仍持有 + 本窗口作业未收口 + 当前 scope 等于 owner_scope”
  决定;running/pending 不并发恢复,已释放/无记录不提供恢复,跨 scope 给切换提示。
- 入口状态明确标注“维护记录,未实时探测”;held 时说明只有维护记录释放才算结束;
  held 但持有作业已完成时写“维护记录未对账”,不提供强制成功。
- load 增加请求代次守卫,晚回包不覆盖更新的窗口;作业详情返回的 id 与请求不符
  按读取失败处理。

未改后端准入、网关协议或任何维护记录;未部署。
2026-11-03 23:02:00 +08:00
姚章浩 bd452e85b3 test(library): 维护 scope 终态按正式释放语义断言 released
build / build (push) Successful in 1m32s
ReleaseLibraryMaintenance 的真实终态是 state=released + released_at,原断言写成 verified 会误红;改为按生产语义核对 released/open。
2026-11-03 13:05:26 +08:00
399 changed files with 41973 additions and 3568 deletions
+5
View File
@@ -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.
+82
View File
@@ -0,0 +1,82 @@
name: deploy-production
on:
workflow_dispatch:
inputs:
action:
description: deploy 或 writeback
required: true
default: deploy
sha:
description: 验收过的完整提交 SHA
required: true
bundle:
description: release.json 的完整 SHA256
required: true
task:
description: 对应的 HiFox 任务 UUID
required: true
confirm:
description: deploy-production 或 retry-writeback
required: true
approval_event:
description: HiFox 自动触发填写的状态事件 UUID
required: false
acceptance_digest:
description: HiFox 自动触发填写的验收记录摘要
required: false
concurrency:
group: cloud-test-governance-main-production
cancel-in-progress: false
permissions:
contents: read
jobs:
guard:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: 核对手动入口及发布输入
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_REF" = refs/heads/main
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
git init -q .
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
git checkout -q --detach "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
python3 scripts/production_cd.py guard --event "$GITHUB_EVENT_PATH"
publish:
needs: [guard]
runs-on: kg-production-cd
timeout-minutes: 40
steps:
- name: 取同一提交的控制端代码
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_REF" = refs/heads/main
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
git init -q .
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
git checkout -q --detach "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
- name: 调用云主站受限发布入口并读回回执
env:
KG_CD_SSH_KEY: ${{ secrets.KG_CD_SSH_KEY }}
KG_CD_KNOWN_HOSTS: ${{ secrets.KG_CD_KNOWN_HOSTS }}
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
+80
View File
@@ -0,0 +1,80 @@
name: prepare-candidate
on:
workflow_dispatch:
inputs:
plan:
description: 'Release task UUID, exact SHA, baseline, requirement PRs and additional reviewed commits (JSON)'
required: true
mode:
description: 'verify or prepare'
required: true
default: verify
permissions:
contents: read
concurrency:
group: knowledge-governance-candidate
cancel-in-progress: false
jobs:
guard:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Verify release scope and CI
env:
KG_CANDIDATE_READ_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
case "$GITHUB_REF" in refs/heads/*) ;; *) exit 1 ;; esac
git init -q .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
auth() { git -c credential.helper='!f() { printf "username=x-access-token\npassword=%s\n" "$KG_CANDIDATE_READ_TOKEN"; }; f' "$@"; }
auth fetch -q origin "$GITHUB_REF" +refs/heads/main:refs/remotes/origin/main
git checkout --detach -q "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
export KG_CANDIDATE_FORGE="$GITHUB_SERVER_URL"
python3 scripts/candidate_release.py guard --event "$GITHUB_EVENT_PATH" --repo .
prepare:
if: ${{ inputs.mode == 'prepare' && gitea.ref == 'refs/heads/main' }}
needs: [guard]
runs-on: kg-candidate
timeout-minutes: 45
steps:
- name: Build and deploy isolated candidate
env:
KG_CANDIDATE_ACCESS: ${{ secrets.KG_CANDIDATE_ACCESS }}
run: |
set -eu
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REF" = refs/heads/main
test -n "$KG_CANDIDATE_ACCESS"
python3 - <<'PY'
import json, os, sys
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener
with open(os.environ['GITHUB_EVENT_PATH']) as source:
event = json.load(source)
if event.get('inputs', {}).get('mode') != 'prepare':
sys.exit('candidate workflow mode is not prepare')
data = json.dumps({'run': os.environ['GITHUB_RUN_ID'], 'plan': json.loads(event['inputs']['plan'])}).encode()
request = Request('http://127.0.0.1:38984/prepare', data=data, headers={
'Authorization': 'Bearer ' + os.environ['KG_CANDIDATE_ACCESS'], 'Content-Type': 'application/json'})
opener = build_opener(ProxyHandler({}))
try:
with opener.open(request, timeout=2540) as response:
print(response.read(65536).decode())
except HTTPError as exc:
print(exc.read(4096).decode(), file=sys.stderr)
sys.exit(1)
PY
+5858 -12
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -50,7 +50,8 @@ RUN set -eux; \
dws version
WORKDIR /app
COPY --from=build /out/ /app/
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/artifact_fetch.py \
scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/dws_dingtalk_scan.py \
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"]
+8
View File
@@ -27,6 +27,14 @@ BUILD_TIME ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
verify:
$(PY) scripts/ci_checks.py
.PHONY: qa qa-doctor qa-self-test
qa:
$(PY) scripts/qa_env.py run
qa-doctor:
$(PY) scripts/qa_env.py doctor
qa-self-test:
$(PY) -m unittest discover -s scripts -p test_qa_env.py -v
# 清单:哪些是必需项、在哪个档案(local / ci)下必需
list:
$(PY) scripts/ci_checks.py --list
+13 -18
View File
@@ -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。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。
+545
View File
@@ -52,6 +52,7 @@
"/api/v1/qa-ops/master/weekly-mail/confirmations/{week}": {"get":{"operationId":"getQAWeeklyMailConfirmation","tags":["QA operations"],"summary":"读取该周是否已确认自动发送;current=false表示确认后正文已被修改,需要重新确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"post":{"operationId":"confirmQAWeeklyMail","tags":["QA operations"],"summary":"确认本周周报可自动发送,绑定当前草稿版本与正文哈希;后续改动使确认失效,不发送改动后的正文","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"delete":{"operationId":"unconfirmQAWeeklyMail","tags":["QA operations"],"summary":"取消该周的自动发送确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}},
"/api/v1/qa-ops/master/weekly-mail/sends": {"get":{"operationId":"listQAWeeklyMailSends","tags":["QA operations"],"summary":"读取周报邮件发送记录:周次、草稿版本、发送中/已发送/失败及错误摘要,不返回正文或收件人","parameters":[{"name":"week","in":"query","required":false,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}},
"/api/v1/qa-ops/master/weekly-mail/test": {"post":{"operationId":"sendQAWeeklyMailTest","tags":["QA operations"],"summary":"管理员用当前已保存的邮件设置立即发送一封测试邮件,正文取该周已保存草稿;不写入发送记录、不改变确认状态、不把该周标记为已发送","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["week"],"properties":{"week":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可测试发送"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因"},"503":{"description":"邮件设置存储不可用"}}}},
"/api/v1/qa-ops/master/weekly-mail/send/{week}": {"get":{"operationId":"previewQAWeeklyMailSend","tags":["QA operations"],"summary":"管理员补发前核对:按周、已确认版本与正文hash返回真实主送/抄送人数、版本与是否已发送;不投递、不写记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"revision","in":"query","required":true,"schema":{"type":"integer","minimum":1}},{"name":"body_sha256","in":"query","required":true,"schema":{"type":"string","pattern":"^[0-9a-f]{64}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"邮件设置存储不可用"}}},"post":{"operationId":"sendQAWeeklyMailFormal","tags":["QA operations"],"summary":"管理员正式补发周报:精确指定周、已确认版本与正文hash;已结束周可发、当前周须到设定时点、未来周拒绝;正文/看板图片/主送/抄送与自动发送共用,写入正式发送记录并返回真实message_id;已发送幂等、结果未知不重发","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["revision","body_sha256"],"properties":{"revision":{"type":"integer","minimum":1},"body_sha256":{"type":"string","pattern":"^[0-9a-f]{64}$"}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且需同源操作意图"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知/授权码缺失"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因且不写已发送"},"503":{"description":"邮件设置存储不可用"}}}},
"/api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image": {"post":{"operationId":"saveQAWeeklyMailImage","tags":["QA operations"],"summary":"管理员保存该周确认对应的统计看板 PNG;发送时作为内嵌图片(cid)放在正文末尾,正文改动使确认失效后不再使用旧图","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["png_base64"],"properties":{"png_base64":{"type":"string","maxLength":12000000}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可上传"},"429":{"description":"请求过快"},"503":{"description":"邮件设置存储不可用"}}}},
"/api/v1/qa-ops/departments/statistics": {
"post": {
@@ -1368,6 +1369,45 @@
}
}
},
"/api/v1/library/jobs/{id}/reconcile-capture": {
"post": {
"tags": [
"Runtime"
],
"operationId": "reconcileLibraryCapture",
"summary": "仅在 completed capture queue、精确 test_sealed 版本与归档复核一致时,修复该封存作业终态;不重新封存",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "已修复或已成功(幂等)"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"403": {
"description": "需要管理员权限"
},
"404": {
"description": "作业不存在"
},
"409": {
"description": "队列/阶段/版本/归档证据不一致,拒绝修复"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/library/restore-availability": {
"get": {
"tags": [
@@ -1932,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": [
@@ -2642,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": [
@@ -3394,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": [
@@ -3442,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": [
@@ -5819,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,
+144 -34
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"os"
"os/signal"
"path"
"strings"
"syscall"
"time"
@@ -16,16 +17,20 @@ 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"
"knowledge-governance/internal/qawemail"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/serviceverify"
"knowledge-governance/internal/version"
)
@@ -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()
@@ -90,48 +114,109 @@ func run(ctx context.Context, getenv func(string) string) error {
return errors.New("read production release authorization token")
}
}
// P10: with a mounted API key the probe verifies a real knowledge-base read
// (readiness); without one it degrades to the liveness-only HTTP check.
var weknoraReadiness func(context.Context) error
var knowledgeBaseLister httpapi.KnowledgeBaseLister
if strings.TrimSpace(config.TestWeKnoraBaseURL) != "" {
if apiKey, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); keyErr == nil {
probeTimeout := config.TestWeKnoraHTTPTimeout
if probeTimeout > 10*time.Second || probeTimeout <= 0 {
probeTimeout = 10 * time.Second
}
if probeClient, clientErr := weknora.NewClient(weknora.ClientConfig{BaseURL: config.TestWeKnoraBaseURL, APIKey: apiKey, Timeout: probeTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}); clientErr == nil {
knowledgeBaseLister = probeClient
routingKB := config.InternalRoutingKnowledgeBaseID
weknoraReadiness = func(probeCtx context.Context) error {
_, _, err := probeClient.ListKnowledge(probeCtx, routingKB, 1, 1)
return err
}
}
}
}
// 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)
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
},
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 := 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 {
settings, err := actionStore.GetActiveUISettings(resolveCtx)
if err != nil {
return ""
}
return settings.ProductionWeKnoraBaseURL
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvProduction)
}
testEndpointResolver := func(resolveCtx context.Context) string {
settings, err := actionStore.GetActiveUISettings(resolveCtx)
if err != nil {
return ""
}
return settings.TestWeKnoraBaseURL
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvTest)
}
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
// 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,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
weknoraProbe := func(probeCtx context.Context) (string, error) {
result := readinessProber.Check(probeCtx)
return result.Target, result.Err
}
knowledgeBaseLister := &weKnoraLister{
resolve: func(resolveCtx context.Context) (string, string, error) {
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return connection.BaseURL, connection.APIKey, err
},
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, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
if err != nil {
return err
}
@@ -143,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 != "" {
@@ -177,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),
@@ -190,14 +289,16 @@ func run(ctx context.Context, getenv func(string) string) error {
QAOpsTenantKey: qaSettings.TenantKey,
QAOpsEnabled: qaSettings.Enabled,
QAOpsProblem: qaSettings.Problem,
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()),
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID),
Monitor: monitorProvider,
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
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,
@@ -207,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,
@@ -217,6 +319,8 @@ func run(ctx context.Context, getenv func(string) string) error {
LibraryTargetWriters: config.LibraryTargetWriters,
LibraryTargetIngressURL: config.LibraryTargetIngressURL,
LibraryTargetIngressService: config.LibraryTargetIngressService,
LibraryTargetIngressMode: config.LibraryTargetIngressMode,
LibraryTargetHealthURL: config.LibraryTargetHealthURL,
LibraryTargetDockerSocket: config.LibraryTargetDockerSocket,
LibraryTargetJournalRoot: config.LibraryTargetJournalRoot,
LibrarySourceInstance: config.SourceInstance(),
@@ -242,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 {
+117
View File
@@ -0,0 +1,117 @@
package main
import (
"context"
"fmt"
"log"
"strings"
"time"
"knowledge-governance/internal/kbbinding"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/readiness"
)
// newWeKnoraReadinessResolver 把「探测目标」收敛到与业务同一组真源:
// 端点来自网页「知识库映射」保存的连接配置(endpoint 内部已做 env 兜底),知识库来自
// 当前持久化绑定(未绑定才用 env 引导值),凭据每次重新读同一份 key 文件。
// 任何一项读取失败都必须显式报错——静默退回旧值正是 F13 的成因。
func newWeKnoraReadinessResolver(
endpoint func(context.Context) string,
envKnowledgeBaseID string,
loadBinding func(context.Context) (string, error),
readKey func() (string, error),
) func(context.Context) (readiness.Target, error) {
resolver := readiness.Resolver{
Endpoint: endpoint,
DefaultKB: envKnowledgeBaseID,
LoadBinding: func(resolveCtx context.Context) (string, error) {
if loadBinding == nil {
return "", nil
}
stored, err := loadBinding(resolveCtx)
if err != nil {
log.Printf("readiness: load routing bindings: %v", err)
}
return stored, err
},
ReadKey: func() (string, error) {
if readKey == nil {
return "", nil
}
value, err := readKey()
if err != nil {
log.Printf("readiness: read WeKnora API key: %v", err)
}
return value, err
},
}
return resolver.Resolve
}
// weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据,
// 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。
type weKnoraLister struct {
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) {
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 端点未配置")
}
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, 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
}
return client.ListKnowledgeBases(ctx)
}
+111
View File
@@ -0,0 +1,111 @@
package main
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"knowledge-governance/internal/readiness"
)
// F13 的接线回归:探测目标必须来自「网页保存的端点 + 当前持久化绑定」,
// env 只能是未绑定时的引导兜底;任何一项都不许在启动时固化。
func TestReadinessResolverUsesPersistedBindingOverEnv(t *testing.T) {
const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
const storedKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
resolve := newWeKnoraReadinessResolver(
func(context.Context) string { return "https://weknora.test" },
envKB,
func(context.Context) (string, error) { return storedKB, nil },
func() (string, error) { return "key-1", nil },
)
target, err := resolve(context.Background())
if err != nil {
t.Fatal(err)
}
if target.KnowledgeBaseID != storedKB || target.BaseURL != "https://weknora.test" || target.APIKey != "key-1" {
t.Fatalf("resolved target = %#v", target)
}
}
func TestReadinessResolverFallsBackToEnvOnlyWhenUnbound(t *testing.T) {
const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
resolve := newWeKnoraReadinessResolver(
func(context.Context) string { return "https://weknora.test" },
envKB,
func(context.Context) (string, error) { return "", nil },
func() (string, error) { return "key-1", nil },
)
target, err := resolve(context.Background())
if err != nil || target.KnowledgeBaseID != envKB {
t.Fatalf("unbound fallback = %#v, %v", target, err)
}
}
func TestReadinessResolverReportsBindingAndCredentialFailures(t *testing.T) {
bindingDown := newWeKnoraReadinessResolver(
func(context.Context) string { return "https://weknora.test" },
"env-kb",
func(context.Context) (string, error) { return "", errors.New("db unavailable") },
func() (string, error) { return "key-1", nil },
)
target, err := bindingDown(context.Background())
if err == nil {
t.Fatalf("binding read failure must not silently probe env: %#v", target)
}
keyDown := newWeKnoraReadinessResolver(
func(context.Context) string { return "https://weknora.test" },
"env-kb",
func(context.Context) (string, error) { return "", nil },
func() (string, error) { return "", errors.New("key file missing") },
)
if _, err := keyDown(context.Background()); err == nil {
t.Fatal("missing API key must surface, not degrade to liveness-only")
}
}
func TestReadinessResolverMarksUnconfiguredEndpoint(t *testing.T) {
resolve := newWeKnoraReadinessResolver(
func(context.Context) string { return "" },
"env-kb",
func(context.Context) (string, error) { return "", nil },
func() (string, error) { return "key-1", nil },
)
// 端点缺失时归类为「未配置」,不是「服务不可用」。
result := readiness.Prober{Resolve: resolve}.Check(context.Background())
if !errors.Is(result.Err, readiness.ErrNotConfigured) {
t.Fatalf("blank endpoint probe = %v, want ErrNotConfigured", result.Err)
}
}
func TestKnowledgeBaseListerFollowsTheCurrentEndpoint(t *testing.T) {
base := func(name string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if request.URL.Path != "/api/v1/knowledge-bases" {
writer.WriteHeader(http.StatusNotFound)
return
}
_, _ = writer.Write([]byte(`{"success":true,"data":[{"id":"` + name + `","name":"` + name + `"}]}`))
}))
}
first, second := base("kb-a"), base("kb-b")
defer first.Close()
defer second.Close()
endpoint := first.URL
lister := &weKnoraLister{
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" {
t.Fatalf("initial endpoint bases = %#v, %v", bases, err)
}
endpoint = second.URL
bases, err = lister.ListKnowledgeBases(context.Background())
if err != nil || len(bases) != 1 || bases[0].ID != "kb-b" {
t.Fatalf("rotated endpoint bases = %#v, %v", bases, err)
}
}
+26 -6
View File
@@ -10,10 +10,13 @@ import (
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"knowledge-governance/internal/libraryagent"
"knowledge-governance/internal/librarydsn"
"knowledge-governance/internal/librarymaintenance"
)
@@ -25,22 +28,43 @@ func main() {
flag.StringVar(&config.ArchiveRoot, "archive", filepath.Join(home, ".local/share/knowledge-governance/library"), "sealed artifact root")
flag.StringVar(&config.JournalRoot, "journal", filepath.Join(home, ".local/share/knowledge-governance/freeze"), "freeze journal root")
flag.StringVar(&config.SourceApp, "source-app", "WKNFull-app", "source container describing the stack")
flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container")
flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container; empty = the source DB lives on a managed instance and is reached with the source app env (DB_HOST/...)")
flag.StringVar(&config.SourceES, "source-es", "WKNFull-elasticsearch", "source Elasticsearch container")
flag.StringVar(&config.SourceS3Endpoint, "source-s3-endpoint", "", "host-reachable source object-store endpoint (overrides the container-internal one)")
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container")
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE")
flag.StringVar(&config.Project, "project", "weknora071full", "Compose project owning the writers")
flag.StringVar(&config.Writers, "writers", "app", "declared writer services")
nonWriters := flag.String("non-writers", defaultNonWriters, "service=reason for every other project service")
allowUIDs := flag.String("allow-peer-uid", "", "extra peer uids allowed to connect (comma separated; default: same uid only)")
flag.DurationVar(&config.MaxDuration, "max-duration", 10*time.Minute, "upper bound for one operation")
describe := flag.Bool("describe", false, "print the fixed configuration and exit")
flag.Parse()
if strings.TrimSpace(*allowUIDs) != "" {
for _, raw := range strings.Split(*allowUIDs, ",") {
raw = strings.TrimSpace(raw)
if raw == "" {
continue
}
uid, err := strconv.ParseUint(raw, 10, 32)
if err != nil {
log.Fatalf("--allow-peer-uid 需要十进制 uid:%q", raw)
}
config.AllowedPeerUIDs = append(config.AllowedPeerUIDs, uint32(uid))
}
}
config.NonWriters = *nonWriters
agent, err := libraryagent.New(config)
if err != nil {
log.Fatal(err)
}
if *describe {
// describe 只回答"这两个库从哪来"。地址与凭据一律不出现:这段输出会被贴进
// 工单与日志,而 RDS 的连接串里带口令。
log.Printf("source_db=%s governance_db=%s",
librarydsn.SourceMode(config.SourcePG), librarydsn.GovernanceMode(config.GovernancePG))
return
}
// 实例级维护接线(入口闸门 + 后台队列)不在 agent 的 Config 里:它由同一份
// 环境声明提供给子进程。启动时先说清楚有没有——缺了封存会在开窗口前被拒,
// 不允许"以为接好了"跑到一半才发现没有排空证据。
@@ -49,10 +73,6 @@ func main() {
} else {
log.Printf("library agent: 实例级维护目标 %s 入口 %s 闸门 %s", target.Instance, target.IngressURL, target.IngressService)
}
if *describe {
log.Printf("library agent config: %+v", agent.Describe())
return
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
log.Printf("library agent listening on %s (project %s, writers %s)", config.Socket, config.Project, config.Writers)
+44
View File
@@ -0,0 +1,44 @@
package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// 文件模式没配置:必须失败关闭并点名缺的那个变量——"静默退回容器模式"会让
// 操作员以为在读 RDS,实际在读本机容器(或者干脆读到不存在的容器)。
func TestGovernanceFileModeFailsClosedWithoutDSNFile(t *testing.T) {
t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", "")
_, err := readRoutingBindings(context.Background(), options{governancePG: ""})
if err == nil {
t.Fatal("没有 DSN 文件却读成功了")
}
if !strings.Contains(err.Error(), "LIBRARY_GOVERNANCE_DSN_FILE") {
t.Fatalf("错误没有点名缺哪一项:%v", err)
}
}
// 外部 DSN 连不上/写错时,错误必须是固定说法:pgx 的错误里带的是连接串(主机、
// 用户名,口令它自己打码),直接透传就等于把地址写进日志与工单。
func TestGovernanceFileModeNeverLeaksPasswordInErrors(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "governance.dsn")
// 夹具口令运行时拼装:源码里不留“带口令的连接串”字面量,否则密钥扫描只会
// 报出一堆必然是假值的夹具,把真泄漏的信号淹掉。
password := strings.Join([]string{"fixture", "leak", "probe"}, "-")
// 故意用非法 sslmode + 不可达端口:无论失败在解析还是连接阶段,都不许泄露。
if err := os.WriteFile(path, []byte("postgres://gov:"+password+"@127.0.0.1:1/gov?sslmode=bogus&connect_timeout=1\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", path)
_, err := readRoutingBindings(context.Background(), options{governancePG: ""})
if err == nil {
t.Fatal("坏 DSN 竟然读成功了")
}
if strings.Contains(err.Error(), password) {
t.Fatalf("错误里漏了口令:%v", err)
}
}
+173 -34
View File
@@ -30,9 +30,11 @@ import (
"syscall"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/librarydeadletter"
"knowledge-governance/internal/librarydsn"
"knowledge-governance/internal/libraryfreeze"
"knowledge-governance/internal/libraryhandoff"
"knowledge-governance/internal/librarymaintenance"
@@ -146,9 +148,13 @@ func usage() {
Flags (defaults target the local WKNFull test stack):
-source-app WKNFull-app container whose env describes the source
-source-pg WKNFull-postgres source PostgreSQL container (address resolution)
-source-pg WKNFull-postgres source PostgreSQL container; empty = the source DB is a
managed instance: connect with the source app env
(DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD), TLS mode from
LIBRARY_SOURCE_DB_SSLMODE (default require)
-source-es WKNFull-elasticsearch
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here; empty = read
the DSN from LIBRARY_GOVERNANCE_DSN_FILE (0600 file)
-project weknora071full Compose project owning the writer group
-writers WKNFull-app declared writer services (comma separated)
-non-writers WKNFull-frontend=reason,... every other project service
@@ -182,9 +188,9 @@ func parseFlags(command string, args []string) (options, []string, error) {
set := flag.NewFlagSet(command, flag.ContinueOnError)
set.SetOutput(os.Stderr)
set.StringVar(&opts.sourceApp, "source-app", opts.sourceApp, "source container describing the stack")
set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container")
set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container; empty = connect to the source app's external (managed) database")
set.StringVar(&opts.sourceES, "source-es", opts.sourceES, "source Elasticsearch container")
set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container")
set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE")
set.StringVar(&opts.project, "project", opts.project, "Compose project owning the writers")
set.StringVar(&opts.writers, "writers", opts.writers, "declared writer services")
set.StringVar(&opts.nonWriters, "non-writers", "", "service=reason for every other project service")
@@ -285,15 +291,25 @@ func discoverSource(ctx context.Context, opts options, binding map[string]string
if app["DB_DRIVER"] != "postgres" {
return config, errors.New("source database driver is not postgres")
}
address, err := containerAddress(ctx, opts.sourcePG)
if err != nil {
return config, err
// 两种来源:给了 -source-pg 就按容器地址拼(0.7.1 栈);没给说明库是托管
// 实例(RDS 型 0.9.0 栈没有源库容器),用源应用容器 env 里的 DB_* 直连。
if librarydsn.SourceMode(opts.sourcePG) == librarydsn.SourceExternal {
dsn, dsnErr := librarydsn.SourceURL(app, os.Getenv)
if dsnErr != nil {
return config, dsnErr
}
config.DatabaseURL = dsn
} else {
address, addressErr := containerAddress(ctx, opts.sourcePG)
if addressErr != nil {
return config, addressErr
}
dsn, dsnErr := librarydsn.ContainerURL(address, app)
if dsnErr != nil {
return config, dsnErr
}
config.DatabaseURL = dsn
}
dsn := strings.Join([]string{
"postgres://" + urlEscape(app["DB_USER"]) + ":" + urlEscape(app["DB_PASSWORD"]) +
"@" + address + ":" + app["DB_PORT"] + "/" + urlEscape(app["DB_NAME"]) + "?sslmode=disable",
}, "")
config.DatabaseURL = dsn
config.AppImageID, err = containerImageID(ctx, opts.sourceApp)
if err != nil {
return config, err
@@ -388,17 +404,12 @@ func parseBool(value string) bool {
return false
}
func urlEscape(value string) string {
replacer := strings.NewReplacer("%", "%25", ":", "%3A", "@", "%40", "/", "%2F", "?", "%3F", "#", "%23", "&", "%26", " ", "%20")
return replacer.Replace(value)
}
// scopeBindings 返回 scope→知识库 映射。治理 API 用的是 LIBRARY_PRODUCTION_KB_*,
// CLI 读的是治理库里的 routing bindings;同一台机器上两份不一致时,
// CLI 抓到的会是"配置里那个库"而不是 API 认为的目标——所以环境变量优先,
// 读不到才退回 bindings。两边讲同一份身份,验收才可比。
func scopeBindings(ctx context.Context, container string) (map[string]string, error) {
binding, err := readRoutingBindings(ctx, container)
func scopeBindings(ctx context.Context, opts options) (map[string]string, error) {
binding, err := readRoutingBindings(ctx, opts)
if err != nil {
return nil, err
}
@@ -410,17 +421,105 @@ func scopeBindings(ctx context.Context, container string) (map[string]string, er
return binding, nil
}
func readRoutingBindings(ctx context.Context, container string) (map[string]string, error) {
raw, err := dockerOutput(ctx, "exec", container, "psql", "-U", "governance", "-d", "governance", "-tAc",
"SELECT internal_kb_id||'|'||external_kb_id FROM routing_kb_bindings WHERE id='active'")
// readRoutingBindings 读治理库里生效的 scope 绑定。两种来源:
// - 给了 -governance-pg:docker exec 进治理库容器跑 psql(0.7.1 本机栈);
// - 没给:治理库是托管实例(RDS 型 0.9.0 栈没有 governance 容器),DSN 来自
// LIBRARY_GOVERNANCE_DSN_FILE 指向的 0600 文件。
//
// 两条路径只共用行解析,不共用连接方式:容器里没有网络到 RDS 的凭据,宿主机也不该
// 为了读两列去 docker exec 一个不存在的容器。
func readRoutingBindings(ctx context.Context, opts options) (map[string]string, error) {
if librarydsn.GovernanceMode(opts.governancePG) == librarydsn.GovernanceFile {
dsn, err := librarydsn.GovernanceURL(os.Getenv)
if err != nil {
return nil, err
}
return readRoutingBindingsFromDSN(ctx, dsn)
}
raw, err := dockerOutput(ctx, "exec", opts.governancePG, "psql", "-U", "governance", "-d", "governance", "-tAc",
routingBindingsQuery)
if err != nil {
return nil, errors.New("read routing bindings failed")
}
internal, external, ok := strings.Cut(strings.TrimSpace(raw), "|")
if !ok || internal == "" || external == "" {
return nil, errors.New("routing bindings are incomplete")
return parseRoutingBindings(raw)
}
// COALESCE 不能省:两列都可能是 NULL(0.9.0 迁移把\"旧知识库绑定已解除\"落成 NULL,
// 平台约定\"对外库没有对应目标时留空\")。裸拼接遇 NULL 得到整行 NULL,文件模式
// 会在 Scan 成 string 时直接失败,报出的还是一句\"read routing bindings failed\"——
// 真正的原因(哪一列没绑)被吞掉。这里先拼成固定形状,由 parseRoutingBindings 判。
const routingBindingsQuery = "SELECT COALESCE(internal_kb_id,'')||'|'||COALESCE(external_kb_id,'') FROM routing_kb_bindings WHERE id='active'"
// readRoutingBindingsFromDSN 用外部 DSN 读同一份绑定。
//
// 只读会话是刻意的:这条路径只是读两列,出了问题必须是"读不到",而不是在治理库上
// 留下一次写入。错误一律收敛成固定说法:pgx 的错误里会带连接串(口令它自己打了码,
// 但主机与用户名照旧出去),而这里连那份地址都不该出现在日志或工单里。
func readRoutingBindingsFromDSN(ctx context.Context, dsn string) (map[string]string, error) {
parsed, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, errors.New("governance database url is invalid")
}
return map[string]string{"internal": internal, "external": external}, nil
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "30000"
parsed.MaxConns = 2
pool, err := pgxpool.NewWithConfig(ctx, parsed)
if err != nil {
return nil, errors.New("open governance database failed")
}
defer pool.Close()
var raw string
if err = pool.QueryRow(ctx, routingBindingsQuery).Scan(&raw); err != nil {
return nil, errors.New("read routing bindings failed")
}
return parseRoutingBindings(raw)
}
// parseRoutingBindings 解一行 `<internal>|<external>`。两条来源(psql -tAc 与 pgx
// 只读会话)拼的是同一句 SQL,所以只有这一份解析语义。
//
// 对内库必填:没有对内库就没有\"整库\"可言,此时必须点名是哪一列没绑,而不是退化成
// 泛化的读失败。对外库可空:平台侧约定\"对外库没有对应目标时留空\",绑定本身仍然
// 有效(`status`、internal scope 照常可跑);只有真去用 external scope 时才拒绝,
// 且绝不回退到对内库——那会把对内库的内容当成对外库封存出去。
func parseRoutingBindings(raw string) (map[string]string, error) {
trimmed := strings.TrimSpace(raw)
// 空输出 = 没有生效绑定行,等于对内库没绑:这跟"读失败"是两件事,
// 必须说成前者,否则现场又会退回一句泛化错误。
if trimmed == "" {
return nil, errInternalKBMissing
}
internal, external, ok := strings.Cut(trimmed, "|")
if !ok {
return nil, errors.New("read routing bindings failed")
}
internal = strings.TrimSpace(internal)
external = strings.TrimSpace(external)
if internal == "" {
return nil, errInternalKBMissing
}
binding := map[string]string{"internal": internal}
if external != "" {
binding["external"] = external
}
return binding, nil
}
var (
errInternalKBMissing = errors.New("对内知识库未绑定(routing_kb_bindings.internal_kb_id 为空)")
errExternalKBMissing = errors.New("对外知识库未配置(routing_kb_bindings.external_kb_id 为空)")
)
// scopeKnowledgeBase 取本次 scope 的目标库。空值必须在这里就拒绝:往下走会变成
// \"knowledge base not found in source\"——那是拿空 UUID 查源库得到的假原因。
func scopeKnowledgeBase(binding map[string]string, scope string) (string, error) {
if kb := strings.TrimSpace(binding[scope]); kb != "" {
return kb, nil
}
if scope == "external" {
return "", errExternalKBMissing
}
return "", errInternalKBMissing
}
func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool, error) {
@@ -432,11 +531,25 @@ func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool
// that a database-enforced property rather than a convention.
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "120000"
// 启动参数不足以保证只读:角色级/库级设置会在启动参数之后生效,托管实例
// (RDS)上实测就是这样——SHOW 回来是 off。而池里每条连接是独立的会话,
// 对单条连接 SET 管不到其他连接,所以放在 AfterConnect:每条新连接都显式
// 置只读,池里就没有能写的会话。下面的 SHOW 只是对任意一条连接再核一次。
parsed.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(ctx, "SET SESSION default_transaction_read_only = on")
return err
}
pool, err := pgxpool.NewWithConfig(ctx, parsed)
if err != nil {
return nil, errors.New("open source database failed")
}
var readOnly string
// 连接失败与"能连上但会话可写"必须分开报:把两者压成同一句,现场只能看到
// 一句无信息量的失败,反而会去怀疑权限或只读设置。
if err = pool.Ping(ctx); err != nil {
pool.Close()
return nil, errors.New("source database connection failed")
}
if err = pool.QueryRow(ctx, "SHOW default_transaction_read_only").Scan(&readOnly); err != nil || readOnly != "on" {
pool.Close()
return nil, errors.New("source session is not read-only")
@@ -510,6 +623,11 @@ func openFreeze(ctx context.Context, opts options) (*libraryfreeze.Coordinator,
//
// 入口/队列的声明与容器内 worker 共用同一组 LIBRARY_TARGET_* 名称,
// 数据库/索引/桶则取自本次真实发现的源,避免"关的是 A 的门、读的是 B 的队列"。
//
// LIBRARY_TARGET_INGRESS_MODE=none 只给整栈没有闸门的测试环境(0.9.0 测试栈):
// 必须同时给 LIBRARY_NO_INGRESS_ACK=test-only,窗口里一笔闸门动作都不做,
// 排空证据降为"写者全停 + 队列静默",恢复由 LIBRARY_TARGET_HEALTH_URL 的 200 证明。
// 缺省仍是 gate:没有显式确认就照旧要求闸门。
func captureMaintenanceConfig(opts options, source sourceConfig, get func(string) string) (librarymaintenance.Config, error) {
target, err := librarymaintenance.TargetFromEnv(get)
if err != nil {
@@ -529,9 +647,12 @@ func captureMaintenanceConfig(opts options, source sourceConfig, get func(string
Writers: writers,
NonWriters: nonWriters,
DockerSocket: opts.dockerSocket,
IngressMode: target.Mode,
IngressAck: target.Ack,
IngressURL: target.IngressURL,
IngressService: target.IngressService,
IngressDrainFile: target.IngressDrainFile,
HealthURL: target.HealthURL,
Database: identity,
Index: source.SearchIndex,
Bucket: source.Object.Bucket,
@@ -587,7 +708,12 @@ func openArchive(opts options) (*librarysnapshot.Archive, error) {
func runStatus(ctx context.Context, opts options) error {
report := map[string]any{}
binding, bindingErr := scopeBindings(ctx, opts.governancePG)
// 只报来源模式:地址与凭据连 describe/status 都不出现,日志自然也不会带出去。
report["databases"] = map[string]string{
"source_db": librarydsn.SourceMode(opts.sourcePG),
"governance_db": librarydsn.GovernanceMode(opts.governancePG),
}
binding, bindingErr := scopeBindings(ctx, opts)
var config sourceConfig
var err error
if bindingErr != nil {
@@ -680,7 +806,12 @@ func runPreflight(ctx context.Context, opts options) error {
if opts.scope != "internal" && opts.scope != "external" {
return errors.New("-scope must be internal or external")
}
binding, err := scopeBindings(ctx, opts.governancePG)
binding, err := scopeBindings(ctx, opts)
if err != nil {
return err
}
// 绑定缺哪一半在连源库之前就要说清楚:external 未配置不是"源库里没这个库"。
kb, err := scopeKnowledgeBase(binding, opts.scope)
if err != nil {
return err
}
@@ -693,7 +824,6 @@ func runPreflight(ctx context.Context, opts options) error {
return err
}
defer pool.Close()
kb := config.Scopes[opts.scope]
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
if err != nil {
return err
@@ -773,7 +903,13 @@ func runCapture(ctx context.Context, opts options) error {
return err
}
defer archive.Close()
binding, err := scopeBindings(ctx, opts.governancePG)
binding, err := scopeBindings(ctx, opts)
if err != nil {
return err
}
// 先定住本次 scope 的库:external 没配置时,封存必须在开维护窗口之前就停,
// 不能先停写者再发现目标为空。
kb, err := scopeKnowledgeBase(binding, opts.scope)
if err != nil {
return err
}
@@ -801,7 +937,7 @@ func runCapture(ctx context.Context, opts options) error {
if err != nil {
return err
}
scopedKB := binding[opts.scope]
scopedKB := kb
if found {
manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive)
if err != nil {
@@ -814,7 +950,6 @@ func runCapture(ctx context.Context, opts options) error {
return err
}
defer pool.Close()
kb := config.Scopes[opts.scope]
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
if err != nil {
return err
@@ -1150,7 +1285,12 @@ func runDeadLetters(ctx context.Context, opts options) error {
if opts.scope != "internal" && opts.scope != "external" {
return errors.New("-scope must be internal or external")
}
binding, err := scopeBindings(ctx, opts.governancePG)
binding, err := scopeBindings(ctx, opts)
if err != nil {
return err
}
// external 未配置时,死信观测同样要明说"没配置",而不是拿空库去查源库。
kb, err := scopeKnowledgeBase(binding, opts.scope)
if err != nil {
return err
}
@@ -1163,7 +1303,6 @@ func runDeadLetters(ctx context.Context, opts options) error {
return err
}
defer pool.Close()
kb := config.Scopes[opts.scope]
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
if err != nil {
return err
@@ -0,0 +1,59 @@
package main
import (
"strings"
"testing"
"knowledge-governance/internal/libraryfreeze"
)
// noGateMaintenanceEnv 是 0.9.0 测试栈:没有闸门,用显式确认 + 健康探针代替。
func noGateMaintenanceEnv() map[string]string {
env := maintenanceEnv()
delete(env, "LIBRARY_TARGET_INGRESS_URL")
delete(env, "LIBRARY_TARGET_INGRESS_SERVICE")
delete(env, "LIBRARY_TARGET_INGRESS_DRAIN_FILE")
env["LIBRARY_TARGET_INGRESS_MODE"] = libraryfreeze.IngressModeNone
env["LIBRARY_NO_INGRESS_ACK"] = libraryfreeze.NoIngressAck
env["LIBRARY_TARGET_HEALTH_URL"] = "http://127.0.0.1:18081/health"
return env
}
func TestCaptureMaintenanceConfigNoGateWithAck(t *testing.T) {
env := noGateMaintenanceEnv()
config, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] })
if err != nil {
t.Fatalf("no-gate 声明被拒:%v", err)
}
if config.IngressMode != libraryfreeze.IngressModeNone || config.IngressAck != libraryfreeze.NoIngressAck {
t.Fatalf("入口形态没透传:%+v", config)
}
if config.IngressURL != "" || config.IngressService != "" || config.IngressDrainFile != "" {
t.Fatalf("no-gate 配置里出现了闸门项:%+v", config)
}
if config.HealthURL != "http://127.0.0.1:18081/health" || config.RedisAddr != "127.0.0.1:26379" {
t.Fatalf("健康探针/队列没透传:%+v", config)
}
// 目标身份仍取自本次真实发现的源:no-gate 只改证据形态,不改动的是谁。
if config.Database != "127.0.0.1:25432/kgmaint_target" || config.Index != "kgmaint_1028a_chunks" {
t.Fatalf("目标身份不对:%+v", config)
}
}
func TestCaptureMaintenanceConfigNoGateWithoutAckIsRefused(t *testing.T) {
env := noGateMaintenanceEnv()
delete(env, "LIBRARY_NO_INGRESS_ACK")
_, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] })
if err == nil || !strings.Contains(err.Error(), "LIBRARY_NO_INGRESS_ACK") {
t.Fatalf("没有显式确认却放过了 no-gate:%v", err)
}
}
// no-gate 不得悄悄接受半套闸门声明:要么有闸门,要么明确没有。
func TestCaptureMaintenanceConfigNoGateRejectsPartialGate(t *testing.T) {
env := noGateMaintenanceEnv()
env["LIBRARY_TARGET_INGRESS_SERVICE"] = "ingress"
if _, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] }); err == nil {
t.Fatal("no-gate 与闸门服务同时存在却没有拒绝")
}
}
+103
View File
@@ -0,0 +1,103 @@
package main
import (
"strings"
"testing"
)
// internal 为空必须拒绝并点名。实测到的现场就是这一行:0.9.0 迁移后
// internal_kb_id 与 external_kb_id 都是 NULL,旧解析退化成
// "read routing bindings failed",操作员无法判断是连不上还是没绑定。
// NULL 与空串在 SQL 侧由 routingBindingsQuery 的 COALESCE 收敛成同一形状,
// 解析侧两者都必须落到同一条错误上。
func TestParseRoutingBindingsRejectsEmptyInternal(t *testing.T) {
for _, raw := range []string{"|", "|ext-kb", " \n| \n", "\n|\n", ""} {
binding, err := parseRoutingBindings(raw)
if err == nil {
t.Fatalf("internal 为空却解析成功:%q → %v", raw, binding)
}
if binding != nil {
t.Fatalf("internal 为空仍返回了映射:%q → %v", raw, binding)
}
if !strings.Contains(err.Error(), "对内知识库未绑定") || !strings.Contains(err.Error(), "internal_kb_id") {
t.Fatalf("错误没有点名 internal 未绑定:%q → %v", raw, err)
}
}
}
// 0.9.0 测试实例的真实形状:只有对内库(wiki-demo),平台约定对外库没有对应
// 目标时留空。绑定仍然有效,internal scope 能解析;external scope 必须失败、
// 点名 external_kb_id,并且绝不回退到对内库。
func TestParseRoutingBindingsAllowsEmptyExternal(t *testing.T) {
binding, err := parseRoutingBindings("0da9b571-6f13-46a1-85fa-e63d2ef5666e|")
if err != nil {
t.Fatalf("对外库为空不该让整份绑定失效:%v", err)
}
if got := binding["internal"]; got != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" {
t.Fatalf("对内库解析错误:%q", got)
}
if value, present := binding["external"]; present {
t.Fatalf("对外库没配置却写进了映射:%q", value)
}
kb, err := scopeKnowledgeBase(binding, "internal")
if err != nil || kb != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" {
t.Fatalf("internal scope 不该被 external 为空牵连:kb=%q err=%v", kb, err)
}
kb, err = scopeKnowledgeBase(binding, "external")
if err == nil {
t.Fatalf("对外库未配置却解析出了目标库:%q", kb)
}
if kb != "" {
t.Fatalf("external scope 回退到了别的库:%q", kb)
}
if !strings.Contains(err.Error(), "对外知识库未配置") || !strings.Contains(err.Error(), "external_kb_id") {
t.Fatalf("错误没有点名 external 未配置:%v", err)
}
}
// 两个库都绑定时行为不变:这是 0.7.1 栈与对外库已配置的 0.9.0 栈的常态路径。
func TestParseRoutingBindingsBothScopesUnchanged(t *testing.T) {
// psql -tAc 输出带行尾换行,pgx 那边不带——两边都必须是同一个结果。
for _, raw := range []string{"kb-internal|kb-external", "kb-internal|kb-external\n", " kb-internal | kb-external \n"} {
binding, err := parseRoutingBindings(raw)
if err != nil {
t.Fatalf("两个库都绑定却解析失败:%q → %v", raw, err)
}
if len(binding) != 2 || binding["internal"] != "kb-internal" || binding["external"] != "kb-external" {
t.Fatalf("解析结果与原行为不一致:%q → %v", raw, binding)
}
for _, scope := range []string{"internal", "external"} {
if _, err := scopeKnowledgeBase(binding, scope); err != nil {
t.Fatalf("%s scope 不该失败:%v", scope, err)
}
}
}
}
// 没有分隔符说明拿到的不是那一行(空结果集、psql 报错文本等),只能是读失败。
func TestParseRoutingBindingsRejectsMalformedRow(t *testing.T) {
for _, raw := range []string{"kb-without-separator", "ERROR: relation \"routing_kb_bindings\" does not exist"} {
if _, err := parseRoutingBindings(raw); err == nil {
t.Fatalf("没有分隔符却解析成功:%q", raw)
}
}
}
// 不连库的语法/形状校验:裸拼接遇 NULL 会得到整行 NULL,文件模式在 Scan 成
// string 时就会失败并丢掉真实原因。两句来源共用这一条 SQL,因此只查这一处。
func TestRoutingBindingsQueryCoalescesBothColumns(t *testing.T) {
query := routingBindingsQuery
for _, column := range []string{"internal_kb_id", "external_kb_id"} {
if !strings.Contains(query, "COALESCE("+column+",'')") {
t.Fatalf("查询没有把 %s 的 NULL 收敛成空串:%s", column, query)
}
}
if !strings.Contains(query, "||'|'||") {
t.Fatalf("查询不再产出 '<internal>|<external>' 形状:%s", query)
}
if !strings.Contains(query, "WHERE id='active'") {
t.Fatalf("查询没有锁定生效绑定行:%s", query)
}
}
@@ -0,0 +1,59 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// v090 采集脚本是本轮新增的唯一入口。为什么用 bash -n 而不是"跑一遍":跑一遍要
// 停写入者、连 RDS——那是真实采集,不是单元测试。语法与声明在这里钉住,能让
// "标志写错一个字母"在 CI 里就红,而不是等到开维护窗口时才发现。
func TestV090CaptureScriptIsSyntacticallyValid(t *testing.T) {
bash, err := exec.LookPath("bash")
if err != nil {
t.Fatalf("需要 bash 才能检查脚本语法(CI 与测试机都有):%v", err)
}
path := filepath.Join("..", "..", "scripts", "library-capture-v090.sh")
out, err := exec.Command(bash, "-n", path).CombinedOutput()
if err != nil {
t.Fatalf("bash -n %s 失败:%v\n%s", path, err, out)
}
}
// 脚本内容断言:外部库模式(两个 -pg 传空)、写者声明、容器名、归档根、
// LIBRARYCTL_BIN 缺失即失败——这些一旦漂移,真跑时会封错栈或读错库。
func TestV090CaptureScriptDeclaresExternalDatabases(t *testing.T) {
body, err := os.ReadFile(filepath.Join("..", "..", "scripts", "library-capture-v090.sh"))
if err != nil {
t.Fatalf("读脚本:%v", err)
}
for _, want := range []string{
"set -euo pipefail",
"LIBRARYCTL_MISSING",
"-project weknora-v090",
"-writers app",
"-source-app weknora-v090-app",
"-source-es weknora-v090-elasticsearch",
`-source-pg ""`,
`-governance-pg ""`,
"frontend=UI only; no knowledge writes",
"docreader=parse RPC service; app persists parse output",
"elasticsearch=search store; not an initiator",
"redis=queue/cache store; not an initiator",
"/var/lib/knowledge-governance/library",
"/var/lib/knowledge-governance/freeze",
} {
if !strings.Contains(string(body), want) {
t.Fatalf("脚本缺少 %q", want)
}
}
// 0.7.1 的服务名绝不能出现在 v090 入口里:那会让封存停错栈。
for _, forbidden := range []string{"WKNFull", "weknora071full"} {
if strings.Contains(string(body), forbidden) {
t.Fatalf("v090 脚本里出现了 0.7.1 的 %q", forbidden)
}
}
}
+4 -7
View File
@@ -2,8 +2,6 @@ package main
import (
"context"
"crypto/ed25519"
"encoding/base64"
"errors"
"log"
"net"
@@ -35,10 +33,6 @@ func run() error {
if len(data) < 32 || len(control) < 32 || data == control {
return errors.New("gateway_distinct_tokens_required")
}
pub, e := base64.StdEncoding.DecodeString(os.Getenv("OBJECT_GATEWAY_AUDIT_PUBLIC_KEY"))
if e != nil || len(pub) != ed25519.PublicKeySize {
return errors.New("gateway_auditor_key_required")
}
provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET")
scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket))
pool, e := pgxpool.New(ctx, os.Getenv("OBJECT_GATEWAY_DATABASE_URL"))
@@ -50,7 +44,10 @@ func run() error {
if e != nil {
return errors.New("gateway_backend_configuration_invalid")
}
g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024, Isolation: objectgateway.AuditVerifier{Path: os.Getenv("OBJECT_GATEWAY_AUDIT_FILE"), PublicKey: pub, Scope: scope, GatewayID: os.Getenv("OBJECT_GATEWAY_ID")}}
// The target bucket is shared with other writers. Admission is the journal
// plus backend capability; retired attestation env vars are deliberately
// ignored so an old deployment file cannot gate this path.
g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024}
if governanceURL := os.Getenv("OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL"); governanceURL != "" {
cfg, e := pgxpool.ParseConfig(governanceURL)
if e != nil {
+82
View File
@@ -0,0 +1,82 @@
package main
import (
"context"
"encoding/base64"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// startErrorMessage builds the addressed binary and runs it long enough to
// observe why the real entry point refused to listen.
func startErrorMessage(t *testing.T, extra ...string) (string, int) {
t.Helper()
bin := filepath.Join(t.TempDir(), "object-gateway")
build := exec.Command("go", "build", "-o", bin, ".")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build gateway: %v\n%s", err, out)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, bin)
cmd.Env = append([]string{
"PATH=" + os.Getenv("PATH"),
"HOME=" + os.Getenv("HOME"),
"OBJECT_GATEWAY_LISTEN=127.0.0.1:0",
"OBJECT_GATEWAY_DATABASE_URL=postgres://gateway@127.0.0.1:1/gateway?sslmode=disable&connect_timeout=2",
"OBJECT_GATEWAY_PROVIDER=minio",
"OBJECT_GATEWAY_ENDPOINT=http://127.0.0.1:19100",
"OBJECT_GATEWAY_BUCKET=maintenance-fixture-bucket",
"OBJECT_GATEWAY_REGION=us-east-1",
"OBJECT_GATEWAY_ACCESS_KEY=fixture-access-key",
"OBJECT_GATEWAY_SECRET_KEY=fixture-secret-key",
"OBJECT_GATEWAY_DATA_TOKEN=" + strings.Repeat("d", 32),
"OBJECT_GATEWAY_CONTROL_TOKEN=" + strings.Repeat("c", 32),
}, extra...)
out, err := cmd.CombinedOutput()
if ctx.Err() != nil {
t.Fatalf("gateway did not terminate; output=%s", out)
}
code := 0
if exit, ok := err.(*exec.ExitError); ok {
code = exit.ExitCode()
} else if err != nil {
t.Fatalf("run gateway: %v", err)
}
return string(out), code
}
// The default shared-bucket path must not require a whole-bucket exclusive
// writer attestation. Only the journal/backend admission gate may refuse it,
// and a stale attestation file left behind by an older deployment must not
// gate the default path either.
func TestGatewayEntrypointDoesNotRequireBucketAttestation(t *testing.T) {
for _, tc := range []struct {
name string
env []string
}{
{name: "no_audit_configured"},
{name: "stale_audit_file_ignored", env: []string{
"OBJECT_GATEWAY_ID=retired-gateway",
"OBJECT_GATEWAY_AUDIT_FILE=/nonexistent/expired-attestation.json",
"OBJECT_GATEWAY_AUDIT_PUBLIC_KEY=" + base64.StdEncoding.EncodeToString(make([]byte, 32)),
}},
} {
t.Run(tc.name, func(t *testing.T) {
out, code := startErrorMessage(t, tc.env...)
if code == 0 {
t.Fatalf("gateway exited 0 instead of reporting its admission state: %s", out)
}
if strings.Contains(out, "gateway_auditor_key_required") || strings.Contains(out, "gateway_exclusive_writer_evidence_unverified") {
t.Fatalf("shared-bucket admission still gated by whole-bucket attestation: %s", out)
}
if !strings.Contains(out, "gateway_persistence_unavailable") && !strings.Contains(out, "gateway_backend_not_ready") {
t.Fatalf("gateway did not reach journal/backend admission: %s", out)
}
})
}
}
+6 -1
View File
@@ -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"))
}
@@ -0,0 +1,96 @@
package main
import (
"context"
"errors"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
type capturePersistenceFake struct {
failAdvance error
failStage error
advanced []governance.LibraryJobState
stages []string
}
func (f *capturePersistenceFake) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState,
_, _, _, _, _ string, _ time.Time) error {
f.advanced = append(f.advanced, state)
return f.failAdvance
}
func (f *capturePersistenceFake) UpdateLibraryStage(_ context.Context, _, stage, state string,
_, _, _, _ *int64, _ string, _ time.Time) error {
f.stages = append(f.stages, stage+"/"+state)
return f.failStage
}
// The handler must stop before touching the source when the starting state
// cannot be persisted. This is the failure injection that the old log-and-ignore
// path hid behind a completed queue row.
func TestBeginLibraryCaptureStopsOnAdvanceFailure(t *testing.T) {
store := &capturePersistenceFake{failAdvance: errors.New("injected advance failure")}
err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now())
if err == nil || !strings.Contains(err.Error(), "cannot be advanced") {
t.Fatalf("err=%v", err)
}
if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobRunning {
t.Fatalf("advance calls=%v", store.advanced)
}
if len(store.stages) != 0 {
t.Fatalf("stage was written before advance failure: %v", store.stages)
}
}
func TestBeginLibraryCaptureStopsOnStageFailure(t *testing.T) {
store := &capturePersistenceFake{failStage: errors.New("injected stage failure")}
err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now())
if err == nil || !strings.Contains(err.Error(), "stage cannot be advanced") {
t.Fatalf("err=%v", err)
}
if len(store.stages) != 1 || store.stages[0] != "export/running" {
t.Fatalf("stage calls=%v", store.stages)
}
}
// Terminal persistence is two writes; either failure must be returned rather
// than turning the queue row into completed while the business job is pending.
func TestCompleteLibraryCaptureStopsOnStageFailure(t *testing.T) {
store := &capturePersistenceFake{failStage: errors.New("injected success stage failure")}
err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now())
if err == nil || !strings.Contains(err.Error(), "success stage cannot be persisted") {
t.Fatalf("err=%v", err)
}
if len(store.advanced) != 0 {
t.Fatalf("advance must not run after stage failure: %v", store.advanced)
}
}
func TestCompleteLibraryCaptureStopsOnAdvanceFailure(t *testing.T) {
store := &capturePersistenceFake{failAdvance: errors.New("injected success advance failure")}
err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now())
if err == nil || !strings.Contains(err.Error(), "success terminal cannot be persisted") {
t.Fatalf("err=%v", err)
}
if len(store.stages) != 1 || store.stages[0] != "export/succeeded" {
t.Fatalf("stage calls=%v", store.stages)
}
if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded {
t.Fatalf("advance calls=%v", store.advanced)
}
}
func TestCompleteLibraryCapturePersistsBothFacts(t *testing.T) {
store := &capturePersistenceFake{}
if err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now()); err != nil {
t.Fatal(err)
}
if len(store.stages) != 1 || store.stages[0] != "export/succeeded" ||
len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded {
t.Fatalf("stages=%v advanced=%v", store.stages, store.advanced)
}
}
@@ -0,0 +1,65 @@
package main
import (
"errors"
"strings"
"testing"
"knowledge-governance/internal/jobs"
)
// R3g: only retained deterministic capture failures become permanent after the
// agent has recovered the writer. Cancelled body-index coverage markers are
// deliberately absent.
func TestRetainedLibraryCaptureFailuresArePermanent(t *testing.T) {
for _, marker := range []string{
"missing library generated question index",
"empty library index content",
} {
t.Run(marker, func(t *testing.T) {
original := errors.New("LIBRARYCTL_FAILED: " + marker + ";已执行 recover 并确认写入者恢复")
got := terminalLibraryCaptureError(original)
terminal, code := jobs.Terminal(got)
if !terminal || code != jobs.ErrCodeValidationFailed {
t.Fatalf("retained validation failure must park immediately: terminal=%v code=%q err=%v", terminal, code, got)
}
if got.Error() != original.Error() {
t.Fatalf("original message changed: got %q want %q", got.Error(), original.Error())
}
})
}
}
func TestCancelledCoverageFailureStaysRetryable(t *testing.T) {
for _, marker := range []string{
"unverified legacy library chunk index coverage",
"missing indexed library chunk",
} {
err := terminalLibraryCaptureError(errors.New(marker + ";已执行 recover 并确认写入者恢复"))
if terminal, code := jobs.Terminal(err); terminal {
t.Fatalf("cancelled marker %q must not be terminal; code=%q", marker, code)
}
}
}
func TestTransientLibraryCaptureFailureStaysRetryable(t *testing.T) {
for _, message := range []string{
"library agent is unreachable",
"context deadline exceeded",
`LIBRARYCTL_FAILED: job "lib-internal-x" already exists with state "failed";已执行 recover 并确认写入者恢复`,
"missing library generated question index; writer restore not confirmed",
} {
got := terminalLibraryCaptureError(errors.New(message))
if terminal, code := jobs.Terminal(got); terminal {
t.Fatalf("%q must stay retryable, got terminal code=%q", message, code)
}
}
}
func TestRetainedFailureDoesNotChangeMessage(t *testing.T) {
original := errors.New("LIBRARYCTL_FAILED: missing library generated question index;已执行 recover 并确认写入者恢复")
got := terminalLibraryCaptureError(original)
if !strings.Contains(got.Error(), "missing library generated question index") {
t.Fatalf("lost original cause: %v", got)
}
}
+3 -3
View File
@@ -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)
}
@@ -447,7 +447,7 @@ func TestThreeBlockersVerifyChain(t *testing.T) {
Scan(&scopeState, &scopeIngress, &scopeReleased); err != nil {
t.Fatal(err)
}
if scopeReleased == nil || scopeState != "verified" || scopeIngress != "open" {
if scopeReleased == nil || scopeState != "released" || scopeIngress != "open" {
t.Fatalf("scope maintenance final state=%s ingress=%s released=%v", scopeState, scopeIngress, scopeReleased)
}
sentinelPG := tbUnrelatedSentinel(t, ctx, pool)
+171 -25
View File
@@ -9,6 +9,8 @@ import (
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
@@ -17,13 +19,16 @@ 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"
"knowledge-governance/internal/librarysnapshot"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/versionhistory"
"knowledge-governance/internal/weknoraaccess"
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
catalogrefresh "knowledge-governance/internal/workflows/catalogrefresh"
"knowledge-governance/internal/workflows/sourcescan"
@@ -98,6 +103,27 @@ func stageSizesFrom(manifest librarysnapshot.Manifest) map[string]stageSize {
// libraryCaptureJobType is shared with the API which enqueues it.
const libraryCaptureJobType = "library.capture"
// Retained deterministic source-content failures: the agent has already
// restored the writer, so retrying the same journal only replaces the first
// cause with "already exists". Body-index coverage markers are intentionally
// absent; that inferred rule was removed in R3f.
var terminalLibraryCaptureMarkers = []string{
"missing library generated question index",
"empty library index content",
}
func terminalLibraryCaptureError(err error) error {
if err == nil || !strings.Contains(err.Error(), "已执行 recover 并确认写入者恢复") {
return err
}
for _, marker := range terminalLibraryCaptureMarkers {
if strings.Contains(err.Error(), marker) {
return jobs.Permanent(jobs.ErrCodeValidationFailed, err)
}
}
return err
}
// librarySyncJobType 是生产同步作业的队列类型;与封存严格分开,状态不共用。
const librarySyncJobType = "library.sync"
@@ -146,8 +172,56 @@ func run(ctx context.Context, getenv func(string) string) error {
} else if len(pending) > 0 {
return fmt.Errorf("治理库 schema 落后(待应用迁移 %v):本角色不拥有 DDL,先由控制面进程完成迁移", pending)
}
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).
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())
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
// 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。
@@ -186,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
}
@@ -264,7 +338,42 @@ func run(ctx context.Context, getenv func(string) string) error {
return worker.Run(ctx, config.PollInterval)
}
func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[string]jobs.Handler, error) {
type libraryCapturePersistence interface {
UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error
AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error
}
// beginLibraryCaptureJob persists the starting state before any source
// operation. If either write fails the handler must return, so the queue cannot
// be reported completed while the business job is still pending.
func beginLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID string, now time.Time) error {
if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobRunning, "export", "", "", "", "", now); err != nil {
return fmt.Errorf("library seal job %s cannot be advanced: %w", jobID, err)
}
if err := store.UpdateLibraryStage(ctx, jobID, "export", "running", nil, nil, nil, nil,
"主机侧正在暂停写入者、导出并恢复", now); err != nil {
return fmt.Errorf("library seal job %s stage cannot be advanced: %w", jobID, err)
}
return nil
}
// completeLibraryCaptureJob persists both terminal facts. A failed write must
// be returned (queue failed), not logged and ignored; the capture journal keeps
// replay idempotent, and the admin reconcile path can repair only after the
// exact queue/version/archive evidence is present.
func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID, snapshotID string, now time.Time) error {
if err := store.UpdateLibraryStage(ctx, jobID, "export", "succeeded", nil, nil, nil, nil,
"已封存快照 "+snapshotID, now); err != nil {
return fmt.Errorf("library seal job %s success stage cannot be persisted: %w", jobID, err)
}
if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobSucceeded, "export", "", "",
snapshotID, "", now); err != nil {
return fmt.Errorf("library seal job %s success terminal cannot be persisted: %w", jobID, err)
}
return nil
}
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)
@@ -325,12 +434,8 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
// 持久作业:页面读的是这里写的阶段与结果,worker 重启后仍能如实展示。
libraryJobID := "libseal-" + payload.CaptureJob
startedAt := time.Now().UTC()
if advanceErr := store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobRunning, "export", "", "", "", "", startedAt); advanceErr != nil {
log.Printf("library seal job %s cannot be advanced: %v", libraryJobID, advanceErr)
}
if stageErr := store.UpdateLibraryStage(ctx, libraryJobID, "export", "running", nil, nil, nil, nil,
"主机侧正在暂停写入者、导出并恢复", startedAt); stageErr != nil {
log.Printf("library seal job %s stage update failed: %v", libraryJobID, stageErr)
if beginErr := beginLibraryCaptureJob(ctx, store, libraryJobID, startedAt); beginErr != nil {
return beginErr
}
// 平台审计过的精确死信解除指纹:读取失败必须阻断(fail closed),
// 不能因为存储不可用就静默按"没有解除"或"全部解除"处理。
@@ -362,7 +467,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobFailed, "export", err.Error(),
"agent 已执行恢复检查;确认来源 healthy 后可重试同一作业号", "", "", finishedAt)
log.Printf("library capture failed scope=%s capture_job=%s: %v", payload.Scope, payload.CaptureJob, err)
return err
return terminalLibraryCaptureError(err)
}
// 执行后复核:结果里 agent 自报的身份必须还是期望实例,否则这次封存
// 可能来自别的栈,绝不能登记成"本实例的测试封存"。
@@ -388,10 +493,9 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
if versionErr != nil {
return fmt.Errorf("library seal job %s cannot record version: %w", libraryJobID, versionErr)
}
_ = store.UpdateLibraryStage(ctx, libraryJobID, "export", "succeeded", nil, nil, nil, nil,
"已封存快照 "+result.SnapshotID, finishedAt)
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobSucceeded, "export", "", "",
result.SnapshotID, "", finishedAt)
if completeErr := completeLibraryCaptureJob(ctx, store, libraryJobID, result.SnapshotID, finishedAt); completeErr != nil {
return completeErr
}
log.Printf("library capture completed scope=%s capture_job=%s snapshot=%s replay=%v requested_by=%s",
payload.Scope, payload.CaptureJob, result.SnapshotID, result.Replay, payload.RequestedBy)
return nil
@@ -471,19 +575,30 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
return handlers, nil
}
apiKey, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
if 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)
}
client, err := weknora.NewClient(weknora.ClientConfig{
BaseURL: config.TestWeKnoraBaseURL,
APIKey: apiKey,
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
})
if err != nil {
return nil, fmt.Errorf("create test WeKnora client: %w", err)
// 与 API 探测共用同一有效目标:加密存储里的连接优先、旧部署文件/端点兜底;
// 当前持久化绑定优先、env 兜底。
remoteResolver := readiness.Resolver{
LoadBinding: func(resolveCtx context.Context) (string, error) {
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
return internal, bindingErr
},
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}
upload, err := testweknora.NewUploadHandler(testweknora.UploadHandlerConfig{
Store: store,
Client: client,
@@ -499,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)
@@ -530,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
}
+4 -4
View File
@@ -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)
}
+8
View File
@@ -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:
+6
View File
@@ -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.
+6 -1
View File
@@ -18,4 +18,9 @@
1. 跑 `make verify`(本地全绿不等于远端跑通,需要一次真实 run 的证据)。
2. 把**使用者可见**的变化写成 `CHANGELOG.md` 的 `[Unreleased]` 条目(按四类,别写过程)。
3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。
3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。
## 资源首次复用的归属审计(后续)
- 当前首次复用只依赖“目标行逐列一致 + 对象字节一致”,不再要求本目标历史成功同步/预备份来源。
- 后续可补:资源首次写入者/首次绑定 KB、跨 KB 引用计数、孤儿资源与同 tenant 共享资源的可审计归属视图;
不以此重新阻断正常的同内容首次复用。
+44
View File
@@ -0,0 +1,44 @@
# 知识治理候选和批次验收
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
## 发起候选
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
````markdown
```kg-release-v1
{"task":"<发布任务 UUID>","base":"<当前主站 SHA>","sha":"<候选 SHA>","items":[{"task":"<业务任务 UUID>","pr":123}],"extra":[]}
```
````
2. Agent 执行 `candidate_coordinator.py prepare <发布任务 UUID>`。Gitea 核对候选 SHA 的 CI、每个 PR 的落地提交和完整主干范围。需准备候选时,独立 Runner 通过回环入口调度本机执行器。执行器复查发布负责人评论、Gitea 作业证明和当前主站 SHA 后,从准确提交构建镜像并封存。
3. 执行器在独立验收数据库上启动同份归档,核验 API 提交、三个运行镜像、迁移账本、Web 入口及归档摘要。在发布任务和业务任务回填候选版本与地址。对「待测试」业务任务,由执行器转「测试中」。本地候选地址绑定回环,验收 Agent 应和执行器同机,或使用经工程侧验证的私有转发。
4. `candidate_coordinator.py status <发布任务 UUID>` 读取候选回执或对应 Gitea 运行链接。遇到调度结果不明,先从 Gitea 读回运行再决定恢复路径。
## 登记验收
业务验收报告分别放在原业务任务,批次共享功能回归报告放在发布任务。保持测试角色原有输出,使用获授权的验收人或测试 Agent 在对应任务评论追加以下结构化结论。报告应保留用例明细和原始证据链接。该段的 `required` 是本轮登记的必测用例数。
````markdown
```kg-qa-v1
{"sha":"<完整提交 SHA>","bundle":"<归档清单 SHA256>","url":"<候选地址>","verdict":"passed","required":3,"passed":3,"failed":0,"blocked":0}
```
````
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
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 库。
+131
View File
@@ -0,0 +1,131 @@
# 知识治理平台开发与测试
以下命令从仓库根目录运行。日常开发可在 Ubuntu 宿主进行,指定提交的回归在 `hifox-qa` 的独立检出中运行。部署到阿里云测试服后的验收按 [操作 Runbook](OPERATIONS_RUNBOOK.md) 和 [用户流程验收](USER_FLOWS_ACCEPTANCE.md) 执行。
## QA 虚拟机一键回归
在 `hifox-qa` 检出提测提交后,运行下列入口。将 SHA 占位值换成提测记录里的完整提交 SHA。
```bash
make qa-doctor
KG_QA_SHA='<完整提交 SHA>' make qa
```
`make qa-doctor` 检查工具链、HiFox 机器在线状态、OMP 模型调用、测试库身份和已安装的迁移。`make qa` 安装锁定依赖,在专用测试库上通过 API 初始化和迁移,随后核对完整迁移序列、API 就绪状态、Web 首页及 Vite 健康代理。通过后执行 Go 和 Vitest 测试,结束时关闭本次启动的服务。每次运行的服务日志保存在 `~/.local/state/knowledge-governance/qa/`。需要提交前完整门禁时执行 `make verify`。
初次配置由负责人在 QA 虚拟机准备 `~/.config/knowledge-governance/`。以下示例使用虚构的 RDS 主机名。
| 文件 | 内容 |
| --- | --- |
| `qa.json` | 当前用户所有、权限 `0600`,字段 `host`、`port`、`database`、`user` |
| `qa.pgpass` | 当前用户所有、权限 `0600`,填写与 `qa.json` 匹配的口令条目 |
| `rds-ca.pem` | 对应实例的 CA 证书,用于校验 RDS 主机名 |
```json
{"host":"rds.example.test","port":5432,"database":"kg_qa_app","user":"kg_qa_app"}
```
专用非生产 RDS 库和角色以 `kg_qa_` 开头,权限和网络准备见第 2 节。首次运行接受空库,后续运行接受与当前提交兼容的迁移序列。缺库、认证失败、迁移不兼容和端口冲突均会使命令非零退出。浏览器业务 E2E 和专用集成库的 Go 测试按第 4 节执行。
## 1. 检出代码与安装依赖
准备 Git、Make、Python 3、Go 1.26(含同一工具链的 `gofmt`)、Node.js 22 和 npm。数据库检查另需 PostgreSQL 客户端 `psql`。首次安装依赖需要能访问 Go 和 npm 的依赖源。
```bash
# QA 在独立克隆中拉取提测分支,使用提测记录里的完整提交 SHA
export KG_TARGET_BRANCH='<提测分支名>' KG_TARGET_SHA='<完整提交 SHA>'
git fetch origin "$KG_TARGET_BRANCH" && git switch --detach "$KG_TARGET_SHA" &&
test "$(git rev-parse HEAD)" = "$KG_TARGET_SHA" && test -z "$(git status --porcelain)"
# 上面的命令链若失败,先解决检出或工作区问题再继续
# 检查当前 shell 的工具链,非交互任务也应设置相同的 PATH
export PATH="$(go env GOROOT)/bin:$PATH"
go version
command -v gofmt
node --version
npm --version
python3 --version
make deps-install
```
`make deps-install` 通过 `go mod download` 和 `npm ci` 安装依赖。Go 依赖由 `go.mod` / `go.sum` 约束,前端由 `web/package-lock.json` 锁定。依赖安装失败时先检查工具链、依赖源和锁文件,避免临时改写清单来绕过问题。
## 2. 准备开发和测试数据库
无库检查可直接跳到第 4 节。启动 API 或执行真库测试前,由数据库管理员在**非生产 PostgreSQL RDS** 上预建专用空库和登录角色。建议分配 `kg_qa_app` 给应用冒烟,`kg_qa_it` 给 Go 集成测试,各用独立角色。开发宿主另用开发专用库,避免与 QA 共享数据。库未分配时先申请,启动流程以库已存在为前提。
| 用途 | 所需权限 | 数据初始化 |
| --- | --- | --- |
| 应用启动与 UI 冒烟 | `CONNECT`,以及目标 schema 内的 `USAGE`、`CREATE` 和对应用对象的读写权限。迁移角色须能修改自己创建的对象。 | 首次 API 启动执行仓库内嵌迁移。用户表为空时创建初始管理员,首次登录必须修改密码。初始口令通过测试环境负责人交接。 |
| Go PostgreSQL 集成测试 | `CONNECT` 和目标测试库的 `CREATE` 权限,用于建立各用例自己的 schema。 | 用例创建隔离 schema、执行迁移、写入测试数据并清理。相同测试不要并发指向同一个库,避免固定 schema 名冲突。 |
两类角色均只授予对应非生产库所需的权限。使用空库和合成数据。密码由操作者在目标机配置到权限为 `0600` 的 PostgreSQL passfile,条目按 `host:port:database:user:password` 填写。使用 RDS CA 校验证书。以下命令先读回实际数据库、角色与 TLS 状态,核对三者再启动 API 或运行真库测试。
```bash
# 用获准的 RDS 主机名、端口、库名、角色和文件路径替换示例值
export PGHOST='<非生产 RDS 主机名>' PGPORT=5432
export PGDATABASE=kg_qa_app PGUSER=kg_qa_app
export PGPASSFILE="$HOME/.config/knowledge-governance/qa.pgpass"
export PGSSLROOTCERT="$HOME/.config/knowledge-governance/rds-ca.pem"
export PGSSLMODE=verify-full PGCONNECT_TIMEOUT=5
psql -X -v ON_ERROR_STOP=1 -c \
'SELECT current_database(), current_user, ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid();'
```
如果是云厂商提供的私网地址,先确认执行机通过获准的网络路径可访问 RDS。库名、角色、TLS、连接权限或迁移权限有问题时,先交由环境负责人核对配置。实例上已有数据的库不能当作空库初始化。
## 3. 启动后端和前端
**终端 A,启动 API。** 在干净 shell 中执行第 2 节的应用库配置和连通性检查。使用独立测试配置,不加载现网 `.env`。
```bash
export DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5"
export APP_ADDR=127.0.0.1:8088
export TEST_WEKNORA_ENABLED=false PP_SCAN_ENABLED=false
export RELEASE_WORKER_ENABLED=false PRODUCTION_RELEASE_REQUESTS_ENABLED=false
export DOBOTAI_OPS_READ_ENABLED=false DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED=false
go run ./cmd/api
```
API 会在监听前连接 PostgreSQL、应用迁移并初始化管理员。Web 页面和同步 API 联调只需运行 API 与 Vite。需要验证后台队列时,另用相同的隔离应用库配置启动普通 worker(`go run ./cmd/worker`)。涉及取件或来源刷新的任务还依赖容器内 `/app/scripts` 及获准的来源接线,按部署说明准备。发布 worker 无需启动。
Vite 通过 `localhost:8088` 转发 `/api` 和健康检查。如果 `8088` 已被其他部署占用,使用端口空闲的 QA 虚拟机运行本节。仅改前端时,可复用一个获准联调的测试 API,但需要先确认 `localhost:8088/health` 可达,并核对该地址指向的环境。
**终端 B,启动 Web。**
```bash
npm --prefix web run dev -- --host 127.0.0.1 --port 5173 --strictPort
```
在运行服务的机器打开 `http://127.0.0.1:5173/`。另开终端检查 API 与前端代理,再复查迁移记录。最后一条命令需要第 2 节的应用库配置。
```bash
curl --fail --silent --show-error http://127.0.0.1:8088/health
curl --fail --silent --show-error http://127.0.0.1:5173/health
psql -X -v ON_ERROR_STOP=1 -c \
'SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1;'
```
空库首次启动后,用专用测试账号登录,按当次验收标准验证页面及接口。联调结束在两个终端按 `Ctrl+C` 停服务,数据库由环境管理员按测试数据保留规则管理。
## 4. 选择测试命令
| 目的 | 命令 |
| --- | --- |
| 查看检查及适用范围 | `make list` |
| 后端包测试 | `make tests-go` |
| 单个 Go 包及相关子包 | `go test -count=1 ./internal/httpapi/...` |
| 前端 Vitest 套件 | `make tests-web` |
| 单个前端测试文件 | `npm --prefix web test -- src/App.test.tsx` |
| 完整提交前检查,与 CI 共用入口 | `make verify` |
`make verify` 包含安装、格式、静态检查、构建、测试、版本和安全检查,并写出 `ci-report.json`。在未导入真库测试配置的 shell 中运行。若检出时用了 `--no-tags`,先执行 `git fetch --tags origin`,以便版本检查读取正式标签对应的提交。依赖安装与安全检查需要相应网络或缓存。允许跳过的外部依赖用例见 [test-scope.json](../scripts/test-scope.json),真库测试应单独执行并记录结果。
在应用冒烟之外验证真实 PostgreSQL 行为时,重新按第 2 节切换并核对 **集成测试库和角色**,然后执行目标用例。下面以 UI 设置版本切换用例为例。
```bash
TEST_DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5" \
go test -count=1 -v ./internal/platform/postgres -run '^TestUISettingsActivationRetiresPreviousRevisionIntegration$'
```
检查输出出现目标用例的 `PASS`。用例被跳过或没有匹配时,应补齐配置或纠正用例名后重跑。前端 Vitest 负责组件与业务逻辑检查,浏览器 E2E 应单独执行并按 Feature 保存证据。提测记录至少包括完整提交 SHA、执行命令、退出码,以及失败用例的日志或浏览器截图。
+44
View File
@@ -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)。
## 验证边界
自动回归覆盖授权生成、成功后状态更新、目录访问失败与部分可用、取消与进程退出、过期、重试、跨管理员/会话隔离、同源限制、官方链接校验及元数据脱敏。
真实本人授权需要管理员在钉钉官方页面确认;自动测试与生成真实授权链接不替代本人授权,也不证明其公司目录权限。
+97 -5
View File
@@ -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 |
+5 -1
View File
@@ -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` 有名字
+53
View File
@@ -0,0 +1,53 @@
# 云测试治理主站应用 CD
正式入口为 `http://100.85.111.121:8088/`。云端 Compose 项目为 `knowledge-governance-cloud-test`,工作目录 `/opt/knowledge-governance`,当前配置链为 `compose.json`,服务为 `api`、`web`、`worker`。Web 容器提供 `8088`,通过挂载的 nginx 配置代理 API 的 `127.0.0.1:18098`。应用 CD 与知识库内容发布各自保留原有授权流程。
## 建立验收产物
1. 从干净检出的完整提交构建一次 API、worker、web 镜像。构建调用方对三个镜像都注入 `org.opencontainers.image.revision=<完整 SHA>`。API 构建身份沿用 `scripts/version.py --identity` 输出,传给 Dockerfile 的版本、提交和构建时间参数。API 与 worker 各自记录镜像 ID,即使它们来自同一个 Dockerfile。
2. 封存后用同一份归档部署到隔离验收环境。输出目录必须是新路径,父目录应已存在。三个 `--api/--web/--worker` 参数是本地镜像的完整 ID。
```bash
python3 scripts/production_cd.py pack --sha "$SHA" --task "$TASK_UUID" \
--api "$API_ID" --web "$WEB_ID" --worker "$WORKER_ID" --output "$BUNDLE_DIR"
docker load -i "$BUNDLE_DIR/api.tar"
docker load -i "$BUNDLE_DIR/web.tar"
docker load -i "$BUNDLE_DIR/worker.tar"
```
3. 用验收环境自身的 Compose 和数据库启动这些镜像。用下面的命令读回验收环境运行身份。此处三个服务参数是实际的**测试容器名**。在业务验收入口执行实际用例并将输出、结果与报告链接放在同一份验收记录里。
```bash
python3 scripts/production_cd.py attest --sha "$SHA" --task "$TASK_UUID" \
--api "$QA_API" --web "$QA_WEB" --worker "$QA_WORKER" --test-url "$QA_URL" --directory "$BUNDLE_DIR"
BUNDLE_SHA=$(sha256sum "$BUNDLE_DIR/release.json" | cut -d' ' -f1)
```
4. 由验收人使用获授权的 HiFox CLI 登记业务结论,读回任务、验收字段和状态。`cd_acceptance` 是 JSON 字符串类型的 metadata,其解析结果为 `{"verdict":"passed","sha":"…","bundle":"…","evidence":"https://…"}`。录入人应先核对真实报告与运行身份。自动发布时,`evidence` 使用同一 HiFox 任务的验收报告评论链接(带 `#comment-<UUID>`)。评论须正文包含完整提交和归档清单摘要,并在发布人确认前完成。用 `task view --output json` 核对实际任务 UUID、空间、状态和验收字段。验收登记重试复用原归档摘要与原记录。以当前版本只接受一个任务,多个任务分别验收。
5. 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 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
+1 -1
View File
@@ -3,7 +3,7 @@
> 这份文档是**破坏性变化与数据迁移步骤的落脚点**:`CHANGELOG.md` 里以 `**破坏性**` 开头的条目
> **必须**链接到本文(或本文的某个小节)。发布记录本身仍在 `CHANGELOG.md` —— 本文不维护第二份变更列表。
>
> 本仓 CI **只做 CI**:不打 tag、不发 Release、不部署。发布与部署都是**独立的人工审批动作**。
> 常规 CI 负责检查、构建与静态预览。版本 tag 与 Release 由人批准后执行。主站应用部署使用独立的[人工确认 CD](PRODUCTION_CD_RUNBOOK.md)。
## 一、正式发布(由人批准后执行)
+57
View File
@@ -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 服务;运行环境可用性需另行通过真实页面检查,不能用这些用例替代。
+228
View File
@@ -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. 写操作角色细分(目前统一管理员)。
+17 -12
View File
@@ -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 存储与备份(整库逻辑备份的定时)★本期新增
- 入口:**系统设置 → 存储与备份**(管理员)
+8
View File
@@ -56,8 +56,16 @@ LIBRARY_TARGET_INGRESS_URL 入口地址(恢复后要能 200)
LIBRARY_TARGET_INGRESS_SERVICE Compose 里的入口闸门服务名
LIBRARY_TARGET_INGRESS_DRAIN_FILE 闸门写排空证据的宿主机文件
LIBRARY_TARGET_REDIS_ADDR/_PASSWORD/_DB 后台队列(asynq)地址
LIBRARY_TARGET_INGRESS_MODE gate(缺省)或 none;none 只给没有闸门的测试栈
LIBRARY_NO_INGRESS_ACK mode=none 时必须逐字符等于 test-only
LIBRARY_TARGET_HEALTH_URL mode=none 时的健康探针(恢复后必须 200)
```
`none` 是显式降档,不是默认:整栈(如 0.9.0 测试栈)没有入口闸门时,`none` + 确认串
才允许缺入口三项,窗口里不调用任何闸门动作,`gate` 证据位置写
`{"mode":"none","reason":"stack has no ingress gate (test-only)"}`;恢复以
`LIBRARY_TARGET_HEALTH_URL` 返回 200 为准。缺省 `gate` 的行为与文案不变。
另外 `-source-s3-endpoint <URL>` 用来覆盖"源对象存储的访问入口":容器里写的
`MINIO_ENDPOINT` 往往是服务名(`langfuse-minio:9000`),封存跑在宿主机上时解析不到,
资源导出会失败(`read library resource`)。覆盖只换入口,桶与对象键不变;`status`
+2 -2
View File
@@ -1,6 +1,6 @@
# v0.7.1 整库发布的数据契约与覆盖边界
这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关的独占审核是测试夹具,不代表生产已隔离;B22 控制读取角色是真实 SELECT-only PG 角色。
这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关按限定 key 工作,不要求整桶独占审核;B22 控制读取角色是真实 SELECT-only PG 角色。
## 1. 源 schema、历史身份与准入
@@ -55,7 +55,7 @@
- 真实v071历史catalog镜像对照及UUID/自然键矩阵在r11执行,隔离结论与外部当前目录采样分开。A04已识别嵌套引用有有限支持,旧外部cursor仍不自动转换,不因内部结构正例而升级整项。
- r8/r9进程恢复历史证据只在原发送协议、不可变计划/receipt及相应场景前提不变时复用。本轮对schema/引用准入有收紧,不能把历史执行日志称为当前源码正式进程全链重跑;完整当前隔离适配器回归单列。
- clean-finalization unknown保持held是安全行为,但未满足全部自动收敛要求。若要求自动完成,需要能绑定原写入、完整内容和代次的充分服务端证据;相同干净正文、人工猜测归属或放宽共享规则均不可替代。
- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。生产独占/ACL网络凭据、网关OSS业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。
- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。网关真实 OSS 业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。
## 6. 目录与唯一键的有限支持矩阵
+48
View File
@@ -0,0 +1,48 @@
# 目标库隔离 ID 映射
同一 WeKnora 实例里可以有多个知识库。同步把源快照写进目标库时,如果沿用源库的 UUID 主键,
第二个目标库会与实例里已有库的行撞主键(真实证据:2 knowledges / 2 chunks / 23 wiki_pages /
17 wiki_folders 已存在于旧库),写入前的跨范围检查会拒绝整次同步。关闭检查等于让两个库共享身份,
删除/恢复/校验会互相误伤,因此身份必须在目标侧派生。
## 映射规则
```
digest = sha256("knowledge-governance/target-identity/v1" || tenant || kb || table || source_id)
target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 variant/version 位)
```
这是**本产品自定义的稳定 ID 算法**(`target_id_mode=scoped-sha256-v1`),只保证确定性与目标隔离;
它不是标准 RFC 4122 UUIDv5(UUIDv5 用 SHA-1 + 标准 namespace),不要按 UUIDv5 互操作。
- 只绑定**稳定目标身份**(目标 tenant、目标 KB)与源身份,表名参与命名空间;
- 不绑定 job、时间、快照版本等瞬态值:同一目标重复同步/重试/跨版本得到同一 ID;
- 不同目标 KB、不同表得到不同 ID;
- 源归档字节不变,映射只存在于目标侧派生视图(写集合、写入行、索引文档、校验预期);
- 计划把策略持久化为 `target_id_mode=scoped-sha256-v1`:新进程按该字段重建映射,旧计划/写前镜像
没有该字段则按原 ID 回放,绝不二次映射。
## 参与映射的表与字段
| 表 | 身份 | 引用字段 |
|---|---|---|
| knowledges | id | — |
| chunks | id | knowledge_id, tag_id, parent_chunk_id, pre_chunk_id, next_chunk_id, relation_chunks, indirect_relation_chunks, metadata(仅精确匹配) |
| knowledge_tags | id | — |
| knowledge_tag_relations | (knowledge_id, tag_id) | 两个分量分别映射 |
| wiki_folders | id | parent_id |
| wiki_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) |
| wiki_page_issues | id | page_id, knowledge_id, chunk_id |
| resource_bindings | id | owner_id(按 owner_type) |
| resources | **不映射** | resource_id 保持共享身份 |
| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id |
正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列
(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。
## 一致性边界
- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算;
- 索引计划的目标文档 ID 与 `_source` 引用同步映射,before-image(目标写前镜像)保持原样;
- 恢复重放写前镜像时映射关闭,避免把目标原始 ID 再映射一次;
- 资源对象路径/location_hash 仍由既有资源改写逻辑处理,不因 ID 映射而变化。
+24 -12
View File
@@ -4,12 +4,14 @@
`cmd/object-gateway` 提供 `kg-object-gateway-v1`,只监听 loopback;外部接入需要另行审核的 TLS 终结与网络隔离。治理 PG 保存不可变计划、grant、intent、逐版本 receipt 和 attempt→grant delivery。部署迁移身份显式应用 `internal/objectgateway/schema.sql`;启动不自动迁移。运行身份只授必要 SELECT/INSERT 和 scope 行 UPDATE,不授 DDL/TRUNCATE/证据修改或业务库写权限。
scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶只能有一个受审核 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。
scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶在本网关内只使用一个 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。这不要求整桶只有本网关一个写者:别的服务可以在同一桶的其它 key 上正常读写。
数据认证端点:`POST /v1/acquire`、`/v1/resolve`、`/v1/execute`、`/v1/reconcile`、`/v1/observe`,以及 `GET /v1/capabilities`。所有请求核验协议和 scope。`capabilities.automatic_grants` 必须为真,正式 stack 才接受自动授权能力;未接控制源、只读角色权限异常、协议不符或不可达均拒绝,无直写回退。
PG 行锁负责原子准入,不是远端存储 fence。intent 必须持久提交后才发送一次请求;连接死亡、租约过期不清除未知 intent。任何未终态 intent 均阻止 scope 换 epoch。重复 operation 只读回执或精确对账,不重发 PUT;暂时查不到版本仍 held。删除必须绑定已确认 create 的精确 VersionID,不删 latest、不生成删除标记。
同 key 竞争按 key 判定,不按桶判定:create 前已存在任何版本 → 回执 `rejected` 且不修改该对象;PUT 后除精确版本读回外还核对当前 latest,若并发写者已产生更新的当前版本,则只按精确 VersionID 撤回本次写入,保留对方版本并返回冲突;读不到当前版本时保持 held,不删除、不猜测。版本化存储的 PUT 不是原子 create-if-absent,因此“本 key 多数情况下归本计划”不是存储层保证。
不可变证据表拒绝 UPDATE/DELETE/TRUNCATE。Ready 核 fsync、synchronous_commit、full_page_writes、主库可写及必要表/触发器;管理员与迁移身份仍是可信边界,触发器不能抵御 DBA 的 DDL。
## 正式控制交付路径
@@ -54,13 +56,13 @@ SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`libr
- `OBJECT_GATEWAY_ARCHIVE_ROOT`:原持久计划所在归档绝对路径,部署只读挂载。
- `OBJECT_GATEWAY_TARGET_ID`:与正式 worker `LibraryTargetIdentity()` 完全相同的逻辑目标身份;不能用另一个环境的值。
- `OBJECT_GATEWAY_PROVIDER`、`OBJECT_GATEWAY_ENDPOINT`、`OBJECT_GATEWAY_BUCKET`、`OBJECT_GATEWAY_REGION`:精确存储身份。
- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:仅网关持有的对象写凭据。
- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:网关持有的对象凭据,需在目标桶 PUT/GET/按版本 DELETE/列举版本。沿用现有 AK 即可,不要求另建独立只读或独占写凭据。
- `OBJECT_GATEWAY_DATA_TOKEN`、`OBJECT_GATEWAY_CONTROL_TOKEN`:不同且至少 32 字节;普通 worker 仅持有 data token。
- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:独立审核者的 Ed25519 签名隔离证据,绑定协议、scope、gateway ID、时间窗及 writer/policy/拒写/排空摘要。审核私钥不能交给 worker 或网关。
- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:**已退役**。旧部署残留的值被忽略,不参与启动、Ready、每次 Execute 或能力判断;不需要管理员签发整桶独占证明,也不会因过期文件拒绝发布。
秘密只经服务环境/私有文件注入,不进 argv、URL 或日志。所有调用端错误都使用固定原因码。
正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,部署必须使用独立只读凭据。
正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,可继续使用现有凭据,不再要求独立只读 OSS AK。
## 已关闭的本仓旁路
@@ -70,24 +72,34 @@ SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`libr
- `librarystack` 不再为缺网关的 MinIO/S3 返回直写 writer。
- `libraryctl` capture 的 S3 构造与读取保留;未把读取当作写入口禁用。
这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;部署权限才负责防止外部旧进程直接调用存储。
这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;共享桶不要求撤除其它写者,跨写者的同 key 竞争按冲突/held 处理。
## 实测与未完成边界
已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证。隔离审计 authority/故障注入仍是测试设施,不是生产权限证明。
已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证,以及共享桶下“无整桶证明启动 + 其它 key 并发写入 + 同 key 既有对象拒绝”的真实 PG/MinIO 用例。历史隔离审计 authority/故障注入是当时的测试设施,不是当前部署前置。
正式 worker 隔离进程证据:真实 Docker 入口闸门/队列、只读 worker 对象身份、独立治理读取角色、网关与业务 PG/ES/MinIO;首次 PG 后和对象提交后两次 SIGKILL,同一原 job/operation/plan 的三代 attempt 完成发布,原对象发送 epoch 与回执不变。隔离构建标签 `kg_isolated_drill` 仅把真实租约缩短至4秒,并拒绝非 loopback 一次性 r8 库;正常构建仍为10分钟。维护上游是无业务凭据的独立 HTTP 夹具,不是运行中的 WeKnora;签名证据绑定本次真实拒写/排空材料,不代表生产独占审核。
已补独立 `library.recover` 正式worker链、恢复中再次SIGKILL、完整before-image/CAS/精确版本读回,以及来源/目标/原job/计划/operation/任意队列身份拒绝。ES故障代理只转发真实ES并丢弃已提交响应,未伪造服务响应。
尚未完成:clean-finalization unknown的充分归属与自动收敛;独立运行环境只读对象凭据、ACL/网络和全部writer排空;网关真实OSS端到端;原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署独占分列,不把生产变更授权当成本机开发授权的前置。
尚未完成:clean-finalization unknown的充分归属与自动收敛;网关真实 OSS 端到端与真实部署验收(父执行);原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署分列。
维护隔离、独占审核与 grant 是独立前置。配置 true、健康 200、测试自签 authority 都不能代替已部署拒写/排空证据。目前未签发真实环境独占证明,未改生产权限或上游 WeKnora 源码/Schema。
整桶独占审核、全部 writer 排空、独立只读对象凭据已不再是发布前置;维护窗口内停目标写入容器并读回确认即可更新。网关按 key 拒绝冲突、精确版本回滚,但不承诺无关写者同时修改同一 key 时仍能自动完成——那种情况会明确冲突或 held,需要人工按回执处理。未改生产权限或上游 WeKnora 源码/Schema。
## 维护式更新(已采用)
目标测试 KB 的更新走维护窗口,不再要求证明整桶只有一个写者:
1. 停目标测试 WeKnora 的写入应用容器(只停该服务,不停机器人、适配器、共享 PG/ES 或其它 KB 的服务),并由容器状态/健康读回确认已停止。这是本轮文档化的运维步骤;代码侧没有新增停容器实现。
2. 用既有维护/预备份链记录本次目标 KB/对象范围:实例级维护窗口与写者停写证据由 `internal/libraryfreeze` + `internal/librarymaintenance` 采集,`libraryctl capture`(页面入口 `POST /api/v1/library/captures`)完成闸门排空→停写者→导出快照并保留 `post_stop_digest`;不把通用主机备份当作 KB 预备份的替代。
3. 用原 plan、原 WriteSet 摘要和限定对象清单走既有 `ProductionLibraryTarget.Apply`(经正式 worker owned attempt 与网关 grant)更新资源;网关沿用现有 AK,不换凭据、不签独占证明。
4. 启动原容器,健康检查与页面业务验收;失败走既有 `library.recover`/`RestoreDrill` 恢复链按原预备份回放并启动原服务,不无限留停机。
5. 无关服务与无关 key 全程不需要停;同 key 若仍有外部写者,按上节的冲突/held 处理:双方版本都保留,由人按证据处置,不自动合并。
部署需变更的组件:`object-gateway`(本候选镜像)、`worker`(同提交镜像),以及两者 env 中移除/留空已退役的 `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`。`api`、`web` 无协议变更,可不同步。journal、治理 PG 只读 authority、archive 与 target identity 配置保持不变。
## 部署与回退(未执行)
未来测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准。每批先冻结主机、桶、全部角色/STS/预签名写入口、端口/网络规则、影响、维护窗口与回滚;当前没有执行这些外部变更。
测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准;本候选未在任一主机执行停机、备份、更新或启动。r5 的已完成 OSS 测试授权不能重复使用。
先关新写准入→排空并对账旧请求→撤旧直写权限/切只读身份并实测拒写→独立审核→批准的新限定对象验收→父复核,才可切业务客户端。r5 的已完成 OSS 测试授权不能重复使用。
回退先关准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。权限/网络回退须另批。当前整模块 INCOMPLETE,禁止部署部分候选。
按“停目标写入容器→读回确认→备份目标 KB 范围→更新资源→启动→健康/页面验收”执行;失败按原备份恢复并启动原服务。回退先关新写准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。当前整模块仍未完成真实 OSS 端到端与 clean-finalization 收敛,禁止把本候选当作完整生产就绪。
+125 -28
View File
@@ -3,6 +3,7 @@ package appconfig
import (
"errors"
"fmt"
"net/url"
"path/filepath"
"strconv"
"strings"
@@ -46,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
@@ -64,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;本功能**不使用凭据**。
@@ -129,6 +142,11 @@ type Config struct {
// 入口闸门:关入口与排空在它身上做(被代理服务自己不排空)。
LibraryTargetIngressService string
LibraryTargetIngressDrainFile string
// 入口形态:gate(默认)或 none。none 只给整栈没有入口闸门的测试环境用,
// 必须同时给 LibraryTargetNoIngressAck,且证据等级降一档并如实记录。
LibraryTargetIngressMode string
LibraryTargetNoIngressAck string
LibraryTargetHealthURL string
// 后台静默检查:目标队列 + 目标库(HTTP 排空不等于后台任务排空)。
LibraryTargetRedisAddr string
LibraryTargetRedisPassword string
@@ -175,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"),
@@ -197,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,
@@ -213,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")),
@@ -247,19 +274,23 @@ func Load(getenv func(string) string) (Config, error) {
LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")),
LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")),
LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")),
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
LibraryEmbeddingDimension: embeddingDimension,
LibraryCapacityBudgetBytes: capacityBudget,
LibraryRetentionVersions: retentionVersions,
LibraryRetentionDays: retentionDays,
LibraryExecutorStatusMaxAge: 2 * time.Minute,
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
LibraryTargetIngressMode: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_MODE")),
// 确认串不 Trim:必须逐字符相等,多一个空格都算没确认。
LibraryTargetNoIngressAck: getenv("LIBRARY_NO_INGRESS_ACK"),
LibraryTargetHealthURL: strings.TrimSpace(getenv("LIBRARY_TARGET_HEALTH_URL")),
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
LibraryEmbeddingDimension: embeddingDimension,
LibraryCapacityBudgetBytes: capacityBudget,
LibraryRetentionVersions: retentionVersions,
LibraryRetentionDays: retentionDays,
LibraryExecutorStatusMaxAge: 2 * time.Minute,
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
}
if config.DatabaseURL == "" {
return Config{}, errors.New("DATABASE_URL is required")
@@ -334,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 {
@@ -387,9 +427,35 @@ func Load(getenv func(string) string) (Config, error) {
if config.LibraryAgentSocket != "" && !filepath.IsAbs(config.LibraryAgentSocket) {
return Config{}, errors.New("LIBRARY_AGENT_SOCKET 必须是绝对路径(unix socket 由主机侧 agent 持有)")
}
// 入口形态:缺省 gate,行为与之前完全一致。none 只给整栈没有入口闸门的
// 测试环境用,必须显式确认;确认串逐字符相等,多一个空格都算没确认。
if config.LibraryTargetIngressMode == "" {
config.LibraryTargetIngressMode = "gate"
}
switch config.LibraryTargetIngressMode {
case "gate", "none":
default:
return Config{}, fmt.Errorf("LIBRARY_TARGET_INGRESS_MODE 无效(%q):只能是 gate 或 none",
config.LibraryTargetIngressMode)
}
noGate := config.LibraryTargetIngressMode == "none"
if noGate && config.LibraryTargetNoIngressAck != "test-only" {
return Config{}, errors.New("no-gate 维护必须显式确认:LIBRARY_NO_INGRESS_ACK 必须逐字符等于 test-only,拒绝启动")
}
if !noGate && config.LibraryTargetNoIngressAck != "" {
return Config{}, errors.New("LIBRARY_NO_INGRESS_ACK 只在 LIBRARY_TARGET_INGRESS_MODE=none 下有效")
}
if config.LibraryTargetHealthURL != "" {
parsed, err := url.Parse(config.LibraryTargetHealthURL)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") ||
parsed.Host == "" || parsed.User != nil {
return Config{}, errors.New("LIBRARY_TARGET_HEALTH_URL 必须是 http(s) 地址且不带凭据")
}
}
// 目标维护要么完整配置,要么完全不配;半配置会让窗口"看起来存在"却挡不住目标。
targetSet := config.LibraryTargetInstance != "" || config.LibraryTargetProject != "" ||
len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != ""
len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != "" ||
noGate || config.LibraryTargetHealthURL != ""
if targetSet {
missing := make([]string, 0, 4)
if config.LibraryTargetInstance == "" {
@@ -401,16 +467,21 @@ func Load(getenv func(string) string) (Config, error) {
if len(config.LibraryTargetWriters) == 0 {
missing = append(missing, "LIBRARY_TARGET_WRITERS")
}
if config.LibraryTargetIngressURL == "" {
if noGate {
// 没有闸门可声明:健康探针是唯一能证明"目标回来了"的必需项。
if config.LibraryTargetHealthURL == "" {
missing = append(missing, "LIBRARY_TARGET_HEALTH_URL")
}
} else if config.LibraryTargetIngressURL == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
}
if config.LibraryTargetJournalRoot == "" {
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
}
if config.LibraryTargetIngressService == "" {
if !noGate && config.LibraryTargetIngressService == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
}
if config.LibraryTargetIngressDrainFile == "" {
if !noGate && config.LibraryTargetIngressDrainFile == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_DRAIN_FILE")
}
if config.LibraryTargetRedisAddr == "" {
@@ -419,13 +490,17 @@ func Load(getenv func(string) string) (Config, error) {
if len(missing) > 0 {
return Config{}, fmt.Errorf("目标维护配置不完整:缺少 %s", strings.Join(missing, "、"))
}
if noGate && (config.LibraryTargetIngressURL != "" || config.LibraryTargetIngressService != "" ||
config.LibraryTargetIngressDrainFile != "") {
return Config{}, errors.New("no-gate 维护不得同时配置入口地址/闸门服务/排空文件:要么有闸门,要么明确没有")
}
if !filepath.IsAbs(config.LibraryTargetJournalRoot) {
return Config{}, errors.New("LIBRARY_TARGET_JOURNAL_ROOT 必须是绝对路径")
}
if !filepath.IsAbs(config.LibraryTargetDockerSocket) {
return Config{}, errors.New("LIBRARY_TARGET_DOCKER_SOCKET 必须是绝对路径")
}
if !filepath.IsAbs(config.LibraryTargetIngressDrainFile) {
if !noGate && !filepath.IsAbs(config.LibraryTargetIngressDrainFile) {
return Config{}, errors.New("LIBRARY_TARGET_INGRESS_DRAIN_FILE 必须是绝对路径")
}
if len(config.LibraryTargetNonWriters) == 0 {
@@ -466,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 == "") {
+43
View File
@@ -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")
+562
View File
@@ -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,
}
}
+280
View File
@@ -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)
}
}
+21 -5
View File
@@ -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
}
+243
View File
@@ -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")
}
}
+27 -9
View File
@@ -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`:
+1 -1
View File
@@ -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)
}
}
+14 -4
View File
@@ -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
+40
View File
@@ -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
}
+31 -2
View File
@@ -16,9 +16,8 @@ func developmentNotes(changelog, version, sha string) string {
return ""
}
lines := strings.Split(changelog, "\n")
prefix := "## 开发快照 snapshot/v" + version + " - "
for i, line := range lines {
if strings.HasPrefix(line, prefix) {
if developmentHeadingMatches(line, version) {
end := len(lines)
for j := i + 1; j < len(lines); j++ {
if strings.HasPrefix(lines[j], "## ") {
@@ -39,3 +38,33 @@ func developmentNotes(changelog, version, sha string) string {
}
return ""
}
// developmentHeadingMatches 接受两种真实标题:
// - 旧格式:## 开发快照 snapshot/v0.1.1 - 2026-10-18
// - 开发快照:## 开发快照 0.1.351(索引预检使用目标映射 ID)
//
// 版本号后必须是字符串结束或分隔符,避免 0.1.35 命中 0.1.351;
// 只读取到下一个二级标题,不跨版本吞正文。
func developmentHeadingMatches(line, version string) bool {
prefixes := []string{
"## 开发快照 snapshot/v" + version,
"## 开发快照 " + version,
}
for _, prefix := range prefixes {
if !strings.HasPrefix(line, prefix) {
continue
}
rest := line[len(prefix):]
if rest == "" {
return true
}
if strings.HasPrefix(rest, "—") || strings.HasPrefix(rest, "(") {
return true
}
switch rest[0] {
case ' ', '\t', '-', '(':
return true
}
}
return false
}
+5 -2
View File
@@ -36,8 +36,11 @@ type ServiceHealth struct {
ObservedAt time.Time `json:"observed_at"`
LastSuccessAt *time.Time `json:"last_success_at"`
ConsecutiveFailures int `json:"consecutive_failures"`
Configured bool `json:"configured"`
Applicable bool `json:"applicable"`
// ProbeTarget names the object being probed (instance + short binding id),
// never credentials or full UUIDs, so a red light can be attributed.
ProbeTarget string `json:"probe_target"`
Configured bool `json:"configured"`
Applicable bool `json:"applicable"`
}
type KnowledgeBaseProgress struct {
+1
View File
@@ -116,6 +116,7 @@ type CatalogRouteRequest struct {
// fulfillment path needs to materialize and fetch it later.
type CatalogRouteFile struct {
NodeID string
ParentNodeID string
Name string
RelativePath string
SizeBytes *int64
+13
View File
@@ -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 {
@@ -148,6 +156,11 @@ func classifyRole(method, path string) string {
if strings.HasPrefix(path, "/api/v1/backup-schedule") && method != http.MethodGet {
return roleAdmin
}
// 核对封存结果会把一个 pending 业务作业修成 succeeded;只允许管理员,
// 且 handler 仍要求 completed queue、精确版本和归档复核。
if strings.HasPrefix(path, "/api/v1/library/jobs/") && strings.HasSuffix(path, "/reconcile-capture") {
return roleAdmin
}
// 版本记录的同步会拉起一次对远端仓库的抓取(消耗网络与数据库写入),
// 与"谁能改生产绑定"同级:读任何角色可看,同步只能管理员。
if strings.HasPrefix(path, "/api/v1/version-history") && method != http.MethodGet {
+23
View File
@@ -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})
}
+91
View File
@@ -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)
}
}
+3
View File
@@ -98,6 +98,8 @@ type backupScheduleView struct {
HostCronLines []string `json:"host_cron_lines"`
HostCronService string `json:"host_cron_service"`
HostScriptPresent bool `json:"host_script_present"`
// HostCheckedAt 是本次真实主机探测时间;没有探测(只读库)时为空。
HostCheckedAt string `json:"host_checked_at,omitempty"`
LastRunStamp string `json:"last_run_stamp"`
LastRunCreatedAt string `json:"last_run_created_at"`
@@ -296,6 +298,7 @@ func (config Config) backupSchedulePayload(ctx context.Context, probeHost bool)
if !probeHost {
return view, nil
}
view.HostCheckedAt = formatTime(config.Now().UTC())
show, err := config.BackupHost.Show(ctx)
if err != nil {
view.HostReachable = false
+63
View File
@@ -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
}
+5 -15
View File
@@ -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})
+1 -1
View File
@@ -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())
}
}
+18 -35
View File
@@ -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")
}
}
+4 -154
View File
@@ -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
}
+2 -1
View File
@@ -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)
}
+83
View File
@@ -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})
}
+82
View File
@@ -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)
}
}
}
}
+212
View File
@@ -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 == ""
}
+30
View File
@@ -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())
}
}
+121
View File
@@ -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"})
}
}
+130
View File
@@ -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)
}
}
}
@@ -0,0 +1,246 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/librarysnapshot"
)
// libraryCaptureReconciler is deliberately narrow: it repairs one business
// seal job only after the completed capture queue, the successful export stage,
// the exact test-sealed version and the archived bytes all agree. It never
// captures, freezes writers, creates snapshots, writes source/target content or
// changes historical failure evidence.
type libraryCaptureReconciler interface {
LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error)
LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error)
LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error)
EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error)
ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error)
ReconcileMisclassifiedLibraryCapture(ctx context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, auditID, actor, reason string, evidence map[string]any, now time.Time) (bool, error)
}
const (
legacyOrphanError = "队列中已无对应作业,业务作业未收到结果"
legacyOrphanRecovery = "封存作业由 agent 恢复来源;确认来源 healthy 后可重发"
)
type libraryCaptureQueueReader interface {
QueueJob(ctx context.Context, id string) (jobs.Job, bool, error)
}
func libraryCaptureReconcile(w http.ResponseWriter, r *http.Request, config Config) {
if r.Method != http.MethodPost {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
store, ok := config.Store.(libraryCaptureReconciler)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "封存作业核对存储不可用"})
return
}
queueStore, ok := config.Store.(libraryCaptureQueueReader)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "队列精确读取不可用"})
return
}
jobID := strings.TrimSpace(r.PathValue("id"))
if jobID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "job id required"})
return
}
job, err := store.LibraryJob(r.Context(), jobID)
if err != nil {
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"})
return
}
if job.Kind != governance.LibraryJobSeal {
conflict(w, "只有封存作业可以核对封存结果")
return
}
systemMisclassified := job.State == governance.LibraryJobFailed && job.Stage == "" &&
job.Error == legacyOrphanError && job.Recovery == legacyOrphanRecovery && job.SnapshotID == ""
if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning &&
job.State != governance.LibraryJobSucceeded && !systemMisclassified {
conflict(w, "作业是真实失败/取消终态,不能改写成成功")
return
}
if job.QueueJobID == "" {
conflict(w, "作业没有关联队列号,不能证明封存完成")
return
}
captureJob := strings.TrimPrefix(job.ID, "libseal-")
if captureJob == "" || captureJob == job.ID {
conflict(w, "作业号不是封存作业身份")
return
}
queue, found, err := queueStore.QueueJob(r.Context(), job.QueueJobID)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture queue"})
return
}
if !found {
conflict(w, "队列作业不存在,不能证明封存完成")
return
}
if queue.Type != libraryCaptureJobType || queue.State != jobs.StateCompleted {
conflict(w, "队列作业不是 completed 的 library.capture")
return
}
var payload struct {
Scope string `json:"scope"`
CaptureJob string `json:"capture_job"`
}
if err := json.Unmarshal(queue.Payload, &payload); err != nil ||
payload.Scope != job.Scope || payload.CaptureJob != captureJob ||
queue.IdempotencyKey != "library.capture:"+captureJob {
conflict(w, "队列作业的 scope/capture_job/幂等键与业务作业不一致")
return
}
stageState, _, err := store.LibraryCaptureExportEvidence(r.Context(), job.ID)
if err != nil || stageState != "succeeded" {
conflict(w, "导出阶段没有成功证据,不能修复终态")
return
}
version, found, err := store.LibraryTestSealedVersionForJob(r.Context(), job.Scope, job.ID)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read exact test-sealed version"})
return
}
if !found || version.Kind != governance.LibraryVersionTestSealed ||
version.Scope != job.Scope || version.SourceJobID != job.ID || version.SnapshotID == "" {
conflict(w, "没有与作业/scope 精确绑定的测试封存版本")
return
}
source := configuredLibrarySource(config, job.Scope)
sourceID, err := source.ID()
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "来源身份配置不完整,无法核对封存来源"})
return
}
evidenceSource, _ := version.Evidence["source_id"].(string)
evidenceCapture, _ := version.Evidence["capture_job"].(string)
if evidenceSource != sourceID || evidenceCapture != captureJob {
conflict(w, "版本来源或 capture_job 与当前作业不一致")
return
}
if config.LibraryArchiveRoot == "" {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "未接线归档根,无法复核归档完整性"})
return
}
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "归档不可读,不能确认封存完整"})
return
}
defer archive.Close()
manifest, err := archive.Load(version.SnapshotID)
if err != nil {
conflict(w, "归档字节复核失败,不能修复作业")
return
}
if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID ||
manifest.KnowledgeBaseID != source.KnowledgeBaseID {
conflict(w, "归档清单来源身份与当前来源不一致")
return
}
if job.SnapshotID != "" && job.SnapshotID != version.SnapshotID {
conflict(w, "作业已有不同快照,不能覆盖")
return
}
if job.State == governance.LibraryJobSucceeded {
if job.SnapshotID != version.SnapshotID {
conflict(w, "作业已成功但快照与精确版本不一致")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"repaired": false, "already_succeeded": true, "job_id": job.ID,
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
"version_id": version.ID,
})
return
}
actor := ""
if identity, ok := sessionFrom(r.Context()); ok {
actor = identity.Username
}
now := time.Now().UTC()
digest, err := governance.LibraryRequestDigest(job.Scope, governance.LibraryJobRecover, map[string]any{
"kind": "capture_reconcile", "job_id": job.ID, "queue_job_id": queue.ID,
"snapshot_id": version.SnapshotID, "capture_job": captureJob, "stage": "export",
})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build reconcile audit digest"})
return
}
if systemMisclassified {
auditID := "librepair-" + digest[:16]
updated, repairErr := store.ReconcileMisclassifiedLibraryCapture(r.Context(), job.ID, job.Scope,
job.QueueJobID, version.SnapshotID, job.Stage, legacyOrphanError, legacyOrphanRecovery,
job.FinishedAt, auditID, actor, "completed capture queue + export succeeded + exact version + archive verified; legacy orphan misclassification", map[string]any{
"original_state": job.State, "original_error": job.Error, "original_recovery": job.Recovery,
"original_finished_at": job.FinishedAt, "queue_job_id": queue.ID,
"snapshot_id": version.SnapshotID, "version_id": version.ID, "archive_verified": true,
}, now)
if repairErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot persist misclassification repair"})
return
}
if !updated {
conflict(w, "原误判行状态/错误/完成时间已变化,拒绝覆盖")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"repaired": true, "already_succeeded": false, "misclassification_repaired": true,
"job_id": job.ID, "snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
"stage": "export", "version_id": version.ID, "audit_repair_id": auditID,
})
return
}
opID := "libop-capture-reconcile-" + digest[:16]
op, _, err := store.EnsureLibraryOperation(r.Context(), governance.LibraryOperation{
ID: opID, Scope: job.Scope, Kind: governance.LibraryJobRecover,
TargetSnapshotID: version.SnapshotID, RequestDigest: digest,
OperationKey: "capture-reconcile:" + job.ID, Actor: actor, CreatedAt: now,
})
if errors.Is(err, governance.ErrLibraryOperationConflict) {
conflict(w, "同一核对键对应了不同证据,拒绝修复")
return
}
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot record reconcile audit"})
return
}
updated, err := store.ReconcileLibraryCaptureTerminal(r.Context(), job.ID, job.Scope, job.QueueJobID, version.SnapshotID, now)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]any{
"error": "cannot persist reconciled job terminal", "audit_operation_id": op.ID,
})
return
}
if !updated {
conflict(w, "作业状态/身份在核对期间变化,拒绝覆盖")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"repaired": true, "already_succeeded": false, "job_id": job.ID,
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
"stage": "export", "version_id": version.ID, "audit_operation_id": op.ID,
})
}
func conflict(w http.ResponseWriter, reason string) {
writeJSON(w, http.StatusConflict, map[string]any{"available": false, "repaired": false, "reason": reason})
}
@@ -0,0 +1,361 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/librarysnapshot"
)
func (f *fakeLibraryStore) QueueJob(_ context.Context, id string) (jobs.Job, bool, error) {
if f.queue == nil || f.queue.ID != id {
return jobs.Job{}, false, nil
}
return *f.queue, true, nil
}
func (f *fakeLibraryStore) LibraryCaptureExportEvidence(_ context.Context, _ string) (string, string, error) {
return f.stageState, "", f.stageErr
}
func (f *fakeLibraryStore) LibraryJobStage(_ context.Context, _, stage string) (string, string, error) {
if f.stageErr != nil {
return "", "", f.stageErr
}
if stage != "export" {
return "", "", errors.New("unexpected stage")
}
return f.stageState, "", nil
}
func (f *fakeLibraryStore) LibraryTestSealedVersionForJob(_ context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) {
if f.versionErr != nil {
return governance.LibraryVersion{}, false, f.versionErr
}
if f.sealedVersion == nil || f.sealedVersion.Scope != scope || f.sealedVersion.SourceJobID != jobID {
return governance.LibraryVersion{}, false, nil
}
return *f.sealedVersion, true, nil
}
func reconcileFixture(t *testing.T) (*fakeLibraryStore, Config, governance.LibraryJob, []byte) {
t.Helper()
root := libraryFixtureRoot(t)
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
archive, err := librarysnapshot.Open(root, 256*1024*1024)
if err != nil {
t.Fatal(err)
}
manifest, err := archive.Load(snapshotID)
archive.Close()
if err != nil {
t.Fatal(err)
}
config := Config{LibraryArchiveRoot: root,
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
source := configuredLibrarySource(config, "internal")
sourceID, err := source.ID()
if err != nil {
t.Fatal(err)
}
job := governance.LibraryJob{ID: "libseal-cap-1", Scope: "internal", Kind: governance.LibraryJobSeal,
State: governance.LibraryJobPending, QueueJobID: "libcap-1"}
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "cap-1"})
store := &fakeLibraryStore{
jobs: []governance.LibraryJob{job},
stageState: "succeeded",
queue: &jobs.Job{ID: "libcap-1", Type: libraryCaptureJobType, State: jobs.StateCompleted,
Payload: payload, IdempotencyKey: "library.capture:cap-1"},
sealedVersion: &governance.LibraryVersion{ID: "libver-1", Scope: "internal",
Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshotID, SourceJobID: job.ID,
Evidence: map[string]any{"source_id": sourceID, "capture_job": "cap-1"}},
}
config.Store = store
return store, config, job, payload
}
func (f *fakeLibraryStore) ReconcileLibraryCaptureTerminal(_ context.Context, jobID, scope, queueJobID, snapshotID string, _ time.Time) (bool, error) {
if f.reconcileDenied {
return false, nil
}
for index := range f.jobs {
if f.jobs[index].ID != jobID || f.jobs[index].Scope != scope || f.jobs[index].Kind != governance.LibraryJobSeal ||
f.jobs[index].QueueJobID != queueJobID || (f.jobs[index].State != governance.LibraryJobPending && f.jobs[index].State != governance.LibraryJobRunning) ||
(f.jobs[index].SnapshotID != "" && f.jobs[index].SnapshotID != snapshotID) {
return false, nil
}
f.jobs[index].State = governance.LibraryJobSucceeded
f.jobs[index].SnapshotID = snapshotID
f.lastState = governance.LibraryJobSucceeded
return true, nil
}
return false, nil
}
func (f *fakeLibraryStore) ReconcileMisclassifiedLibraryCapture(_ context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, _ string, _ string, _ string, _ map[string]any, _ time.Time) (bool, error) {
if f.reconcileDenied {
return false, nil
}
for index := range f.jobs {
j := &f.jobs[index]
if j.ID != jobID || j.Scope != scope || j.Kind != governance.LibraryJobSeal || j.QueueJobID != queueJobID ||
j.State != governance.LibraryJobFailed || j.Stage != expectedStage || j.Error != expectedError ||
j.Recovery != expectedRecovery || j.SnapshotID != "" || (j.FinishedAt == nil) != (expectedFinished == nil) ||
(j.FinishedAt != nil && expectedFinished != nil && !j.FinishedAt.Equal(*expectedFinished)) {
return false, nil
}
j.State = governance.LibraryJobSucceeded
j.SnapshotID = snapshotID
j.Stage = "export"
f.lastState = governance.LibraryJobSucceeded
return true, nil
}
return false, nil
}
var _ libraryCaptureReconciler = (*fakeLibraryStore)(nil)
func runReconcile(t *testing.T, config Config, jobID string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+jobID+"/reconcile-capture", nil)
req.SetPathValue("id", jobID)
rec := httptest.NewRecorder()
libraryCaptureReconcile(rec, req, config)
return rec
}
func TestLibraryCaptureReconcileRepairsExactCompletedCapture(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["repaired"] != true || body["snapshot_id"] == "" || body["audit_operation_id"] == "" {
t.Fatalf("body=%v", body)
}
if store.lastState != governance.LibraryJobSucceeded {
t.Fatalf("advanced state=%s", store.lastState)
}
if len(store.operations) != 1 {
t.Fatalf("audit operations=%v", store.operations)
}
}
func TestLibraryCaptureReconcileAlreadySucceededIsReadOnly(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.State = governance.LibraryJobSucceeded
job.SnapshotID = store.sealedVersion.SnapshotID
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body["already_succeeded"] != true || body["repaired"] != false || store.lastState != "" {
t.Fatalf("body=%v advanced=%q", body, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsQueueNotCompleted(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue.State = jobs.StateRunning
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRejectsStageNotSucceeded(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.stageState = "failed"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongVersionSource(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Evidence["source_id"] = "other-source"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongCaptureJob(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Evidence["capture_job"] = "other-capture"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsBadArchive(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.SnapshotID = "missing-snapshot"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRejectsFailedJob(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.State = governance.LibraryJobFailed
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileIsIdempotent(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
first := runReconcile(t, config, job.ID)
if first.Code != http.StatusOK {
t.Fatalf("first code=%d body=%s", first.Code, first.Body.String())
}
second := runReconcile(t, config, job.ID)
if second.Code != http.StatusOK {
t.Fatalf("second code=%d body=%s", second.Code, second.Body.String())
}
var body map[string]any
_ = json.Unmarshal(second.Body.Bytes(), &body)
if body["already_succeeded"] != true || len(store.operations) != 1 {
t.Fatalf("body=%v ops=%v", body, store.operations)
}
}
func TestLibraryCaptureReconcileRejectsMissingQueue(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue = nil
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsQueueScope(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue.Payload, _ = json.Marshal(map[string]string{"scope": "external", "capture_job": "cap-1"})
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsMissingVersion(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion = nil
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongScopeVersion(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Scope = "external"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsDifferentExistingSnapshot(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.SnapshotID = "other-snapshot"
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileConditionalWriteRejectsConcurrentState(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.reconcileDenied = true
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRepairsExactLegacyMisclassification(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
finished := time.Now().UTC()
job.State = governance.LibraryJobFailed
job.Stage = ""
job.Error = legacyOrphanError
job.Recovery = legacyOrphanRecovery
job.FinishedAt = &finished
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body["misclassification_repaired"] != true || store.lastState != governance.LibraryJobSucceeded {
t.Fatalf("body=%v advanced=%q", body, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsOtherFailedError(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
finished := time.Now().UTC()
job.State = governance.LibraryJobFailed
job.Stage = ""
job.Error = "capture export failed"
job.Recovery = legacyOrphanRecovery
job.FinishedAt = &finished
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRejectsRealFailureAndCancel(t *testing.T) {
for _, state := range []governance.LibraryJobState{governance.LibraryJobFailed, governance.LibraryJobCancelled} {
store, config, job, _ := reconcileFixture(t)
job.State = state
job.Error = "real failure"
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("state=%s code=%d advanced=%q", state, rec.Code, store.lastState)
}
}
}
func TestLibraryCaptureReconcileMisclassificationCASRejectsChange(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
finished := time.Now().UTC()
job.State = governance.LibraryJobFailed
job.Stage = ""
job.Error = legacyOrphanError
job.Recovery = legacyOrphanRecovery
job.FinishedAt = &finished
store.jobs[0] = job
store.reconcileDenied = true
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
@@ -0,0 +1,204 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/librarysnapshot"
postgresstore "knowledge-governance/internal/platform/postgres"
)
// Vertical PostgreSQL path: the real worker startup reconciliation must leave
// a pending seal with a completed capture queue intact, then the actual HTTP
// handler must verify archive/version/stage and repair it. This is not a fake
// store or a direct helper test.
func verticalReconcileFixture(t *testing.T) (*postgresstore.Store, Config, string, *pgxpool.Pool) {
t.Helper()
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatal("isolated database required")
}
cfg.MaxConns = 1
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
ctx := context.Background()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pool.Close)
if _, err := pool.Exec(ctx, `
CREATE TEMP TABLE library_jobs(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
state varchar(16) NOT NULL, stage varchar(32) NOT NULL DEFAULT '',
idempotency_key varchar(255) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL DEFAULT '',
queue_job_id varchar(64) NOT NULL DEFAULT '', snapshot_id varchar(64) NOT NULL DEFAULT '',
target_snapshot_id varchar(64) NOT NULL DEFAULT '', actor varchar(128) NOT NULL DEFAULT '',
error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '',
operation_id varchar(64) NOT NULL DEFAULT '', attempt_epoch integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL, finished_at timestamptz,
target_id text NOT NULL DEFAULT '');
CREATE TEMP TABLE library_job_stages(
job_id varchar(64) NOT NULL, stage varchar(32) NOT NULL, state varchar(16) NOT NULL,
total bigint, completed bigint, bytes_total bigint, bytes_done bigint,
detail text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, PRIMARY KEY(job_id,stage));
CREATE TEMP TABLE library_versions(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(24) NOT NULL,
snapshot_id varchar(64) NOT NULL DEFAULT '', version_label varchar(64) NOT NULL DEFAULT '',
source_job_id varchar(64) NOT NULL DEFAULT '', operation_id varchar(64) NOT NULL DEFAULT '',
attempt_epoch integer NOT NULL DEFAULT 0, evidence jsonb NOT NULL DEFAULT '{}'::jsonb,
created_by varchar(128) NOT NULL DEFAULT '', created_at timestamptz NOT NULL, superseded_at timestamptz);
CREATE TEMP TABLE library_job_repairs(
id varchar(64) PRIMARY KEY, job_id varchar(64) NOT NULL, scope varchar(16) NOT NULL,
kind varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL, snapshot_id varchar(64) NOT NULL,
original_state varchar(16) NOT NULL, original_stage varchar(32) NOT NULL DEFAULT '',
original_error text NOT NULL DEFAULT '', original_recovery varchar(255) NOT NULL DEFAULT '',
original_finished_at timestamptz, reason varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
evidence jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL);
CREATE TEMP TABLE library_operations(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
target_snapshot_id varchar(64) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL,
operation_key varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
created_at timestamptz NOT NULL, target_id text NOT NULL DEFAULT '',
first_backup_snapshot_id varchar(64), first_backup_bytes bigint, first_backup_at timestamptz,
writeset_digest varchar(64), writeset_rows bigint, target_fingerprint varchar(128), anchors_at timestamptz);
CREATE UNIQUE INDEX library_operations_key_test ON library_operations(scope,kind,operation_key);
CREATE TEMP TABLE jobs(
id varchar(64) PRIMARY KEY, type varchar(64) NOT NULL, payload jsonb NOT NULL,
state varchar(16) NOT NULL, priority integer NOT NULL DEFAULT 0, available_at timestamptz NOT NULL,
lease_owner varchar(128), lease_until timestamptz, attempt integer NOT NULL DEFAULT 0,
max_attempts integer NOT NULL DEFAULT 1, last_error text, idempotency_key varchar(255) NOT NULL,
created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL);`); err != nil {
t.Fatal(err)
}
root := libraryFixtureRoot(t)
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
archive, err := librarysnapshot.Open(root, 256*1024*1024)
if err != nil {
t.Fatal(err)
}
manifest, err := archive.Load(snapshotID)
archive.Close()
if err != nil {
t.Fatal(err)
}
config := Config{LibraryArchiveRoot: root,
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
source := configuredLibrarySource(config, "internal")
sourceID, err := source.ID()
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical"})
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at)
VALUES('q-vertical','library.capture',$1,'completed',$2,'library.capture:vertical',$2,$2)`, payload, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at)
VALUES('ver-vertical','internal','test_sealed',$1,'libseal-vertical',$2,$3)`, snapshotID,
map[string]any{"source_id": sourceID, "capture_job": "vertical"}, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at)
VALUES('libseal-vertical','export','succeeded','已封存快照', $1)`, now); err != nil {
t.Fatal(err)
}
store := postgresstore.NewStore(pool)
config.Store = store
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,created_at,updated_at)
VALUES('libseal-vertical','internal','seal','pending','k','d','q-vertical',$1,$1)`, now); err != nil {
t.Fatal(err)
}
return store, config, snapshotID, pool
}
func TestStartupReconcileThenHandlerRepairsPendingCapture(t *testing.T) {
store, config, _, _ := verticalReconcileFixture(t)
ctx := context.Background()
now := time.Now().UTC()
if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 {
t.Fatalf("startup reconcile n=%d err=%v", n, err)
}
job, err := store.LibraryJob(ctx, "libseal-vertical")
if err != nil || job.State != governance.LibraryJobPending {
t.Fatalf("startup changed job: %+v err=%v", job, err)
}
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical/reconcile-capture", nil)
req.SetPathValue("id", "libseal-vertical")
rec := httptest.NewRecorder()
libraryCaptureReconcile(rec, req, config)
if rec.Code != http.StatusOK {
t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String())
}
job, err = store.LibraryJob(ctx, "libseal-vertical")
if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID == "" {
t.Fatalf("handler did not repair: %+v err=%v", job, err)
}
}
func TestStartupReconcilePreservesFailedCapturesForExactReconcile(t *testing.T) {
store, config, snapshotID, pool := verticalReconcileFixture(t)
ctx := context.Background()
now := time.Now().UTC()
source := configuredLibrarySource(config, "internal")
sourceID, err := source.ID()
if err != nil {
t.Fatal(err)
}
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical-failed"})
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at)
VALUES('q-failed','library.capture',$1,'completed',$2,'library.capture:vertical-failed',$2,$2)`, payload, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at)
VALUES('ver-failed','internal','test_sealed',$1,'libseal-vertical-failed',$2,$3)`,
snapshotID, map[string]any{"source_id": sourceID, "capture_job": "vertical-failed"}, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at)
VALUES('libseal-vertical-failed','export','succeeded','已封存快照', $1)`, now); err != nil {
t.Fatal(err)
}
finished := now.Truncate(time.Microsecond)
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,error,recovery,created_at,updated_at,finished_at)
VALUES('libseal-vertical-failed','internal','seal','failed','kf','df','q-failed',$1,$2,$3,$3,$3)`,
"队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", finished); err != nil {
t.Fatal(err)
}
if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 {
t.Fatalf("startup reconcile n=%d err=%v", n, err)
}
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical-failed/reconcile-capture", nil)
req.SetPathValue("id", "libseal-vertical-failed")
rec := httptest.NewRecorder()
libraryCaptureReconcile(rec, req, config)
if rec.Code != http.StatusOK {
t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String())
}
job, err := store.LibraryJob(ctx, "libseal-vertical-failed")
if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID != snapshotID {
t.Fatalf("failed misclassification not repaired: %+v err=%v", job, err)
}
var originalState, originalError string
if err := pool.QueryRow(ctx, `SELECT original_state, original_error FROM library_job_repairs WHERE job_id='libseal-vertical-failed'`).
Scan(&originalState, &originalError); err != nil {
t.Fatal(err)
}
if originalState != "failed" || originalError == "" {
t.Fatalf("audit missing original: state=%q error=%q", originalState, originalError)
}
}
+34 -6
View File
@@ -342,7 +342,11 @@ type libraryOverview struct {
CaptureAvailable bool `json:"capture_available"`
CaptureReason string `json:"capture_reason,omitempty"`
Executor libraryExecutorView `json:"executor"`
Now time.Time `json:"now"`
// 实际目标身份:页面不能只显示"weknora-test"或旧文档级绑定名称。
TargetInstance string `json:"target_instance,omitempty"`
TargetProject string `json:"target_project,omitempty"`
TargetKnowledgeBaseID string `json:"target_knowledge_base_id,omitempty"`
Now time.Time `json:"now"`
}
// libraryVersionRef 只回答"这个快照被登记成哪一类版本、由哪个作业登记"。
@@ -595,6 +599,11 @@ func testSealedOf(versions []governance.LibraryVersion, byID map[string]libraryS
// 它刻意只说配置:能停写入者/关入口/证明排空的真实能力在 worker 侧(docker socket、
// 闸门、排空文件),API 若声称"能力可用"就是拿配置字符串冒充执行证据。
func libraryMaintenanceCapability(config Config) map[string]any {
mode := strings.TrimSpace(config.LibraryTargetIngressMode)
if mode == "" {
mode = "gate"
}
noGate := mode == "none"
missing := make([]string, 0, 6)
if config.LibraryTargetInstance == "" {
missing = append(missing, "LIBRARY_TARGET_INSTANCE")
@@ -605,11 +614,18 @@ func libraryMaintenanceCapability(config Config) map[string]any {
if len(config.LibraryTargetWriters) == 0 {
missing = append(missing, "LIBRARY_TARGET_WRITERS")
}
if config.LibraryTargetIngressURL == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
}
if config.LibraryTargetIngressService == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
if noGate {
// 没有闸门:页面必须如实说"无闸门(测试模式)",不能显示"打开"。
if config.LibraryTargetHealthURL == "" {
missing = append(missing, "LIBRARY_TARGET_HEALTH_URL")
}
} else {
if config.LibraryTargetIngressURL == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
}
if config.LibraryTargetIngressService == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
}
}
if config.LibraryTargetJournalRoot == "" {
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
@@ -617,12 +633,18 @@ func libraryMaintenanceCapability(config Config) map[string]any {
if config.LibraryTargetDockerSocket == "" {
missing = append(missing, "LIBRARY_TARGET_DOCKER_SOCKET")
}
ingressState := "闸门"
if noGate {
ingressState = "无闸门(测试模式)"
}
return map[string]any{
"configured": len(missing) == 0,
"missing": missing,
"instance": config.LibraryTargetInstance,
"project": config.LibraryTargetProject,
"writers": config.LibraryTargetWriters,
"ingress_mode": mode,
"ingress_state": ingressState,
"ingress_service": config.LibraryTargetIngressService,
"note": "配置齐全只说明治理侧接线完整;停写入者、关入口与排空由 worker 在作业内校验并执行",
}
@@ -686,10 +708,16 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
}
now := time.Now().UTC()
overview := libraryOverview{Scope: scope, Jobs: []governance.LibraryJob{}, Now: now,
TargetInstance: config.LibraryTargetInstance, TargetProject: config.LibraryTargetProject,
Gate: libraryGateView{Reasons: []string{}},
Diff: libraryDiffView{State: "unknown", Reason: "生产与测试的文档级差异读取未接线", Added: []any{}, Updated: []any{}, Removed: []any{}}}
// 可发起封存 = worker 真实探测到执行器可用且指向本实例;原因逐条给全。
overview.CaptureAvailable, overview.CaptureReason, overview.Executor = libraryExecutorAvailability(r.Context(), config)
if scope == "internal" {
overview.TargetKnowledgeBaseID = config.LibraryProductionInternalKB
} else {
overview.TargetKnowledgeBaseID = config.LibraryProductionExternalKB
}
// 测试封存来自归档 + 版本登记:归档里**不止**测试封存——生产预备份与目标基线
// 快照同样带 scope,如果只按"这个 scope 最新一份"挑,页面就会把目标自己的内容
+17 -1
View File
@@ -11,6 +11,7 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
)
// 生产闸口与整库状态契约的针对性测试:不做数据库集成,只验证
@@ -37,6 +38,13 @@ type fakeLibraryStore struct {
resumeOK bool
resumeErr error
resumeCalls []string
// capture reconciliation fixtures
queue *jobs.Job
stageState string
stageErr error
sealedVersion *governance.LibraryVersion
versionErr error
reconcileDenied bool
}
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
@@ -127,8 +135,16 @@ func (f *fakeLibraryStore) UpdateLibraryStage(_ context.Context, _, _, _ string,
return nil
}
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState, _, _, _, _, _ string, _ time.Time) error {
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, _, _, _, snapshotID, _ string, _ time.Time) error {
f.lastState = state
for index := range f.jobs {
if f.jobs[index].ID == jobID {
f.jobs[index].State = state
if snapshotID != "" {
f.jobs[index].SnapshotID = snapshotID
}
}
}
return nil
}
@@ -266,3 +266,25 @@ func TestLibraryReadPathsRejectTamperedManifest(t *testing.T) {
t.Fatalf("storage must fail closed: status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
// F11: the HTTP projection must include binding and Wiki log counts; the
// previous projection silently omitted them and the UI turned absence into 0.
func TestLibrarySnapshotTotalsIncludeBindingsAndWikiLogs(t *testing.T) {
view := librarySnapshotViewOfNoUsage("snap-totals", librarysnapshot.Manifest{
Scope: "internal", KnowledgeBaseID: "kb", TenantID: 10000,
Parts: []librarysnapshot.Part{
{Kind: "database", Name: "knowledges", Count: 4},
{Kind: "database", Name: "chunks", Count: 38},
{Kind: "database", Name: "resources", Count: 21},
{Kind: "database", Name: "resource_bindings", Count: 4},
{Kind: "wiki", Name: "wiki_pages", Count: 31},
{Kind: "wiki", Name: "wiki_folders", Count: 21},
{Kind: "wiki", Name: "wiki_log_entries", Count: 11},
},
})
for key, want := range map[string]int64{"documents": 4, "chunks": 38, "resources": 21, "bindings": 4, "wiki_pages": 31, "wiki_folders": 21, "wiki_log_entries": 11} {
if view.Totals[key] != want {
t.Fatalf("totals[%s]=%d want=%d (%v)", key, view.Totals[key], want, view.Totals)
}
}
}
+4
View File
@@ -261,10 +261,14 @@ func librarySnapshotViewOfNoUsage(id string, manifest librarysnapshot.Manifest)
}
case "resources":
snapshot.Totals["resources"] = part.Count
case "resource_bindings":
snapshot.Totals["bindings"] = part.Count
case "wiki_pages":
snapshot.Totals["wiki_pages"] = part.Count
case "wiki_folders":
snapshot.Totals["wiki_folders"] = part.Count
case "wiki_log_entries":
snapshot.Totals["wiki_log_entries"] = part.Count
}
}
sort.Slice(snapshot.Parts, func(i, j int) bool {
+42 -10
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"net/http"
"strings"
"time"
"knowledge-governance/internal/governance"
@@ -23,16 +24,19 @@ type libraryVerifyRequest struct {
// libraryVerificationView 是页面需要的全部事实:当前目标是谁、最近一次验证结果、
// 证据是否对当前目标成立、以及同步闸口能不能据此放行。
type libraryVerificationView struct {
Scope string `json:"scope"`
Target libraryVerificationTarget `json:"target"`
Verified bool `json:"verified"`
Reason string `json:"reason"`
Latest *governance.LibraryRestoreVerification `json:"latest,omitempty"`
History []governance.LibraryRestoreVerification `json:"history"`
Running bool `json:"running"`
JobID string `json:"job_id,omitempty"`
State string `json:"state,omitempty"`
Stage string `json:"stage,omitempty"`
Scope string `json:"scope"`
Target libraryVerificationTarget `json:"target"`
Verified bool `json:"verified"`
Reason string `json:"reason"`
Latest *governance.LibraryRestoreVerification `json:"latest,omitempty"`
// SnapshotLatest 只在请求显式带 snapshot_id 时返回:快照报告不能拿 scope
// 最近一条代替。
SnapshotLatest *governance.LibraryRestoreVerification `json:"snapshot_latest,omitempty"`
History []governance.LibraryRestoreVerification `json:"history"`
Running bool `json:"running"`
JobID string `json:"job_id,omitempty"`
State string `json:"state,omitempty"`
Stage string `json:"stage,omitempty"`
}
type libraryVerificationTarget struct {
@@ -177,11 +181,39 @@ func libraryVerifications(w http.ResponseWriter, r *http.Request, config Config)
if history, err := store.LibraryRestoreVerifications(r.Context(), scope, 10); err == nil {
view.History = history
}
if snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id")); snapshotID != "" {
if exact, ok := config.Store.(interface {
LibraryRestoreVerificationForSnapshot(context.Context, string, string) (governance.LibraryRestoreVerification, bool, error)
}); ok {
item, found, exactErr := exact.LibraryRestoreVerificationForSnapshot(r.Context(), scope, snapshotID)
if exactErr != nil {
view.Reason = "读取该快照的恢复验证记录失败"
writeJSON(w, http.StatusServiceUnavailable, view)
return
}
if found {
view.SnapshotLatest = &item
}
}
}
view.Verified, view.Reason = governance.LibraryVerificationSatisfied(latest, scope)
if !found {
view.Verified = false
view.Reason = "还没有对当前目标做过恢复验证:点「跑一次恢复验证」(真实备份 → canary → 恢复 → 复核)"
}
if snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id")); snapshotID != "" {
// 显式按快照查询时,verified 只回答该快照;不能让 scope 最新通过记录
// 把另一个未演练的快照染绿。
view.Verified = false
if view.SnapshotLatest == nil {
view.Reason = "该快照没有真实恢复验证记录(未验证;不是读取失败)"
} else if view.SnapshotLatest.Status == governance.LibraryVerificationPassed {
view.Verified = true
view.Reason = ""
} else {
view.Reason = "该快照最近一次恢复验证未通过"
}
}
// 在飞作业必须从真实业务行读出来:旧实现只构造 running 字段却从不赋值,
// 页面因此在验收里看不到"已接受/正在执行",按钮也不会进入执行态(审核 B4)。
if jobs, ok := config.Store.(interface {
+32
View File
@@ -34,6 +34,15 @@ func (s *verificationStore) LatestLibraryRestoreVerification(_ context.Context,
return governance.LibraryRestoreVerification{}, false, nil
}
func (s *verificationStore) LibraryRestoreVerificationForSnapshot(_ context.Context, scope, snapshotID string) (governance.LibraryRestoreVerification, bool, error) {
for _, item := range s.verifications {
if item.Scope == scope && item.SnapshotID == snapshotID {
return item, true, nil
}
}
return governance.LibraryRestoreVerification{}, false, nil
}
func (s *verificationStore) LibraryRestoreVerifications(_ context.Context, scope string, limit int) ([]governance.LibraryRestoreVerification, error) {
items := make([]governance.LibraryRestoreVerification, 0, len(s.verifications))
for _, item := range s.verifications {
@@ -131,6 +140,29 @@ func TestLibraryVerificationsWithoutEvidenceIsNotVerified(t *testing.T) {
}
}
// F03: the selected snapshot must resolve its own evidence, never the scope's
// newest passed record.
func TestLibraryVerificationsExactSnapshotDoesNotBorrowLatest(t *testing.T) {
store := &verificationStore{verifications: []governance.LibraryRestoreVerification{
{ID: "verify-new", Scope: "internal", Status: governance.LibraryVerificationPassed,
SnapshotID: "snap-new", JobID: "job-new", FinishedAt: time.Now().UTC()},
{ID: "verify-old", Scope: "internal", Status: governance.LibraryVerificationFailed,
SnapshotID: "snap-old", JobID: "job-old", Failure: "old restore mismatch",
FinishedAt: time.Now().UTC().Add(-time.Hour)},
}}
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal&snapshot_id=snap-old", nil)
libraryVerifications(recorder, request, Config{Store: store})
body := decodeBody(t, recorder)
exact, ok := body["snapshot_latest"].(map[string]any)
if !ok || exact["snapshot_id"] != "snap-old" || exact["status"] != "failed" {
t.Fatalf("snapshot_latest=%v body=%v", body["snapshot_latest"], body)
}
if body["verified"] != false {
t.Fatalf("old failed snapshot must not inherit latest passed: %v", body["verified"])
}
}
func TestLibraryVerificationsWithPassedEvidenceIsVerified(t *testing.T) {
store := &verificationStore{verifications: []governance.LibraryRestoreVerification{{
ID: "libverify-internal-job1", Scope: "internal", Status: governance.LibraryVerificationPassed,
+4
View File
@@ -97,6 +97,10 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"})
return
}
// 目标同名不罕见(两侧都叫“对内知识库”):把当前生效绑定随页返回,
// 前端才能在同一口径下标注“当前绑定/历史”,而不是拿本页条目反推全局。
internal, external := config.effectiveRoutingTargets(r.Context())
page.Bindings = postgresstore.MonitorBindings{Internal: internal, External: external}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, 200, map[string]any{"data": page})
}
+37
View File
@@ -2,6 +2,7 @@ package httpapi
import (
"context"
"encoding/json"
postgresstore "knowledge-governance/internal/platform/postgres"
"net/http/httptest"
"testing"
@@ -51,3 +52,39 @@ func TestMonitorTasksRoute(t *testing.T) {
t.Fatalf("viewer removal %d", removal.Code)
}
}
// F15:筛选里的“当前绑定”必须来自持久化绑定(与业务同一真源),不是 env 旧值,
// 也不能让前端拿本页数据猜全局。
func TestMonitorTasksReportsEffectiveTargetBindings(t *testing.T) {
store := &monitorTasksTestStore{}
handler, err := NewHandler(Config{
Store: store,
InternalRoutingKnowledgeBaseID: "env-old-internal",
ExternalRoutingKnowledgeBaseID: "env-old-external",
RoutingBindings: &bindingStoreFake{internal: "current-internal", external: "current-external"},
})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("GET", "/api/v1/monitor/tasks?limit=20", nil)
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleViewer}))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != 200 {
t.Fatalf("status %d: %s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data struct {
Bindings struct {
Internal string `json:"internal"`
External string `json:"external"`
} `json:"bindings"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.Bindings.Internal != "current-internal" || payload.Data.Bindings.External != "current-external" {
t.Fatalf("bindings = %#v, want the persisted current bindings", payload.Data.Bindings)
}
}
+1 -1
View File
@@ -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
+94
View File
@@ -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})
})
}
}
+142
View File
@@ -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)
}
}
}
}
+42
View File
@@ -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
View File
@@ -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
+3 -22
View File
@@ -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) {
+93
View File
@@ -7,6 +7,7 @@ import (
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qawemail"
"net/http"
"strconv"
"time"
)
@@ -20,6 +21,98 @@ type weeklyMailStore interface {
TestSend(context.Context, string) (string, error)
SaveDashboardImage(context.Context, string, []byte) error
SendDue(context.Context, time.Time) (qawemail.DueResult, error)
PreviewSend(context.Context, string, int64, string, time.Time) (qawemail.SendPreview, error)
SendManual(context.Context, string, int64, string, string, time.Time) (qawemail.ManualResult, error)
}
// weeklyMailSendError names the rule that refused a manual resend. Anything SMTP-related is
// reported by the handler itself, so an unmet precondition never looks like a mail failure.
func weeklyMailSendError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, qawemail.ErrNotCurrent):
writeJSON(w, http.StatusConflict, map[string]string{"error": "该周周报未确认,或确认后正文/版本已变化;请先确认当前版本再补发"})
case errors.Is(err, qawemail.ErrFutureWeek):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "不能补发未来周"})
case errors.Is(err, qawemail.ErrSlotPending):
writeJSON(w, http.StatusConflict, map[string]string{"error": "本周尚未到达设定的发送时点,暂不能补发"})
case errors.Is(err, qawemail.ErrNotConfigured):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "未配置邮件服务器、发件人或收件人,无法补发"})
case errors.Is(err, qawemail.ErrSendInFlight):
writeJSON(w, http.StatusConflict, map[string]string{"error": "该周该版本有一次发送结果未知(记录停在发送中),为避免重复投递未重发;请先核对已发出的邮件"})
case errors.Is(err, qawemail.ErrDeliveryUnknown):
writeJSON(w, http.StatusConflict, map[string]string{"error": "SMTP 已提交但未收到最终确认,投递结果未知;为避免重复已停止重发,请先核对已发出的邮件"})
case errors.Is(err, qawemail.ErrNoPassword):
writeJSON(w, http.StatusConflict, map[string]string{"error": "SMTP 授权码缺失或无法解密,无法补发"})
case errors.Is(err, qawemail.ErrInvalid):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "补发参数无效:需要精确的周、已确认版本与正文 hash"})
default:
weeklyMailError(w, err)
}
}
// qaWeeklyMailSendPreview lets the confirmation dialog show the exact week, revision and
// distribution this send would use — the same settings the send path reads.
func qaWeeklyMailSendPreview(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) {
return
}
store, ok := c.QAWeeklyMail.(weeklyMailStore)
if !ok {
weeklyMailError(w, qawemail.ErrUnavailable)
return
}
query := r.URL.Query()
revision, err := strconv.ParseInt(query.Get("revision"), 10, 64)
if err != nil {
weeklyMailSendError(w, qawemail.ErrInvalid)
return
}
preview, err := store.PreviewSend(r.Context(), r.PathValue("week"), revision, query.Get("body_sha256"), time.Now())
if err != nil {
weeklyMailSendError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": preview})
}
// qaWeeklyMailSend is the formal resend: admin only, bound to the live confirmation, and the same
// render/claim path as the automatic slot. It is not a test send and never targets the review box.
func qaWeeklyMailSend(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-mail") {
return
}
identity, ok := sessionFrom(r.Context())
if !ok || identity.Role != "admin" {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "仅管理员可正式补发周报"})
return
}
store, found := c.QAWeeklyMail.(weeklyMailStore)
if !found {
weeklyMailError(w, qawemail.ErrUnavailable)
return
}
var request struct {
Revision int64 `json:"revision"`
BodySHA256 string `json:"body_sha256"`
}
if decodeQualityJSON(w, r, &request) != nil {
weeklyMailError(w, qawemail.ErrInvalid)
return
}
result, err := store.SendManual(r.Context(), r.PathValue("week"), request.Revision, request.BodySHA256, identity.Username, time.Now())
if err != nil {
weeklyMailSendError(w, err)
return
}
if result.Status == "failed" {
reason := result.Reason
if len(reason) > 300 {
reason = reason[:300]
}
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "正式补发未送达:" + reason})
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": result})
}
func weeklyMailError(w http.ResponseWriter, err error) {
@@ -0,0 +1,91 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/qawemail"
)
// 页面 reload / “完成读真实发送记录”走的就是这个 handler。用真实 PG 的非空历史证明
// 产品读回路径返回 200 且带 message_id,而不是 503——“历史行存在就整个列表不可用”
// 正是上一版 Sends() 的确定性回归。
func TestWeeklyMailSendsHandlerReadsRealHistoryWithMessageID(t *testing.T) {
dsn := os.Getenv("KG_WEEKLY_MAIL_TEST_DSN")
if dsn == "" {
t.Skip("显式一次性周报邮件数据库未提供(KG_WEEKLY_MAIL_TEST_DSN):跳过不等于通过")
}
if !strings.Contains(dsn, "/kg_weekly_mail_test_") || strings.Contains(dsn, "/governance?") {
t.Fatal("拒绝非一次性周报测试库")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal("测试库连接参数无效(详情省略)")
}
defer pool.Close()
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
store := qawemail.NewStore(pool, "fixture-http-history", os.Getenv("KG_WEEKLY_MAIL_TEST_KEY"), nil)
for _, statement := range []string{
`DELETE FROM qa_weekly_email_sends WHERE tenant_key=$1`,
} {
if _, err := pool.Exec(ctx, statement, "fixture-http-history"); err != nil {
t.Fatal(err)
}
}
if _, err := pool.Exec(ctx, `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,message_id,last_error,created_at,updated_at)
VALUES($1,'2026-W45',16,$2,'sent',1,'<real@example.com>','',now(),now()),
($1,'2026-W44',7,$2,'failed',2,'','smtp RCPT 被拒: 550',now(),now() - interval '1 hour')`,
"fixture-http-history", strings.Repeat("a", 64)); err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/sends?week=2026-W45", nil)
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
recorder := httptest.NewRecorder()
qaWeeklyMailSends(recorder, request, Config{QAWeeklyMail: store})
if recorder.Code != http.StatusOK {
t.Fatalf("非空历史必须 200,status=%d body=%s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data struct {
Sends []qawemail.Send `json:"sends"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.Sends) != 1 || payload.Data.Sends[0].MessageID != "<real@example.com>" || payload.Data.Sends[0].Status != "sent" {
t.Fatalf("发送记录必须带回真实 message_id:%+v", payload.Data.Sends)
}
// 全量历史(不带 week)同样必须可读,且 failed 行不伪造 message_id。
all := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/sends", nil)
all = all.WithContext(context.WithValue(all.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
allRecorder := httptest.NewRecorder()
qaWeeklyMailSends(allRecorder, all, Config{QAWeeklyMail: store})
if allRecorder.Code != http.StatusOK {
t.Fatalf("全量历史必须 200,status=%d body=%s", allRecorder.Code, allRecorder.Body.String())
}
if err := json.Unmarshal(allRecorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.Sends) != 2 {
t.Fatalf("应返回 2 条历史,got %+v", payload.Data.Sends)
}
for _, item := range payload.Data.Sends {
if item.Status == "failed" && item.MessageID != "" {
t.Fatalf("failed 行不得有 message_id:%+v", item)
}
}
}
+186
View File
@@ -0,0 +1,186 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/qawemail"
)
type fakeWeeklyMailStore struct {
preview qawemail.SendPreview
previewErr error
result qawemail.ManualResult
sendErr error
calls int
lastWeek string
lastRev int64
lastHash string
lastActor string
}
func (f *fakeWeeklyMailStore) ReadSettings(context.Context) (qawemail.Settings, error) {
return qawemail.Settings{}, nil
}
func (f *fakeWeeklyMailStore) SaveSettings(context.Context, string, qawemail.SettingsInput) (qawemail.Settings, error) {
return qawemail.Settings{}, nil
}
func (f *fakeWeeklyMailStore) Confirm(context.Context, string, string) (qawemail.Confirmation, error) {
return qawemail.Confirmation{}, nil
}
func (f *fakeWeeklyMailStore) Unconfirm(context.Context, string) error { return nil }
func (f *fakeWeeklyMailStore) ReadConfirmation(context.Context, string) (*qawemail.Confirmation, error) {
return nil, nil
}
func (f *fakeWeeklyMailStore) Sends(context.Context, string) ([]qawemail.Send, error) {
return nil, nil
}
func (f *fakeWeeklyMailStore) TestSend(context.Context, string) (string, error) { return "", nil }
func (f *fakeWeeklyMailStore) SaveDashboardImage(context.Context, string, []byte) error {
return nil
}
func (f *fakeWeeklyMailStore) SendDue(context.Context, time.Time) (qawemail.DueResult, error) {
return qawemail.DueResult{}, nil
}
func (f *fakeWeeklyMailStore) PreviewSend(_ context.Context, week string, revision int64, hash string, _ time.Time) (qawemail.SendPreview, error) {
f.lastWeek, f.lastRev, f.lastHash = week, revision, hash
if f.previewErr != nil {
return qawemail.SendPreview{}, f.previewErr
}
out := f.preview
out.Week, out.Revision, out.BodySHA256 = week, revision, hash
return out, nil
}
func (f *fakeWeeklyMailStore) SendManual(_ context.Context, week string, revision int64, hash, actor string, _ time.Time) (qawemail.ManualResult, error) {
f.calls++
f.lastWeek, f.lastRev, f.lastHash, f.lastActor = week, revision, hash, actor
if f.sendErr != nil {
return qawemail.ManualResult{}, f.sendErr
}
out := f.result
out.Week, out.Revision = week, revision
return out, nil
}
func weeklyMailSendRequest(t *testing.T, role, body string, withIntent bool) *http.Request {
t.Helper()
request := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/master/weekly-mail/send/2026-W45", strings.NewReader(body))
request.SetPathValue("week", "2026-W45")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role}))
if withIntent {
request.Header.Set("X-Governance-Action", "qa-weekly-mail")
}
return request
}
// 正式补发是管理员动作:普通角色与缺少同源意图都必须被挡在 SMTP 之前。
func TestWeeklyMailFormalSendRequiresAdminAndIntent(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "sent", MessageID: "<m@example.com>"}}
config := Config{QAWeeklyMail: store}
body := `{"revision":16,"body_sha256":"` + strings.Repeat("a", 64) + `"}`
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, "engineer", body, true), config)
if recorder.Code != http.StatusForbidden {
t.Fatalf("非管理员必须 403,status=%d body=%s", recorder.Code, recorder.Body.String())
}
recorder = httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, body, false), config)
if recorder.Code != http.StatusForbidden {
t.Fatalf("缺少同源操作意图必须 403,status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.calls != 0 {
t.Fatalf("被拒请求不得调用发送:calls=%d", store.calls)
}
}
// 成功补发必须把 week/版本/hash/操作人原样交给 store,并回传真实 message_id 与收件人数。
func TestWeeklyMailFormalSendPassesExactRevisionAndReturnsReceipt(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "sent", MessageID: "<real@example.com>", Recipients: 119, Cc: 8}}
config := Config{QAWeeklyMail: store}
hash := strings.Repeat("b", 64)
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+hash+`"}`, true), config)
if recorder.Code != http.StatusOK {
t.Fatalf("管理员补发应成功,status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.lastWeek != "2026-W45" || store.lastRev != 16 || store.lastHash != hash || store.lastActor != "tester" {
t.Fatalf("补发参数没有精确传递:week=%q rev=%d hash=%q actor=%q", store.lastWeek, store.lastRev, store.lastHash, store.lastActor)
}
var payload struct {
Data qawemail.ManualResult `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.MessageID != "<real@example.com>" || payload.Data.Recipients != 119 || payload.Data.Cc != 8 {
t.Fatalf("响应必须带回真实发送凭据与正式收件人数:%+v", payload.Data)
}
}
// 前置条件不满足必须给出具体原因,而不是冒充 SMTP 失败。
func TestWeeklyMailFormalSendExplainsRefusalsInsteadOfSMTPFailure(t *testing.T) {
cases := []struct {
name string
err error
status int
contains string
}{
{"future", qawemail.ErrFutureWeek, http.StatusBadRequest, "未来周"},
{"slot", qawemail.ErrSlotPending, http.StatusConflict, "尚未到达设定的发送时点"},
{"stale", qawemail.ErrNotCurrent, http.StatusConflict, "正文/版本已变化"},
{"inflight", qawemail.ErrSendInFlight, http.StatusConflict, "结果未知"},
{"nopassword", qawemail.ErrNoPassword, http.StatusConflict, "授权码"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
store := &fakeWeeklyMailStore{sendErr: tc.err}
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+strings.Repeat("c", 64)+`"}`, true), Config{QAWeeklyMail: store})
if recorder.Code != tc.status || !strings.Contains(recorder.Body.String(), tc.contains) {
t.Fatalf("%s 应 %d 且说明原因 %q,status=%d body=%s", tc.name, tc.status, tc.contains, recorder.Code, recorder.Body.String())
}
})
}
}
// SMTP 真实失败:必须 502 且带上真实原因,绝不能回“已发送”。
func TestWeeklyMailFormalSendReportsDeliveryFailure(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "failed", Reason: "发送失败:smtp 登录失败: 535"}}
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+strings.Repeat("d", 64)+`"}`, true), Config{QAWeeklyMail: store})
if recorder.Code != http.StatusBadGateway || !strings.Contains(recorder.Body.String(), "535") {
t.Fatalf("未送达必须 502 并带真实原因,status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
// 补发前预览必须给出真实 week/版本/收件人数,用于确认框;预览本身不投递。
func TestWeeklyMailSendPreviewShowsExactDistribution(t *testing.T) {
store := &fakeWeeklyMailStore{preview: qawemail.SendPreview{Status: "ready", Recipients: 119, Cc: 8}}
hash := strings.Repeat("e", 64)
request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/send/2026-W45?revision=16&body_sha256="+hash, nil)
request.SetPathValue("week", "2026-W45")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
recorder := httptest.NewRecorder()
qaWeeklyMailSendPreview(recorder, request, Config{QAWeeklyMail: store})
if recorder.Code != http.StatusOK {
t.Fatalf("预览应成功,status=%d body=%s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data qawemail.SendPreview `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.Recipients != 119 || payload.Data.Cc != 8 || payload.Data.Revision != 16 || payload.Data.Status != "ready" {
t.Fatalf("预览必须给出正式收件人数与版本:%+v", payload.Data)
}
if store.calls != 0 {
t.Fatal("预览不得触发发送")
}
}
+33 -3
View File
@@ -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
+9 -4
View File
@@ -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"`
+60
View File
@@ -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")
}
+53 -6
View File
@@ -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 负责在目标库
@@ -159,8 +169,12 @@ type Config struct {
LibraryTargetWriters []string
LibraryTargetIngressURL string
LibraryTargetIngressService string
LibraryTargetDockerSocket string
LibraryTargetJournalRoot string
// 入口形态与健康探针只用于如实展示"有没有闸门":none 显示"无闸门(测试模式)",
// 不能把没有闸门的测试栈说成"打开"。
LibraryTargetIngressMode string
LibraryTargetHealthURL string
LibraryTargetDockerSocket string
LibraryTargetJournalRoot string
// LibrarySourceInstance 是死信解除记录的来源实例名(封存源),留空回落到目标实例名。
LibrarySourceInstance string
// LibraryAgentSocket 是主机侧封存 agent 的 unix socket;留空即页面不能发起封存。
@@ -188,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
@@ -218,6 +235,8 @@ type Config struct {
DingtalkSources dingtalkSourcesLister
// DingtalkDocuments 列在线文档/表格并校验可读(只读,dws)。
DingtalkDocuments dingtalkDocLister
DWSLogin *dingtalkdiscovery.DeviceLoginManager
PPConnection *ppauth.Manager
NewID func() (string, error)
Auth *AuthConfig
}
@@ -239,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")
@@ -252,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) })
@@ -282,6 +308,8 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("DELETE /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/sends", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSends(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/test", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailTest(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/send/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSendPreview(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/send/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSend(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailImage(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/field-options", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldOptions(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/records/{id}/fields", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldPatch(w, r, config) })
@@ -371,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"})
@@ -388,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"})
@@ -402,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"})
@@ -559,6 +602,10 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("POST /api/v1/library/jobs/{id}/resume", func(w http.ResponseWriter, r *http.Request) {
libraryJobResume(w, r, config)
})
// 封存完成但终态回写失败时,只按已完成队列+精确版本+归档复核修复该作业。
mux.HandleFunc("POST /api/v1/library/jobs/{id}/reconcile-capture", func(w http.ResponseWriter, r *http.Request) {
libraryCaptureReconcile(w, r, config)
})
// 生产同步唯一入口:闸口未齐不建作业,返回缺项而不是假 Accepted。
mux.HandleFunc("POST /api/v1/library/syncs", func(w http.ResponseWriter, r *http.Request) {
librarySyncEnqueue(w, r, config)
+1 -1
View File
@@ -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
+91
View File
@@ -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)
}
}
}

Some files were not shown because too many files have changed in this diff Show More