Compare commits
98 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c5e033dd0e | |||
| 20fc40a147 | |||
| 045fc44f0e | |||
| 864a1632e0 | |||
| 9f990158b9 | |||
| 3dc854de4b | |||
| 76f687b52d | |||
| 2fc6dc068b | |||
| fe2e7ac4f4 | |||
| c4759bb61c | |||
| bf049cee1f | |||
| 55fba5fc0e | |||
| ce2f90c1c5 | |||
| 2c5ecdf0f3 | |||
| 9105f8316c | |||
| 74aef1e373 | |||
| 1b09f7d35b | |||
| d8d143eca0 | |||
| 52f4117835 | |||
| 7448d130ec | |||
| f0b12412a1 | |||
| 5b6e154459 | |||
| 8930ef29cd | |||
| a55d7f454e | |||
| b55292bba1 | |||
| 02ee5da231 | |||
| e744114ff4 | |||
| c8f05ee46f | |||
| 1e8d8e3cdf | |||
| 842bfccc1b | |||
| 740f0e69ba | |||
| 020cae1228 | |||
| 017cbcb851 | |||
| b3992bfa0f | |||
| 2902ba0af2 | |||
| 555bc6ff56 | |||
| 1dda055e4c | |||
| f87d3fad9b | |||
| 23b19350cc | |||
| 1a9d1fff83 | |||
| 822fb652ff | |||
| 600e9a2dc2 | |||
| eed83039ab | |||
| 43b1e423fe | |||
| 5aa32492de | |||
| 6816289552 | |||
| 1d33ff6976 | |||
| 1d880a0f49 | |||
| c239a5ef0e | |||
| 226d47a72d | |||
| 0f89c82625 | |||
| 9d8a40beab | |||
| 5d525ff592 | |||
| 09b2c1dce5 | |||
| 80d5078363 | |||
| 00c4c13283 | |||
| 65653e5c01 | |||
| ce02ae4eef | |||
| 8d44d54dc7 | |||
| 1c065846f6 | |||
| f38541db06 | |||
| f533c63fef | |||
| c56ab5850b | |||
| 1419ee03fc | |||
| 4e655fb977 | |||
| 99d6109bef | |||
| cb9f0c389f | |||
| 1580ebd826 | |||
| 2c0bb32183 | |||
| 87f97a2f9b | |||
| 154b0b62ad | |||
| 9470a127f7 | |||
| 4a2b2b7d84 | |||
| a9870beade | |||
| 533db535f1 | |||
| 330fd12b3f | |||
| f33730ed74 | |||
| f5e0f8d20f | |||
| 6e67034fbd | |||
| 76671e0784 | |||
| 8835a473dd | |||
| 93aabc8a81 | |||
| 3e7fcce0b1 | |||
| 74ba737b1e | |||
| 013ce4a24e | |||
| 90901a4458 | |||
| 3566f208e0 | |||
| 2ea2111420 | |||
| 828c2c5fa0 | |||
| 4b3aaff321 | |||
| 9556db1ef0 | |||
| 56b8cabed9 | |||
| cc4906b6a9 | |||
| 6adfdcdd4f | |||
| 5874134e04 | |||
| dab74b706b | |||
| fd04bf7886 | |||
| c1d49adb62 |
@@ -1,3 +1,34 @@
|
||||
# Optional independent source, disabled by default. Never use the app writer or
|
||||
# substitute DATABASE_URL. Backend credential file must be a regular 0600 file.
|
||||
DOBOTAI_OPS_READ_ENABLED=false
|
||||
DOBOTAI_OPS_READ_DSN_FILE=
|
||||
DOBOTAI_OPS_TENANT_KEY=
|
||||
DOBOTAI_OPS_DIAL_MODE=direct
|
||||
DOBOTAI_OPS_SSH_TARGET=
|
||||
DOBOTAI_OPS_CONNECT_TIMEOUT=5s
|
||||
DOBOTAI_OPS_QUERY_TIMEOUT=4s
|
||||
DOBOTAI_OPS_MAX_CONNS=2
|
||||
DOBOTAI_OPS_MIN_CONNS=0
|
||||
|
||||
# API and worker share this opt-in binding; no browser-selected paths/credentials.
|
||||
# Runtime root is the read-only existing weekly_report directory (SDK/config and
|
||||
# private secret file). Python must be compatible and already provide PyYAML.
|
||||
# Container deployment requires approved runtime/script mounts; not auto-installed.
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED=false
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT=
|
||||
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=
|
||||
# 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.
|
||||
QA_AI_TRUST_TLS_PROXY=false
|
||||
|
||||
APP_ADDR=:8080
|
||||
DATABASE_URL=postgres://governance@postgres:5432/governance?sslmode=disable
|
||||
PGPASSFILE=/run/secrets/pgpass
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
# Local artifacts (binaries, staging scripts, backups)
|
||||
/release-diag
|
||||
/worker
|
||||
/libraryctl
|
||||
/apply_s5_patch.py
|
||||
/tmp_*
|
||||
.style-backup-*/
|
||||
|
||||
+748
-2
@@ -1,10 +1,141 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 snapshot/v0.1.110 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 同一作业号重跑不再必然冲突:命令先读持久日志与已封存清单,按首次请求(时间、范围、契约、绑定库)幂等重放,`source_read=false`、`writers_stopped=false`;同一作业号换了范围或绑定库仍明确拒绝,已封存清单校验失败也拒绝。
|
||||
- 归档用量改按跨版本去重统计内容字节,并把清单、未被引用 blob、文件实际分配单独列出;不再把"各版本 unique 之和"当归档占用,也不再暗示可回收空间(真实两份清单:各版之和 55,309,695 字节,跨版本去重 55,309,693 字节,磁盘分配 55,373,824 字节)。
|
||||
|
||||
### Added
|
||||
|
||||
- 冻结窗口内的契约复核:窗口内重新读取来源契约,与窗口前不一致即中止(不封存、恢复写入者)。
|
||||
- 写入者组之外的同镜像容器检查:若有不属于声明组的运行中容器使用声明写入者的镜像,拒绝封存。
|
||||
- 补齐 `GET /api/v1/library/snapshots`、`GET /api/v1/library/snapshots/{id}` 的 OpenAPI 契约(上一版遗漏,契约测试可检出)。
|
||||
|
||||
### Changed
|
||||
|
||||
- 按用户确认取消 A06:文档、页面与接口说明不再把内容/问答/引用图片效果/性能测试列为封版或发布门槛;A04 数据完整性口径保留。
|
||||
|
||||
## 开发快照 snapshot/v0.1.108 - 2026-10-28
|
||||
|
||||
### Added
|
||||
|
||||
- 新增整库封存的真实业务入口 `libraryctl`(status / preflight / capture / list / verify / recover):从本机真实测试栈只读读取来源,核对处理已结清,推出兼容契约,在维护窗口内停住声明过的写入者,导出 PostgreSQL 十表、原始索引正文与向量、对象资源与 Wiki 快照,封存为内容寻址候选产物后恢复写入者并等到 healthy。
|
||||
- 新增按 Compose 项目固定身份的冻结控制器:整个项目逐服务声明,出现未声明服务或容器被重建即拒绝,只发 SIGTERM,恢复后必须 healthy。
|
||||
- 新增「整库版本」页(只读):对内/对外最新封存、分项数量与字节、摘要、兼容契约、归档占用;未接线时明确显示原因,不提供未实现的封存按钮。
|
||||
- 新增运维手册 `docs/library-capture.md`,含 2026-10-28 两次真实封存的快照 ID 与实测数字。
|
||||
|
||||
### Changed
|
||||
|
||||
- api 增加 `LIBRARY_ARCHIVE_ROOT` 与整库归档根的只读挂载(写入只发生在主机上的 libraryctl)。
|
||||
|
||||
### Not included
|
||||
|
||||
- 本快照不代表整库业务验收通过:内容/问答/性能验收未绑定,跨系统一致切点、Wiki 删除语义重算、生产预备份与恢复演练、双闸授权、整库同步协调与失败续作仍未完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.105 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复成功作业重放遗漏验收策略检查的问题:旧快照缺少当前策略标识时明确拒绝,不静默升级验收口径,不返回成功状态或快照 ID,也不重新暂停测试写入服务。
|
||||
- 新策略的正常重放与跨库、归档丢失等保护保持有效;此修复不代表内容/问答/性能验收绑定或整库业务链已经完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.104 - 2026-10-28
|
||||
|
||||
### Changed
|
||||
|
||||
- 按已确认的验收口径 A,正文索引作为原始产物保留,不再因无法从数据库反推临时生成上下文而拒绝候选归档;身份、覆盖、摘要及持久化生成问题的精确核验保持不变。
|
||||
- 候选清单加入受支持的验收策略标识并纳入快照身份。候选归档不代表语义验收或生产放行;真实冻结接线、快照绑定的内容/问答/性能验收与完整同步恢复仍待完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.103 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 整库索引校验支持从分块持久元数据核验生成问题:严格匹配分块、问题 source_id 与问题原文,拒绝未知、过期或内容不一致的索引。
|
||||
- 分开核验正文与生成问题的覆盖,问题记录不能掩盖正文索引缺失;元数据中已记录的问题缺少索引同样阻断。未放宽临时章节上下文或未知索引变换的检查。
|
||||
|
||||
## 开发快照 snapshot/v0.1.102 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 阻止旧式 status=0 普通分块缺失索引时被误判完整;仅明确的上下文父分块允许没有索引,显式标记已索引的分块仍须存在。
|
||||
- 缺少可核验的无索引策略时返回覆盖未证实,不推断索引已禁用;Wiki-only 无索引库的完整支持仍待实现,不因此宣称整库验收通过。
|
||||
|
||||
## 开发快照 snapshot/v0.1.101 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复正常正文索引因标题前缀或正文首尾空白处理而被整库归档误拒的问题;仅按已持久化的标题与正文重建确定性内容,保持逐字核验,不使用后缀包含匹配。
|
||||
- 无法由持久数据核验的临时章节上下文、非正文类型的变换及未知内容仍阻断;不将本次兼容修复视为完整索引或整库业务验收通过。
|
||||
|
||||
## 开发快照 snapshot/v0.1.100 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 测试封存暂停共享写入服务前及暂停后,强制检查整个源数据库的解析状态、待处理任务和死信;其他库、其他租户及已删除或未知任务范围的未完成工作均阻断封存。
|
||||
- 保留部署侧入口与后台作业检查;数据库任务结清不代表 Wiki 语义验收通过。本次未清理死信、未暂停实际测试 WeKnora、未执行生产发布。
|
||||
|
||||
## 开发快照 snapshot/v0.1.99 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复整库归档将 Wiki 页面与问题记录的字符串状态误按分块整数状态解析的问题;分块状态仅在分块表中解析,Wiki 状态和正文原样保留。
|
||||
- 候选捕获回归改用非空 Wiki 页面与问题记录,防止空表夹具漏检。本次仍不代表完整同步恢复业务已交付。
|
||||
|
||||
## 开发快照 snapshot/v0.1.98 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复整库候选封存只单向校验搜索索引的问题:数据库标记为已索引的分块必须在导出索引中存在,否则拒绝封存;按分块身份而非总数量核对,避免重复索引掩盖缺失。仅存储的父分块仍允许不建索引。
|
||||
- 本修复增强候选完整性,不代表整库业务入口、生产同步恢复或语义验收已经完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.97 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 补齐已部署 0.1.96 的独立开发说明与精确提交绑定,恢复版本记录核验所需的开发快照证据;不变更正式版本号,不声称整库同步已经交付。
|
||||
- 更正整库验收文档中仍写“未提交、未部署”的历史状态,保留未接线、未验收与生产执行边界。
|
||||
|
||||
## 开发快照 snapshot/v0.1.96 - 2026-10-27
|
||||
|
||||
目标提交:9105f8316cc870a62b5ddacd1496f0cb0f798d87
|
||||
|
||||
### Added
|
||||
|
||||
- 增加整库 PostgreSQL 只读快照、Elasticsearch PIT 导出及独立资源归档,包含完整 Wiki 表、资源关联和摘要校验。
|
||||
- 增加测试写入服务暂停、持久恢复日志、异常与进程中断恢复原语,并实现候选捕获协调函数。
|
||||
|
||||
### Changed
|
||||
|
||||
- 本版本仅交付基础模块:尚无整库业务调用入口、版本验收绑定、生产预备份与同步恢复工作流、新发布页面及完整存储治理。隔离测试通过不等于完整业务验收通过;不包含生产执行或实际清理授权。
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **「版本记录」页**(一级菜单第 5 项):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
|
||||
- 新增解析监控统一工作台:顶部运行指标与依赖卡片、下方单一文件处理表;来源文件与目标测试库归并最新版本,动作、阶段、状态分列,后端统一筛选、计数及分页。支持单条/跨页勾选重试和版本、失败、重试详情;测试库移除重试独立核验治理规则,不误走上传流程。取消六分页和手动开始入口,生产授权仍在发布管理;本次不改变后台自动调度策略,自动处理闭环需另行端到端验收。
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
|
||||
|
||||
- 问答运营按已确认口径显示知识覆盖率、回答正确率及原始分子/分母、排除数量与构成。使用完整筛选范围和当前有效人工优先结论,精确规则命中的未覆盖可进入覆盖分母;部分覆盖不算完全覆盖,待确认/未评估/失效/不计入按对应指标排除,零分母显示“暂无可计算数据”。返回独立规则版本,AI 模型与绩效范围仍未接入。
|
||||
|
||||
- 问答详情支持治理侧人工复核及不可变审计:覆盖、正确性、产品分类、问题类型、根因与理由由管理员明确填写,操作人取登录身份;保存后独立读回复核历史。保留源端判断和自动规则,输入变化使旧人工结论失效,已观测的内容回退不自动恢复旧结论;并发修改冲突、重复请求不重复留档。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。基础数量与本期经确认新增的质量比例分开显示;不接 AI 模型、不定义绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
|
||||
|
||||
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。
|
||||
- 「问答运营 → 区域使用」支持管理员从网页发起持久化通讯录同步,重复请求重放、进行中操作合并;按服务器固定范围注册后台执行器,未接线或未检测到心跳时不创建新任务。界面显示真实任务状态、不编造百分比;失败保留旧快照与区域规则,同步完成不覆盖未保存草稿。旧执行器丢失租约后不能激活结果,重启接管和已提交快照的续跑使用原任务。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- 区域归属表支持长部门路径换行,避免继承全局不换行规则后将生效区域与归属依据列挤出桌面面板。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。基础使用统计见本期新增,不代表绩效验收;翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- 新增治理侧组织快照与区域修订迁移、受确认保护的后台导入命令;不修改 DobotAI 原表或钉钉组织结构。
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估尚未接入,不标为第一阶段完成。
|
||||
- 治理侧重新检查答案:包含 `暂无已发布` 即未覆盖,引用和源端 covered 不能抵消;未命中仍待评估,源端规则单独保留作对照。独立只读源默认关闭、租户后端固定、管理员会话鉴权,源故障不回退治理主库;安全告警明确保留 TEMP/TLS 尚未整改状态。
|
||||
- **「版本记录」页**(一级入口):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
|
||||
- 新增只读接口 `GET /api/v1/build-info`(当前运行产物的构建身份)、`GET /api/v1/version-history`(快照游标分页,不返回伪造的 total)、`POST /api/v1/version-history/sync`(仅管理员手动同步,并发同步复用同一作业)。
|
||||
- 新增迁移 `000046_version_history`(提交记录 + 同步状态):`commit_sha` 是唯一身份,**版本号不是唯一键** —— 两个提交算出同一个开发号时各占一行,用 SHA 区分。
|
||||
- 「当前运行」只认运行产物注入的**完整 SHA 精确匹配**:匹配到就标该条;开发构建显式标注"开发构建";拿不到标识就显示"当前运行版本未知",**不拿最新 main 或最新 tag 顶替**;CI 成功不等于已部署。
|
||||
@@ -18,6 +149,10 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复钉钉新登记来源仍按旧离线目录身份取件的问题:从当前来源配置读取空间坐标,实时枚举所在目录并严格匹配节点身份;同名文件不替代、目录不完整不误报删除。修复解析监控遗漏 `version_id` 取件任务及缺少业务元数据的失败记录,正确显示失败原因、重试入口与历史。
|
||||
|
||||
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
|
||||
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
|
||||
@@ -52,9 +187,620 @@
|
||||
> **版本怎么走**(两行就够):
|
||||
> · **正式版本** = 下面那条 `## [x.y.z] - 日期`,是**发版事实**,由人批准后打注释 tag `vX.Y.Z`;
|
||||
> · **开发版本自动递增** = `<正式版本的主.次>.<自那个 tag 以来的提交数>`(正式 `0.1.0` 之后第 12 个提交 =
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**,**不写进本文件** ⇒ 每个提交都有自己的版本号,
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
|
||||
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.63 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 周报固定保留编辑正文与排版预览的对照界面,移除编辑/预览/对照切换按钮及无用模式状态/样式;自动保存、复制排版内容和下载保持不变。
|
||||
|
||||
## 开发快照 snapshot/v0.1.62 - 2026-10-25
|
||||
|
||||
### Added
|
||||
|
||||
- 周报增加“复制排版内容”,复制渲染后的富文本及可读纯文本,不复制Markdown标记或原文查看器;编辑/预览/对照模式均取当前最新正文,保留下载MD原文。兼容局域网HTTP复制并明确报告失败。
|
||||
|
||||
## 开发快照 snapshot/v0.1.61 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 周报中英文正文移除质量统计月份、时间范围及分母规则说明,保留覆盖率、正确率及原自然月计算口径与来源审计。
|
||||
|
||||
## 开发快照 snapshot/v0.1.60 - 2026-10-25
|
||||
|
||||
### Added
|
||||
|
||||
- 右侧问答详情顶部增加上一条、下一条,沿当前筛选后的完整已载入表格顺序切换;首尾自动禁用,后续页载入后自动开放下一条,读取中或失败仍能切换,关闭保留原表格焦点。
|
||||
|
||||
## 开发快照 snapshot/v0.1.59 - 2026-10-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- 流水表表头五项筛选不再传入统计看板;看板及PNG只按上方已查询的时间范围和关键词统计。保留表头对流水、明细导出及对应AI范围的限定,并拒绝将带字段筛选的返回误作全范围看板。
|
||||
|
||||
## 开发快照 snapshot/v0.1.58 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 问题流水表最左侧增加序号,按当前筛选结果从1连续编号,后台续载与虚拟滚动保持连续;不改变业务字段、原始数据或完整导出口径。
|
||||
|
||||
## 开发快照 snapshot/v0.1.57 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 五项质量筛选移至表格首行对应列,选择后立即查询;上方查询区不再增加字段选项,零匹配和续载时仍可调整表头条件。
|
||||
- 未覆盖问答的是否正确统一为待确认;仅未覆盖可显示待确认,已覆盖保留正确/错误及点踩优先。列表、详情、筛选、统计、完整导出和编辑约束共享同一有效规则,原始问答及历史人工/模型证据保留,不重新调用模型。
|
||||
|
||||
## 开发快照 snapshot/v0.1.56 - 2026-10-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- 五项字段筛选独立换行,保留时间、关键词、查询与同步操作的完整可见范围,修正宽屏旧单行样式挤出筛选区的问题。
|
||||
|
||||
## 开发快照 snapshot/v0.1.55 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 问题流水表首批到达即可浏览,后续在后台自动续载;列表仅传轻量文本预览,完整问答/引用/媒体按需读取,完整明细另行导出,避免等全部正文下载后才显示。
|
||||
- 新增是否覆盖、是否正确、产品分类、问题类型、根因分析五项筛选,可与时间/关键词组合并查询未设置值;后端按完整总表的当前有效标签筛选,列表、看板及导出条件一致。字段筛选时不套用无明细的历史汇总。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 续载异常明确保留已读部分和失败状态,查询变更取消旧请求;详情保存和AI更新不被迟到分页覆盖,完整导出拒绝使用截断预览或不完整结果。
|
||||
|
||||
## 开发快照 snapshot/v0.1.54 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 回答正确性改为直接依据原问题和实际回答判断:已覆盖只保留正确或错误,只有未覆盖允许待确认,不再要求引用原文作为正确结论的前提;未形成有效回答的技术状态保持未评估,点踩仍优先为错误。
|
||||
- 模型评估、人工复核和详情字段编辑共同约束上述规则。旧已覆盖待确认可限定为仅重评正确性,通过统一有效层写入和不可变审计更新,不修改原始问答、其他已维护字段或历史证据。
|
||||
|
||||
## 开发快照 snapshot/v0.1.53 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 版本记录按参考图重排为当前构建信息卡和紧凑折叠列表,当前运行记录默认展开,其他记录收起;变更按新增、调整、修复、安全分类展示,原始说明和提交信息可展开核验。
|
||||
- 增加所有角色可用的只读刷新,保留管理员同步、真实版本身份、筛选及完整历史加载;北京时间、长提交与手机排版统一处理,不增加发布或部署权限。
|
||||
|
||||
## 开发快照 snapshot/v0.1.52 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 移除系统顶部的已打开页面标签栏及关闭入口,保留左侧功能导航、当前位置、来源路径和表格分页。
|
||||
- 左侧导航文字放大至16px、图标放大至20px,图标区域24px、导航项最小高度44px,手机抽屉同步生效。
|
||||
|
||||
## 开发快照 snapshot/v0.1.51 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 按人视图也直接展示所属部门名称,多部门逐行显示、完整路径悬停可看,去掉“个直属部门”折叠摘要;列宽与按区域统一。两个排行复用同一展示实现,移除不再使用的旧分支和样式;统计、兼属和50人分页不变。
|
||||
|
||||
## 开发快照 snapshot/v0.1.50 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 按区域人员表“所属部门”直接显示部门名称,多部门逐行列出并保留完整路径悬停说明;移除该视图的“个直属部门”折叠入口。人员与部门列加宽,区域列收紧;按人视图保留原详情入口和列宽,排序、去重、周期与分页不变。
|
||||
|
||||
## 开发快照 snapshot/v0.1.49 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 区域统计“部门/人员”列移除“本部门直属 N 人”小字;保留独立总人数列、部门展开、直属人员明细和兼属标记,统计数据与其他分析视图不变。
|
||||
|
||||
## 开发快照 snapshot/v0.1.48 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 区域统计按部门表格将“总人数”独立为一列,放在“访问人数”前;移除原访问人数格内的小字总人数。保留含子部门的稳定身份去重口径,人员行对应总人数/访问人数/访问比例均显示“—”,不改变一级默认展开及另外两个分析视图。
|
||||
|
||||
## 开发快照 snapshot/v0.1.47 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 区域统计按部门视图默认只展开到一级部门,二级及以下初始收起;保留手动逐级展开、直属人员、既有统计口径及按区域/按人视图。
|
||||
|
||||
## 开发快照 snapshot/v0.1.46 - 2026-10-21
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计新增“按部门/按区域/按人”分析切换;按部门保留原树形与直属人员。按区域查看已保存区域内人员,按人查看完整去重名册,均按提问次数降序并保留零提问人员,固定50人/页与页码选择,展示区域、所属部门、次数和最近提问时间。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新分析复用同一累计/自然月/自然周快照,不额外创建模型或聚合作业;同区域多部门人员只列一次,跨区域及未归属者单列待核对,不自动选主区域。分析分页与切换只读,不改变原问答、区域映射、部门汇总、已保存周报及外部发送闸门。
|
||||
|
||||
## 开发快照 snapshot/v0.1.45 - 2026-10-21
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计部门展开后展示直属人员及直属人数;人员行保留本统计范围的提问次数、最近提问时间与零使用人员,多部门人员显示“兼属 N 部门”,悬停可查看完整部门路径,也可点击或键盘展开名单。人员行只读,不参与部门勾选或区域绑定。
|
||||
|
||||
### Changed
|
||||
|
||||
- 兼属按稳定身份的不同直接部门去重,不把祖先继承计为额外部门,不合并同名不同人。累计、自然月及自然周统计范围、分支/区域去重人数与次数保持,展开人员不会重复累计;无部门关联人员明确列出,未命名如实提示,不新增绩效裁决、源端修改或模型调用。
|
||||
|
||||
## 开发快照 snapshot/v0.1.44 - 2026-10-21
|
||||
|
||||
### Changed
|
||||
|
||||
- 问题统计看板去掉个人月明细入口,十一张卡片右上角新增“统计口径”,悬停、键盘聚焦及触屏可查看实际范围、公式与排除数量;图片导出保留完整十一项及口径入口,不包含交互浮层。
|
||||
- 覆盖率与正确率趋势改为北京时间逐自然月独立计算,每月1日重新累计;使用总表当前有效结论、人工优先及点踩否,分别按是÷(是+否)计算,待确认等排除,空月/零分母留空。旧周上报、冻结及第40–43周累计证据保留,不再混画到月轴。
|
||||
- 每周看板的两项质量仪表与新建/主动重新预填周报使用月内累计;跨月周取周一所在月并截止该月底,非跨月周截止该周实际时点,当前周不预读未来。保留已保存周报正文、修订与重试标识,不自动改写旧稿,不修改源问答或触发付费模型及对外发送。
|
||||
|
||||
## 开发快照 snapshot/v0.1.43 - 2026-10-20
|
||||
|
||||
### Added
|
||||
|
||||
- 知识覆盖率与回答正确率趋势新增第40–43周“总表累计”绿色曲线:按北京时间各自然周截止纳入整张总表的累计问题,使用当前有效字段及点踩结论动态计算;覆盖率和正确率分别使用“是÷(是+否)”,待确认等未明确结论不进入对应分母,零分母不伪造百分比。逐点展示实际截止、累计条数、分子分母及规则版本,保留原历史上报和冻结证据。
|
||||
- 字段依据区区分真实模型返回与本地规则/历史唯一标签复用:语言识别、中文原文保留及历史分类复用逐字段展示来源与回填状态,明确标注“非模型”,不把外部受控任务冒充平台服务模型配置。
|
||||
- 看板每30秒顺序读取最新总表,当前选周截止推进至当前时点,已闭周查询保持原范围;离开或换条件取消旧请求,读取失败明确提示,不展示过期图表或导出旧图。
|
||||
|
||||
## 开发快照 snapshot/v0.1.42 - 2026-10-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- 问题存在当前点踩时,总表有效“是否正确”固定为“否”,列表、详情和动态质量统计使用同一规则;通过已保存来源关联读取本地镜像最新反馈,避免导入快照漏掉后续点踩。仅点赞或无反馈不推定正确,原问答、旧模型结论、人工复核与字段修改审计保持不变。
|
||||
- 详情对已点踩问题锁定“是否正确”并简洁说明;后端拒绝改为“是”或“待确认”的冲突选择,其余字段仍可编辑。迁移59只补充派生读模型、反馈索引及总表快照失效通知,不回写 DobotAI 源数据,也不重算或覆盖旧周冻结与历史上报。
|
||||
|
||||
## 开发快照 snapshot/v0.1.41 - 2026-10-20
|
||||
|
||||
### Added
|
||||
|
||||
- 周报生成升级为按北京时间自然周保存的 Markdown 编辑器,提供编辑、预览、对照、自动保存、立即保存及 MD/本周明细 CSV 下载;每个租户每周一份共享草稿,切周或离开前保存未提交输入,刷新与重新打开恢复正文。
|
||||
- 按周报模板预填英文在上、中文在下的各六节正文,复用正式总表和已保存区域统计;历史周优先使用相应上报/冻结质量指标,缺失才使用当周实时指标。统计建议可人工修改,重点保留待填写,不编造 FAQ 调整或英文事项,不自动发送或归档。
|
||||
- 治理库新增迁移 58:独立稀疏字段覆盖、不可变字段改动审计、周草稿及逐版保存收据。保存绑定输入与编辑版本,同 nonce 重试不重复留档,冲突和读回失败保留输入;已有草稿重新预填须明确确认,存在人工数据时拒绝删除式降级迁移。
|
||||
|
||||
### Changed
|
||||
|
||||
- 详情顶部五个质量字段可直接下拉修改,范围取源主表实际使用的覆盖/正确性选项及与模型共享的产品、问题、根因字典;只保存明确选择的字段,不补齐其他空白、不把模型值冒充整条人工复核。移除单独人工复核/反馈展示,保留原始问答、旧人工历史和后台留痕。
|
||||
- 区域统计的月份及 ISO 周同时支持下拉选择和直接输入,合法值在回车或失焦后应用;未完成、非法及未来输入在本地提示,不发送错误统计请求,保留原自然月/周和缓存口径。
|
||||
|
||||
## 开发快照 snapshot/v0.1.40 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计明确支持按累计、北京时间自然月、北京时间自然周三种范围;自然周按周一至周日,可选择历史周,校验跨年周次、非法周和未来周,独立缓存包含周次及组织版本。
|
||||
|
||||
### Changed
|
||||
|
||||
- 部门树默认显示公司、中心及二级部门,更深层收起;保留手动展开与搜索,父行去重人数和提问次数不随收起变化。
|
||||
- 选中部门后在当前统计页选择区域并绑定,复用预览、双版本锁和保存后独立读回,不跳转另一张映射表;父选仍覆盖后代,既有非选中部门规则保留。
|
||||
- 区域设置重做为原页面内的名称列表面板,支持新增、改名、删除及未保存草稿保护。删除已绑定区域须确认解除直接绑定,目录与规则一次保存,不删除原问答;重复点击原删除位置只取消确认。
|
||||
- 区域筛选及绑定选项取已保存目录,新增/改名/删除后刷新,删除当前筛选项回全部;问题统计看板的平均使用频率和使用覆盖率沿用同一已保存组织配置,保留自然月口径与零分母未知,不重新计算冻结历史。
|
||||
|
||||
## 开发快照 snapshot/v0.1.39 - 2026-10-19
|
||||
|
||||
### Changed
|
||||
|
||||
- “问题流水”改为“问题流水表”;详情从右侧非模态弹出,不再生成左侧遮罩或焦点陷阱。移除详情中的区域、组织关联/版本/快照、记录来源、问答状态与流程触发人员展示,原始数据与审计不删除。
|
||||
- 是否覆盖、是否正确、产品分类、问题类型、根因分析置于详情顶部固定区域,正文独立滚动;查询与立即同步统一尺寸和基线。
|
||||
- 字段评估与中文翻译统一为“AI分析”,分别预览缺口、确认后按实际需要创建两类持久任务;部分成功重试保留幂等标识,跳过已确认种类与零缺口种类,不覆盖人工或已有非空结论。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 大流水表保留全量载入与无分页滚动,改为仅渲染可见行和缓冲行、稳定行引用及固定列宽;列表长文本限预览,详情与导出仍取完整原文,重复后台状态不再驱动整表刷新。
|
||||
- AI执行改为数据库准入控制的默认4并发、独立任务租约与过期栅栏;慢模型调用不阻塞其他工作槽或自动扫描。429遵守共享有界冷却;输出截断单独归因,最多三次有界重试并逐次扩大输出预算,最终失败保留可见状态。
|
||||
- 兼容源引用的knowledge_title字段,不将只有标题的引用伪造为正文证据;证据不足仍待确认,不将模型自报置信度当作准确率。修正人工复核区仍声称AI未接入的旧提示。
|
||||
|
||||
## 开发快照 snapshot/v0.1.38 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计新增可展开部门树:部门、访问人数、访问比例、访问次数、最近提问时间五列,访问人数附当前通讯录总人数;整支含自身和全部子部门,按稳定人员身份去重,调岗依当前归属,零分母显示“—”,收起不重算数字。
|
||||
- 统计仅读独立治理总表中的提问事件,支持累计与北京时间自然月;单并发后台聚合、请求合并和60秒缓存,目录或区域配置版本变化立即隔离旧缓存;加载/失败不伪装零数据,不占用代理转发链路。
|
||||
|
||||
### Changed
|
||||
|
||||
- 原“区域配置”入口改为“区域统计”,区域设置保留自定义区域新增/改名、未使用区域删除、部门映射预览与双版本锁保存;勾选父部门联选全部后代,取消子支时解除祖先整支选中,防止未选部门被父级新规则误覆盖。
|
||||
- 统计与区域设置共享选择;搜索、按区域查看及展开收起只改变可见行,既有总表、原始问答、历史趋势、模型任务与生产数据不修改。
|
||||
|
||||
## 开发快照 snapshot/v0.1.37 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 统计看板的覆盖率、正确率趋势支持独立持久保存的用户历史报表值,按北京时间ISO自然周展示、精确到两位小数并注明来源;和系统冻结使用分开的曲线,不伪造记录数、分子分母或冻结时间。
|
||||
|
||||
### Changed
|
||||
|
||||
- 历史汇总只影响两个趋势图,不覆盖当前周质量或原始问答;关键词筛选不挪用无明细的历史汇总,所选截止后的数据不提前展示,缺失周留空。页面和完整PNG共用相同绘图数据。
|
||||
- 增加治理侧迁移57:历史统计独立表保留来源指纹与导入审计,禁止原位覆盖/删除,存在历史数据时拒绝破坏性down;普通来源同步不能覆盖该表,不修改DobotAI生产或既有冻结证据。
|
||||
|
||||
## 开发快照 snapshot/v0.1.36 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 管理员可独立配置、真实测试问答评估模型;字段分析与原问题译中支持单条/筛选范围预览、后台持久批次、暂停/恢复/失败重试、真实进度及逐字段依据与模型版本。自动处理默认关闭,首次启用排除历史,关闭暂停未开始任务并停止新增。
|
||||
- 原问题采用本地语种识别,排除型号、协议、URL与代码的干扰;中文直接复用原文,外语译中保留原始问题和既有人工译文。历史流程人员摘要保留原对象,并使用明确稳定身份与谨慎的唯一姓名兜底关联目录。
|
||||
|
||||
### Changed
|
||||
|
||||
- 全部问答看板与PNG改读独立正式总表的有效字段,保留旧源和冻结历史,不把历史标签伪装成人工复核。覆盖固定执行精确连续文本规则A,模型只补正式字典内四字段,`待确认`、`未知`及正确行合法空根因不重复排队。
|
||||
- 流水查询/同步区紧凑展示,移除两条指定技术提示与常驻本地库数量,保留真实失败和权限阻断;支持双击详情与固定浅底深字标签。新增治理侧迁移54–56,不修改DobotAI源库;新源事件结束后才首次收录,后续源更新或删除仍不覆盖总表。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 总表有效字段使用明确版本来源,前端不再用旧纯规则/人工契约拒绝历史与AI有效标签;原源数据契约和非空人工结论仍严格校验。
|
||||
- 历史导入记录允许管理员手动补缺,正常自动入场仍限新成功问答;持久重试保留累计尝试次数与固定分母,过期租约及输入/人工版本漂移阻止迟到结果覆盖。
|
||||
|
||||
### Security
|
||||
|
||||
- 独立主密钥加密存储、write-only服务密钥、管理员同源操作、乐观版本和幂等收据;不回显或默认复制Agent密钥,录入仅有效HTTPS/本机回环。模型请求保留公网地址校验、禁止重定向与证书校验,允许独立安全DNS适配Fake-IP而不放宽私网边界。
|
||||
- 调用只携带所需原问答/获准片段,不发送无关人员与部门;保持原始payload与历史非空业务值,不回写源生产库、不启动全历史处理或外部发送。
|
||||
|
||||
## 开发快照 snapshot/v0.1.33 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 问题流水读取治理侧独立正式总表,合并历史 Excel 与已收录的 2.0 问答;历史译文、答案、覆盖/正确标注、分类及人员字段保留原值,缺失不造值,来源可辨。
|
||||
- 新增受输入哈希、已批准逐行清单和真实恢复备份约束的历史导入命令,固定首表与提问时间/提问人/原始问题组合;保留批次、原字段、行号、重复跳过与缺字段暂缓证据。重复导入只读回收据,不覆盖后续主表修改。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增治理侧加表迁移 53。2.0 镜像仍独立同步,正式主表只接收新事件;稳定来源关联与原始事件键不随本地修改丢失,源端更新和删除不覆盖或清除主表。
|
||||
- 主表评估/复核与可替换的源副本分开持久化;首次收录保留已有评估及审计来源,后续人工复核绑定主表自身的输入版本,不被源同步失效。原 2.0 看板、历史冻结及周报统计范围不因导入被静默混算。
|
||||
|
||||
### Security
|
||||
|
||||
- 主表列表、详情、复核与历史接口复用固定租户、管理员会话、严格参数、同源写意图、乐观锁和幂等回执;拒绝缓存、稳定 ID 与原始溯源不可漂移。字段计数和质量范围只读标量元数据,不为全范围统计解压长答案。
|
||||
- 导入仅连接本地治理库,不连接或修改 DobotAI 2.0 生产源、现有隧道与外部表;应用回退保留加表,有历史导入、本地修改或新增复核时拒绝有损结构回退。
|
||||
|
||||
## 开发快照 snapshot/v0.1.32 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问题统计看板按参考布局提供完整十一项:2.0 累计问题、本周新增、覆盖率与正确率半环、问题类型饼图、产品横条排行、所选自然周逐日折线、区域平均使用频率与使用覆盖率、两条历史质量周趋势。未知分类保留为未分类,未知分母及历史缺失点不伪造为零。
|
||||
- 支持导出当前完整看板 PNG,包含所有图形、中文、图例与数值,独立于屏幕滚动高度;不包含导航、筛选控件、按钮或个人月明细。桌面与窄屏共享同一份数据及响应式图形。
|
||||
- 治理侧保存自然周质量冻结快照与逐条标量贡献;普通 worker 在符合采集条件的下一周一自动冻结上一周,保存实际时点、源观测、版本和分子分母。首次启用前、错过采集或没有完整观测的历史周保持空白,后续人工改判不回写已冻结比率。
|
||||
|
||||
### Changed
|
||||
|
||||
- 看板通过单一只读一致性接口聚合治理副本、有效质量与组织版本,不连接源端、不下载全部长答案;累计、所选自然周和截止月分别计算,原问题关键词按字面筛选。区域分母使用配置后的通讯录去重人数,仅用于使用统计,个人月明细与四页共享查询保留。
|
||||
- 新增加表迁移 52。应用回退保留加表;发现冻结历史时拒绝有损 down。未接入翻译/AI 评估模型、绩效名单、1.0 归档或自动发送。
|
||||
|
||||
### Security
|
||||
|
||||
- 统计接口维持固定租户、管理员会话、同源动作头、严格 JSON 和 no-store;输入指纹变化返回冲突,不混合新旧结论。数据库拒绝修改、删除或追加已提交的冻结贡献;浏览器查询不写指标,PNG 使用自包含 SVG,不加载外部图片或执行原始 HTML。
|
||||
|
||||
## 开发快照 snapshot/v0.1.31 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 区域配置支持新增、改名业务区域;稳定区域 ID 与部门映射同版本保存,改名不丢失归属。部门按一级、二级、三级及更深层级展示,支持层级/完整路径筛选、多选及批量归属。
|
||||
- 勾选、批量应用、预览和保存分离;取消本次勾选不删除既有映射,批量配置父部门不清除未选子部门的显式规则。预览核对去重人数,保存后独立读取并校验配置版本。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增治理库迁移 51,为历史区域修订补齐原四区目录;业务目录与映射原子留档,跨页问答、看板、使用统计、个人月明细和周报共用同一版本及名称。旧请求未传目录时沿用当前目录,不恢复固定四区白名单。
|
||||
- 迁移回退发现自定义区域历史时拒绝丢失目录;应用回退可保留加列迁移。统计人数不升级为在职或绩效分母,不改钉钉组织、DobotAI 原始数据及旧 Excel 流程。
|
||||
|
||||
### Security
|
||||
|
||||
- 配置请求拒绝缺失版本、重复 JSON 字段及嵌套 null;区域目录校验稳定 ID、重名及保留键,名称按文本展示,自定义名称不读取原型属性。保留管理员同源写入、租户隔离和双版本冲突保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.30 - 2026-10-18
|
||||
|
||||
### Changed
|
||||
|
||||
- 继续清理问答运营的冗余提示:质量统计移除完整范围留档、模型接入和读取时间说明;个人月明细移除重复的绩效/零记录解释及读取时间,保留实际数量、范围版本、分页和真实错误。质量统计按钮使用简短名称,不改统计与审计逻辑。
|
||||
|
||||
## 开发快照 snapshot/v0.1.29 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营调整为“问题流水、问题统计看板、区域配置、周报生成”四页,流水与看板共用年份、自然周和查询条件;区域页不再显示问题查询框,完整字段及人工复核入口保留。
|
||||
- 重做统计看板:展示完整筛选范围的问题量、覆盖率、正确率、人工复核、北京时间每日趋势、质量分布、区域、问题类型和产品分类;个人月明细折叠保留,未知分类与零分母不虚构结论。
|
||||
- 周报页提供手动草稿、Markdown 预览及 MD/完整明细 CSV 下载。核对副本版本、完整数量、质量范围与覆盖分布后生成;CSV 保留完整十五列并防护公式注入,不发送、不归档、不作为正式持久化周报验收。
|
||||
|
||||
### Changed
|
||||
|
||||
- 删除问答记录、同步栏和区域页中的冗余解释文字、读取时间与源连接提示,保留真实错误、未同步、权限阻断和安全告警。
|
||||
|
||||
## 开发快照 snapshot/v0.1.28 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营新增持久本地副本,每 5 分钟后台同步并支持立即同步;列表、详情、检索、质量范围和使用统计改为读取本地数据库。
|
||||
- AI 答案详情提供安全 Markdown 预览与原文查看,支持表格、代码块和链接;不执行原始 HTML,外部图片默认不请求。
|
||||
|
||||
### Changed
|
||||
|
||||
- 增加治理侧问答副本表与同步状态;同步由普通 worker 执行,使用独立只读源连接,源失败保留最后成功副本,权限校验失败阻断读取。
|
||||
- 副本激活与质量输入变化的复核失效同事务提交;同步持久去重、租约校验及重启恢复不改变源问答或现有生产写入。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 本地读取不再逐条重复写质量留档或解压完整范围长答案来统计字段,保留完整列、输入版本一致性和真实缺失值。
|
||||
- 初次观察即已同步完成时自动重查列表,避免较早的首次未同步错误一直停留。
|
||||
|
||||
## 开发快照 snapshot/v0.1.27 - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- 并行分支存在同号开发提交时,历史变更说明与补记标签计划按完整 SHA 选择,不再被前一条同号记录遮蔽;不强改推导版本号或移动既有标签。
|
||||
|
||||
## 开发快照 snapshot/v0.1.26 - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- 版本记录收录已交付开发快照与当前运行提交,不再只同步 main;开发版本显示对应的独立变更说明。
|
||||
- 修复同步重复返回旧已完成任务:进行中同步合并,完成后允许新一轮同步。
|
||||
- 构建启动后自动请求版本同步;部署后独立读回当前完整 SHA、开发标签与变更说明,缺失时不宣称交付完成。
|
||||
|
||||
### Added
|
||||
|
||||
- 增加开发快照计划、显式发布及远端读回工具;历史说明按原提交补记,正式 tag 与 Release 保持独立授权。
|
||||
|
||||
## 开发快照 snapshot/v0.1.25 - 2026-10-18
|
||||
|
||||
目标提交:90901a4458054aca721047c9a2896f2130d46b5c
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.24 - 2026-10-18
|
||||
|
||||
目标提交:3566f208e0e15fdec2cc98c29f93c46f5f7c91ca
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
|
||||
|
||||
## 开发快照 snapshot/v0.1.23 - 2026-10-18
|
||||
|
||||
目标提交:2ea2111420e501fec37e0ea0c4bcd3cd8c866403
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.22 - 2026-10-18
|
||||
|
||||
目标提交:828c2c5fa0d4e3e0eee3987085a4d782872f7e95
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营按已确认口径显示知识覆盖率、回答正确率及原始分子/分母、排除数量与构成。使用完整筛选范围和当前有效人工优先结论,精确规则命中的未覆盖可进入覆盖分母;部分覆盖不算完全覆盖,待确认/未评估/失效/不计入按对应指标排除,零分母显示“暂无可计算数据”。返回独立规则版本,AI 模型与绩效范围仍未接入。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。基础数量与本期经确认新增的质量比例分开显示;不接 AI 模型、不定义绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
## 开发快照 snapshot/v0.1.21 - 2026-10-17
|
||||
|
||||
目标提交:4b3aaff3219e78ae3dfd5d12ba36f82e323a21ba
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答详情支持治理侧人工复核及不可变审计:覆盖、正确性、产品分类、问题类型、根因与理由由管理员明确填写,操作人取登录身份;保存后独立读回复核历史。保留源端判断和自动规则,输入变化使旧人工结论失效,已观测的内容回退不自动恢复旧结论;并发修改冲突、重复请求不重复留档。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。仅提供数量,不接 AI 模型、不定义质量率或绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
## 开发快照 snapshot/v0.1.20 - 2026-10-17
|
||||
|
||||
目标提交:9556db1ef01add21064553f64be6a7e25f838e9e
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
|
||||
|
||||
## 开发快照 snapshot/v0.1.19 - 2026-10-17
|
||||
|
||||
目标提交:56b8cabed9213911b6beb4aeaac9baa22e872a00
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。基础使用统计见本期新增,不代表绩效验收;翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估尚未接入,不标为第一阶段完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.18 - 2026-10-17
|
||||
|
||||
目标提交:cc4906b6a9f33683a5c0017d83b24d96d5c997b1
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 「问答运营 → 区域使用」支持管理员从网页发起持久化通讯录同步,重复请求重放、进行中操作合并;按服务器固定范围注册后台执行器,未接线或未检测到心跳时不创建新任务。界面显示真实任务状态、不编造百分比;失败保留旧快照与区域规则,同步完成不覆盖未保存草稿。旧执行器丢失租约后不能激活结果,重启接管和已提交快照的续跑使用原任务。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件;问答组织关联尚未接入。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。当前不是使用/绩效统计验收,翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
|
||||
## 开发快照 snapshot/v0.1.17 - 2026-10-17
|
||||
|
||||
目标提交:6adfdcdd4fe0e5c35018bf0e4857c203dd24e5d1
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 区域归属表支持长部门路径换行,避免继承全局不换行规则后将生效区域与归属依据列挤出桌面面板。
|
||||
|
||||
## 开发快照 snapshot/v0.1.16 - 2026-10-17
|
||||
|
||||
目标提交:5874134e049b0896a202b41d9d400d1be5386f89
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件;网页触发的后台同步队列及问答组织关联尚未接入。
|
||||
|
||||
## 开发快照 snapshot/v0.1.15 - 2026-10-17
|
||||
|
||||
目标提交:dab74b706b5b87da3ecb71a8e0f6b6caa5fba4ad
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。当前不是实时通讯录同步或使用/绩效统计验收,翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- 新增治理侧组织快照与区域修订迁移、受确认保护的后台导入命令;不修改 DobotAI 原表或钉钉组织结构。
|
||||
|
||||
## 开发快照 snapshot/v0.1.14 - 2026-10-17
|
||||
|
||||
目标提交:fd04bf7886aa4eba68b247dd7c1092894a5282da
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估、人员区域映射尚未接入,不标为第一阶段完成。
|
||||
- 治理侧重新检查答案:包含 `暂无已发布` 即未覆盖,引用和源端 covered 不能抵消;未命中仍待评估,源端规则单独保留作对照。独立只读源默认关闭、租户后端固定、管理员会话鉴权,源故障不回退治理主库;安全告警明确保留 TEMP/TLS 尚未整改状态。
|
||||
- **「版本记录」页**(一级入口):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
|
||||
|
||||
## 开发快照 snapshot/v0.1.13 - 2026-10-14
|
||||
|
||||
目标提交:c1d49adb622f3bf18e51bddb415795a894ed227e
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 补三Agent交接闭环工作流(状态机、快照tag与验收模板)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.12 - 2026-10-14
|
||||
|
||||
目标提交:9a8a3e77956149d116360bbb561efd67e20fb062
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
|
||||
## 开发快照 snapshot/v0.1.11 - 2026-10-14
|
||||
|
||||
目标提交:2c7265efc47a2cd6b324bf278fa5ddb0c4a9fe57
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → 数据源配置」**收敛成两个入口**:**dws 导入**(按当前钉钉账号列出可访问的知识库与钉盘空间)与 **PP 导入**。AList(已由钉盘文件替代)、静态登记的钉钉知识库、本地手工导入与 PP legacy 都**不再出现在这一页**;已接入的这类来源用**归档**下架(`POST /api/v1/source-connections/{id}/archive`,管理员、幂等,带写意图头与幂等键):从列表、来源与目录、计划刷新与手动扫描里消失,**目录快照、发布记录与审计数据一行不删**。恢复用 `…/restore`(保持停用、不自动带回调度),或让 dws 重新登记同一来源 —— 钉钉空间登记是确定性 ID + `ON CONFLICT`,**原地复活同一行、不产生重复**。卡片上新增「去掉来源」按钮(管理员,带确认弹窗)。
|
||||
- 迁移 `000047_source_connection_archive`:新增 `archived_at` / `archived_by` 与只覆盖未归档行的部分索引;列表、目录、计划刷新、手动扫描四类查询一律排除归档行(漏一条就等于入口没去掉)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.10 - 2026-10-14
|
||||
|
||||
目标提交:64b32c2da64881b3c9bf6de6b8f9af3f833128fd
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → 数据源配置」默认只列 PP 资料与「可加入的来源」:AList 来源(已由钉盘文件替代)与静态登记的钉钉知识库来源(改为按当前钉钉账号发现)**不再默认列出**,收进「显示 AList/钉钉知识库来源(N)」折叠开关 —— **来源一个都没删**,展开后照旧可改刷新周期与启停,「来源与目录」里的内容不变。手动导入来源(本地手工验收)不在这次范围内,照旧显示。
|
||||
|
||||
## 开发快照 snapshot/v0.1.9 - 2026-10-14
|
||||
|
||||
目标提交:b7f7e4f12101569db5bb76af9d836043eefc342b
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- **上线前护栏 + 事故复盘**:`scripts/deploy-api-web.sh` 现在先校验 `.env` 的键值形状(值里再出现 `KEY=` 或键名不合法 ⇒ **拒绝上线**),配置校验失败时也会给出"两行粘成一行"的线索。事故:`.env` 最后一行没有结尾换行、又被追加新键 ⇒ 两行粘成一行 ⇒ `VERSION_HISTORY_GITEA_BASE_URL` 变成非法值 ⇒ api/worker 按设计拒绝启动、崩溃重启(平台整体不可用)。已修数据、加护栏、加回归用例。
|
||||
|
||||
## 开发快照 snapshot/v0.1.8 - 2026-10-14
|
||||
|
||||
目标提交:4cb51108454c3559e8a6305ad3316f74ed4e2daf
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 「版本记录」页的链接改为**抓取与链接分离**:抓取仍走配置的(内网)地址,页面上的「查看提交 / 查看 tag」用 `VERSION_HISTORY_LINK_ORIGIN`(公网 origin)拼 —— 原先两者共用内网地址,内网外的浏览器点开是空白;另外 tag 记录原先不带链接(空 `href` 点下去没反应),现在补上链接、没有链接就不渲染该按钮。
|
||||
|
||||
## 开发快照 snapshot/v0.1.7 - 2026-10-14
|
||||
|
||||
目标提交:90db243a68a5d16d643dd0273614b93666d65ca7
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
|
||||
|
||||
## 开发快照 snapshot/v0.1.6 - 2026-10-14
|
||||
|
||||
目标提交:062a3b3cb60ede5ebcca64a0f14df53fffa1f359
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 前端入口的缓存策略:`index.html` 此前没有缓存头,CDN/浏览器会启发式缓存它,于是**页面会一直停在旧构建上**(实测被腾讯云 EdgeOne 卡住:源站已是新包,公网入口仍发旧包,看起来像"新菜单/新页面没上线")。现在 `index.html` 每次回源校验(`no-cache, must-revalidate`)、带内容哈希的 `/assets/` 长缓存(`immutable`),旧哈希资源明确 404 而不是回退成 HTML。
|
||||
|
||||
## 开发快照 snapshot/v0.1.5 - 2026-10-14
|
||||
|
||||
目标提交:4d43a9386a8a97969a1568956213f6f17b13edfb
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- tag 之前的提交不再被编号 + 部署脚本注入构建身份。
|
||||
|
||||
## 开发快照 snapshot/v0.1.4 - 2026-10-13
|
||||
|
||||
目标提交:0974d8dfa2aad5650eefbcee3edb365a8afd4868
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- **「版本记录」页**(一级菜单第 5 项):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
|
||||
- 新增只读接口 `GET /api/v1/build-info`(当前运行产物的构建身份)、`GET /api/v1/version-history`(快照游标分页,不返回伪造的 total)、`POST /api/v1/version-history/sync`(仅管理员手动同步,并发同步复用同一作业)。
|
||||
- 新增迁移 `000046_version_history`(提交记录 + 同步状态):`commit_sha` 是唯一身份,**版本号不是唯一键** —— 两个提交算出同一个开发号时各占一行,用 SHA 区分。
|
||||
- 「当前运行」只认运行产物注入的**完整 SHA 精确匹配**:匹配到就标该条;开发构建显式标注"开发构建";拿不到标识就显示"当前运行版本未知",**不拿最新 main 或最新 tag 顶替**;CI 成功不等于已部署。
|
||||
|
||||
### Security
|
||||
|
||||
- 版本记录同步**匿名只读**远端仓库(**不使用任何凭据**),来源限配置里批准的 origin 与固定仓库:拒绝任意 URL、拒绝跨主机重定向,单个响应设大小上限与超时、5xx/429 才有退避重试。
|
||||
- 提交正文与变更记录一律按**纯文本**渲染(不产生 HTML/脚本注入面);页面不含打 tag / 发布 / 部署入口;同步动作仅管理员可用,服务端再次判角色。
|
||||
|
||||
## 开发快照 snapshot/v0.1.3 - 2026-10-13
|
||||
|
||||
目标提交:ad9c5d20d467a077e88bbfe63b1a56355d263e51
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- Merge remote-tracking branch 'origin/main'。
|
||||
|
||||
## 开发快照 snapshot/v0.1.1 - 2026-10-13
|
||||
|
||||
目标提交:3a1d32da8fba90eb5081865b1f3ad424a46639ee
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 重写平台定位与能力边界并归档原说明。
|
||||
|
||||
## 开发快照 snapshot/v0.1.1 - 2026-10-13
|
||||
|
||||
目标提交:950c1b429bc814d9fa7c2c1449f999a05537af21
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 抬档门禁(破坏性 ⇒ 0.x 抬次 / ≥1.0.0 抬主)+ 1.0.0 前置(稳定契约承诺)。
|
||||
|
||||
## [0.1.0] - 2026-10-13
|
||||
|
||||
### Added
|
||||
|
||||
@@ -125,6 +125,16 @@ make list # 查看检查清单与适用范围
|
||||
|
||||
版本与变更见 [CHANGELOG](CHANGELOG.md),正式版本流程见 [发布 Runbook](docs/RELEASE_RUNBOOK.md)。`make version` 查看构建身份;日常开发构建与正式构建分开标识,软件版本 tag 不等同于知识发布批次。
|
||||
|
||||
## 问答运营模型配置
|
||||
|
||||
管理员在「系统设置 → 服务配置 → 问答评估模型」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
|
||||
API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。
|
||||
|
||||
当本机代理的 Fake-IP DNS 导致公网端点被安全守卫拒绝时,可仅为这两个治理组件设置 `QA_AI_DNS_OVER_TLS=alidns`:通过证书验证的公共 DNS-over-TLS 解析,再按同样的公网 IP、HTTPS 和禁止重定向规则发请求;不修改系统 DNS、代理或隧道,不允许以启用私网访问替代修复。
|
||||
|
||||
问题流水支持先预览已执行筛选/单条范围,再创建持久后台批次;字段分析和原问题译中独立计数,仅补真正空白。暂停不撤回已发请求,共享任务若仍被另一活动批次需要会继续执行;恢复或重试失败项不扩大原批次分母。详情保留逐字段依据、模型/提示词版本及回填/跳过说明。自动处理首次启用排除历史,关闭暂停未开始的自动任务,重开恢复披露的增量积压;不因保存配置而全量外发。
|
||||
|
||||
## 后续方向
|
||||
|
||||
- 扩展多数据源调度与增量同步的覆盖范围。
|
||||
|
||||
+1235
-1
File diff suppressed because it is too large
Load Diff
@@ -20,7 +20,12 @@ import (
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"knowledge-governance/internal/qawemail"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
"knowledge-governance/internal/version"
|
||||
)
|
||||
|
||||
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
|
||||
@@ -28,13 +33,29 @@ import (
|
||||
// (见 compose.yaml 的 /data/dws 与文件型 keychain 挂载)——凭据只有一份。
|
||||
type dingtalkSourceLister struct{}
|
||||
|
||||
func (dingtalkSourceLister) ReadDWSMetadata(ctx context.Context) (dingtalkdiscovery.CredentialStatus, error) {
|
||||
return dingtalkdiscovery.ReadCredentialStatus(ctx, dingtalkdiscovery.ExecRunner{})
|
||||
}
|
||||
|
||||
func (dingtalkSourceLister) ListAvailableDingtalkSources(ctx context.Context) (dingtalkdiscovery.Result, error) {
|
||||
return dingtalkdiscovery.Discover(ctx, dingtalkdiscovery.ExecRunner{})
|
||||
}
|
||||
|
||||
// 同一份 dws 凭据也用来列在线文档/表格并校验可读。
|
||||
func (dingtalkSourceLister) ListDingtalkDocuments(ctx context.Context, query string, limit int) (dingtalkdiscovery.DocResult, error) {
|
||||
return dingtalkdiscovery.DiscoverDocs(ctx, dingtalkdiscovery.ExecRunner{}, query, limit)
|
||||
}
|
||||
|
||||
func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node string) (dingtalkdiscovery.DocumentNode, error) {
|
||||
return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node)
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if len(os.Args) == 2 && os.Args[1] == "--version-record-status" {
|
||||
os.Exit(versionRecordStatus(ctx, os.Getenv))
|
||||
}
|
||||
if err := run(ctx, os.Getenv); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -124,8 +145,41 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
|
||||
if config.VersionHistoryGiteaBaseURL != "" {
|
||||
versionHistoryStore, versionHistoryRepo = postgresstore.NewStore(pool), config.VersionHistoryRepo
|
||||
info := version.Snapshot()
|
||||
if info.IdentityAvailable && info.CommitSHA != nil {
|
||||
if _, e := actionStore.EnqueueVersionHistorySync(ctx, config.VersionHistoryRepo, "system:deployment", *info.CommitSHA, time.Now()); e != nil {
|
||||
log.Print("version history deployment synchronization could not be queued")
|
||||
}
|
||||
}
|
||||
}
|
||||
qaReader, qaSettings := openQAOperations(ctx, getenv, config.DatabaseURL, pool)
|
||||
if closer, ok := qaReader.(interface{ Close() }); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
if qaSettings.Problem != "" {
|
||||
log.Print("QA operations source is unavailable; governance remains online")
|
||||
}
|
||||
qaOrganizationStore := qaopsorg.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY"))
|
||||
qaSyncSettings, qaSyncErr := qaopsorg.LoadSyncSettings(getenv)
|
||||
if qaSyncErr != nil {
|
||||
log.Print("QA directory synchronization is not configured; governance remains online")
|
||||
}
|
||||
var qaSyncStore httpapi.QAOrgSyncStore
|
||||
if getenv("DOBOTAI_OPS_TENANT_KEY") != "" {
|
||||
qaSyncStore = qaOrganizationStore
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
QAAI: qaopsai.NewFromEnvironment(pool, getenv, config.DatabaseURL),
|
||||
QAWeeklyMail: qawemail.NewStore(pool, qaSettings.TenantKey, getenv("QA_AI_MASTER_KEY_FILE"), nil),
|
||||
QAAITrustTLSProxy: getenv("QA_AI_TRUST_TLS_PROXY") == "true",
|
||||
QAQuality: qaopsquality.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY")),
|
||||
QAOrgSync: qaSyncStore,
|
||||
QAOrgSyncEnabled: qaSyncErr == nil && qaSyncSettings.Enabled,
|
||||
QAOrg: qaOrganizationStore,
|
||||
QAOps: qaReader,
|
||||
QAOpsTenantKey: qaSettings.TenantKey,
|
||||
QAOpsEnabled: qaSettings.Enabled,
|
||||
QAOpsProblem: qaSettings.Problem,
|
||||
Store: postgresstore.NewStore(pool),
|
||||
Monitor: monitorProvider,
|
||||
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
|
||||
@@ -143,9 +197,11 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
ProductionReleaseAuthorizationToken: releaseAuthorizationToken,
|
||||
// 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。
|
||||
DingtalkSources: dingtalkSourceLister{},
|
||||
DingtalkDocuments: dingtalkSourceLister{},
|
||||
BackupSchedule: postgresstore.NewStore(pool),
|
||||
VersionHistory: versionHistoryStore,
|
||||
VersionHistoryRepo: versionHistoryRepo,
|
||||
LibraryArchiveRoot: config.LibraryArchiveRoot,
|
||||
BackupHost: backuphost.New(backuphost.Config{
|
||||
SSHConfig: config.BackupHostSSHConfig,
|
||||
Target: config.BackupHostTarget,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/httpapi"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// API serving never constructs or probes a production-source client. The worker
|
||||
// alone synchronizes the explicitly authorized local copy; this is not a fallback.
|
||||
func openQAOperations(_ context.Context, getenv func(string) string, governanceDSN string, pool *pgxpool.Pool) (httpapi.QAOpsReader, dobotaiops.Settings) {
|
||||
settings := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !settings.Enabled {
|
||||
return nil, settings
|
||||
}
|
||||
if settings.TenantKey == "" || len(settings.TenantKey) > 128 || strings.ContainsRune(settings.TenantKey, 0) {
|
||||
settings.Problem = "local_mirror_tenant_invalid"
|
||||
return nil, settings
|
||||
}
|
||||
// Missing/offline source credentials stop synchronization, not last-good local reads.
|
||||
settings.Problem = ""
|
||||
return qaopsmirror.NewStore(pool, settings.TenantKey), settings
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAOpsConnectionFailureIsContainedOutsideMainDatabase(t *testing.T) {
|
||||
reader, settings := openQAOperations(context.Background(), func(string) string { return "" }, "postgres://main@host/governance", nil)
|
||||
if reader != nil || settings.Enabled || settings.Problem != "" {
|
||||
t.Fatal("QA operations must be disabled by default")
|
||||
}
|
||||
env := map[string]string{"DOBOTAI_OPS_READ_ENABLED": "true", "DOBOTAI_OPS_TENANT_KEY": "approved-tenant", "DOBOTAI_OPS_READ_DSN_FILE": "/nonexistent-qaops-fixture-secret"}
|
||||
reader, settings = openQAOperations(context.Background(), func(k string) string { return env[k] }, "postgres://main@host/governance", nil)
|
||||
if reader == nil || !settings.Enabled || settings.Problem != "" {
|
||||
t.Fatal("API serving still constructs a source connection instead of a local reader")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/version"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Operator-only read-back in the existing API binary; no new public endpoint,
|
||||
// no session/credential creation and no migrations or remote forge access.
|
||||
func versionRecordStatus(ctx context.Context, getenv func(string) string) int {
|
||||
info := version.Snapshot()
|
||||
if !info.IdentityAvailable || info.CommitSHA == nil {
|
||||
return printVersionStatus(false, "build_identity_missing", "")
|
||||
}
|
||||
config, e := appconfig.Load(getenv)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "configuration_invalid", *info.CommitSHA)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
pool, e := pgxpool.New(ctx, config.DatabaseURL)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "database_unavailable", *info.CommitSHA)
|
||||
}
|
||||
defer pool.Close()
|
||||
tag := "snapshot/v" + info.DisplayVersion
|
||||
kind := "development"
|
||||
if info.BuildKind == "release" {
|
||||
tag = "v" + info.DisplayVersion
|
||||
kind = "release"
|
||||
}
|
||||
evidence, _ := json.Marshal([]map[string]any{{"name": tag, "annotated": true}})
|
||||
var ready bool
|
||||
e = pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM version_history_commits c WHERE repo_key=$1 AND commit_sha=$2 AND version_label=$3 AND record_kind=$4 AND btrim(release_notes)<>'' AND release_tags @> $5::jsonb AND snapshot_id=(SELECT max(id) FROM version_history_sync_runs WHERE repo_key=$1 AND status='completed' AND complete))`, config.VersionHistoryRepo, *info.CommitSHA, info.DisplayVersion, kind, evidence).Scan(&ready)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "database_unavailable", *info.CommitSHA)
|
||||
}
|
||||
if !ready {
|
||||
return printVersionStatus(false, "version_record_pending", *info.CommitSHA)
|
||||
}
|
||||
return printVersionStatus(true, "verified", *info.CommitSHA)
|
||||
}
|
||||
func printVersionStatus(ready bool, code, sha string) int {
|
||||
raw, _ := json.Marshal(map[string]any{"ready": ready, "code": code, "commit_sha": sha})
|
||||
fmt.Fprintln(os.Stdout, string(raw))
|
||||
if ready {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,839 @@
|
||||
// Command libraryctl is the operator entry point for the whole-library capture
|
||||
// chain: it reads one test knowledge base (internal or external) from the real
|
||||
// WeKnora test stack, freezes its writers for the duration of the export and
|
||||
// seals a content-addressed candidate artifact.
|
||||
//
|
||||
// Boundaries this command keeps:
|
||||
// - the source is read through a read-only PostgreSQL session; no source
|
||||
// schema, data or program is modified;
|
||||
// - only SIGTERM is sent to the declared writer group, and only when every
|
||||
// service of the Compose project is declared (a new sibling container is
|
||||
// refused, not ignored);
|
||||
// - credentials are read from the running containers at the moment of the
|
||||
// call and are never printed, logged or written to disk;
|
||||
// - the sealed artifact is a *candidate*: it is not a release, and it does
|
||||
// not replace snapshot-bound content, Q&A and performance acceptance.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
releaseworkflow "knowledge-governance/internal/workflows/release"
|
||||
)
|
||||
|
||||
type options struct {
|
||||
sourceApp string
|
||||
sourcePG string
|
||||
sourceES string
|
||||
governancePG string
|
||||
project string
|
||||
writers string
|
||||
nonWriters string
|
||||
archiveRoot string
|
||||
journalRoot string
|
||||
dockerSocket string
|
||||
maxDocuments int
|
||||
maxObjectBytes int64
|
||||
scope string
|
||||
job string
|
||||
dryRun bool
|
||||
snapshot string
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
command := os.Args[1]
|
||||
opts, rest, err := parseFlags(command, os.Args[2:])
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "LIBRARYCTL_FLAGS:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
_ = rest
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
defer cancel()
|
||||
var runErr error
|
||||
switch command {
|
||||
case "status":
|
||||
runErr = runStatus(ctx, opts)
|
||||
case "preflight":
|
||||
runErr = runPreflight(ctx, opts)
|
||||
case "capture":
|
||||
runErr = runCapture(ctx, opts)
|
||||
case "list":
|
||||
runErr = runList(opts)
|
||||
case "verify":
|
||||
runErr = runVerify(opts)
|
||||
case "recover":
|
||||
runErr = runRecover(ctx, opts)
|
||||
default:
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
if runErr != nil {
|
||||
fmt.Fprintln(os.Stderr, "LIBRARYCTL_FAILED:", runErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Fprint(os.Stderr, `libraryctl <status|preflight|capture|list|verify|recover> [flags]
|
||||
|
||||
status probe the real source and print what is configured / blocked
|
||||
preflight read the source, run settlement + candidate validation (no writes, no stop)
|
||||
capture freeze the declared writer group, archive a candidate, restore writers
|
||||
list list sealed candidates and stored bytes
|
||||
verify re-verify one sealed candidate (digests, coverage, identity)
|
||||
recover restore writers from an interrupted freeze journal
|
||||
|
||||
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-es WKNFull-elasticsearch
|
||||
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here
|
||||
-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
|
||||
-archive ~/.local/share/knowledge-governance/library
|
||||
-journal ~/.local/share/knowledge-governance/freeze
|
||||
-docker-socket /var/run/docker.sock
|
||||
-scope internal|external (preflight/capture)
|
||||
-job <id> (capture; default: lib-<scope>-<UTC timestamp>)
|
||||
-dry-run (capture: export + validate only, no archive, no stop)
|
||||
-snapshot <id> (verify)
|
||||
`)
|
||||
}
|
||||
|
||||
func parseFlags(command string, args []string) (options, []string, error) {
|
||||
home, _ := os.UserHomeDir()
|
||||
opts := options{
|
||||
sourceApp: "WKNFull-app",
|
||||
sourcePG: "WKNFull-postgres",
|
||||
sourceES: "WKNFull-elasticsearch",
|
||||
governancePG: "knowledge-governance-p1-postgres-1",
|
||||
project: "weknora071full",
|
||||
writers: "WKNFull-app",
|
||||
archiveRoot: filepath.Join(home, ".local/share/knowledge-governance/library"),
|
||||
journalRoot: filepath.Join(home, ".local/share/knowledge-governance/freeze"),
|
||||
dockerSocket: "/var/run/docker.sock",
|
||||
maxDocuments: 100000,
|
||||
maxObjectBytes: 134217728,
|
||||
}
|
||||
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.sourceES, "source-es", opts.sourceES, "source Elasticsearch container")
|
||||
set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container")
|
||||
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")
|
||||
set.StringVar(&opts.archiveRoot, "archive", opts.archiveRoot, "sealed artifact root")
|
||||
set.StringVar(&opts.journalRoot, "journal", opts.journalRoot, "freeze journal root")
|
||||
set.StringVar(&opts.dockerSocket, "docker-socket", opts.dockerSocket, "Docker engine socket")
|
||||
set.IntVar(&opts.maxDocuments, "max-documents", opts.maxDocuments, "maximum indexed documents per scope")
|
||||
set.Int64Var(&opts.maxObjectBytes, "max-object-bytes", opts.maxObjectBytes, "maximum bytes per stored object")
|
||||
set.StringVar(&opts.scope, "scope", "", "internal|external")
|
||||
set.StringVar(&opts.job, "job", "", "capture job id")
|
||||
set.BoolVar(&opts.dryRun, "dry-run", false, "export and validate without archiving or stopping")
|
||||
set.StringVar(&opts.snapshot, "snapshot", "", "snapshot id for verify")
|
||||
if err := set.Parse(args); err != nil {
|
||||
return opts, nil, err
|
||||
}
|
||||
return opts, set.Args(), nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- discovery
|
||||
|
||||
func dockerOutput(ctx context.Context, args ...string) (string, error) {
|
||||
bounded, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(bounded, "docker", args...).Output()
|
||||
if err != nil {
|
||||
var exit *exec.ExitError
|
||||
if errors.As(err, &exit) && len(exit.Stderr) > 0 {
|
||||
return "", fmt.Errorf("docker %s failed", args[0])
|
||||
}
|
||||
return "", fmt.Errorf("docker %s failed", args[0])
|
||||
}
|
||||
return strings.TrimSpace(string(out)), nil
|
||||
}
|
||||
|
||||
func containerEnv(ctx context.Context, name string) (map[string]string, error) {
|
||||
raw, err := dockerOutput(ctx, "inspect", "--format", "{{json .Config.Env}}", name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var entries []string
|
||||
if err := json.Unmarshal([]byte(raw), &entries); err != nil {
|
||||
return nil, errors.New("invalid container environment")
|
||||
}
|
||||
env := map[string]string{}
|
||||
for _, entry := range entries {
|
||||
if key, value, ok := strings.Cut(entry, "="); ok {
|
||||
env[key] = value
|
||||
}
|
||||
}
|
||||
return env, nil
|
||||
}
|
||||
|
||||
func containerAddress(ctx context.Context, name string) (string, error) {
|
||||
raw, err := dockerOutput(ctx, "inspect", "--format",
|
||||
"{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}", name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, field := range strings.Fields(raw) {
|
||||
if field != "" && field != "0.0.0.0" {
|
||||
return field, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("container %s has no reachable address", name)
|
||||
}
|
||||
|
||||
func containerImageID(ctx context.Context, name string) (string, error) {
|
||||
return dockerOutput(ctx, "inspect", "--format", "{{.Image}}", name)
|
||||
}
|
||||
|
||||
// sourceConfig is everything needed to read the test library. Credential fields
|
||||
// are never printed: String() masks them and no log line formats the struct.
|
||||
type sourceConfig struct {
|
||||
Scopes map[string]string
|
||||
DatabaseURL string
|
||||
Search v071.SearchExporterConfig
|
||||
Object v071.S3ObjectStoreConfig
|
||||
AppImageID string
|
||||
SearchIndex string
|
||||
ObjectDetail string
|
||||
}
|
||||
|
||||
func discoverSource(ctx context.Context, opts options, binding map[string]string) (sourceConfig, error) {
|
||||
var config sourceConfig
|
||||
if binding == nil {
|
||||
return config, errors.New("routing bindings are required")
|
||||
}
|
||||
config.Scopes = binding
|
||||
app, err := containerEnv(ctx, opts.sourceApp)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
if app["DB_DRIVER"] != "postgres" {
|
||||
return config, errors.New("source database driver is not postgres")
|
||||
}
|
||||
if app["STORAGE_TYPE"] != "oss" {
|
||||
return config, fmt.Errorf("unsupported source storage type %q", app["STORAGE_TYPE"])
|
||||
}
|
||||
address, err := containerAddress(ctx, opts.sourcePG)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
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
|
||||
}
|
||||
esAddress, err := containerAddress(ctx, opts.sourceES)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
config.SearchIndex = app["ELASTICSEARCH_INDEX"]
|
||||
config.Search = v071.SearchExporterConfig{BaseURL: "http://" + esAddress + ":9200", Index: app["ELASTICSEARCH_INDEX"],
|
||||
AuthorizationToken: app["ELASTICSEARCH_PASSWORD"], PageSize: 500}
|
||||
endpoint := app["OSS_ENDPOINT"]
|
||||
if endpoint == "" {
|
||||
return config, errors.New("source object endpoint is not configured")
|
||||
}
|
||||
if !strings.Contains(endpoint, "://") {
|
||||
endpoint = "https://" + endpoint
|
||||
}
|
||||
config.Object = v071.S3ObjectStoreConfig{Provider: "oss", Endpoint: endpoint, Region: app["OSS_REGION"],
|
||||
AccessKeyID: app["OSS_ACCESS_KEY"], SecretAccessKey: app["OSS_SECRET_KEY"], Bucket: app["OSS_BUCKET_NAME"],
|
||||
Secure: strings.HasPrefix(endpoint, "https://"), MaxObjectBytes: opts.maxObjectBytes}
|
||||
config.ObjectDetail = "bucket=" + app["OSS_BUCKET_NAME"] + " region=" + app["OSS_REGION"]
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func urlEscape(value string) string {
|
||||
replacer := strings.NewReplacer("%", "%25", ":", "%3A", "@", "%40", "/", "%2F", "?", "%3F", "#", "%23", "&", "%26", " ", "%20")
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
|
||||
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'")
|
||||
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 map[string]string{"internal": internal, "external": external}, nil
|
||||
}
|
||||
|
||||
func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool, error) {
|
||||
parsed, err := pgxpool.ParseConfig(config.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid source database url")
|
||||
}
|
||||
// The capture chain never writes to the source. The read-only session makes
|
||||
// that a database-enforced property rather than a convention.
|
||||
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "120000"
|
||||
pool, err := pgxpool.NewWithConfig(ctx, parsed)
|
||||
if err != nil {
|
||||
return nil, errors.New("open source database failed")
|
||||
}
|
||||
var readOnly string
|
||||
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")
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func tenantAndKnowledgeBase(ctx context.Context, pool *pgxpool.Pool, knowledgeBaseID string) (uint64, error) {
|
||||
var tenant uint64
|
||||
err := pool.QueryRow(ctx, "SELECT tenant_id FROM knowledge_bases WHERE id=$1 AND deleted_at IS NULL", knowledgeBaseID).Scan(&tenant)
|
||||
if err != nil || tenant == 0 {
|
||||
return 0, errors.New("knowledge base not found in source")
|
||||
}
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
func writerDeclaration(opts options) ([]string, map[string]string, error) {
|
||||
writers := []string{}
|
||||
for _, name := range strings.Split(opts.writers, ",") {
|
||||
if trimmed := strings.TrimSpace(name); trimmed != "" {
|
||||
writers = append(writers, trimmed)
|
||||
}
|
||||
}
|
||||
if len(writers) == 0 {
|
||||
return nil, nil, errors.New("no writer service declared")
|
||||
}
|
||||
nonWriters := map[string]string{}
|
||||
for _, entry := range strings.Split(opts.nonWriters, ",") {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if entry == "" {
|
||||
continue
|
||||
}
|
||||
name, reason, ok := strings.Cut(entry, "=")
|
||||
if !ok || strings.TrimSpace(reason) == "" {
|
||||
return nil, nil, fmt.Errorf("non-writer %q needs service=reason", entry)
|
||||
}
|
||||
nonWriters[strings.TrimSpace(name)] = strings.TrimSpace(reason)
|
||||
}
|
||||
return writers, nonWriters, nil
|
||||
}
|
||||
|
||||
func openFreeze(ctx context.Context, opts options) (*libraryfreeze.Coordinator, *libraryfreeze.ProjectController, error) {
|
||||
writers, nonWriters, err := writerDeclaration(opts)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err = os.MkdirAll(opts.journalRoot, 0700); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err = os.Chmod(opts.journalRoot, 0700); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
control, err := libraryfreeze.NewProjectController(opts.dockerSocket, opts.project, writers, nonWriters, 2*time.Minute)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
coordinator, err := libraryfreeze.Open(opts.journalRoot, opts.project, control)
|
||||
if err != nil {
|
||||
control.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return coordinator, control, nil
|
||||
}
|
||||
|
||||
func openArchive(opts options) (*librarysnapshot.Archive, error) {
|
||||
if err := os.MkdirAll(opts.archiveRoot, 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Chmod(opts.archiveRoot, 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return librarysnapshot.Open(opts.archiveRoot, 256*1024*1024)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- commands
|
||||
|
||||
func runStatus(ctx context.Context, opts options) error {
|
||||
report := map[string]any{}
|
||||
binding, bindingErr := readRoutingBindings(ctx, opts.governancePG)
|
||||
var config sourceConfig
|
||||
var err error
|
||||
if bindingErr != nil {
|
||||
err = bindingErr
|
||||
} else {
|
||||
config, err = discoverSource(ctx, opts, binding)
|
||||
}
|
||||
if err != nil {
|
||||
report["source_discovery"] = err.Error()
|
||||
} else {
|
||||
report["source"] = map[string]any{
|
||||
"app_image": config.AppImageID,
|
||||
"scopes": config.Scopes,
|
||||
"search_index": config.SearchIndex,
|
||||
"elasticsearch": config.Search.BaseURL,
|
||||
"object_store": config.ObjectDetail,
|
||||
"database": "postgres (read-only session, credentials withheld)",
|
||||
"credentials_logged": false,
|
||||
}
|
||||
pool, poolErr := openSourceDatabase(ctx, config)
|
||||
if poolErr != nil {
|
||||
report["database"] = poolErr.Error()
|
||||
} else {
|
||||
defer pool.Close()
|
||||
settled := "settled"
|
||||
if settleErr := v071.LibrarySourceSettled(ctx, pool); settleErr != nil {
|
||||
settled = settleErr.Error()
|
||||
}
|
||||
report["settlement"] = settled
|
||||
counts := map[string]int{}
|
||||
for _, scope := range []string{"internal", "external"} {
|
||||
kb := config.Scopes[scope]
|
||||
tenant, tenantErr := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if tenantErr != nil {
|
||||
counts[scope+"_error"] = -1
|
||||
continue
|
||||
}
|
||||
pg, exportErr := v071.ExportLibrary(ctx, pool, v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb})
|
||||
if exportErr != nil {
|
||||
counts[scope+"_error"] = -1
|
||||
continue
|
||||
}
|
||||
for _, table := range pg.Tables {
|
||||
if table.Name == "chunks" || table.Name == "knowledges" {
|
||||
counts[scope+"_"+table.Name] = len(table.Rows)
|
||||
}
|
||||
}
|
||||
_ = kb
|
||||
}
|
||||
report["postgres_rows"] = counts
|
||||
}
|
||||
}
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
report["archive"] = err.Error()
|
||||
} else {
|
||||
defer archive.Close()
|
||||
usage, usageErr := archive.Usage()
|
||||
if usageErr != nil {
|
||||
report["archive"] = usageErr.Error()
|
||||
} else {
|
||||
total := int64(0)
|
||||
for _, item := range usage {
|
||||
total += item.UniqueBytes
|
||||
}
|
||||
report["archive"] = map[string]any{"root": opts.archiveRoot, "snapshots": len(usage), "stored_bytes": total}
|
||||
}
|
||||
}
|
||||
if coordinator, control, freezeErr := openFreeze(ctx, opts); freezeErr != nil {
|
||||
report["freeze"] = freezeErr.Error()
|
||||
} else {
|
||||
defer coordinator.Close()
|
||||
defer control.Close()
|
||||
items, inventoryErr := control.Inventory(ctx)
|
||||
if inventoryErr != nil {
|
||||
report["freeze"] = inventoryErr.Error()
|
||||
} else {
|
||||
group := []map[string]any{}
|
||||
for _, item := range items {
|
||||
group = append(group, map[string]any{"id": item.ID, "running": item.Running, "healthy": item.Healthy})
|
||||
}
|
||||
report["freeze"] = map[string]any{"project": opts.project, "writers": group, "journal": opts.journalRoot}
|
||||
}
|
||||
}
|
||||
printJSON(report)
|
||||
return nil
|
||||
}
|
||||
|
||||
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 := readRoutingBindings(ctx, opts.governancePG)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
config, err := discoverSource(ctx, opts, binding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := openSourceDatabase(ctx, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = v071.LibrarySourceSettled(ctx, pool); err != nil {
|
||||
return err
|
||||
}
|
||||
search, err := v071.NewSearchExporter(config.Search)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
contract, err := compatibilityContract(ctx, pool, search, config.SearchIndex, tenant, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pg, err := v071.ExportLibrary(ctx, pool, v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
es, err := search.ExportLibrary(ctx, v071.SearchIdentity{TenantID: tenant, KnowledgeBaseID: kb}, opts.maxDocuments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
validation := "candidate-valid"
|
||||
if err = v071.ValidateLibraryCandidateForPreflight(v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb}, pg, es); err != nil {
|
||||
validation = err.Error()
|
||||
}
|
||||
tables := map[string]int{}
|
||||
for _, table := range pg.Tables {
|
||||
tables[table.Name] = len(table.Rows)
|
||||
}
|
||||
printJSON(map[string]any{"scope": opts.scope, "knowledge_base_id": kb, "tenant_id": tenant,
|
||||
"compatibility": contract, "postgres_rows": tables, "index_documents": len(es.Documents),
|
||||
"mapping_sha256": es.MappingSHA256, "validation": validation, "writes": 0, "writers_stopped": 0})
|
||||
if validation != "candidate-valid" {
|
||||
return errors.New("candidate validation failed: " + validation)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func compatibilityContract(ctx context.Context, pool *pgxpool.Pool, search *v071.SearchExporter, index string, tenant uint64, kb string) (v071.LibrarySnapshotCompatibility, error) {
|
||||
inspector, err := v071.NewTargetContractInspector(v071.TargetContractInspectorConfig{DB: pool, Mapping: search,
|
||||
KnowledgeBaseID: kb, TenantID: tenant, IndexName: index, ReadTestedBase: true})
|
||||
if err != nil {
|
||||
return v071.LibrarySnapshotCompatibility{}, err
|
||||
}
|
||||
contract, err := inspector.Contract(ctx, releaseworkflow.PlanItem{TestKnowledgeBaseID: kb})
|
||||
if err != nil {
|
||||
return v071.LibrarySnapshotCompatibility{}, err
|
||||
}
|
||||
return v071.LibrarySnapshotCompatibility{WeKnoraVersion: contract.WeKnoraVersion, SchemaVersion: contract.MigrationVersion,
|
||||
RetrieverEngine: contract.RetrieverEngine, EmbeddingModel: contract.EmbeddingModel,
|
||||
EmbeddingDimension: contract.EmbeddingDimension, IndexMappingSHA256: contract.ElasticsearchMappingSHA256}, nil
|
||||
}
|
||||
|
||||
func runCapture(ctx context.Context, opts options) error {
|
||||
if opts.scope != "internal" && opts.scope != "external" {
|
||||
return errors.New("-scope must be internal or external")
|
||||
}
|
||||
if opts.dryRun {
|
||||
return runPreflight(ctx, opts)
|
||||
}
|
||||
job := opts.job
|
||||
if job == "" {
|
||||
job = "lib-" + opts.scope + "-" + time.Now().UTC().Format("20060102T150405")
|
||||
}
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
coordinator, control, err := openFreeze(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer coordinator.Close()
|
||||
defer control.Close()
|
||||
if err = coordinator.Recover(ctx); err != nil {
|
||||
return fmt.Errorf("pending freeze requires recovery: %w", err)
|
||||
}
|
||||
// Replay is answered from the persisted journal + sealed archive: the same job
|
||||
// re-used with the same scope/binding returns the original candidate without
|
||||
// reading the source or stopping a writer, and a job re-used with different
|
||||
// parameters is refused instead of silently sealing under a stale identity.
|
||||
existing, found, err := coordinator.Inspect(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
binding, err := readRoutingBindings(ctx, opts.governancePG)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
scopedKB := binding[opts.scope]
|
||||
if found {
|
||||
manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printCapture(job, existing.SnapshotID, manifest, true)
|
||||
}
|
||||
config, err := discoverSource(ctx, opts, binding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := openSourceDatabase(ctx, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
search, err := v071.NewSearchExporter(config.Search)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
objects, err := v071.NewS3ObjectStore(config.Object)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
contract, err := compatibilityContract(ctx, pool, search, config.SearchIndex, tenant, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The contract above is read before the maintenance window. Re-read it inside
|
||||
// the stopped window and refuse if a model/index change happened in between:
|
||||
// sealing a candidate whose contract no longer matches the source would hide
|
||||
// exactly the change a later production sync cannot reproduce.
|
||||
verifyContract := func(ctx context.Context) error {
|
||||
live, err := compatibilityContract(ctx, pool, search, config.SearchIndex, tenant, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if live != contract {
|
||||
return errors.New("source contract changed between preflight and the frozen window; capture aborted")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// sourceReady proves the declared writer group is complete and no other
|
||||
// running container uses a declared writer image. Recorded work settlement is
|
||||
// enforced separately by CaptureLibrary; neither check can see unrecorded or
|
||||
// remote work, so this is not a cross-system consistency proof.
|
||||
sourceReady := func(ctx context.Context) error {
|
||||
items, err := control.Inventory(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return errors.New("writer group is empty")
|
||||
}
|
||||
declared := make(map[string]bool, len(items))
|
||||
for _, item := range items {
|
||||
declared[item.ID] = true
|
||||
}
|
||||
images, err := writerImageIDs(ctx, items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkNoUndeclaredWriter(ctx, images, declared)
|
||||
}
|
||||
result, err := v071.CaptureLibrary(ctx, coordinator, archive, pool, search, objects, sourceReady,
|
||||
v071.LibraryCaptureRequest{JobID: job, Scope: opts.scope,
|
||||
Identity: v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb},
|
||||
Compatibility: contract, CreatedAt: time.Now().UTC(), MaxDocuments: opts.maxDocuments,
|
||||
VerifyContract: verifyContract})
|
||||
if err != nil {
|
||||
printJSON(map[string]any{"job": job, "state": result.State, "snapshot_id": result.SnapshotID, "error": err.Error()})
|
||||
return err
|
||||
}
|
||||
manifest, err := archive.Load(result.SnapshotID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printCapture(job, result.SnapshotID, manifest, false)
|
||||
}
|
||||
|
||||
// replayCapture answers a repeated job from persisted state. It never reads the
|
||||
// source and never stops a writer; conflicting parameters are refused.
|
||||
func replayCapture(job, scope, expectedKB string, result libraryfreeze.Result, archive *librarysnapshot.Archive) (librarysnapshot.Manifest, error) {
|
||||
if result.State != "succeeded" || result.SnapshotID == "" {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q already exists with state %q: recover it or use a new job id", job, result.State)
|
||||
}
|
||||
manifest, err := archive.Load(result.SnapshotID)
|
||||
if err != nil {
|
||||
return librarysnapshot.Manifest{}, errors.New("captured library archive no longer verifies")
|
||||
}
|
||||
if manifest.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
|
||||
return librarysnapshot.Manifest{}, errors.New("existing job was sealed under a different validation policy")
|
||||
}
|
||||
if manifest.Scope != scope {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q was captured for scope %q, not %q", job, manifest.Scope, scope)
|
||||
}
|
||||
if manifest.KnowledgeBaseID != expectedKB {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q was captured for knowledge base %q, which is no longer the %q binding", job, manifest.KnowledgeBaseID, scope)
|
||||
}
|
||||
return manifest, nil
|
||||
}
|
||||
|
||||
func printCapture(job, snapshotID string, manifest librarysnapshot.Manifest, replay bool) error {
|
||||
parts := make([]map[string]any, 0, len(manifest.Parts))
|
||||
var total int64
|
||||
for _, part := range manifest.Parts {
|
||||
parts = append(parts, map[string]any{"kind": part.Kind, "name": part.Name, "count": part.Count, "bytes": part.Bytes, "sha256": part.SHA256})
|
||||
total += part.Bytes
|
||||
}
|
||||
sort.Slice(parts, func(i, j int) bool {
|
||||
return fmt.Sprint(parts[i]["kind"])+fmt.Sprint(parts[i]["name"]) < fmt.Sprint(parts[j]["kind"])+fmt.Sprint(parts[j]["name"])
|
||||
})
|
||||
printJSON(map[string]any{"job": job, "state": "succeeded", "snapshot_id": snapshotID,
|
||||
"scope": manifest.Scope, "knowledge_base_id": manifest.KnowledgeBaseID, "tenant_id": manifest.TenantID,
|
||||
"compatibility": manifest.Compatibility, "parts": parts, "logical_bytes": total,
|
||||
"validation_policy": manifest.ValidationPolicy, "writers_restored": true,
|
||||
"replay": replay, "source_read": !replay, "writers_stopped": !replay})
|
||||
return nil
|
||||
}
|
||||
|
||||
func writerImageIDs(ctx context.Context, items []libraryfreeze.Service) ([]string, error) {
|
||||
images := make([]string, 0, len(items))
|
||||
seen := map[string]bool{}
|
||||
for _, item := range items {
|
||||
image, err := containerImageOf(ctx, item.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !seen[image] {
|
||||
seen[image] = true
|
||||
images = append(images, image)
|
||||
}
|
||||
}
|
||||
return images, nil
|
||||
}
|
||||
|
||||
// checkNoUndeclaredWriter refuses to run when a running container uses a declared
|
||||
// writer image but is not part of the declared group: such a container could keep
|
||||
// writing during the maintenance window.
|
||||
func checkNoUndeclaredWriter(ctx context.Context, images []string, declared map[string]bool) error {
|
||||
for _, image := range images {
|
||||
out, err := dockerOutput(ctx, "ps", "-q", "--filter", "ancestor="+image)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, id := range strings.Fields(out) {
|
||||
if !declared[id] {
|
||||
return fmt.Errorf("container %s uses a declared writer image but is not in the declared writer group", id[:12])
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func containerImageOf(ctx context.Context, id string) (string, error) {
|
||||
image, err := dockerOutput(ctx, "inspect", "--format", "{{.Image}}", id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if image == "" {
|
||||
return "", errors.New("declared writer has no image identity")
|
||||
}
|
||||
return image, nil
|
||||
}
|
||||
func runList(opts options) error {
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
usage, err := archive.Usage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
total, err := archive.ContentUsage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items := make([]map[string]any, 0, len(usage))
|
||||
for _, item := range usage {
|
||||
manifest, err := archive.Load(item.VersionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items = append(items, map[string]any{"snapshot_id": item.VersionID, "scope": manifest.Scope,
|
||||
"knowledge_base_id": manifest.KnowledgeBaseID, "created_at": manifest.CreatedAt,
|
||||
"logical_bytes": item.LogicalBytes, "unique_bytes": item.UniqueBytes, "shared_bytes": item.SharedBytes,
|
||||
"parts": len(manifest.Parts), "policy": manifest.ValidationPolicy})
|
||||
}
|
||||
printJSON(map[string]any{"archive": opts.archiveRoot, "snapshots": items,
|
||||
// 跨版本去重后的内容字节;文件系统事实单列,任何一项都不是可回收空间。
|
||||
"versions": total.Versions, "content_bytes": total.ContentBytes,
|
||||
"blob_file_bytes": total.BlobFileBytes, "blob_allocated_bytes": total.BlobAllocatedBytes,
|
||||
"unreferenced_blobs": total.UnreferencedBlobs, "unreferenced_bytes": total.UnreferencedBytes,
|
||||
"manifest_file_bytes": total.ManifestFileBytes, "manifest_allocated_bytes": total.ManifestAllocatedBytes})
|
||||
return nil
|
||||
}
|
||||
|
||||
func runVerify(opts options) error {
|
||||
if opts.snapshot == "" {
|
||||
return errors.New("-snapshot is required")
|
||||
}
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(opts.snapshot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parts := make([]map[string]any, 0, len(manifest.Parts))
|
||||
for _, part := range manifest.Parts {
|
||||
parts = append(parts, map[string]any{"kind": part.Kind, "name": part.Name, "count": part.Count, "bytes": part.Bytes, "sha256": part.SHA256})
|
||||
}
|
||||
printJSON(map[string]any{"snapshot_id": opts.snapshot, "verified": true, "format": manifest.Format,
|
||||
"policy": manifest.ValidationPolicy, "scope": manifest.Scope, "knowledge_base_id": manifest.KnowledgeBaseID,
|
||||
"tenant_id": manifest.TenantID, "created_at": manifest.CreatedAt, "compatibility": manifest.Compatibility, "parts": parts})
|
||||
return nil
|
||||
}
|
||||
|
||||
func runRecover(ctx context.Context, opts options) error {
|
||||
coordinator, control, err := openFreeze(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer coordinator.Close()
|
||||
defer control.Close()
|
||||
if err = coordinator.Recover(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := control.Inventory(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
group := []map[string]any{}
|
||||
for _, item := range items {
|
||||
group = append(group, map[string]any{"id": item.ID, "running": item.Running, "healthy": item.Healthy})
|
||||
}
|
||||
printJSON(map[string]any{"recovered": true, "writers": group})
|
||||
return nil
|
||||
}
|
||||
|
||||
func printJSON(value any) {
|
||||
encoder := json.NewEncoder(os.Stdout)
|
||||
encoder.SetIndent("", " ")
|
||||
_ = encoder.Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// sealedFixture writes one complete sealed candidate and returns its ID.
|
||||
func sealedFixture(t *testing.T, archive *librarysnapshot.Archive, scope, knowledgeBaseID string, createdAt time.Time) string {
|
||||
t.Helper()
|
||||
rows := func(count int) string {
|
||||
if count == 0 {
|
||||
return "[]"
|
||||
}
|
||||
items := make([]string, count)
|
||||
for i := range items {
|
||||
items[i] = fmt.Sprintf(`{"id":"00000000-0000-4000-8000-%012d"}`, i)
|
||||
}
|
||||
return "[" + strings.Join(items, ",") + "]"
|
||||
}
|
||||
parts := []struct {
|
||||
kind, name string
|
||||
count int64
|
||||
}{
|
||||
{"database", "knowledges", 4},
|
||||
{"database", "chunks", 38},
|
||||
{"database", "resources", 0},
|
||||
{"database", "resource_bindings", 0},
|
||||
{"database", "knowledge_tags", 0},
|
||||
{"database", "knowledge_tag_relations", 0},
|
||||
{"index", "chunks", 122},
|
||||
{"wiki", "wiki_pages", 31},
|
||||
{"wiki", "wiki_folders", 21},
|
||||
{"wiki", "wiki_page_issues", 0},
|
||||
{"wiki", "wiki_log_entries", 11},
|
||||
}
|
||||
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy,
|
||||
Format: librarysnapshot.Format, Scope: scope, TenantID: 10000, KnowledgeBaseID: knowledgeBaseID,
|
||||
CreatedAt: createdAt, Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1",
|
||||
SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4",
|
||||
EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("b", 64)}}
|
||||
for _, part := range parts {
|
||||
stored, err := archive.Put(bytes.NewReader([]byte(rows(int(part.count)))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored.Kind, stored.Name, stored.Count = part.kind, part.name, part.count
|
||||
manifest.Parts = append(manifest.Parts, stored)
|
||||
}
|
||||
id, err := archive.Seal(manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func fixtureArchive(t *testing.T) (*librarysnapshot.Archive, string) {
|
||||
t.Helper()
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kglc-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := librarysnapshot.Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { archive.Close() })
|
||||
return archive, root
|
||||
}
|
||||
|
||||
const fixtureKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
|
||||
|
||||
// A repeated job with the same parameters must return the original candidate
|
||||
// without touching the source or stopping a writer (this function has no access
|
||||
// to either), instead of failing with a conflicting-request error.
|
||||
func TestReplayCaptureReturnsOriginalCandidate(t *testing.T) {
|
||||
archive, _ := fixtureArchive(t)
|
||||
created := time.Date(2026, 10, 28, 3, 34, 57, 0, time.UTC)
|
||||
id := sealedFixture(t, archive, "internal", fixtureKB, created)
|
||||
manifest, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !manifest.CreatedAt.Equal(created) || manifest.Compatibility.EmbeddingModel != "text-embedding-v4" {
|
||||
t.Fatalf("replay lost the original request identity: %+v", manifest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplayCaptureRejectsChangedParameters(t *testing.T) {
|
||||
archive, root := fixtureArchive(t)
|
||||
id := sealedFixture(t, archive, "internal", fixtureKB, time.Date(2026, 10, 28, 3, 34, 57, 0, time.UTC))
|
||||
// Different scope.
|
||||
if _, err := replayCapture("lib-internal-1", "external", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("scope conflict was accepted")
|
||||
}
|
||||
// Binding moved to another knowledge base.
|
||||
if _, err := replayCapture("lib-internal-1", "internal", "aec3dfc9-4ad3-4a39-926b-5bfa5d6a9654",
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("knowledge base binding change was accepted")
|
||||
}
|
||||
// A job that never succeeded must not be answered as success.
|
||||
if _, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "failed"}, archive); err == nil {
|
||||
t.Fatal("failed job replayed as success")
|
||||
}
|
||||
// A sealed candidate that no longer verifies must not be reported as replay.
|
||||
if err := os.Remove(root + "/versions/" + id + ".json"); err == nil {
|
||||
if _, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("missing sealed candidate replayed as success")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:], os.Getenv, os.Stdout); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "directory import failed; check private input and governance connection (details withheld)")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(args []string, getenv func(string) string, out io.Writer) error {
|
||||
if len(args) != 1 || getenv("QAOPS_CONFIRM_DIRECTORY_IMPORT") != "import-governance-directory" || getenv("DOBOTAI_OPS_TENANT_KEY") == "" || getenv("DATABASE_URL") == "" {
|
||||
return errors.New("explicit input, tenant, governance database and confirmation required")
|
||||
}
|
||||
info, err := os.Lstat(args[0])
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > 16<<20 {
|
||||
return errors.New("input must be a private regular JSON file")
|
||||
}
|
||||
file, err := os.Open(args[0])
|
||||
if err != nil {
|
||||
return errors.New("input unavailable")
|
||||
}
|
||||
defer file.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, (16<<20)+1))
|
||||
decoder.DisallowUnknownFields()
|
||||
var input qaopsorg.Import
|
||||
if decoder.Decode(&input) != nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||
return errors.New("input invalid")
|
||||
}
|
||||
if !input.Complete {
|
||||
return qaopsorg.ErrInvalid
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.New(ctx, getenv("DATABASE_URL"))
|
||||
if err != nil {
|
||||
return qaopsorg.ErrUnavailable
|
||||
}
|
||||
defer pool.Close()
|
||||
store := qaopsorg.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY"))
|
||||
saved, err := store.ReplaceDirectory(ctx, input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
active, err := store.GetView(ctx)
|
||||
if err != nil || active.DirectoryID != saved.DirectoryID {
|
||||
return qaopsorg.ErrConflict
|
||||
}
|
||||
return json.NewEncoder(out).Encode(map[string]any{"directory_id": active.DirectoryID, "source": active.DirectorySource, "synced_at": active.DirectorySyncedAt, "departments": len(active.View.Departments), "people": active.View.TotalPeople, "readback_verified": true})
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDirectoryImportRequiresExplicitGovernanceConfirmationAndPrivateInput(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
if run(nil, func(string) string { return "" }, &output) == nil || output.Len() != 0 {
|
||||
t.Fatal("unconfigured importer must not connect or report success")
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "directory.json")
|
||||
if os.WriteFile(path, []byte(`{"complete":false}`), 0644) != nil {
|
||||
t.Fatal("fixture creation failed")
|
||||
}
|
||||
env := func(k string) string {
|
||||
return map[string]string{"QAOPS_CONFIRM_DIRECTORY_IMPORT": "import-governance-directory", "DOBOTAI_OPS_TENANT_KEY": "fixture", "DATABASE_URL": "postgres://invalid.invalid/no_connection_expected"}[k]
|
||||
}
|
||||
if run([]string{path}, env, &output) == nil {
|
||||
t.Fatal("public personnel input accepted")
|
||||
}
|
||||
if os.Chmod(path, 0600) != nil {
|
||||
t.Fatal("fixture chmod failed")
|
||||
}
|
||||
if run([]string{path}, env, &output) == nil || output.Len() != 0 {
|
||||
t.Fatal("partial sync accepted or importer reported fabricated success")
|
||||
}
|
||||
}
|
||||
+24
-1
@@ -53,6 +53,13 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
|
||||
log.Print("QA directory synchronization unavailable; handler was not registered")
|
||||
}
|
||||
mirrorStore, mirrorErr := configureRecordsSync(pool, getenv, config.DatabaseURL, handlers)
|
||||
if mirrorErr != nil {
|
||||
log.Print("QA local mirror configuration invalid; handler was not registered")
|
||||
}
|
||||
worker, err := jobs.NewWorker(jobs.WorkerConfig{
|
||||
Queue: store,
|
||||
WorkerID: config.WorkerID,
|
||||
@@ -64,6 +71,13 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ai := configureQAProcessing(pool, getenv, config.DatabaseURL); ai != nil {
|
||||
go ai.Run(ctx, func(error) { log.Print("QA AI worker unavailable; durable work and original labels retained") })
|
||||
}
|
||||
if mirrorStore != nil {
|
||||
go runRecordsSyncScheduler(ctx, mirrorStore, func(error) { log.Print("QA local mirror scheduler unavailable; last committed data retained") })
|
||||
}
|
||||
go weeklyMailLoop(ctx, pool, getenv)
|
||||
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
|
||||
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
|
||||
})
|
||||
@@ -134,11 +148,20 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
triggeredBy := ""
|
||||
var payload struct {
|
||||
TriggeredBy string `json:"triggered_by"`
|
||||
TargetSHA string `json:"target_sha"`
|
||||
}
|
||||
if err := json.Unmarshal(job.Payload, &payload); err == nil {
|
||||
triggeredBy = payload.TriggeredBy
|
||||
}
|
||||
run, err := syncer.Sync(ctx, job.ID, triggeredBy)
|
||||
activeSyncer := syncer
|
||||
if payload.TargetSHA != "" {
|
||||
var e error
|
||||
activeSyncer, e = versionhistory.NewSyncer(versionhistory.SyncerConfig{Source: client, Store: store, RepoKey: config.VersionHistoryRepo, MaxPages: config.VersionHistoryMaxPages, TargetSHAs: []string{payload.TargetSHA}})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
run, err := activeSyncer.Sync(ctx, job.ID, triggeredBy)
|
||||
if err != nil {
|
||||
log.Printf("version history sync failed job=%s run=%d code=%s: %v", job.ID, run.ID, run.ErrorCode, err)
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
)
|
||||
|
||||
func configureQAProcessing(pool *pgxpool.Pool, getenv func(string) string, governanceDSN string) *qaopsai.Store {
|
||||
return qaopsai.NewFromEnvironment(pool, getenv, governanceDSN)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAIWorkerUsesIndependentGovernanceConfigurationWithoutOpeningSource(t *testing.T) {
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
if configureQAProcessing(nil, get, "postgres://fixture@localhost/local") != nil {
|
||||
t.Fatal("disabled AI worker registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_READ_ENABLED"] = "true"
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-ai-worker"
|
||||
values["DOBOTAI_OPS_READ_DSN_FILE"] = "/nonexistent-fixture-source-secret"
|
||||
if configureQAProcessing(nil, get, "postgres://fixture@localhost/local") == nil {
|
||||
t.Fatal("AI worker still depends on source availability or was not registered")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type recordsSyncSchedulerStore interface {
|
||||
EnqueueDue(context.Context) (bool, error)
|
||||
TrackQualityWeeks(context.Context, time.Time) error
|
||||
FreezePreviousQualityWeek(context.Context, time.Time) (bool, error)
|
||||
}
|
||||
|
||||
func runRecordsSyncCycle(ctx context.Context, store recordsSyncSchedulerStore, at time.Time) error {
|
||||
_, syncErr := store.EnqueueDue(ctx)
|
||||
trackingErr := store.TrackQualityWeeks(ctx, at)
|
||||
if trackingErr != nil {
|
||||
return errors.Join(syncErr, trackingErr)
|
||||
}
|
||||
_, freezeErr := store.FreezePreviousQualityWeek(ctx, at)
|
||||
return errors.Join(syncErr, freezeErr)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type frozenScheduleSpy struct {
|
||||
calls []string
|
||||
trackErr error
|
||||
}
|
||||
|
||||
func (s *frozenScheduleSpy) EnqueueDue(context.Context) (bool, error) {
|
||||
s.calls = append(s.calls, "sync")
|
||||
return true, nil
|
||||
}
|
||||
func (s *frozenScheduleSpy) TrackQualityWeeks(context.Context, time.Time) error {
|
||||
s.calls = append(s.calls, "track")
|
||||
return s.trackErr
|
||||
}
|
||||
func (s *frozenScheduleSpy) FreezePreviousQualityWeek(context.Context, time.Time) (bool, error) {
|
||||
s.calls = append(s.calls, "freeze")
|
||||
return true, nil
|
||||
}
|
||||
func TestRecordsSchedulerActuallyCapturesFrozenWeeklyMetrics(t *testing.T) {
|
||||
s := &frozenScheduleSpy{}
|
||||
if e := runRecordsSyncCycle(context.Background(), s, time.Now()); e != nil || !reflect.DeepEqual(s.calls, []string{"sync", "track", "freeze"}) {
|
||||
t.Fatal("weekly capture is not on the real scheduler invocation path", e, s.calls)
|
||||
}
|
||||
broken := &frozenScheduleSpy{trackErr: errors.New("isolated tracking unavailable")}
|
||||
if e := runRecordsSyncCycle(context.Background(), broken, time.Now()); e == nil || !reflect.DeepEqual(broken.calls, []string{"sync", "track"}) {
|
||||
t.Fatal("snapshot failure must not suppress source sync or freeze untracked history")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func configureRecordsSync(pool *pgxpool.Pool, getenv func(string) string, governanceDSN string, handlers map[string]jobs.Handler) (*qaopsmirror.Store, error) {
|
||||
settings := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !settings.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
if settings.TenantKey == "" || len(settings.TenantKey) > 128 || strings.ContainsRune(settings.TenantKey, 0) {
|
||||
return nil, qaopsmirror.ErrInvalid
|
||||
}
|
||||
store := qaopsmirror.NewStore(pool, settings.TenantKey)
|
||||
handlers[store.SyncJobType()] = func(ctx context.Context, job jobs.Job) error {
|
||||
return store.HandleSync(ctx, job, func(ctx context.Context) (qaopsmirror.Source, error) {
|
||||
current := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !current.Enabled || current.Problem != "" || current.TenantKey != settings.TenantKey {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
// One source connection, shared by every manifest and bounded payload read in this job.
|
||||
current.Connection.MaxConns = 1
|
||||
current.Connection.MinConns = 0
|
||||
return dobotaiops.Build(ctx, current.Connection)
|
||||
})
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// The next due time and automatic operation key live in PostgreSQL, so a worker
|
||||
// restart does not reset the five-minute cadence or duplicate an active import.
|
||||
func runRecordsSyncScheduler(ctx context.Context, store *qaopsmirror.Store, onError func(error)) {
|
||||
tick := time.NewTicker(15 * time.Second)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if e := runRecordsSyncCycle(ctx, store, time.Now()); e != nil && ctx.Err() == nil && onError != nil {
|
||||
onError(e)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLocalMirrorWorkerRegistrationNeverConnectsSource(t *testing.T) {
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
handlers := map[string]jobs.Handler{}
|
||||
if store, e := configureRecordsSync(nil, get, "postgres://fixture@localhost/local", handlers); e != nil || store != nil || len(handlers) != 0 {
|
||||
t.Fatal("disabled mirror registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_READ_ENABLED"] = "true"
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-worker-tenant"
|
||||
values["DOBOTAI_OPS_READ_DSN_FILE"] = "/nonexistent-fixture-source-secret"
|
||||
store, e := configureRecordsSync(nil, get, "postgres://fixture@localhost/local", handlers)
|
||||
if e != nil || store == nil || handlers[qaopsmirror.NewStore(nil, "fixture-worker-tenant").SyncJobType()] == nil {
|
||||
t.Fatal("local mirror handler missing; registration must not connect to source", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
func configureDirectorySync(pool *pgxpool.Pool, getenv func(string) string, handlers map[string]jobs.Handler) error {
|
||||
settings, err := qaopsorg.LoadSyncSettings(getenv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !settings.Enabled {
|
||||
return nil
|
||||
}
|
||||
if err = settings.CheckWorkerRuntime(); err != nil {
|
||||
return err
|
||||
}
|
||||
store := qaopsorg.NewStore(pool, settings.Tenant)
|
||||
handlers[store.SyncJobType()] = func(ctx context.Context, job jobs.Job) error {
|
||||
return store.HandleDirectorySync(ctx, job, settings.Runner)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDirectorySyncWorkerRegistrationIsOptInAndRuntimeChecked(t *testing.T) {
|
||||
handlers := map[string]jobs.Handler{}
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
if err := configureDirectorySync(nil, get, handlers); err != nil || len(handlers) != 0 {
|
||||
t.Fatal("disabled sync registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED"] = "true"
|
||||
if err := configureDirectorySync(nil, get, handlers); err == nil {
|
||||
t.Fatal("incomplete binding registered")
|
||||
}
|
||||
root := t.TempDir()
|
||||
script := filepath.Join(root, "fixture.py")
|
||||
if err := os.WriteFile(script, []byte("# fixture; not executed by registration"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-tenant"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON"] = "/bin/sh"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = script
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT"] = root
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT"] = root
|
||||
if err := configureDirectorySync(nil, get, handlers); err != nil || handlers[qaopsorg.NewStore(nil, "fixture-tenant").SyncJobType()] == nil {
|
||||
t.Fatal("configured worker was not wired")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = filepath.Join(root, "missing.py")
|
||||
if err := configureDirectorySync(nil, get, map[string]jobs.Handler{}); err == nil {
|
||||
t.Fatal("missing runtime advertised as ready")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/qawemail"
|
||||
)
|
||||
|
||||
// weeklyMailLoop sends the confirmed weekly report exactly inside the configured slot.
|
||||
// It runs in the ordinary worker so the console never depends on a browser staying open.
|
||||
func weeklyMailLoop(ctx context.Context, pool *pgxpool.Pool, getenv func(string) string) {
|
||||
tenant := getenv("DOBOTAI_OPS_TENANT_KEY")
|
||||
if tenant == "" {
|
||||
log.Print("weekly mail disabled: tenant key not configured")
|
||||
return
|
||||
}
|
||||
store := qawemail.NewStore(pool, tenant, getenv("QA_AI_MASTER_KEY_FILE"), nil)
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
lastState := ""
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
result, err := store.SendDue(runCtx, time.Now())
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("weekly mail attempt failed: %v", err)
|
||||
continue
|
||||
}
|
||||
if result.State != lastState {
|
||||
lastState = result.State
|
||||
log.Printf("weekly mail state=%s week=%s reason=%s", result.State, result.Week, result.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,13 @@ services:
|
||||
VERSION_HISTORY_LINK_ORIGIN: "${VERSION_HISTORY_LINK_ORIGIN:-}"
|
||||
VERSION_HISTORY_HTTP_TIMEOUT: "${VERSION_HISTORY_HTTP_TIMEOUT:-15s}"
|
||||
VERSION_HISTORY_MAX_PAGES: "${VERSION_HISTORY_MAX_PAGES:-200}"
|
||||
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
|
||||
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
|
||||
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
|
||||
# Mount this independent master-key file read-only using the deployment overlay.
|
||||
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
|
||||
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.
|
||||
TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key
|
||||
TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
|
||||
@@ -69,6 +76,8 @@ services:
|
||||
- pgpass
|
||||
- test_weknora_api_key
|
||||
volumes:
|
||||
# 整库封存产物:只读挂载,api 只读不写(写入只发生在主机上的 libraryctl)。
|
||||
- /home/zheromiku/.local/share/knowledge-governance/library:/var/lib/knowledge-governance/library:ro
|
||||
# 与 worker 共用同一份 dws 状态:refresh token 是轮换制,绝不能在两处各留一份。
|
||||
- /home/zheromiku/.dws:/data/dws
|
||||
# dws 的文件型 keychain 必须有 $HOME/.local/share/dws-cli,故挂到 DWS_HOME 下。
|
||||
@@ -99,6 +108,8 @@ services:
|
||||
environment:
|
||||
<<: *app-environment
|
||||
WORKER_ID: worker-1
|
||||
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
|
||||
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
||||
PP_SCAN_ENABLED: "${PP_SCAN_ENABLED:-false}"
|
||||
PP_SCAN_ALLOWED_ROOT: "${PP_SCAN_CONTAINER_DATA_ROOT:-/home/zheromiku/dobot-portal-sync/data}"
|
||||
PP_SCAN_LEDGER_PATH: "${PP_SCAN_CONTAINER_DATA_ROOT:-/home/zheromiku/dobot-portal-sync/data}/public-weknora-sync/state.jsonl"
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ server {
|
||||
set $api_upstream http://api:8080;
|
||||
proxy_pass $api_upstream;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
@@ -22,7 +22,7 @@ server {
|
||||
location = /health {
|
||||
set $health_upstream http://api:8080;
|
||||
proxy_pass $health_upstream/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Host $http_host;
|
||||
}
|
||||
|
||||
# 带内容哈希的构建产物:可以长期缓存(换版本必然换文件名);旧哈希文件已被新构建替换
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
# 三 Agent 交接闭环工作流(架构 / 开发 / 验收)
|
||||
|
||||
> 适用仓库:`Weknora/knowledge-governance`(默认分支 `main`)。
|
||||
> 本文件是**交接契约**,不是介绍:它规定角色边界、状态机、版本口径与交接证据格式,
|
||||
> 供三个独立会话(架构 / 开发 / 验收)在同一仓库上串行协作时逐条核对。
|
||||
> 依据:工单 `#6` 的「文档内容合同」8 条(正文=目标与范围,评论=证据,commit/tag=版本)。
|
||||
|
||||
## 0. 与工单合同条目的对应(便于独立验收逐条核对)
|
||||
|
||||
| 合同条目 | 本文位置 |
|
||||
|---|---|
|
||||
| 1 三角色职责 | §1 |
|
||||
| 2 main 单线、串行修改 | §2 |
|
||||
| 3 六个状态名、标签互斥、blocked 要素 | §3 |
|
||||
| 4 每轮可交接的修改链路(自测→commit→快照 tag→推送→核实→review) | §4、§5 |
|
||||
| 5 不可变与回退规则 | §5 |
|
||||
| 6 开发/验收交接模板 | §6 |
|
||||
| 7 关单条件 | §7 |
|
||||
| 8 安全与边界 | §8 |
|
||||
|
||||
## 1. 三角色职责
|
||||
|
||||
| 角色 | 能做 | 不能做 |
|
||||
|---|---|---|
|
||||
| **架构** | 需求、设计、把目标/范围/验收标准写成工单;维护工单正文与验收矩阵;写设计文档 | 不写业务代码、不改测试/依赖/构建配置、不推送、不启动其他 Agent |
|
||||
| **开发** | **唯一**可以改业务代码、测试、依赖、迁移、构建配置与项目文档的角色;自测、commit、打快照 tag、推送 main 与 tag | 不设置 `accepted`、不关单、不改验收标准、不部署 |
|
||||
| **验收** | 独立复核差异与版本信息,逐项判定 PASS/FAIL/BLOCKED;通过后置 `accepted` 并关单 | 不修复代码(发现问题置 `rework` 并把问题列清)、不自行 `checkout`/`reset` |
|
||||
| **prototype(UI)** | **仅**当工单涉及 UI 原型时介入,产出可打开的原型与交互证据 | 不参与非 UI 任务,不代替开发提交业务代码 |
|
||||
|
||||
角色约束是**流程约束**,不是技术 ACL 隔离:本机共用 Gitea 管理员凭据,谁也拦不住谁越权,
|
||||
所以每个角色都要靠"读回核实"而非"相信对方自述"来交付。
|
||||
|
||||
## 2. main 单线、单仓库串行
|
||||
|
||||
- 只使用 `main` 一条线:**不创建分支、不建 worktree、不走 PR、不做合并**(通用引擎规范里 PR 是可选姿态,
|
||||
本仓沿用"以直推为主"的口径)。
|
||||
- 同一仓库的代码修改**串行**:一个工单在主开发阶段只由一个开发会话持有。
|
||||
- **review 期间开发停止修改代码**:工单进入 `status:review` 后,除按 `rework` 要求修复外不再改动。
|
||||
- 切换现场前先取证:`git status --short --branch`、`git worktree list`、`git rev-parse origin/main`。
|
||||
工作区不干净、或存在不属于本工单的改动时**不得混入**,安全处理不了就置 `status:blocked`。
|
||||
- 别人的 feature 分支与成果原样保留:不 `reset`、不 `stash`、不 cherry-pick、不清理旧分支/worktree/tag。
|
||||
|
||||
## 3. 工单状态机
|
||||
|
||||
六个完整状态名,**互斥**,同一工单最多一个状态标签:
|
||||
|
||||
```
|
||||
status:ready → status:developing → status:review → status:accepted
|
||||
↑ │
|
||||
└── status:rework ─┘ status:blocked(可从中途进入,解除后回原状态)
|
||||
```
|
||||
|
||||
| 标签 | 含义 | 进入条件(缺一不可) |
|
||||
|---|---|---|
|
||||
| `status:ready` | 设计完成、用户已批准开发 | 用户明确批准;范围与验收标准写明 |
|
||||
| `status:developing` | 开发已领取并在实施 | 评论记录工单号、起始 SHA |
|
||||
| `status:review` | 已交付待独立验收 | commit/tag/推送/远端核实/交接证据齐全 |
|
||||
| `status:rework` | 验收失败 | 验收列出明确不通过项(不授权扩范围) |
|
||||
| `status:accepted` | 指定版本通过验收待核实交付 | 验收矩阵逐项通过,结论绑定 tag + 完整 SHA |
|
||||
| `status:blocked` | 受阻停手 | 有原因、处理人、解除条件、原状态;解除后**恢复原状态** |
|
||||
|
||||
- `Closed` 是 **Issue 状态**,不是标签:通过验收后由验收移除状态标签并关闭。
|
||||
- 未批准的工单保持 Open 且**不打** `status:ready`。
|
||||
- 标签 ID **按仓库实时读取**(`GET /api/v1/repos/{owner}/{repo}/labels`),不跨仓库复用 ID。
|
||||
- ⚠️ Gitea 1.26.2 实测:`PATCH /issues/{n}` 带 `labels` 返回 201 **却不改任何标签**(静默无效);
|
||||
替换标签必须用 `PUT /issues/{n}/labels`,且每次写完 `GET /issues/{n}` **读回核验**。
|
||||
- ⚠️ 本仓历史遗留标签 `status/working`(`/` 而非 `:`)不符合本约定,遇到时应归一为 `status:developing`。
|
||||
|
||||
## 4. 快照 tag 与正式版本分线
|
||||
|
||||
**两种版本语义必须分开**,混用会让 CI 变红或让快照被误当发布。
|
||||
|
||||
| | 快照(开发交付用) | 正式版本(发布用) |
|
||||
|---|---|---|
|
||||
| 命名 | `snapshot/vX.Y.Z` | `vX.Y.Z` |
|
||||
| 类型 | **注释 tag**(`git tag -a`) | **注释 tag**(`git tag -a`) |
|
||||
| 批准 | 开发按工单直接创建,序号递增 | **用户单独批准** |
|
||||
| 与 CHANGELOG 的关系 | 无要求;快照序号独立于构建显示版本,**不要求二者相等** | 必须同步写 `CHANGELOG.md` 顶部该版本段 |
|
||||
| CI 门禁 | 不被当作正式版本 | 受版本一致性门禁约束 |
|
||||
| 含义 | 代码快照,**不代表验收、不代表发布** | 发布事实,需 Release 等后续动作 |
|
||||
|
||||
**为什么不能用 `vX.Y.Z` 当快照(实测结论,勿凭直觉改回)**
|
||||
|
||||
- `make verify` → `scripts/check_changelog.py --tags`(`Makefile:27`、`scripts/ci_checks.py:254`)对每个
|
||||
`vX.Y.Z` tag 断言:tag 指到的提交里 `CHANGELOG.md` 顶部正式版本 == tag 版本,且必须是注释 tag
|
||||
(`scripts/check_changelog.py:44-45,257-278`)。
|
||||
- CI 检出会把 `git ls-remote --tags origin` 落成 `.ci-remote-tags` 并 `fetch --tags`(`.gitea/scripts/ci_checkout.sh:122,127`);
|
||||
`CI=true` 时拿不到清单直接判红 ⇒ **不带 CHANGELOG 段的正式 tag 会让 main 从此每次推送都红**。
|
||||
- 正式 tag 的匹配是 `^v(\d+\.\d+\.\d+)$`(`scripts/check_changelog.py:45`),`snapshot/v0.1.1` **不匹配**,
|
||||
因此不参与版本一致性判定;`scripts/version.py:119-151` 的发布证据也只认 `refs/tags/v<版本号>` 的注释 tag
|
||||
与 CHANGELOG 顶部一致 ⇒ 快照 tag 不会把构建身份变成 release。
|
||||
- 结论:快照一律用 `snapshot/vX.Y.Z`;要发正式版就单独走批准 + CHANGELOG 流程。
|
||||
- 修复后的下一快照序号递增(`snapshot/v0.1.2`),**不得移动已交付的快照 tag**。
|
||||
|
||||
## 5. 每轮可交接的完整链路 + 不可变性
|
||||
|
||||
一轮可交付的修改必须走完整条链,任何一步失败都要如实报告**实际状态**,不能假装完整交付:
|
||||
|
||||
```
|
||||
自测(真实命令 + 真实结果)
|
||||
→ commit(信息含工单号;不用 Closes/Fixes/Resolves 等自动关单关键词)
|
||||
→ 创建递增的不可变快照 tag(注释 tag)
|
||||
→ 正常推送 main 与该 tag
|
||||
→ 远端核实(main 含结束 SHA;tag 解引用后指向结束 SHA)
|
||||
→ 工单评论完整交接证据 → status:review
|
||||
```
|
||||
|
||||
- 开发的**正常 main 与快照 tag 推送无需逐次确认**;但**部署与正式发布不在授权内**。
|
||||
- 推送前必须先核查:目标名未被占用、推送是否会触发生产部署(`.gitea/workflows/` 里是否有 deploy 作业)。
|
||||
本仓唯一工作流 `build.yml` 头部明确"只做 CI,不做 CD"(`on: push: branches: "**"`)⇒ 普通 CI 允许放行。
|
||||
- **保留旧提交与旧 tag**:不强推、不覆盖、不删除旧 tag、不改写历史。
|
||||
- 回退只能由开发执行 `git revert` 并创建**新的**版本(`revert` + 递增快照),旧提交与旧 tag 原样留着。
|
||||
- CI 绿 ≠ 已部署;`main` 不是自动可发布版本。
|
||||
|
||||
## 6. 交接与验收模板
|
||||
|
||||
### 6.1 开发交接(写进工单评论)
|
||||
|
||||
| 字段 | 内容 |
|
||||
|---|---|
|
||||
| 工单 | 编号 + 标题 |
|
||||
| 起始 SHA | 动手前的 `origin/main` 完整 SHA |
|
||||
| 结束 SHA | 本次提交的完整 SHA |
|
||||
| tag | 快照 tag 名 + 类型(注释)+ 解引用后的 SHA |
|
||||
| 实现摘要 | 改了什么、为什么这么改 |
|
||||
| 文件清单 | `git diff --stat` 的范围,逐条列出 |
|
||||
| 测试命令与结果 | **真实执行的命令 + 真实输出**(不可只写"已测试") |
|
||||
| 已知问题 | 未验证项、环境限制、待批事项 |
|
||||
| 剩余完成项 | 明确列表;没有就写"无" |
|
||||
|
||||
### 6.2 验收结论(写进工单评论)
|
||||
|
||||
| 字段 | 内容 |
|
||||
|---|---|
|
||||
| 版本锚点 | tag + 完整 SHA(结论必须绑在这上面) |
|
||||
| 逐项判定 | 合同/矩阵每项 `PASS` / `FAIL` / `BLOCKED`,FAIL 必须列明确问题 |
|
||||
| 复验命令与结果 | 独立跑过的只读检查(如 `git diff --check`、远端 tag 读回)与真实输出 |
|
||||
| 问题与结论 | 通过 ⇒ 下一步;不通过 ⇒ 置 `rework` 并把问题列清;无法验证 ⇒ 置 `blocked` |
|
||||
|
||||
验收不得凭开发总结宣告通过;也不得自行 `checkout`/`reset` 去凑现场 —— 现场不对就要求开发准备。
|
||||
|
||||
## 7. 关单条件
|
||||
|
||||
同时满足才可关单:
|
||||
|
||||
1. 验收矩阵全部通过;
|
||||
2. 目标版本可追溯(tag + 完整 SHA 可读回);
|
||||
3. 远端交付已核实(远端 main 含结束 SHA,tag 解引用一致);
|
||||
4. 交接与验收文档齐全(含真实执行证据);
|
||||
5. 无未解除的阻塞项。
|
||||
|
||||
**不需要** PR、不需要合并、**不默认需要部署**。
|
||||
|
||||
## 8. 安全与边界
|
||||
|
||||
- 不提交任何密钥/隐私:决定只用 secret 文件(仓库外、0600),日志与评论不出现秘密与正文原文。
|
||||
- 每个外部写操作(标签、评论、tag、推送)都**读回核实**;结果不明确时不得宣布成功。
|
||||
- 不使用自动关单关键词,不绕过独立验收。
|
||||
- 角色约束不是技术隔离;`main` 也不是自动可发布版本。
|
||||
- 每次执行开始先确认:仓库、路径、工单、当前状态、最新评论、授权;缺一项且无法查询就先问,不猜。
|
||||
@@ -0,0 +1,75 @@
|
||||
# 整库封存(libraryctl)运维手册
|
||||
|
||||
本文只讲**测试库**的整库封存链:怎么跑、它证明了什么、它**没有**证明什么。生产发布与恢复、清理不在本文范围。
|
||||
|
||||
## 它做什么
|
||||
|
||||
`libraryctl capture -scope internal|external`:
|
||||
|
||||
1. 从**本机真实测试栈**(默认 Compose 项目 `weknora071full`)读来源配置:容器环境里的数据库/检索/对象存储参数,运行时读取,不落盘、不回显。
|
||||
2. 用**只读会话**(`default_transaction_read_only=on`)连来源 PostgreSQL;连接串只在进程内存里。
|
||||
3. 核对来源已结清:所有文档 `parse_status=completed`、无待处理操作、无死信(任一不满足就拒绝,不看其他 KB 的局部状态)。
|
||||
4. 从持久数据推出兼容契约:迁移版本、dirty、租户、Embedding 模型与维度、检索引擎、索引名、索引映射摘要(`text-embedding-v4` / 1024 维 / schema 74)。
|
||||
5. 在**维护窗口**内停住声明过的写入者(只对声明为 writer 的服务发 SIGTERM,等它真的停下),导出 PostgreSQL 十表 + Elasticsearch 正文与向量 + 对象资源,做双向覆盖与摘要核验,封存为内容寻址产物。
|
||||
6. 无论成败都恢复写入者并等到 healthy;崩溃留下的日志用 `libraryctl recover` 收尾。
|
||||
7. 打印快照 ID、分项(kind/name/数量/字节/SHA256)与兼容契约。
|
||||
|
||||
## 写入者声明(安全边界)
|
||||
|
||||
`scripts/library-capture.sh` 里逐项声明了项目内**每一个**服务:一个 writer(`app`),其余每个都写了"为什么它不会写知识"。`ProjectController` 的规则:
|
||||
|
||||
- 整个 Compose 项目被枚举(含停止的),只按声明停机;
|
||||
- 项目里出现未声明的服务 → **拒绝执行**,不会"只停已知的那几个";
|
||||
- 首次清点后固定容器 ID,容器被重建(同名新实例)→ 拒绝,避免停到一个没被声明的实例;
|
||||
- 只发 SIGTERM,没有会在恢复后才触发的 SIGKILL 定时器;
|
||||
- 启动后必须等到 healthy 才算恢复。
|
||||
|
||||
## 命令
|
||||
|
||||
```bash
|
||||
# 接线与来源探针(只读,不停服务)
|
||||
./scripts/library-capture.sh status
|
||||
# 预检:读来源 + 结清检查 + 候选校验,不写盘、不停服务
|
||||
./scripts/library-capture.sh preflight -scope internal
|
||||
# 真实封存(停 app → 导出 → 恢复 app)
|
||||
./scripts/library-capture.sh capture -scope internal
|
||||
./scripts/library-capture.sh capture -scope external
|
||||
# 已封存产物
|
||||
./scripts/library-capture.sh list
|
||||
./scripts/library-capture.sh verify -snapshot <id>
|
||||
# 崩溃后的收尾(恢复写入者)
|
||||
./scripts/library-capture.sh recover
|
||||
```
|
||||
|
||||
产物默认写到 `~/.local/share/knowledge-governance/library`(0700),日志写到 `~/.local/share/knowledge-governance/freeze`(0700)。api 容器只以只读方式挂载前者,「整库版本」页据此展示。
|
||||
|
||||
同一个作业号重跑是**幂等重放**:直接返回已封存的同一份候选(`replay=true`、`source_read=false`、`writers_stopped=false`),不读来源、不停写入者;同一作业号换了 scope 或绑定库则明确拒绝。
|
||||
|
||||
页面侧的发起入口尚未接线(需要最小权限的主机执行边界,见进度文件),当前只能在目标主机执行命令。
|
||||
|
||||
## 2026-10-28 实测(本机测试栈)
|
||||
|
||||
| 项 | 对内 | 对外 |
|
||||
| --- | --- | --- |
|
||||
| 快照 | `f992d64ea45bf737a0721a465b5aef2b150ef7757157eb84f3aaf8b6972d98f9` | `01343b0b310b3977c2fdda05f5b8a6272148c4f7bfa124a6c5944123cf0c51c3` |
|
||||
| 文档 / 分块 / 索引 | 4 / 38 / 122 | 0 / 0 / 0 |
|
||||
| 资源 / Wiki 页 | 21 / 31 | 0 / 1 |
|
||||
| 分项数 / 逻辑字节 | 32 / 55,309,044 | 13 / 1,121 |
|
||||
| 策略 | artifact-acceptance-v1 | artifact-acceptance-v1 |
|
||||
|
||||
两次封存都记录了 `stop_verified=true`、`restored=true`,`WKNFull-app` 恢复后 healthy;来源未做任何写操作。
|
||||
|
||||
## 它证明了什么 / 没有证明什么
|
||||
|
||||
已证明(A04 数据完整性口径):这一份整库内容在**写入者停住**之后被完整导出,PostgreSQL 与 Elasticsearch 双向覆盖、生成问题、资源与摘要逐项核验通过,产物可寻址、可复读、可校验。这正是封版所需的完整性口径。
|
||||
|
||||
用户已确认取消 A06:**不要求**内容、问答、引用/图片效果与性能测试及其报告,也不作为封版/生产发布门槛。因此这里不再把"没有做效果测试"列为缺口。
|
||||
|
||||
仍然不成立(不许把完整性通过说成这些):
|
||||
|
||||
- **跨 PG / ES / 资源的一致切点**只在维护窗口内取得;写入者组完整性有检查,但没有独立的切点证据,不能当成已验收的一致性证明;
|
||||
- **Wiki 删除贡献的语义重算**没有做;Wiki 队列空不等于语义正确;
|
||||
- 对外库当前是空的(0 文档 1 Wiki 页),这份快照只说明"它当时确实是空的";
|
||||
- 生产独立预备份、恢复演练、双闸授权、整库同步协调与失败续作都没有接线,本文不涉及;
|
||||
- 从页面发起封存、持久作业互斥、启动恢复还没有接线(封存目前只能在目标主机执行命令);
|
||||
- 上游父子分块漏正文索引的风险仍在:本次通过是因为库里现有数据已补齐,**以后再重解析**仍可能漏项,届时封存会因覆盖核验失败而阻断(这是设计如此)。
|
||||
@@ -0,0 +1,133 @@
|
||||
# 知识库级版本同步:开发与验收清单
|
||||
|
||||
## 交付边界
|
||||
|
||||
本清单记录已确认需求与验收条件,不表示功能已实现。日常编辑按文档,生产版本及恢复按知识库完整状态;发布管理仅有对内、对外两个目标。开发授权不包含生产同步、生产恢复或真实数据清理。生产执行仍须在发布管理经管理员授权;保留数量、天数、容量预算未设置,自动清理默认关闭。
|
||||
|
||||
现有文档包发布与执行级补偿只能作为复用基础,不能作为本清单完成证据。静态样图不作为产品运行证据。组织绩效与周报外发不在本次范围。
|
||||
|
||||
## 已确认:验收口径 A(原始产物)
|
||||
|
||||
用户选择不修改 WeKnora,以冻结的完整知识版本绑定内容、问答与性能验收。源端索引可能含未持久化的生成上下文,不再要求从 PostgreSQL 正文反推每条正文索引的生成过程。
|
||||
|
||||
- 原样归档索引内容与向量,不重新生成;继续校验库/文档/分块身份关联、覆盖、数量、资源及摘要。已持久化生成问题仍按 ID 和原文精确校验。
|
||||
- 新候选清单记录 `validation_policy=artifact-acceptance-v1`,该字段纳入内容寻址身份;历史无该字段的快照不冒称执行了新口径。
|
||||
- 候选归档成功不证明冻结、内容质量、问答正确性或性能通过。测试验收必须绑定具体快照身份;旧快照验收不得放行新快照。生产发布仍须独立授权。
|
||||
- 本次只完成候选产物保留和口径记录,真实冻结业务接线与持久化验收绑定尚未完成,不能因此放行生产。
|
||||
|
||||
## 已确认:封存隔离方案 A
|
||||
|
||||
用户选择封存期间自动暂停测试 WeKnora 服务,封存后恢复,不修改 WeKnora 源码。测试问答在暂停期间暂不可用,停用时长须实测;不暂停生产服务,也不因此取得生产同步、恢复或真实清理授权。
|
||||
|
||||
实现要求:先等待处理任务完成,枚举并核实全部测试写入者和副本;暂停后重新检查状态,数据库、索引和对象存储保持可读。持久记录暂停前运行状态及作业归属,覆盖成功、失败、取消和进程重启后的恢复;仅恢复本作业暂停的服务,并读回服务健康。完整归档封存后即可恢复测试服务,后续生产传输从归档读取,不延长测试停用时间。
|
||||
|
||||
方案已确认不等于暂停/恢复功能已实现;恢复保障验证前不停止运行中的测试服务。
|
||||
|
||||
## 开发与测试顺序
|
||||
|
||||
1. 核查实际 WeKnora 的文档删除、Wiki 更新与完成信号,以及跨数据库、对象、索引的快照与恢复契约。
|
||||
2. 实现完整版本清单、一致性校验、授权与持久化作业;逐项运行失败用例再实现通过。
|
||||
3. 接通实际导出、独立生产预备份、传输、验证、恢复及持久化进度;隔离环境演练故障、重启与重试。
|
||||
4. 发布管理接真实接口,存储管理接真实测量及依赖保护;验证浏览器交互与权限。
|
||||
5. 完整回归、审查、提交交付;生产实测单列等待授权,不以隔离验收代替。
|
||||
|
||||
## 验收项目
|
||||
|
||||
| ID | 范围 | 必须证明的行为 | 状态 |
|
||||
| --- | --- | --- | --- |
|
||||
| V01 | 两个目标 | 只按对内、对外操作;身份来自已配置映射,不按名称猜测 | 待验证 |
|
||||
| V02 | 测试就绪 | 全部解析、索引及 Wiki 就绪;问答与性能验收绑定本版,旧验收不能放行新变化 | 待验证 |
|
||||
| V03 | Wiki 撤销 | 删除文档后验证共享正文、实体、概念、边与引用的实际变化;删除成功或引用剥离不能代替此证据 | 待验证 |
|
||||
| V04 | 完整固定版本 | 清单覆盖文档集合、处理结果、资源、索引、完整 Wiki;无部分文档配整库 Wiki 的路径 | 待验证 |
|
||||
| V05 | 并发修改 | 导出中发生源变更时拒绝不一致版本,或由已证明的固定快照协议隔离;导出前后表面计数相同不算充分证明 | 待验证 |
|
||||
| V06 | 内容范围 | 仅允许知识数据;账号、会话、凭据及无关知识库不被同步或恢复 | 待验证 |
|
||||
| B01 | 写前预备份 | 每次生产变更前创建旧状态完整备份,校验恢复资料完整性;失败时零生产知识写入 | 待验证 |
|
||||
| B02 | 独立恢复依赖 | 资源在测试侧删除后,保留版本仍能恢复,不依赖测试临时对象或短期签名地址 | 待验证 |
|
||||
| B03 | 完整 Wiki 资产 | 每版保存完整 Wiki 及引用关联,校验摘要、数量和版本绑定 | 待验证 |
|
||||
| S01 | 数据同步 | 数据库、资源、索引、Wiki 均真实落地并校验,增量仅为传输优化 | 待验证 |
|
||||
| S02 | 无生产再计算 | 生产侧不解析、Embedding 或生成 Wiki,使用测试验收结果 | 待验证 |
|
||||
| S03 | 一致生效 | 不宣称不存在的跨系统原子性;明确可见性保护、失败补偿与验证边界 | 待验证 |
|
||||
| S04 | 故障与恢复 | 各阶段失败、超时与进程重启后可追溯、可恢复,不重复破坏性动作 | 待验证 |
|
||||
| S05 | 幂等与互斥 | 重复请求不启动重复同步;同目标同步、恢复、清理之间互斥;不同请求体复用键被拒绝 | 待验证 |
|
||||
| R01 | 版本恢复 | 恢复生产整套文档、资源、索引与 Wiki;测试知识库不回退 | 待验证 |
|
||||
| R02 | 恢复失败 | 不标记成功、不丢旧恢复依据,明确受影响阶段及后续可执行措施 | 待验证 |
|
||||
| R03 | 速度 | 分开实测备份与恢复耗时、数据量、吞吐及环境;未经测量不承诺快速 | 待验证 |
|
||||
| P01 | 作业阶段 | 持久化准备、备份、同步、验证、恢复阶段与开始/更新时间、错误;生产验证成功才完成 | 待验证 |
|
||||
| P02 | 四类进度 | 数据库记录、资源文件/字节、索引分块、Wiki 页面/关联数据来自实际测量;总量未知不造百分比 | 待验证 |
|
||||
| P03 | 明细 | 可查看实际对象、数量、字节、校验及异常;筛选与总量不依赖前端当前页 | 待验证 |
|
||||
| U01 | 主要入口 | 对内/对外切换、启动同步、版本与快照、当前作业预备份入口均可见;旧版历史可追溯 | 待验证 |
|
||||
| U02 | 权限 | 未就绪明确阻断原因;会话注入操作者;只读/工程师不能获得生产执行权限 | 待验证 |
|
||||
| U03 | 操作确认 | 启动、恢复显示准确目标及影响并保留授权;运行中禁止重复启动 | 待验证 |
|
||||
| D01 | 存储策略 | 未设阈值如实显示未设置,自动清理默认关闭,不隐含年龄删除 | 待验证 |
|
||||
| D02 | 占用测量 | 区分逻辑大小、独占、共享、实际占用;无法测量显示未知,不当成零 | 待验证 |
|
||||
| D03 | 保护引用 | 当前恢复依据、活跃作业、锁定/保留版本及共享资源受到保护 | 待验证 |
|
||||
| D04 | 清理预览 | 列明对象、依赖、受影响版本及可测释放量;执行前重新核验引用与活跃作业 | 待验证 |
|
||||
| D05 | 容量门禁 | 空间不足告警或阻断,不为继续作业偷删受保护备份 | 待验证 |
|
||||
| D06 | 测试残留 | 覆盖取件缓存、临时解析、同步暂存、失败上传、删除/重解析残留,不删除源文件 | 待验证 |
|
||||
| D07 | 实际回收 | 区分逻辑删除与实际释放,核查对象历史版本/分片及数据库、索引回收;保留版本清理后仍可恢复 | 待验证 |
|
||||
|
||||
## 证据登记规则
|
||||
|
||||
每项完成需附实现位置、运行命令与退出码、可回看的证据路径、验证环境及尚未覆盖范围。单元测试、隔离数据库集成、模拟外部服务、真实测试知识库、生产验收分别标注,不能相互替代。
|
||||
|
||||
真实清理和生产恢复尚未授权的项目保持待授权/待验证;不得为了打勾执行。整项范围未覆盖不得以子切片通过称为本阶段完成。
|
||||
|
||||
## 已运行的基础模块证据(不等于整体验收)
|
||||
|
||||
实现位置:`internal/librarysnapshot/` 与 `internal/releaseadapter/v071/library_*.go`。
|
||||
|
||||
- PostgreSQL 整库只读 Repeatable Read 导出:显式包含空 Wiki 表;未完成解析、删除文档残留任务、死信、未知 schema、Neo4j 启用场景拒绝自动放行。
|
||||
- Elasticsearch 使用 PIT 与 search_after,核查精确总量、返回范围、重复项与部分结果;PIT 只证明索引自身的视图。
|
||||
- 候选归档独立持有资源字节,校验表、scope、资源依赖、索引关联及摘要;内容寻址复用、重开加载、同一文件描述符校验读取、共享/独占引用字节已测试。引用字节不是物理占用或实际可回收字节。
|
||||
- `go test -race ./internal/librarysnapshot ./internal/releaseadapter/v071 -count=1`:退出码 0;默认跳过需要显式配置的隔离集成,不能据此声称集成通过。
|
||||
- 隔离 PostgreSQL + Elasticsearch 集成另行运行,退出码 0。只创建随机 `kg_library_test_` 前缀夹具;结束后 PostgreSQL 同前缀库残留计数为 0。
|
||||
- MVCC 反向自检:仅通过 Go overlay 把 Repeatable Read 改为 Read Committed,同一真实隔离集成退出码 1,失败断言为 `mixed PostgreSQL versions during export`。原始实现复跑退出码 0。
|
||||
- `make verify`:退出码 0。本地门禁不是远端 CI,也不是新 UI 或真实知识库完整验收。
|
||||
|
||||
证据保存在本机仓库忽略目录 `backups/library-sync-foundation-20261027/`:`unit-tests.jsonl`、`kg-library-integration.log`、`kg-library-mvcc-negative.log`、`kg-library-verify.log`。隔离执行脚本副本同目录留存,不含静态凭据;运行时从本地测试容器读取。
|
||||
|
||||
### 当前不能放行的边界
|
||||
|
||||
1. `ArchiveLibraryCandidate` 的 seal 只代表归档完整性,不代表跨系统同一时点、Wiki 语义验收通过或生产授权。尚未接到生产执行器。
|
||||
2. 数据库 MVCC 与 ES PIT 是各自独立的快照,不能把两者拼接视为一致整版。用户已确认方案 A:封存期间自动暂停测试服务;全部写入者隔离、异常恢复及实际停用时长尚待实现与验证,不修改 WeKnora 源码,不暂停生产。
|
||||
3. 已检查本地 v0.7.1 源码:`EnqueueWikiRetract` 在持久化 pending op 失败时记录警告后返回;因此 pending/dead-letter 都为空仍不证明撤销语义已处理。必须补充删除后共享 Wiki 内容的实测与验收绑定。
|
||||
4. 生产预备份、独立恢复演练、持久化协调作业、授权 API、真实进度、发布页面与完整存储治理仍未交付;以上验收项目保持待验证。
|
||||
5. 基础模块已随 `0.1.96 / 9105f8316cc870a62b5ddacd1496f0cb0f798d87` 提交、推送并部署到本地测试治理平台;运行 API/worker 的二进制摘要已读回校验。该部署不等于业务功能接线或完整验收通过;未执行生产同步、恢复或真实业务清理。完整验收仍受本节及下述缺失接线阻塞。
|
||||
|
||||
## 真实测试源只读诊断(未通过)
|
||||
|
||||
`TestLibrarySourceReadOnlyDiagnostic` 仅在明确 opt-in 下运行,数据库连接强制只读;只调用 ES 查询/PIT 和 OSS 对象读取,不执行生产操作、源数据清理或服务暂停。测试凭据仅通过子进程环境注入,不记录配置值。
|
||||
|
||||
本次实际执行退出码 1:对内库 125 条索引记录中有 13 条关联到未被完整文档集合纳入的分块;进一步只读查询定位为 4 个未删除分块(3 个 text、1 个 summary)缺少同租户的父文档,不是临时上下文内容比较失败。现有身份校验保持拒绝,没有忽略这些记录或据此放行。独立 OSS 读取校验覆盖 21 个资源、53,490,166 字节。对外库读到 0 文档、0 分块、1 个 Wiki 页面,候选结构归档可读回,但未冻结且模型兼容身份为明确诊断占位,不能当作版本验收通过。
|
||||
|
||||
证据:`backups/library-source-readonly-20261028/`。真实源诊断失败与默认 CI 的环境跳过分别记录;此次发现不授权清理这批分块或索引,之前仅限死信 ID 1 的授权不扩展使用。
|
||||
|
||||
## 联合隔离捕获验收
|
||||
|
||||
新增 `TestLibraryCaptureIsolatedStack`,在同一次 `CaptureLibrary` 调用中连接真实隔离 PostgreSQL、随机 Elasticsearch 索引、真实 Docker 暂停/恢复控制器和本地资源文件读取器。写入服务使用无网络、无宿主挂载的 busybox 夹具,不是实际 WeKnora;资源读取不是实际 OSS/S3 验收。
|
||||
|
||||
- 非空文档、分块、资源、Wiki 正文及字符串状态归档后读回;检查无跨租户记录或会话数据泄漏。
|
||||
- 删除真实夹具索引记录后,新捕获必须失败,原运行容器仍恢复健康。
|
||||
- 删除源资源文件、修改源 PostgreSQL、删除源 ES 文档后,成功作业重放仍返回原快照,不再调用源端就绪检查或资源读取;归档重新加载通过。
|
||||
- 反向自检使用 Go overlay 仅关闭 legacy 索引覆盖检查:同一联合用例退出码 1,明确报 `missing real index accepted`;未修改的实现复跑退出码 0。
|
||||
- `make verify` 与三包 race 回归退出码 0;新用例在默认 CI 中显式声明环境跳过,本地单独实际执行。夹具索引和容器删除后读回不存在,随机隔离数据库已删除。
|
||||
|
||||
证据:`backups/library-stack-acceptance-20261028/`。该联合用例补充捕获协调证据,不证明真实源全部写入者受控、Wiki 撤销语义、内容/问答/性能验收绑定或生产同步恢复已经完成。
|
||||
|
||||
## 方案 A:暂停与恢复原语的实测证据
|
||||
|
||||
新增 `internal/libraryfreeze/`,包含持久化作业日志、源服务组互斥、暂停前原运行状态、不可变容器 ID、恢复读回,以及本地 Unix socket Docker 控制器。Docker 控制器只接受对应 source 且 `environment=test`、`freeze-role=writer` 的容器;不按模糊名称选取,不控制数据库/索引存储,不使用远程默认 Docker context。运行容器必须有健康检查。
|
||||
|
||||
已经执行的验证:
|
||||
|
||||
- `go test -race ./internal/libraryfreeze ./internal/librarysnapshot ./internal/releaseadapter/v071 -count=1`,退出码 0。
|
||||
- `KG_FREEZE_DOCKER_ISOLATED=1 go test -race -v ./internal/libraryfreeze -run '^TestFreezeIsolatedDocker$' -count=1`,退出码 0。使用已缓存 busybox 创建随机标签、无网络、无宿主挂载的一次性容器,真实验证停止→捕获窗口→重启健康、原本停止容器不启动;控制子进程在停止后退出,再由新恢复调用读持久日志启动原容器。清理后按标签读回无残留。
|
||||
- 异常覆盖:停止回包丢失、停止未生效、新副本出现、容器被替换、捕获错误/panic/取消、日志写入失败、恢复健康失败、畸形日志、同源并发及重复恢复。捕获 panic 和日志失写故障先实际报红,修复后通过。
|
||||
- 不使用有延迟强杀计时器的停止方式;仅发送 SIGTERM 并等待实际停止。若停止结果不明且服务仍运行,不把“现在运行”误判为已恢复,日志保持待恢复,防止随后迟到的停止把服务留在关闭状态。
|
||||
- 新增 Docker 集成用例已在 `scripts/test-scope.json` 精确声明 opt-in;普通 CI 明确跳过,不冒称执行。完整 `make verify` 退出码 0,属于本地门禁。
|
||||
|
||||
证据:本机 `backups/library-sync-foundation-20261027/kg-freeze-docker-integration.log`、`kg-library-freeze-verify.log`。
|
||||
|
||||
已新增 `internal/releaseadapter/v071/library_capture.go`,在源服务组互斥下串起预检、暂停、停后复检、PG/ES 导出、独立归档和恢复。协调测试使用 PG/服务控制夹具与 HTTP 搜索夹具,覆盖预检忙时零停止、暂停前后新增任务阻断、搜索失败恢复、旧作业重放不重新暂停、跨 scope 复用拒绝、归档丢失不返回成功;不把这组夹具当成实际业务知识库全链路验收。最终竞态回归、隔离 Docker 重跑与 `make verify` 均退出码 0,最终日志为同目录 `kg-freeze-docker-final.log`、`kg-library-freeze-final-verify.log`。
|
||||
|
||||
**仍缺少的接线**:真实测试部署的全部写入者枚举及标签/健康契约、部署侧入口及后台作业就绪检查的实际提供方、worker 调用捕获协调函数、启动恢复入口和持续恢复调度。`CaptureLibrary` 已强制在暂停前后检查整个源数据库的解析、pending 与 dead-letter 状态(跨库、跨租户及未知/删除范围);此检查不能代替入口隔离与 Wiki 语义验收。单独的本地 Docker 控制器不能控制远端测试主机;远端场景需在测试主机运行受限执行器,不能向浏览器或普通 API 暴露 Docker socket。上述测试不能证明这些接线已完成,尚未暂停实际测试 WeKnora。
|
||||
@@ -29,6 +29,7 @@ require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/yuin/goldmark v1.7.4 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
|
||||
@@ -52,6 +52,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/yuin/goldmark v1.7.4 h1:BDXOHExt+A7gwPCJgPIIq7ENvceR7we7rOS9TNoLZeg=
|
||||
github.com/yuin/goldmark v1.7.4/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
|
||||
@@ -69,6 +69,9 @@ type Config struct {
|
||||
VersionHistoryAllowedOrigins []string
|
||||
// VersionHistoryLinkOrigin 是**页面链接**用的 origin(给内网外的浏览器点开),
|
||||
// 留空即与抓取 origin 相同。只用于拼展示链接,不参与任何请求。
|
||||
// LibraryArchiveRoot 是整库封存产物的只读归档根(主机私有 0700 目录的只读挂载)。
|
||||
// 留空即"未接线":页面只显示原因,不显示空表冒充没有快照。
|
||||
LibraryArchiveRoot string
|
||||
VersionHistoryLinkOrigin string
|
||||
VersionHistoryHTTPTimeout time.Duration
|
||||
VersionHistoryMaxPages int
|
||||
@@ -116,6 +119,7 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
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")),
|
||||
LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")),
|
||||
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
|
||||
VersionHistoryHTTPTimeout: 15 * time.Second,
|
||||
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
|
||||
@@ -226,6 +230,9 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if config.LibraryArchiveRoot != "" && !filepath.IsAbs(config.LibraryArchiveRoot) {
|
||||
return Config{}, errors.New("LIBRARY_ARCHIVE_ROOT 必须是绝对路径(归档根按只读目录挂载)")
|
||||
}
|
||||
if config.TestWeKnoraHTTPTimeout, err = durationOrDefault(getenv("TEST_WEKNORA_HTTP_TIMEOUT"), config.TestWeKnoraHTTPTimeout); err != nil {
|
||||
return Config{}, fmt.Errorf("TEST_WEKNORA_HTTP_TIMEOUT: %w", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// CredentialStatus contains metadata only, never credential values.
|
||||
type CredentialStatus struct {
|
||||
Authenticated bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at,omitempty"`
|
||||
}
|
||||
|
||||
func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, error) {
|
||||
raw, err := runner.RunDWS(ctx, "auth", "status", "--readonly", "--format", "json")
|
||||
if err != nil {
|
||||
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"`
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCredentialStatusReadOnlyMetadata(t *testing.T) {
|
||||
key := "auth status --readonly --format json"
|
||||
runner := &fakeRunner{responses: map[string]string{key: `{"authenticated":true,"refresh_token_valid":true,"expires_at":"2026-10-26T20:21:10+08:00","refresh_expires_at":"2026-11-25T18:21:10+08:00","access_token":"not-a-real-secret"}`}}
|
||||
result, err := ReadCredentialStatus(context.Background(), runner)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !result.Authenticated || !result.RefreshTokenValid || len(runner.seen) != 1 || runner.seen[0] != key {
|
||||
t.Fatalf("unexpected status or command: %+v %+v", result, runner.seen)
|
||||
}
|
||||
raw, _ := json.Marshal(result)
|
||||
if strings.Contains(string(raw), "not-a-real-secret") || strings.Contains(string(raw), "access_token") {
|
||||
t.Fatal("credential leaked")
|
||||
}
|
||||
}
|
||||
func TestCredentialStatusRejectsUnknownOutput(t *testing.T) {
|
||||
_, err := ReadCredentialStatus(context.Background(), &fakeRunner{})
|
||||
if err == nil {
|
||||
t.Fatal("missing authentication field accepted")
|
||||
}
|
||||
}
|
||||
func TestCredentialStatusLoggedOut(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{"auth status --readonly --format json": `{"authenticated":false}`}}
|
||||
got, err := ReadCredentialStatus(context.Background(), runner)
|
||||
if err != nil || got.Authenticated {
|
||||
t.Fatalf("%+v %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DocumentNode 是一篇钉钉在线文档/表格,用于「钉钉文档·表格」这一类数据源:
|
||||
// 它不在知识库、也不在钉盘的目录树里,只能按节点单独登记。
|
||||
type DocumentNode struct {
|
||||
NodeID string `json:"node_id"`
|
||||
NodeType string `json:"node_type"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
ContentType string `json:"content_type"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// DocResult 是一次文档发现的结果。Notice 说明「为什么没列全」,不把失败伪装成空列表。
|
||||
type DocResult struct {
|
||||
Documents []DocumentNode `json:"documents"`
|
||||
Notice string `json:"notice,omitempty"`
|
||||
FetchedAt time.Time `json:"fetched_at"`
|
||||
}
|
||||
|
||||
// RecentDocsArgs 列出最近编辑的文档;没有关键词时的默认入口。
|
||||
func RecentDocsArgs(limit int) []string {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
return []string{"drive", "+recent", "--operate-type", "1", "--limit", "20", "--page-all",
|
||||
"--max-items", fmt.Sprint(limit), "--max-pages", "10"}
|
||||
}
|
||||
|
||||
// SearchDocsArgs 按关键词在文档空间检索。
|
||||
func SearchDocsArgs(query string, limit int) []string {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
return []string{"drive", "+search-docs", "--query", query, "--limit", fmt.Sprint(limit)}
|
||||
}
|
||||
|
||||
// DocInfoArgs / SheetListArgs 是校验「这篇还能不能读」的只读命令:
|
||||
// 文档取元信息,表格取工作表清单——都真实打一次接口,不用缓存谎报可读。
|
||||
func DocInfoArgs(node string) []string { return []string{"doc", "info", "--node", node} }
|
||||
func SheetListArgs(node string) []string { return []string{"sheet", "list", "--node", node} }
|
||||
|
||||
// IsSheet 判断节点是否表格:表格要用 sheet 校验,文档用 doc。
|
||||
func IsSheet(contentType string) bool {
|
||||
kind := strings.ToUpper(strings.TrimSpace(contentType))
|
||||
return strings.Contains(kind, "SHEET") || strings.Contains(kind, "ABLE")
|
||||
}
|
||||
|
||||
// DiscoverDocs 枚举可登记的在线文档:有关键词就检索,没有就给最近编辑的一批。
|
||||
// 与 Discover 一样,读不到就返回 ErrUnavailable,而不是空结果。
|
||||
func DiscoverDocs(ctx context.Context, runner Runner, query string, limit int) (DocResult, error) {
|
||||
result := DocResult{FetchedAt: time.Now().UTC()}
|
||||
args := RecentDocsArgs(limit)
|
||||
if trimmed := strings.TrimSpace(query); trimmed != "" {
|
||||
args = SearchDocsArgs(trimmed, limit)
|
||||
}
|
||||
raw, err := runner.RunDWS(ctx, args...)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
docs, notice, err := parseDocs(raw)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
result.Documents, result.Notice = docs, notice
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ValidateDocument 真实读一次节点,返回它的规范元信息;读不到就是不可登记。
|
||||
func ValidateDocument(ctx context.Context, runner Runner, node string) (DocumentNode, error) {
|
||||
node = strings.TrimSpace(node)
|
||||
if node == "" {
|
||||
return DocumentNode{}, fmt.Errorf("%w: empty node", ErrUnavailable)
|
||||
}
|
||||
raw, err := runner.RunDWS(ctx, DocInfoArgs(node)...)
|
||||
if err != nil {
|
||||
return DocumentNode{}, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
doc, err := parseDocInfo(raw)
|
||||
if err != nil {
|
||||
return DocumentNode{}, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
if doc.NodeID == "" {
|
||||
doc.NodeID = node
|
||||
}
|
||||
if IsSheet(doc.ContentType) {
|
||||
if _, err := runner.RunDWS(ctx, SheetListArgs(doc.NodeID)...); err != nil {
|
||||
return DocumentNode{}, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// parseDocs 解析 `drive +recent` / `drive +search-docs`:
|
||||
// {"ok":true,"data":{"items":[{nodeId,nodeType,name,docUrl,contentType,accessTime}]}}
|
||||
// 第二个返回值是「结果不完整」的说明(服务端还有下一页或条目被截断)。
|
||||
func parseDocs(raw []byte) ([]DocumentNode, string, error) {
|
||||
var payload struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Count int `json:"count"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
Items []struct {
|
||||
NodeID string `json:"nodeId"`
|
||||
NodeType string `json:"nodeType"`
|
||||
Name string `json:"name"`
|
||||
DocURL string `json:"docUrl"`
|
||||
ContentType string `json:"contentType"`
|
||||
AccessTime string `json:"accessTime"`
|
||||
} `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return nil, "", fmt.Errorf("decode docs: %w", err)
|
||||
}
|
||||
if !payload.OK {
|
||||
return nil, "", errors.New("docs listing reported failure")
|
||||
}
|
||||
out := make([]DocumentNode, 0, len(payload.Data.Items))
|
||||
seen := map[string]bool{}
|
||||
for _, item := range payload.Data.Items {
|
||||
id := strings.TrimSpace(item.NodeID)
|
||||
if id == "" || seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
nodeType := strings.TrimSpace(item.NodeType)
|
||||
if nodeType == "" {
|
||||
nodeType = "file"
|
||||
}
|
||||
out = append(out, DocumentNode{
|
||||
NodeID: id,
|
||||
NodeType: nodeType,
|
||||
Name: strings.TrimSpace(item.Name),
|
||||
URL: strings.TrimSpace(item.DocURL),
|
||||
ContentType: strings.TrimSpace(item.ContentType),
|
||||
UpdatedAt: strings.TrimSpace(item.AccessTime),
|
||||
})
|
||||
}
|
||||
notice := ""
|
||||
if payload.Data.HasMore {
|
||||
notice = fmt.Sprintf("只列出前 %d 篇,还有更多;用关键词检索可以找到其余的。", len(out))
|
||||
}
|
||||
return out, notice, nil
|
||||
}
|
||||
|
||||
// parseDocInfo 解析 `dws doc info --node`。服务端字段是 camelCase,部分历史响应是
|
||||
// snake_case,两种都认,避免因为命名差异把可读文档判成不可读。
|
||||
func parseDocInfo(raw []byte) (DocumentNode, error) {
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return DocumentNode{}, fmt.Errorf("decode doc info: %w", err)
|
||||
}
|
||||
if ok, present := payload["ok"].(bool); present && !ok {
|
||||
return DocumentNode{}, errors.New("doc info reported failure")
|
||||
}
|
||||
source := payload
|
||||
if data, ok := payload["data"].(map[string]any); ok {
|
||||
source = data
|
||||
}
|
||||
pick := func(keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if value, ok := source[key].(string); ok && strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
doc := DocumentNode{
|
||||
NodeID: pick("nodeId", "node_id", "dentUuid", "dentryUuid", "id"),
|
||||
NodeType: pick("nodeType", "node_type"),
|
||||
Name: pick("name", "title", "docName"),
|
||||
URL: pick("docUrl", "doc_url", "url"),
|
||||
ContentType: pick("contentType", "content_type", "extension"),
|
||||
UpdatedAt: pick("updateTime", "updatedAt", "modifiedTime"),
|
||||
}
|
||||
if doc.NodeType == "" {
|
||||
doc.NodeType = "file"
|
||||
}
|
||||
if doc.Name == "" {
|
||||
return DocumentNode{}, errors.New("doc info has no title")
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const recentDocsFixture = `{"ok":true,"data":{"count":2,"hasMore":false,"items":[
|
||||
{"nodeId":"node-a","nodeType":"file","name":"售后周会纪要","docUrl":"https://alidocs.dingtalk.com/i/nodes/node-a","contentType":"ALIDOC","accessTime":"2026-10-25T10:00:00Z"},
|
||||
{"nodeId":"node-b","nodeType":"file","name":"服务工单统计","docUrl":"https://alidocs.dingtalk.com/i/nodes/node-b","contentType":"ALISHEET","accessTime":"2026-10-24T09:00:00Z"}]}}`
|
||||
|
||||
func TestDiscoverDocsListsRecentDocumentsWithTheirType(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{strings.Join(RecentDocsArgs(50), " "): recentDocsFixture}}
|
||||
result, err := DiscoverDocs(context.Background(), runner, "", 50)
|
||||
if err != nil {
|
||||
t.Fatalf("discover docs: %v", err)
|
||||
}
|
||||
if len(result.Documents) != 2 {
|
||||
t.Fatalf("documents = %d, want 2", len(result.Documents))
|
||||
}
|
||||
// 文档与表格必须能区分:表格要走 sheet 校验,文档走 doc。
|
||||
if got := result.Documents[1]; got.ContentType != "ALISHEET" || !IsSheet(got.ContentType) {
|
||||
t.Fatalf("sheet node not recognised: %+v", got)
|
||||
}
|
||||
if IsSheet(result.Documents[0].ContentType) {
|
||||
t.Fatal("an ALIDOC document must not be treated as a sheet")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDocsSearchesByKeywordWhenOneIsGiven(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{strings.Join(SearchDocsArgs("周会", 50), " "): recentDocsFixture}}
|
||||
if _, err := DiscoverDocs(context.Background(), runner, " 周会 ", 50); err != nil {
|
||||
t.Fatalf("search docs: %v", err)
|
||||
}
|
||||
if got := runner.seen[0]; !strings.Contains(got, "+search-docs") || !strings.Contains(got, "--query 周会") {
|
||||
t.Fatalf("keyword search was not used: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDocsReportsUnavailableInsteadOfAnEmptyList(t *testing.T) {
|
||||
runner := &fakeRunner{failures: map[string]error{strings.Join(RecentDocsArgs(50), " "): errors.New("token expired")}}
|
||||
if _, err := DiscoverDocs(context.Background(), runner, "", 50); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("want ErrUnavailable, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDocumentAsksForSheetSheetsWhenTheNodeIsATable(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{
|
||||
strings.Join(DocInfoArgs("node-b"), " "): `{"ok":true,"data":{"nodeId":"node-b","name":"服务工单统计","contentType":"ALISHEET"}}`,
|
||||
strings.Join(SheetListArgs("node-b"), " "): `{"ok":true,"data":{"sheets":[{"sheetId":"s1","name":"10月"}]}}`,
|
||||
}}
|
||||
doc, err := ValidateDocument(context.Background(), runner, "node-b")
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if doc.Name != "服务工单统计" {
|
||||
t.Fatalf("name = %q", doc.Name)
|
||||
}
|
||||
if len(runner.seen) != 2 || !strings.HasPrefix(runner.seen[1], "sheet list") {
|
||||
t.Fatalf("a table must be verified with sheet list, calls = %v", runner.seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDocumentRejectsUnreadableNodes(t *testing.T) {
|
||||
runner := &fakeRunner{failures: map[string]error{strings.Join(DocInfoArgs("node-x"), " "): errors.New("404")}}
|
||||
if _, err := ValidateDocument(context.Background(), runner, "node-x"); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("want ErrUnavailable, got %v", err)
|
||||
}
|
||||
if _, err := ValidateDocument(context.Background(), runner, " "); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatal("an empty node must not validate")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// aclProbeSQL 只用目录/ACL 函数判断"这个连接是不是最小只读":
|
||||
// - 角色属性:SUPER/CREATEROLE/CREATEDB/BYPASSRLS/REPLICATION
|
||||
// - 库/模式级:public schema CREATE、当前库 CREATE
|
||||
// - 继承面:角色成员关系数、可 SET ROLE 到的角色数
|
||||
// - 所有权:该角色拥有的 relation / schema 数
|
||||
// - "直接 ACL 只读但有效权限可写"的风险面:可执行的 SECURITY DEFINER 函数数
|
||||
// - 四张目标表的 SELECT 与写权限
|
||||
//
|
||||
// 它不改任何东西,也不尝试任何写语句(工单明确禁止用"写后回滚"证明只读)。
|
||||
const aclProbeSQL = `
|
||||
SELECT current_user,
|
||||
COALESCE((SELECT rolsuper FROM pg_roles WHERE rolname = current_user), FALSE),
|
||||
COALESCE((SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user), FALSE),
|
||||
COALESCE((SELECT rolcreatedb FROM pg_roles WHERE rolname = current_user), FALSE),
|
||||
COALESCE((SELECT rolbypassrls FROM pg_roles WHERE rolname = current_user), FALSE),
|
||||
COALESCE((SELECT rolreplication FROM pg_roles WHERE rolname = current_user), FALSE),
|
||||
has_schema_privilege(current_user, 'public', 'CREATE'),
|
||||
has_database_privilege(current_user, current_database(), 'CREATE'),
|
||||
(SELECT count(*)::int FROM pg_auth_members WHERE member = (SELECT oid FROM pg_roles WHERE rolname = current_user)),
|
||||
(SELECT count(*)::int FROM pg_roles r WHERE r.rolname <> current_user AND pg_has_role(current_user, r.oid, 'SET')),
|
||||
(SELECT count(*)::int FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE c.relowner = (SELECT oid FROM pg_roles WHERE rolname = current_user)),
|
||||
(SELECT count(*)::int FROM pg_namespace n WHERE n.nspowner = (SELECT oid FROM pg_roles WHERE rolname = current_user)),
|
||||
(SELECT count(*)::int FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
||||
WHERE p.prosecdef AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
||||
AND has_function_privilege(current_user, p.oid, 'EXECUTE')),
|
||||
has_table_privilege(current_user, 'public.turns', 'SELECT'),
|
||||
has_table_privilege(current_user, 'public.turns', 'INSERT'),
|
||||
has_table_privilege(current_user, 'public.turns', 'UPDATE'),
|
||||
has_table_privilege(current_user, 'public.turns', 'DELETE'),
|
||||
has_table_privilege(current_user, 'public.turns', 'TRUNCATE'),
|
||||
has_table_privilege(current_user, 'public.messages', 'SELECT'),
|
||||
has_table_privilege(current_user, 'public.messages', 'INSERT'),
|
||||
has_table_privilege(current_user, 'public.messages', 'UPDATE'),
|
||||
has_table_privilege(current_user, 'public.messages', 'DELETE'),
|
||||
has_table_privilege(current_user, 'public.messages', 'TRUNCATE'),
|
||||
has_table_privilege(current_user, 'public.coverage_decisions', 'SELECT'),
|
||||
has_table_privilege(current_user, 'public.coverage_decisions', 'INSERT'),
|
||||
has_table_privilege(current_user, 'public.coverage_decisions', 'UPDATE'),
|
||||
has_table_privilege(current_user, 'public.coverage_decisions', 'DELETE'),
|
||||
has_table_privilege(current_user, 'public.coverage_decisions', 'TRUNCATE'),
|
||||
has_table_privilege(current_user, 'public.channel_actors', 'SELECT'),
|
||||
has_table_privilege(current_user, 'public.channel_actors', 'INSERT'),
|
||||
has_table_privilege(current_user, 'public.channel_actors', 'UPDATE'),
|
||||
has_table_privilege(current_user, 'public.channel_actors', 'DELETE'),
|
||||
has_table_privilege(current_user, 'public.channel_actors', 'TRUNCATE')`
|
||||
|
||||
// ACLReport 是自检结果,用于启动日志与运维核对(不含任何业务数据)。
|
||||
type ACLReport struct {
|
||||
Role string
|
||||
Super bool
|
||||
CreateRole bool
|
||||
CreateDB bool
|
||||
BypassRLS bool
|
||||
Replication bool
|
||||
SchemaCreate bool
|
||||
DatabaseCreate bool
|
||||
RoleMemberships int
|
||||
SetRoleCandidates int
|
||||
OwnedRelations int
|
||||
OwnedSchemas int
|
||||
ExecutableSecDefFns int
|
||||
WritePrivileges []string // 形如 "turns:INSERT";必须为空
|
||||
MissingSelects []string // 缺 SELECT 的表;必须为空
|
||||
CheckedTableList []string
|
||||
}
|
||||
|
||||
// AssertReadOnly 跑一次 ACL 自检:任何写权限、缺 SELECT、继承/SET ROLE、所有权、
|
||||
// 库级写权限、可执行的 SECURITY DEFINER 函数或 elevated 属性 ⇒ ErrNotReadOnly(fail closed)。
|
||||
func AssertReadOnly(ctx context.Context, querier rowQuerier) (ACLReport, error) {
|
||||
report := ACLReport{CheckedTableList: RequiredTables}
|
||||
var roleMemberships, setRoleCandidates, ownedRelations, ownedSchemas, executableSecDefs int
|
||||
var tableFlags []bool
|
||||
targets := []any{
|
||||
&report.Role, &report.Super, &report.CreateRole, &report.CreateDB, &report.BypassRLS,
|
||||
&report.Replication, &report.SchemaCreate, &report.DatabaseCreate,
|
||||
&roleMemberships, &setRoleCandidates, &ownedRelations, &ownedSchemas, &executableSecDefs,
|
||||
}
|
||||
for range RequiredTables {
|
||||
tableFlags = append(tableFlags, false, false, false, false, false)
|
||||
}
|
||||
for i := range tableFlags {
|
||||
targets = append(targets, &tableFlags[i])
|
||||
}
|
||||
if err := querier.QueryRow(ctx, aclProbeSQL).Scan(targets...); err != nil {
|
||||
return ACLReport{}, fmt.Errorf("%w: ACL probe failed", ErrUnavailable)
|
||||
}
|
||||
report.RoleMemberships = roleMemberships
|
||||
report.SetRoleCandidates = setRoleCandidates
|
||||
report.OwnedRelations = ownedRelations
|
||||
report.OwnedSchemas = ownedSchemas
|
||||
report.ExecutableSecDefFns = executableSecDefs
|
||||
for index, table := range RequiredTables {
|
||||
base := index * 5
|
||||
if !tableFlags[base] {
|
||||
report.MissingSelects = append(report.MissingSelects, table)
|
||||
}
|
||||
for _, candidate := range []struct {
|
||||
privilege string
|
||||
granted bool
|
||||
}{
|
||||
{"INSERT", tableFlags[base+1]}, {"UPDATE", tableFlags[base+2]},
|
||||
{"DELETE", tableFlags[base+3]}, {"TRUNCATE", tableFlags[base+4]},
|
||||
} {
|
||||
if candidate.granted {
|
||||
report.WritePrivileges = append(report.WritePrivileges, table+":"+candidate.privilege)
|
||||
}
|
||||
}
|
||||
}
|
||||
var problems []string
|
||||
if report.Super || report.CreateRole || report.CreateDB || report.BypassRLS || report.Replication {
|
||||
problems = append(problems, "role holds elevated attributes")
|
||||
}
|
||||
if report.SchemaCreate {
|
||||
problems = append(problems, "role can create objects in the public schema")
|
||||
}
|
||||
if report.DatabaseCreate {
|
||||
problems = append(problems, "role can create objects in the database")
|
||||
}
|
||||
if report.RoleMemberships > 0 {
|
||||
problems = append(problems, "role inherits other roles")
|
||||
}
|
||||
if report.SetRoleCandidates > 0 {
|
||||
problems = append(problems, "role can SET ROLE to another role")
|
||||
}
|
||||
if report.OwnedRelations > 0 || report.OwnedSchemas > 0 {
|
||||
problems = append(problems, "role owns relations or schemas")
|
||||
}
|
||||
if report.ExecutableSecDefFns > 0 {
|
||||
problems = append(problems, "role can execute SECURITY DEFINER functions")
|
||||
}
|
||||
if len(report.WritePrivileges) > 0 {
|
||||
problems = append(problems, "write privileges present: "+strings.Join(report.WritePrivileges, ", "))
|
||||
}
|
||||
if len(report.MissingSelects) > 0 {
|
||||
problems = append(problems, "missing SELECT on: "+strings.Join(report.MissingSelects, ", "))
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return report, fmt.Errorf("%w: %s", ErrNotReadOnly, strings.Join(problems, "; "))
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// rowQuerier 是本包需要的最小查询面(*pgxpool.Pool 满足)。
|
||||
type rowQuerier interface {
|
||||
QueryRow(ctx context.Context, sql string, args ...any) rowScanner
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Package dobotaiops provides the governance backend's independent read-only
|
||||
// access to DobotAI production Q&A. It never runs source migrations or writes
|
||||
// source business data. Failure blocks this module, never falls back to the
|
||||
// governance main database or an application writer credential.
|
||||
// Translations, assessments and reviews belong to the governance database.
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnavailable:外部只读接入当前不可用(未配置、secret 缺失或不可读、
|
||||
// 拨号/连接失败)。调用方应把它当成"这一块功能没开",治理自身功能继续工作。
|
||||
ErrUnavailable = errors.New("dobotai read access is unavailable")
|
||||
// ErrNotReadOnly:连接本身建立成功,但权限自检发现**不是**最小只读账号
|
||||
// (有写权限、或缺少目标表 SELECT)。这是配置/账号问题,必须 fail closed。
|
||||
ErrNotReadOnly = errors.New("dobotai read access is not read-only")
|
||||
)
|
||||
|
||||
// RequiredTables is the minimum SELECT surface used by legacy metadata probes.
|
||||
// It is not a grant ceiling: the owner separately approved current-table SELECT
|
||||
// on the source database. All business queries still project fixed safe fields.
|
||||
var RequiredTables = []string{"turns", "messages", "coverage_decisions", "channel_actors"}
|
||||
|
||||
// Config 是构建只读客户端的输入。所有时间/连接参数都有硬上限,防止误配把生产拖垮。
|
||||
type Config struct {
|
||||
// DSNFile 是仓库外的 secret 文件路径(0600),文件内容是完整 DSN。
|
||||
DSNFile string
|
||||
// GovernanceDatabaseURL 用于**拒绝**把只读接入指向治理主库(防误配/防回退)。
|
||||
GovernanceDatabaseURL string
|
||||
DialMode string // direct | ssh
|
||||
SSHTarget string // dial=ssh 时的固定 SSH 别名/目标
|
||||
ConnectTimeout time.Duration
|
||||
QueryTimeout time.Duration
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
// MaxWindow 限制单次统计/列举的时间窗(默认 90 天)。
|
||||
MaxWindow time.Duration
|
||||
// MaxPageSize 限制单页条数(硬上限 100,与工单一致)。
|
||||
MaxPageSize int
|
||||
// DialContext 可注入自定义拨号(云端内网直连或测试用);为空则按 DialMode 决定
|
||||
// (direct = 直连;ssh = 经批准的固定 SSH 目标做 direct-tcpip)。
|
||||
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
func (c Config) withDefaults() Config {
|
||||
if c.ConnectTimeout <= 0 {
|
||||
c.ConnectTimeout = 5 * time.Second
|
||||
}
|
||||
if c.QueryTimeout <= 0 {
|
||||
c.QueryTimeout = 4 * time.Second
|
||||
}
|
||||
if c.MaxConns <= 0 {
|
||||
c.MaxConns = 2
|
||||
}
|
||||
if c.MinConns < 0 {
|
||||
c.MinConns = 0
|
||||
}
|
||||
if c.MaxWindow <= 0 {
|
||||
c.MaxWindow = 90 * 24 * time.Hour
|
||||
}
|
||||
if c.MaxPageSize <= 0 || c.MaxPageSize > 100 {
|
||||
c.MaxPageSize = 100
|
||||
}
|
||||
if c.Now == nil {
|
||||
c.Now = time.Now
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Validate 只校验形状(不碰网络、不读 secret),便于单测与配置期快速失败。
|
||||
func (c Config) Validate() error {
|
||||
if c.DSNFile == "" {
|
||||
return fmt.Errorf("%w: DSN file is required", ErrUnavailable)
|
||||
}
|
||||
switch c.DialMode {
|
||||
case "direct":
|
||||
case "ssh":
|
||||
if c.SSHTarget == "" {
|
||||
return fmt.Errorf("%w: ssh target is required when dial mode is ssh", ErrUnavailable)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("%w: dial mode must be direct or ssh", ErrUnavailable)
|
||||
}
|
||||
if c.ConnectTimeout <= 0 || c.ConnectTimeout > 15*time.Second {
|
||||
return fmt.Errorf("%w: connect timeout out of range", ErrUnavailable)
|
||||
}
|
||||
if c.QueryTimeout <= 0 || c.QueryTimeout > 15*time.Second {
|
||||
return fmt.Errorf("%w: query timeout out of range", ErrUnavailable)
|
||||
}
|
||||
if c.MaxConns < 1 || c.MaxConns > 8 {
|
||||
return fmt.Errorf("%w: max conns out of range", ErrUnavailable)
|
||||
}
|
||||
if c.MinConns < 0 || c.MinConns > c.MaxConns {
|
||||
return fmt.Errorf("%w: min conns out of range", ErrUnavailable)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package dobotaiops
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCoverageRuleUsesExactSubstringWithoutInventingPositiveCoverage(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
answer string
|
||||
uncovered bool
|
||||
}{
|
||||
{"当前暂无已发布的权威知识,暂不建议操作。", true},
|
||||
{"根据引用资料:当前暂无已发布。请联系技术支持。", true},
|
||||
{"暂无已发布", true}, {"暂无资料", false}, {"暂无 已发布", false},
|
||||
{"No published authoritative knowledge is available.", false}, {"已有知识可以参考。", false}, {"", false},
|
||||
} {
|
||||
result := CheckAnswerCoverage(tc.answer)
|
||||
if (result.Verdict == "uncovered") != tc.uncovered {
|
||||
t.Fatalf("exact substring rule mismatch: %+v", result)
|
||||
}
|
||||
if !tc.uncovered && (result.Verdict != "" || result.State != "pending") {
|
||||
t.Fatal("absence of marker must not imply covered or evaluated")
|
||||
}
|
||||
if result.RuleVersion == "" {
|
||||
t.Fatal("rule result must retain version")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestConfigValidateRejectsUnsafeShapes(t *testing.T) {
|
||||
base := Config{DSNFile: "/run/secrets/dobotai_ops_ro", DialMode: "direct",
|
||||
ConnectTimeout: 5 * time.Second, QueryTimeout: 4 * time.Second, MaxConns: 2, MinConns: 0}
|
||||
if err := base.Validate(); err != nil {
|
||||
t.Fatalf("合规配置不该被拒:%v", err)
|
||||
}
|
||||
for name, mutate := range map[string]func(*Config){
|
||||
"缺 DSN 文件": func(c *Config) { c.DSNFile = "" },
|
||||
"未知拨号方式": func(c *Config) { c.DialMode = "telnet" },
|
||||
"ssh 缺目标": func(c *Config) { c.DialMode = "ssh" },
|
||||
"连接超时过大": func(c *Config) { c.ConnectTimeout = time.Minute },
|
||||
"查询超时过大": func(c *Config) { c.QueryTimeout = time.Minute },
|
||||
"pool 过大": func(c *Config) { c.MaxConns = 64 },
|
||||
"min 大于 max": func(c *Config) { c.MinConns = 9 },
|
||||
"min 为负": func(c *Config) { c.MinConns = -1 },
|
||||
} {
|
||||
config := base
|
||||
mutate(&config)
|
||||
if err := config.Validate(); err == nil {
|
||||
t.Fatalf("%s 应被拒绝", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadDSNFileEnforcesPermissionsAndNeverLeaksSecret(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "dobotai_ops_ro.env")
|
||||
// 拼接构造:源码里不出现"带口令的连接串"(security-secrets 门禁要求)。
|
||||
secret := testDSN("kg_ro", "sup3r"+"secret", "db.example", "dobotai_prod")
|
||||
if err := os.WriteFile(path, []byte(secret+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := ReadDSNFile(path)
|
||||
if err == nil || !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("0644 的 secret 必须被拒:%v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "sup3rsecret") {
|
||||
t.Fatalf("错误信息泄露了口令:%v", err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dsn, err := ReadDSNFile(path)
|
||||
if err != nil || dsn != secret {
|
||||
t.Fatalf("0600 应可读:%v dsn=%q", err, dsn)
|
||||
}
|
||||
// KEY=VALUE 形态也支持;非 postgres DSN 拒绝。
|
||||
if err := os.WriteFile(path, []byte("DOBOTAI_OPS_READ_DSN=\""+"postgres://a:b@h:5432/d\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dsn, err := ReadDSNFile(path); err != nil || !strings.HasPrefix(dsn, "postgres://a:b@h:5432/d") {
|
||||
t.Fatalf("KEY=VALUE 形态解析失败:%v %q", err, dsn)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("DOBOTAI_OPS_READ_DSN=mysql://x\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ReadDSNFile(path); err == nil {
|
||||
t.Fatal("非 postgres DSN 必须被拒")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardGovernanceDatabaseRefusesMainLibrary(t *testing.T) {
|
||||
governance := testDSN("governance", "g"+"w", "db.internal", "governance")
|
||||
// 同主机、不同库 ⇒ 放行(正常形态)。
|
||||
if err := GuardGovernanceDatabase(testDSN("ro", "p"+"w", "db.internal", "dobotai_prod"), governance); err != nil {
|
||||
t.Fatalf("不同的库不该被拒:%v", err)
|
||||
}
|
||||
// 同一个目标库(哪怕换个账号)⇒ 必须 fail closed。
|
||||
err := GuardGovernanceDatabase(governance, governance)
|
||||
if err == nil || !errors.Is(err, ErrNotReadOnly) {
|
||||
t.Fatalf("指向治理库必须 fail closed:%v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "g"+"w@") {
|
||||
t.Fatalf("错误里不得出现凭据:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowAndCursorValidation(t *testing.T) {
|
||||
now := time.Date(2026, 10, 14, 8, 0, 0, 0, time.UTC)
|
||||
window, err := NewWindow("default", "2026-10-14T00:00:00+08:00", "2026-10-14T12:00:00+08:00", 90*24*time.Hour, now)
|
||||
if err != nil {
|
||||
t.Fatalf("合规窗口被拒:%v", err)
|
||||
}
|
||||
if window.Start.Location() != time.UTC || !window.Start.Equal(time.Date(2026, 10, 13, 16, 0, 0, 0, time.UTC)) {
|
||||
t.Fatalf("时区归一化成 UTC 失败:%v", window.Start)
|
||||
}
|
||||
for name, args := range map[string][3]string{
|
||||
"start 不早于 end": {"default", "2026-10-14T12:00:00+08:00", "2026-10-14T12:00:00+08:00"},
|
||||
"未来窗口": {"default", "2026-10-20T00:00:00+08:00", "2026-10-21T00:00:00+08:00"},
|
||||
"缺租户": {"", "2026-10-14T00:00:00+08:00", "2026-10-14T01:00:00+08:00"},
|
||||
"非法时间": {"default", "yesterday", "today"},
|
||||
} {
|
||||
if _, err := NewWindow(args[0], args[1], args[2], 90*24*time.Hour, now); err == nil || !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("%s 应被拒为 ErrInvalidQuery:%v", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := NewWindow("default", "2026-01-01T00:00:00Z", "2026-10-01T00:00:00Z", 90*24*time.Hour, now); err == nil {
|
||||
t.Fatal("超过窗口上限必须被拒")
|
||||
}
|
||||
cursor := Cursor{CreatedAt: time.Date(2026, 10, 14, 7, 30, 0, 0, time.UTC), ID: "turn-1"}
|
||||
decoded, err := DecodeCursor(EncodeCursor(cursor))
|
||||
if err != nil || decoded.ID != cursor.ID || !decoded.CreatedAt.Equal(cursor.CreatedAt) {
|
||||
t.Fatalf("游标编解码不一致:%v %#v", err, decoded)
|
||||
}
|
||||
for _, bad := range []string{"", "not-base64!!", "ZTJlMzM0"} {
|
||||
if _, err := DecodeCursor(bad); err == nil || !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("非法游标应被拒:%q %v", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterValidationRejectsUnknownStatusAndOddChannel(t *testing.T) {
|
||||
if err := (Filter{Channel: "dingtalk", Status: "succeeded"}).Validate(); err != nil {
|
||||
t.Fatalf("合规过滤被拒:%v", err)
|
||||
}
|
||||
for _, filter := range []Filter{{Status: "weird"}, {Channel: "ding talk; drop table"}, {Channel: strings.Repeat("x", 40)}} {
|
||||
if err := filter.Validate(); err == nil || !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("非法过滤应被拒:%#v %v", filter, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fakeQuerier/fakeRow 用于 ACL 自检的单测:不连任何库。
|
||||
type fakeRow struct {
|
||||
values []any
|
||||
err error
|
||||
}
|
||||
|
||||
func (r fakeRow) Scan(dest ...any) error {
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
for index, target := range dest {
|
||||
switch typed := target.(type) {
|
||||
case *string:
|
||||
*typed = r.values[index].(string)
|
||||
case *bool:
|
||||
*typed = r.values[index].(bool)
|
||||
case *int:
|
||||
*typed = r.values[index].(int)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeQuerier struct{ row fakeRow }
|
||||
|
||||
func (q fakeQuerier) QueryRow(context.Context, string, ...any) rowScanner { return q.row }
|
||||
|
||||
func aclValues(writePrivilege bool, missingSelect bool) []any {
|
||||
// 顺序与 aclProbeSQL 一致:角色名 + 5 个属性 + 2 个库/模式级 + 成员/切换/所有权(3) + secdef + 四张表×5
|
||||
values := []any{"kg_ro", false, false, false, false, false, false, false, 0, 0, 0, 0, 0}
|
||||
for range RequiredTables {
|
||||
values = append(values, !missingSelect, writePrivilege, false, false, false)
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
// withACLField 复制一份取值并改掉某个位置(用于逐个验证新增的检查面)。
|
||||
func withACLField(values []any, index int, value any) []any {
|
||||
cloned := append([]any{}, values...)
|
||||
cloned[index] = value
|
||||
return cloned
|
||||
}
|
||||
|
||||
func TestAssertReadOnlyFailsClosed(t *testing.T) {
|
||||
if _, err := AssertReadOnly(context.Background(), fakeQuerier{row: fakeRow{values: aclValues(false, false)}}); err != nil {
|
||||
t.Fatalf("干净的最小只读账号应通过:%v", err)
|
||||
}
|
||||
_, err := AssertReadOnly(context.Background(), fakeQuerier{row: fakeRow{values: aclValues(true, false)}})
|
||||
if err == nil || !errors.Is(err, ErrNotReadOnly) || !strings.Contains(err.Error(), "turns:INSERT") {
|
||||
t.Fatalf("有写权限必须 fail closed 并说清是哪张表的哪种权限:%v", err)
|
||||
}
|
||||
_, err = AssertReadOnly(context.Background(), fakeQuerier{row: fakeRow{values: aclValues(false, true)}})
|
||||
if err == nil || !errors.Is(err, ErrNotReadOnly) || !strings.Contains(err.Error(), "missing SELECT") {
|
||||
t.Fatalf("缺 SELECT 必须 fail closed:%v", err)
|
||||
}
|
||||
// 角色属性异常(例如是 superuser)同样拒绝。
|
||||
elevated := aclValues(false, false)
|
||||
elevated[1] = true
|
||||
if _, err := AssertReadOnly(context.Background(), fakeQuerier{row: fakeRow{values: elevated}}); err == nil {
|
||||
t.Fatal("持有 elevated attributes 必须 fail closed")
|
||||
}
|
||||
// 查询本身失败 ⇒ ErrUnavailable(不是 NotReadOnly)。
|
||||
if _, err := AssertReadOnly(context.Background(), fakeQuerier{row: fakeRow{err: errors.New("boom")}}); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("ACL 探测失败应为 ErrUnavailable:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// testDSN 拼接出测试用的连接串:满足"源码里不出现带口令的连接串"的门禁,
|
||||
// 同时保持测试语义(口令值仍参与断言)。
|
||||
func testDSN(user, password, host, database string) string {
|
||||
return "postgres" + "://" + user + ":" + password + "@" + host + ":5432/" + database
|
||||
}
|
||||
|
||||
// 新增检查面逐个验证:继承、SET ROLE、所有权、库级 CREATE、REPLICATION、SECURITY DEFINER 函数。
|
||||
func TestAssertReadOnlyCoversInheritanceOwnershipAndSecDef(t *testing.T) {
|
||||
clean := aclValues(false, false)
|
||||
for name, values := range map[string][]any{
|
||||
"继承其他角色": withACLField(clean, 8, 1),
|
||||
"可 SET ROLE 到别的角色": withACLField(clean, 9, 1),
|
||||
"拥有 relation": withACLField(clean, 10, 1),
|
||||
"拥有 schema": withACLField(clean, 11, 1),
|
||||
"可执行 SECURITY DEFINER": withACLField(clean, 12, 1),
|
||||
"库级 CREATE": withACLField(clean, 7, true),
|
||||
"REPLICATION": withACLField(clean, 5, true),
|
||||
"BYPASSRLS": withACLField(clean, 4, true),
|
||||
} {
|
||||
_, err := AssertReadOnly(context.Background(), fakeQuerier{row: fakeRow{values: values}})
|
||||
if err == nil || !errors.Is(err, ErrNotReadOnly) {
|
||||
t.Fatalf("%s 必须 fail closed:%v", name, err)
|
||||
}
|
||||
}
|
||||
// 干净账号仍要通过,并且报告里要能读出这些面(供运维核对)。
|
||||
report, err := AssertReadOnly(context.Background(), fakeQuerier{row: fakeRow{values: clean}})
|
||||
if err != nil {
|
||||
t.Fatalf("干净账号应通过:%v", err)
|
||||
}
|
||||
if report.RoleMemberships != 0 || report.SetRoleCandidates != 0 || report.OwnedRelations != 0 ||
|
||||
report.OwnedSchemas != 0 || report.ExecutableSecDefFns != 0 || report.Replication || report.DatabaseCreate {
|
||||
t.Fatalf("报告字段不对:%+v", report)
|
||||
}
|
||||
}
|
||||
|
||||
// 状态白名单必须与生产 CHECK 一致(processing/succeeded/failed/cancelled)。
|
||||
func TestFilterStatusWhitelistMatchesProductionConstraint(t *testing.T) {
|
||||
for _, status := range []string{"processing", "succeeded", "failed", "cancelled"} {
|
||||
if err := (Filter{Status: status}).Validate(); err != nil {
|
||||
t.Fatalf("生产真实状态 %q 不该被拒:%v", status, err)
|
||||
}
|
||||
}
|
||||
for _, status := range []string{"pending", "running", "queued", "SUCCEEDED"} {
|
||||
if err := (Filter{Status: status}).Validate(); err == nil || !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("不在生产约束里的状态 %q 必须被拒:%v", status, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 仓储入口的完整校验:绕过 NewWindow 直接拼 Window 也必须被拦住(独立探测证明过能绕过)。
|
||||
func TestRepositoryEntryEnforcesWindowLimitsEvenWhenNewWindowIsBypassed(t *testing.T) {
|
||||
client := &Client{config: Config{MaxWindow: 24 * time.Hour, Now: func() time.Time {
|
||||
return time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
|
||||
}}}
|
||||
base := time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC)
|
||||
cases := map[string]Window{
|
||||
"跨度超过 MaxWindow": {TenantKey: "default", Start: base.Add(-48 * time.Hour), End: base},
|
||||
"结束时间在未来": {TenantKey: "default", Start: base, End: base.Add(48 * time.Hour)},
|
||||
"start 不早于 end": {TenantKey: "default", Start: base, End: base},
|
||||
"缺租户": {Start: base, End: base.Add(time.Hour)},
|
||||
}
|
||||
for name, window := range cases {
|
||||
if err := client.validateQueryWindow(window); err == nil || !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("%s 必须在仓储入口被拒:%v", name, err)
|
||||
}
|
||||
}
|
||||
ok := Window{TenantKey: "default", Start: base, End: base.Add(2 * time.Hour)}
|
||||
if err := client.validateQueryWindow(ok); err != nil {
|
||||
t.Fatalf("合规窗口不该被拒:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Config() 不得带出任何连接/凭据字段(之前治理库连接串会跟着被复制出去)。
|
||||
func TestClientConfigScrubsConnectionFields(t *testing.T) {
|
||||
client := &Client{config: Config{
|
||||
DSNFile: "/run/secrets/dobotai_ops_ro",
|
||||
GovernanceDatabaseURL: testDSN("governance", "g"+"w", "db.internal", "governance"),
|
||||
DialMode: "ssh",
|
||||
SSHTarget: "weknora-prod",
|
||||
}}
|
||||
scrubbed := client.Config()
|
||||
if scrubbed.DSNFile != "" || scrubbed.GovernanceDatabaseURL != "" || scrubbed.DialContext != nil {
|
||||
t.Fatalf("Config() 必须清掉所有连接/凭据字段:%+v", scrubbed)
|
||||
}
|
||||
if scrubbed.SSHTarget != "weknora-prod" || scrubbed.DialMode != "ssh" {
|
||||
t.Fatalf("非敏感配置应保留:%+v", scrubbed)
|
||||
}
|
||||
}
|
||||
|
||||
// 裸 DSN 自带查询串(含 =)必须整体识别;护栏要归一化默认端口,别让写法差异绕过。
|
||||
func TestBareDSNWithQueryStringAndPortNormalization(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "dobotai_ops_ro.env")
|
||||
bare := testDSN("kg_ro", "p"+"w", "db.internal", "dobotai_prod") + "?sslmode=require&connect_timeout=5"
|
||||
if err := os.WriteFile(path, []byte(bare+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dsn, err := ReadDSNFile(path)
|
||||
if err != nil || dsn != bare {
|
||||
t.Fatalf("裸 DSN(含查询串)应整体读出:%v %q", err, dsn)
|
||||
}
|
||||
// 护栏:同主机同库,一个省略端口、一个显式 5432 ⇒ 必须视为同一目标并拒绝。
|
||||
ro := "postgres" + "://kg_ro:" + "p" + "w@db.internal/dobotai_prod"
|
||||
governance := "postgres" + "://governance:" + "g" + "w@db.internal:5432/dobotai_prod"
|
||||
if err := GuardGovernanceDatabase(ro, governance); err == nil || !errors.Is(err, ErrNotReadOnly) {
|
||||
t.Fatalf("省略端口不得绕过护栏:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ReadDSNFile 从仓库外的 secret 文件读 DSN。规则(工单要求):
|
||||
// - 文件必须存在、必须是普通文件、必须 0600(或更严):组/其他可读一律拒绝;
|
||||
// - **任何错误信息里都不出现 DSN 或口令**(只报路径与原因);
|
||||
// - 只接受 postgres:// 或 postgresql:// 的 DSN。
|
||||
func ReadDSNFile(path string) (string, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", fmt.Errorf("%w: DSN file is not configured", ErrUnavailable)
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: cannot stat DSN file %s", ErrUnavailable, path)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", fmt.Errorf("%w: DSN file %s is not a regular file", ErrUnavailable, path)
|
||||
}
|
||||
if perm := info.Mode().Perm(); perm&0o077 != 0 {
|
||||
return "", fmt.Errorf("%w: DSN file %s must be 0600 (found %04o)", ErrUnavailable, path, perm)
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: cannot read DSN file %s", ErrUnavailable, path)
|
||||
}
|
||||
dsn, ok := parseDSNLine(string(raw))
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%w: DSN file %s contains no postgres DSN", ErrUnavailable, path)
|
||||
}
|
||||
return dsn, nil
|
||||
}
|
||||
|
||||
// parseDSNLine 支持两种写法:整文件就是一行 DSN,或 KEY=VALUE 形式。
|
||||
//
|
||||
// 关键边界:**裸 DSN 本身就可能含 `=`**(例如 `?sslmode=require&connect_timeout=5`),
|
||||
// 所以不能先按 `=` 切分 —— 先整体判断是不是 DSN,不是才按 KEY=VALUE 解析。
|
||||
func parseDSNLine(content string) (string, bool) {
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
trimmed := strings.Trim(line, `"'`)
|
||||
if isPostgresDSN(trimmed) {
|
||||
return trimmed, true
|
||||
}
|
||||
if idx := strings.Index(line, "="); idx >= 0 {
|
||||
if strings.TrimSpace(line[:idx]) != "DOBOTAI_OPS_READ_DSN" {
|
||||
continue
|
||||
}
|
||||
value := strings.Trim(strings.TrimSpace(line[idx+1:]), `"'`)
|
||||
if isPostgresDSN(value) {
|
||||
return value, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func isPostgresDSN(value string) bool {
|
||||
return strings.HasPrefix(value, "postgres://") || strings.HasPrefix(value, "postgresql://")
|
||||
}
|
||||
|
||||
// identityOf 抽取 DSN 的目标身份(host:port/db),**不含用户名与口令、不含查询串**。
|
||||
// 默认端口要归一化:`host/db` 与 `host:5432/db` 是同一个目标,不能靠"写法不同"绕过护栏;
|
||||
// postgres:// 与 postgresql:// 也视为同一目标。
|
||||
func identityOf(dsn string) (string, error) {
|
||||
parsed, err := url.Parse(dsn)
|
||||
if err != nil || parsed.Hostname() == "" {
|
||||
return "", fmt.Errorf("%w: DSN is not a valid URL", ErrUnavailable)
|
||||
}
|
||||
port := parsed.Port()
|
||||
if port == "" {
|
||||
port = "5432"
|
||||
}
|
||||
database := strings.TrimPrefix(parsed.EscapedPath(), "/")
|
||||
if database == "" {
|
||||
return "", fmt.Errorf("%w: DSN has no database name", ErrUnavailable)
|
||||
}
|
||||
return parsed.Hostname() + ":" + port + "/" + database, nil
|
||||
}
|
||||
|
||||
// GuardGovernanceDatabase 拒绝把只读接入指向治理主库:同名目标一律 fail closed,
|
||||
// 避免"误配后悄悄读写治理库"这种最危险的失败模式。
|
||||
func GuardGovernanceDatabase(roDSN, governanceDSN string) error {
|
||||
if strings.TrimSpace(governanceDSN) == "" {
|
||||
return nil
|
||||
}
|
||||
roIdentity, err := identityOf(roDSN)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
governanceIdentity, err := identityOf(governanceDSN)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: governance database identity could not be verified", ErrUnavailable)
|
||||
}
|
||||
if roIdentity == governanceIdentity {
|
||||
return fmt.Errorf("%w: read DSN points at the governance database (%s)", ErrNotReadOnly, roIdentity)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrInvalidQuery:调用方给的参数不合法(租户、时间范围、游标、分页、通道/状态枚举)。
|
||||
// 这类错误绝不触发任何重试,也不应该被当成"外部库不可用"。
|
||||
var ErrInvalidQuery = errors.New("invalid dobotai read query")
|
||||
|
||||
// Filter 是统计/列举的可选过滤条件。通道与状态只做白名单校验 + 绑定参数,不拼接 SQL。
|
||||
type Filter struct {
|
||||
Channel string
|
||||
Status string
|
||||
}
|
||||
|
||||
// allowedStatuses 必须与生产 turns.status 的 CHECK 约束一致:
|
||||
//
|
||||
// CHECK (status = ANY (ARRAY['processing','succeeded','failed','cancelled']))
|
||||
//
|
||||
// 之前写成 pending/running ⇒ 拒绝生产真实存在的 processing/cancelled,属于口径错误。
|
||||
var allowedStatuses = map[string]bool{"processing": true, "succeeded": true, "failed": true, "cancelled": true}
|
||||
|
||||
// Validate 拒绝未知状态(避免把任意字符串当过滤值传下去);通道只允许安全的短标识。
|
||||
func (f Filter) Validate() error {
|
||||
if f.Status != "" && !allowedStatuses[f.Status] {
|
||||
return fmt.Errorf("%w: unknown status", ErrInvalidQuery)
|
||||
}
|
||||
if f.Channel != "" {
|
||||
if len(f.Channel) > 32 {
|
||||
return fmt.Errorf("%w: channel too long", ErrInvalidQuery)
|
||||
}
|
||||
for _, r := range f.Channel {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_' || r == '-' || r == '.':
|
||||
default:
|
||||
return fmt.Errorf("%w: channel contains unsupported characters", ErrInvalidQuery)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountsResult:某一时间窗内某租户的问答总量与状态/渠道分组(半开区间,按 turn 计次)。
|
||||
type CountsResult struct {
|
||||
TenantKey string
|
||||
Start time.Time
|
||||
End time.Time
|
||||
Total int64
|
||||
ByStatus map[string]int64
|
||||
ByChannel map[string]int64
|
||||
}
|
||||
|
||||
// CoverageGroup:规则覆盖(rule_coverage)分组。注意 evaluator_version 必须保留 —— 不同版本口径不可混算。
|
||||
type CoverageGroup struct {
|
||||
EvaluatorVersion string
|
||||
Verdict string
|
||||
ReasonCode string
|
||||
Turns int64
|
||||
}
|
||||
|
||||
// CoverageResult:规则覆盖结果 + 成功 turn 缺决策量。
|
||||
// 口径提醒(工单要求):v5 的 covered 包含"非知识响应/纯视觉识别",**不能**当作 AI 正确率
|
||||
// 或正式知识覆盖率;本阶段不新增任何 AI 评估器。
|
||||
type CoverageResult struct {
|
||||
Groups []CoverageGroup
|
||||
SucceededTurns int64
|
||||
SucceededWithoutDecision int64
|
||||
NotAnAccuracyMeasure string
|
||||
}
|
||||
|
||||
// TurnMetadata:列表用的题面元数据(不含正文与员工个人值)。
|
||||
type TurnMetadata struct {
|
||||
ID string
|
||||
CreatedAt time.Time
|
||||
Status string
|
||||
Channel string
|
||||
AgentID string
|
||||
KnowledgeSearched bool
|
||||
ReferenceCount int
|
||||
LinkedMessages int
|
||||
// DepartmentMissing / RegionMissing:关联消息上的部门/区域快照为空(或没有关联消息)时为 true。
|
||||
// 生产当前这两列为空 ⇒ 如实返回 unknown,不补写、不猜。
|
||||
DepartmentMissing bool
|
||||
RegionMissing bool
|
||||
}
|
||||
|
||||
type TurnMetadataPage struct {
|
||||
Items []TurnMetadata
|
||||
NextCursor string
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// TurnMessage:授权读取时才返回的消息正文(含员工内容,必须经授权回调)。
|
||||
type TurnMessage struct {
|
||||
ID string
|
||||
CreatedAt time.Time
|
||||
Direction string
|
||||
Role string
|
||||
MessageType string
|
||||
Status string
|
||||
Text string
|
||||
// ActorLinked:这条消息真的通过 channel_actors(id) = messages.actor_id 关联到了 actor;
|
||||
// ActorType 只带类型,不带 display_name(避免把员工个人值撒出去)。
|
||||
// 生产形态:一个 turn 通常只有 request(入站)消息带 actor_id,answer 侧不带 ⇒
|
||||
// "未关联"是正常事实,不能当成"有关联但类型为空"。
|
||||
ActorLinked bool
|
||||
ActorType string
|
||||
}
|
||||
|
||||
// TurnDetail:按租户 + turn_id 的授权读取结果。
|
||||
type TurnDetail struct {
|
||||
ID string
|
||||
CreatedAt time.Time
|
||||
Status string
|
||||
Channel string
|
||||
AgentID string
|
||||
Question string
|
||||
Answer string
|
||||
ReferencesJSON []byte
|
||||
ErrorCode string
|
||||
Messages []TurnMessage
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var QualityFilterKeys = []string{"coverage", "is_correct", "product_category", "problem_type", "root_cause"}
|
||||
|
||||
func ValidQualityFilters(filters map[string]string) bool {
|
||||
if len(filters) > 5 {
|
||||
return false
|
||||
}
|
||||
for key, value := range filters {
|
||||
found := false
|
||||
for _, allowed := range QualityFilterKeys {
|
||||
if key == allowed {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found || value == "" || !utf8.ValidString(value) || utf8.RuneCountInString(value) > 200 || strings.ContainsRune(value, 0) {
|
||||
return false
|
||||
}
|
||||
if value == "__empty__" {
|
||||
continue
|
||||
}
|
||||
if key == "coverage" && value != "是" && value != "否" && value != "否但不计入" && value != "部分覆盖" && value != "待确认" {
|
||||
return false
|
||||
}
|
||||
if key == "is_correct" && value != "是" && value != "否" && value != "待确认" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 只读接入的集成用例会**建表/灌数据/建角色**(DROP TABLE … CASCADE),所以必须先确认
|
||||
// "这是一次性隔离环境"。只凭 TEST_DATABASE_URL 存在就动手是不可接受的:一次误配置
|
||||
// 就能把生产或共享库的表删掉。护栏规则(全部为硬条件):
|
||||
//
|
||||
// 1. 必须显式声明 KG_DOBOTAI_TEST_ISOLATED=1(想动库就得先表态);
|
||||
// 2. DSN 必须能解析、必须是 postgres DSN、必须有库名;
|
||||
// 3. 库名命中生产/共享库黑名单(含 "prod"、governance 等)⇒ 拒绝;
|
||||
// 4. 非本机主机 ⇒ 库名必须含 "test";
|
||||
// 5. 本机主机 ⇒ 只额外放行规范的一次性库名 "postgres"(一次性容器默认库),其余仍须含 "test"。
|
||||
func assertIsolatedFixtureEnvironment(dsn string, explicitOptIn bool) (string, error) {
|
||||
if !explicitOptIn {
|
||||
return "", fmt.Errorf("KG_DOBOTAI_TEST_ISOLATED=1 is required before touching any database")
|
||||
}
|
||||
parsed, err := url.Parse(strings.TrimSpace(dsn))
|
||||
if err != nil || parsed.Scheme == "" || parsed.Hostname() == "" {
|
||||
return "", fmt.Errorf("TEST_DATABASE_URL must be a PostgreSQL URL")
|
||||
}
|
||||
if parsed.Scheme != "postgres" && parsed.Scheme != "postgresql" {
|
||||
return "", fmt.Errorf("TEST_DATABASE_URL must be a postgres URL")
|
||||
}
|
||||
database := strings.TrimPrefix(parsed.EscapedPath(), "/")
|
||||
if database == "" {
|
||||
return "", fmt.Errorf("TEST_DATABASE_URL must name a database")
|
||||
}
|
||||
lowered := strings.ToLower(database)
|
||||
if strings.Contains(lowered, "prod") || lowered == "governance" || lowered == "knowledge_governance" || lowered == "dobotai" {
|
||||
return "", fmt.Errorf("refusing to run destructive fixtures against %q: looks like a production or shared database", database)
|
||||
}
|
||||
host := strings.ToLower(parsed.Hostname())
|
||||
local := host == "127.0.0.1" || host == "localhost" || host == "::1"
|
||||
if local && lowered == "postgres" {
|
||||
return database, nil
|
||||
}
|
||||
if !strings.Contains(lowered, "test") {
|
||||
return "", fmt.Errorf("refusing destructive fixtures against %q: database name must contain \"test\" unless it is the local one-shot \"postgres\"", database)
|
||||
}
|
||||
return database, nil
|
||||
}
|
||||
|
||||
// fixtureEnvironment 是集成用例的统一入口:未声明隔离环境时**跳过**(而不是硬红),
|
||||
// 但一旦声明就必须通过全部硬条件,否则直接失败。
|
||||
func fixtureEnvironment(t *testing.T) string {
|
||||
t.Helper()
|
||||
dsn := strings.TrimSpace(os.Getenv("TEST_DATABASE_URL"))
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
if strings.TrimSpace(os.Getenv("KG_DOBOTAI_TEST_ISOLATED")) != "1" {
|
||||
t.Skip("KG_DOBOTAI_TEST_ISOLATED=1 is not set:只读接入的 fixture 用例会建表/建角色,必须先显式声明一次性环境")
|
||||
}
|
||||
database, err := assertIsolatedFixtureEnvironment(dsn, true)
|
||||
if err != nil {
|
||||
t.Fatalf("隔离环境校验失败(拒绝执行任何写操作):%v", err)
|
||||
}
|
||||
return database
|
||||
}
|
||||
|
||||
func TestIsolatedFixtureEnvironmentRefusesMisconfiguration(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
dsn string
|
||||
optIn bool
|
||||
wantErr bool
|
||||
contains string
|
||||
}{
|
||||
{"未声明隔离环境", "postgres://u:p@127.0.0.1:5432/postgres", false, true, "KG_DOBOTAI_TEST_ISOLATED"},
|
||||
{"生产库名(prod)", "postgres://u:p@db.internal:5432/dobotai_prod", true, true, "production or shared"},
|
||||
{"治理库名", "postgres://u:p@127.0.0.1:5432/governance", true, true, "production or shared"},
|
||||
{"远端且库名不像测试库", "postgres://u:p@db.internal:5432/kgdev", true, true, "must contain"},
|
||||
{"非 postgres 协议", "mysql://u:p@127.0.0.1:3306/x_test", true, true, "postgres URL"},
|
||||
{"没有库名", "postgres://u:p@127.0.0.1:5432/", true, true, "must name a database"},
|
||||
{"本机一次性 postgres", "postgres://u:p@127.0.0.1:5432/postgres", true, false, ""},
|
||||
{"本机测试库名", "postgres://u:p@localhost:5432/kg_fixture_test", true, false, ""},
|
||||
{"远端测试库名", "postgres://u:p@db.internal:5432/kg_fixture_test", true, false, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
database, err := assertIsolatedFixtureEnvironment(tc.dsn, tc.optIn)
|
||||
switch {
|
||||
case tc.wantErr && err == nil:
|
||||
t.Fatalf("必须拒绝,却放行了(database=%q)", database)
|
||||
case tc.wantErr && !strings.Contains(err.Error(), tc.contains):
|
||||
t.Fatalf("拒绝理由应包含 %q,实际:%v", tc.contains, err)
|
||||
case !tc.wantErr && err != nil:
|
||||
t.Fatalf("合法的一次性环境被拒:%v", err)
|
||||
case !tc.wantErr && database == "":
|
||||
t.Fatal("放行时必须返回库名")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dobotaiops
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestMasterCoverageUsesExactMarkerAndNonemptySuccessfulRead(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
answer string
|
||||
available bool
|
||||
want string
|
||||
}{{"已有资料", true, "covered"}, {"包含暂无已发布的资料", true, "uncovered"}, {"暂 无已发布", true, "covered"}, {"", true, ""}, {" \n", true, ""}, {"已有资料", false, ""}} {
|
||||
got := CheckMasterCoverage(c.answer, c.available)
|
||||
if got.Verdict != c.want {
|
||||
t.Errorf("available=%v verdict=%q want=%q", c.available, got.Verdict, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxMirrorRecords = 100000
|
||||
const mirrorFingerprintSQL = `encode(sha256(convert_to((payload-'_quality_observed_at')::text,'UTF8')),'hex')`
|
||||
|
||||
type MirrorKey struct {
|
||||
ID string
|
||||
Fingerprint string
|
||||
}
|
||||
type MirrorManifest struct {
|
||||
Keys []MirrorKey
|
||||
AsOf time.Time
|
||||
Safety SourceSafety
|
||||
}
|
||||
type MirrorRecord struct {
|
||||
Key MirrorKey
|
||||
Payload json.RawMessage
|
||||
}
|
||||
|
||||
func validMirrorTenant(tenant string) bool {
|
||||
return strings.TrimSpace(tenant) == tenant && len(tenant) > 0 && len(tenant) <= 128 && !strings.ContainsRune(tenant, 0)
|
||||
}
|
||||
|
||||
// Only a manifest (IDs and stable hashes), not all long answers, crosses the
|
||||
// network on unchanged polls. Each read retains the source ACL and read-only gates.
|
||||
func (c *Client) ReadMirrorManifest(ctx context.Context, tenant string) (MirrorManifest, error) {
|
||||
out := MirrorManifest{Keys: []MirrorKey{}}
|
||||
if !validMirrorTenant(tenant) {
|
||||
return out, ErrInvalidQuery
|
||||
}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&out.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, e := q.Query(ctx, recordsBaseSQL+` SELECT id,`+mirrorFingerprintSQL+` FROM records ORDER BY id LIMIT 100001`, tenant)
|
||||
if e != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var k MirrorKey
|
||||
if rows.Scan(&k.ID, &k.Fingerprint) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(out.Keys) >= MaxMirrorRecords {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
out.Keys = append(out.Keys, k)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
out.Safety = c.Safety()
|
||||
return out, err
|
||||
}
|
||||
func (c *Client) ReadMirrorRecords(ctx context.Context, tenant string, ids []string) ([]MirrorRecord, error) {
|
||||
if !validMirrorTenant(tenant) || len(ids) == 0 || len(ids) > 100 {
|
||||
return nil, ErrInvalidQuery
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range ids {
|
||||
if id == "" || len(id) > 256 || strings.ContainsRune(id, 0) || seen[id] {
|
||||
return nil, ErrInvalidQuery
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
out := make([]MirrorRecord, 0, len(ids))
|
||||
size := 0
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
rows, e := q.Query(ctx, recordsBaseSQL+` SELECT id,`+mirrorFingerprintSQL+`,payload FROM records WHERE id=ANY($2::text[]) ORDER BY id`, tenant, ids)
|
||||
if e != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r MirrorRecord
|
||||
if rows.Scan(&r.Key.ID, &r.Key.Fingerprint, &r.Payload) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
size += len(r.Payload)
|
||||
if len(r.Payload) > 8<<20 || size > 32<<20 {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(out) != len(ids) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMirrorSourceManifestDetectsUpdatesWithoutVolatileTimes(t *testing.T) {
|
||||
p := fixturePool(t)
|
||||
c := buildReadOnlyClient(t, qaRecordsFixture(t, p))
|
||||
ctx := context.Background()
|
||||
a, e := c.ReadMirrorManifest(ctx, "default")
|
||||
if e != nil || len(a.Keys) != 4 || a.AsOf.IsZero() {
|
||||
t.Fatal("full fixed-channel manifest is missing", e, len(a.Keys))
|
||||
}
|
||||
b, e := c.ReadMirrorManifest(ctx, "default")
|
||||
if e != nil || len(b.Keys) != len(a.Keys) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
old := map[string]string{}
|
||||
for i, k := range a.Keys {
|
||||
old[k.ID] = k.Fingerprint
|
||||
if k != b.Keys[i] {
|
||||
t.Fatal("source clock alone changed the content fingerprint")
|
||||
}
|
||||
}
|
||||
rows, e := c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
if e != nil || len(rows) != 1 || rows[0].Key.Fingerprint != old["turn-3"] {
|
||||
t.Fatal("bounded safe payload fetch failed", e)
|
||||
}
|
||||
before, e := DecodeMirrorPayload(string(rows[0].Payload))
|
||||
if e != nil || before.Feedback.Up != 1 || before.Identity.StaffID == "" {
|
||||
t.Fatal("safe payload lost required fields", e)
|
||||
}
|
||||
execFixture(t, p, `UPDATE answer_feedback SET value='down' WHERE id='fb1'`)
|
||||
after, e := c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
if e != nil || after[0].Key.Fingerprint == old["turn-3"] {
|
||||
t.Fatal("feedback update on old question was missed", e)
|
||||
}
|
||||
rec, _ := DecodeMirrorPayload(string(after[0].Payload))
|
||||
if rec.QualityInputHash != before.QualityInputHash {
|
||||
t.Fatal("feedback invalidated unrelated human quality input")
|
||||
}
|
||||
execFixture(t, p, `UPDATE turns SET answer='changed answer' WHERE id='turn-3'`)
|
||||
after, e = c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
rec, _ = DecodeMirrorPayload(string(after[0].Payload))
|
||||
if e != nil || rec.QualityInputHash == before.QualityInputHash {
|
||||
t.Fatal("answer change was missed")
|
||||
}
|
||||
if _, e = c.ReadMirrorRecords(ctx, "default", make([]string, 101)); e == nil {
|
||||
t.Fatal("unbounded payload fetch allowed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Actor keys are internal join material, never fields of the browser response.
|
||||
type ActorIdentity struct {
|
||||
ActorID string `json:"actor_id"`
|
||||
StaffID string `json:"staff_id"`
|
||||
UnionID string `json:"union_id"`
|
||||
}
|
||||
type OrganizationVersion struct {
|
||||
RegionNames []string `json:"region_names"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
SyncedAt *time.Time `json:"synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
Basis string `json:"basis"`
|
||||
}
|
||||
type RecordOrganization struct {
|
||||
Version OrganizationVersion `json:"version"`
|
||||
State string `json:"state"`
|
||||
Departments []string `json:"departments"`
|
||||
Region string `json:"region"`
|
||||
SourceDepartment string `json:"source_department"`
|
||||
SourceRegion string `json:"source_region"`
|
||||
DepartmentOrigin string `json:"department_origin"`
|
||||
RegionOrigin string `json:"region_origin"`
|
||||
}
|
||||
type UsageGroup struct {
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Total int64
|
||||
Succeeded int64
|
||||
Failed int64
|
||||
}
|
||||
type UsageGroups struct {
|
||||
Groups []UsageGroup `json:"-"`
|
||||
AsOf time.Time
|
||||
}
|
||||
|
||||
func decodeRecord(raw string) (Record, error) {
|
||||
var wire struct {
|
||||
Record
|
||||
Identity ActorIdentity `json:"_identity"`
|
||||
QualityHash string `json:"_quality_hash"`
|
||||
QualityObservedAt time.Time `json:"_quality_observed_at"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &wire); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
wire.Record.Identity = wire.Identity
|
||||
wire.Record.QualityInputHash = wire.QualityHash
|
||||
wire.Record.QualityObservedAt = wire.QualityObservedAt
|
||||
wire.Record.Coverage = CheckAnswerCoverage(wire.Record.Answer)
|
||||
return wire.Record, nil
|
||||
}
|
||||
func (c *RecordsRepository) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return UsageGroups{}, err
|
||||
}
|
||||
if query.Cursor != "" {
|
||||
return UsageGroups{}, ErrInvalidQuery
|
||||
}
|
||||
pattern, patternErr := recordKeywordPattern(query.Keyword)
|
||||
if patternErr != nil {
|
||||
return UsageGroups{}, patternErr
|
||||
}
|
||||
result := UsageGroups{Groups: []UsageGroup{}}
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if c.readAsOf(ctx, q, &result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, c.baseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var group UsageGroup
|
||||
if rows.Scan(&raw, &group.Total, &group.Succeeded, &group.Failed) != nil || json.Unmarshal([]byte(raw), &group.Identity) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
result.Groups = append(result.Groups, group)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Keep the agreed field ordering after governance enriches an initially empty column.
|
||||
func AddRecordColumns(page *RecordPage, extra ...string) {
|
||||
all := map[string]bool{}
|
||||
for _, col := range append(page.Columns, extra...) {
|
||||
all[col] = true
|
||||
}
|
||||
page.Columns = []string{}
|
||||
for _, col := range recordColumnOrder {
|
||||
if all[col] {
|
||||
page.Columns = append(page.Columns, col)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) {
|
||||
pool := fixturePool(t)
|
||||
dsn := qaRecordsFixture(t, pool)
|
||||
execFixture(t, pool, `UPDATE messages SET actor_union_id_snapshot='fixture-union' WHERE id='msg-req-3'`, `UPDATE messages SET actor_id=NULL WHERE id='msg-req-4'`)
|
||||
client := buildReadOnlyClient(t, dsn)
|
||||
query := RecordQuery{Window: Window{TenantKey: "default", Start: time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC), End: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)}, Limit: 1}
|
||||
page, err := client.ListRecords(context.Background(), query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if page.Total != 4 || len(page.Items) != 1 || page.Items[0].Identity.StaffID != "" {
|
||||
t.Fatal("fixture first page should be anonymous")
|
||||
}
|
||||
found := false
|
||||
for _, actor := range page.ScopeActors {
|
||||
if actor.StaffID == "ext-actor-1" && actor.UnionID == "fixture-union" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if len(page.ScopeQuality) != 4 || len(page.Items[0].QualityInputHash) != 64 {
|
||||
t.Fatal("whole-scope quality versions missing")
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("whole-filter keys missing; later-page department would be hidden")
|
||||
}
|
||||
item, err := client.GetRecord(context.Background(), "default", "turn-3")
|
||||
if err != nil || item.Identity.StaffID != "ext-actor-1" || item.Identity.UnionID != "fixture-union" {
|
||||
t.Fatalf("stable identity not read from inbound actor/message: %v", err)
|
||||
}
|
||||
scope, se := client.ReadQualityScope(context.Background(), query)
|
||||
if se != nil || len(scope.Keys) != 4 || scope.AsOf.IsZero() {
|
||||
t.Fatal("quality metadata scope incomplete", se)
|
||||
}
|
||||
for _, key := range scope.Keys {
|
||||
if len(key.InputHash) != 64 || key.ObservedAt.IsZero() {
|
||||
t.Fatal("scope omitted input version")
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(page)
|
||||
detail, _ := json.Marshal(item)
|
||||
for _, s := range []string{string(raw), string(detail)} {
|
||||
for _, private := range []string{"ext-actor-1", "fixture-union", "actor-row-1", "_identity", "scope_actors"} {
|
||||
if strings.Contains(s, private) {
|
||||
t.Fatal("internal roster key leaked into API JSON")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestQAUsageGroupsCountEventsOnceOverTheFullFilter(t *testing.T) {
|
||||
pool := fixturePool(t)
|
||||
dsn := qaRecordsFixture(t, pool)
|
||||
|
||||
client := buildReadOnlyClient(t, dsn)
|
||||
query := RecordQuery{Window: Window{TenantKey: "default", Start: time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC), End: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)}}
|
||||
result, err := client.ReadUsageGroups(context.Background(), query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var total, success, failed int64
|
||||
for _, g := range result.Groups {
|
||||
total += g.Total
|
||||
success += g.Succeeded
|
||||
failed += g.Failed
|
||||
}
|
||||
if total != 4 || success != 3 || failed != 1 || result.AsOf.IsZero() {
|
||||
t.Fatalf("events multiplied/foreign tenant included: %d %d %d", total, success, failed)
|
||||
}
|
||||
query.Keyword = "%"
|
||||
result, err = client.ReadUsageGroups(context.Background(), query)
|
||||
if err != nil || len(result.Groups) != 0 {
|
||||
t.Fatal("usage keyword wildcard not literal")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Client 是对外部生产库的**独立只读**客户端:自己的 pool、自己的凭据、自己的超时。
|
||||
// 它没有任何写方法,也不做 DDL/迁移 —— 这是本阶段的接口面本身在保证的事。
|
||||
type Client struct {
|
||||
pool *pgxpool.Pool
|
||||
config Config
|
||||
report ACLReport
|
||||
safety SourceSafety
|
||||
}
|
||||
|
||||
// Build 建立只读客户端:
|
||||
// 1. 形状校验 → 2. 从仓库外 0600 secret 读 DSN → 3. 拒绝指向治理主库 →
|
||||
// 4. 建独立 pool(default_transaction_read_only=on、statement_timeout、连接上限)→
|
||||
// 5. Ping → 6. ACL 自检(不是最小只读就 fail closed)。
|
||||
//
|
||||
// 任何一步失败都返回 ErrUnavailable / ErrNotReadOnly;调用方据此把功能标记为不可用,
|
||||
// **绝不回退到治理主库或应用写账号**。
|
||||
func Build(ctx context.Context, cfg Config) (*Client, error) {
|
||||
cfg = cfg.withDefaults()
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dsn, err := ReadDSNFile(cfg.DSNFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := GuardGovernanceDatabase(dsn, cfg.GovernanceDatabaseURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolConfig, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
// 解析失败的原始错误可能带着 DSN,绝不上抛。
|
||||
return nil, fmt.Errorf("%w: DSN could not be parsed", ErrUnavailable)
|
||||
}
|
||||
poolConfig.MaxConns = cfg.MaxConns
|
||||
poolConfig.MinConns = cfg.MinConns
|
||||
poolConfig.MaxConnLifetime = 30 * time.Minute
|
||||
poolConfig.MaxConnIdleTime = 5 * time.Minute
|
||||
poolConfig.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
if poolConfig.ConnConfig.RuntimeParams == nil {
|
||||
poolConfig.ConnConfig.RuntimeParams = map[string]string{}
|
||||
}
|
||||
// 会话级只读 + 语句超时:只读默认不是 ACL 的替代品,两层都要有。
|
||||
poolConfig.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
poolConfig.ConnConfig.RuntimeParams["statement_timeout"] = fmt.Sprintf("%d", (cfg.QueryTimeout + 2*time.Second).Milliseconds())
|
||||
poolConfig.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = "15000"
|
||||
poolConfig.ConnConfig.RuntimeParams["application_name"] = "kg-dobotai-ops-readonly"
|
||||
poolConfig.ConnConfig.RuntimeParams["search_path"] = "pg_catalog,public"
|
||||
if cfg.DialContext != nil {
|
||||
poolConfig.ConnConfig.DialFunc = cfg.DialContext
|
||||
} else if cfg.DialMode == "ssh" {
|
||||
// 拨号地址只从配置里的 DSN 派生(远端解析),不接受 pgx 传入的本机解析结果 ——
|
||||
// 本机 DNS 被 Fake-IP/VPN 劫持时,那个结果会是假地址(实测挂 20s 超时)。
|
||||
dialAddress, addrErr := hostPortOf(dsn)
|
||||
if addrErr != nil {
|
||||
return nil, addrErr
|
||||
}
|
||||
dialer, dialErr := SSHDialer(cfg.SSHTarget, dialAddress)
|
||||
if dialErr != nil {
|
||||
return nil, dialErr
|
||||
}
|
||||
poolConfig.ConnConfig.DialFunc = dialer
|
||||
}
|
||||
|
||||
connectCtx, cancelConnect := context.WithTimeout(ctx, cfg.ConnectTimeout)
|
||||
defer cancelConnect()
|
||||
pool, err := pgxpool.NewWithConfig(connectCtx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: pool could not be created", ErrUnavailable)
|
||||
}
|
||||
client := &Client{pool: pool, config: cfg}
|
||||
pingCtx, cancelPing := context.WithTimeout(ctx, cfg.ConnectTimeout)
|
||||
defer cancelPing()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("%w: cannot reach the external read-only database", ErrUnavailable)
|
||||
}
|
||||
auditCtx, cancelAudit := context.WithTimeout(ctx, cfg.QueryTimeout)
|
||||
defer cancelAudit()
|
||||
report, err := AssertReadOnly(auditCtx, poolQuerier{pool: pool})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
safety, err := AuditSourceSafety(auditCtx, poolQuerier{pool: pool})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
if cfg.MaxConns > int32(safety.ConnectionLimit) {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("%w: pool exceeds source role connection budget", ErrNotReadOnly)
|
||||
}
|
||||
client.report = report
|
||||
client.safety = safety
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Close 释放独立 pool(治理主 pool 完全不受影响)。
|
||||
func (c *Client) Close() {
|
||||
if c != nil && c.pool != nil {
|
||||
c.pool.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// ACL 返回启动时自检的权限报告(只含角色与 ACL,不含业务数据)。
|
||||
func (c *Client) ACL() ACLReport { return c.report }
|
||||
|
||||
// Safety preserves transport/TEMP findings without mislabelling them as fixed.
|
||||
func (c *Client) Safety() SourceSafety { return c.safety }
|
||||
|
||||
// Config 返回生效后的配置,**已清掉所有连接/凭据字段**(secret 文件路径与治理库 DSN 都不外传;
|
||||
// 之前只清了 DSNFile,治理库连接串会跟着这个结构被复制出去)。
|
||||
func (c *Client) Config() Config {
|
||||
cfg := c.config
|
||||
cfg.DSNFile = ""
|
||||
cfg.GovernanceDatabaseURL = ""
|
||||
cfg.DialContext = nil
|
||||
return cfg
|
||||
}
|
||||
|
||||
// Available 是给健康检查/日志用的轻量探测:一次 SELECT 1,带自己的超时。
|
||||
func (c *Client) Available(ctx context.Context) error {
|
||||
if c == nil || c.pool == nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
probeCtx, cancel := context.WithTimeout(ctx, c.config.ConnectTimeout)
|
||||
defer cancel()
|
||||
var one int
|
||||
if err := c.pool.QueryRow(probeCtx, "SELECT 1").Scan(&one); err != nil {
|
||||
return fmt.Errorf("%w: probe failed", ErrUnavailable)
|
||||
}
|
||||
if one != 1 {
|
||||
return fmt.Errorf("%w: probe returned an unexpected value", ErrUnavailable)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// poolQuerier 让 *pgxpool.Pool 适配本包的最小接口(ACL 与仓储都只用这两种方法)。
|
||||
type poolQuerier struct{ pool *pgxpool.Pool }
|
||||
|
||||
func (q poolQuerier) QueryRow(ctx context.Context, sql string, args ...any) rowScanner {
|
||||
return q.pool.QueryRow(ctx, sql, args...)
|
||||
}
|
||||
|
||||
func (q poolQuerier) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
|
||||
return q.pool.Query(ctx, sql, args...)
|
||||
}
|
||||
|
||||
// withReadOnlyTx 把一次读放进 REPEATABLE READ + READ ONLY 事务:统计口径固定在同一个
|
||||
// as_of 上,且即便账号被误配成可写,这里也没有写的机会。
|
||||
func (c *Client) withReadOnlyTx(ctx context.Context, fn func(ctx context.Context, querier querier) error) error {
|
||||
if c == nil || c.pool == nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
queryCtx, cancel := context.WithTimeout(ctx, c.config.QueryTimeout)
|
||||
defer cancel()
|
||||
tx, err := c.pool.BeginTx(queryCtx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: cannot open a read-only transaction", ErrUnavailable)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
if _, err := AssertReadOnly(queryCtx, txQuerier{tx: tx}); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := AuditSourceSafety(queryCtx, txQuerier{tx: tx}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fn(queryCtx, txQuerier{tx: tx}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(queryCtx); err != nil {
|
||||
return fmt.Errorf("%w: read-only transaction failed", ErrUnavailable)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type querier interface {
|
||||
QueryRow(ctx context.Context, sql string, args ...any) rowScanner
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
type txQuerier struct{ tx pgx.Tx }
|
||||
|
||||
func (q txQuerier) QueryRow(ctx context.Context, sql string, args ...any) rowScanner {
|
||||
return q.tx.QueryRow(ctx, sql, args...)
|
||||
}
|
||||
|
||||
func (q txQuerier) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
|
||||
return q.tx.Query(ctx, sql, args...)
|
||||
}
|
||||
|
||||
// ErrUnavailableIfNil 让调用方把 nil 客户端当成"未启用"而不是 panic。
|
||||
func ErrUnavailableIfNil(client *Client) error {
|
||||
if client == nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hostPortOf 从 DSN 取"主机:端口"(缺端口按 5432),只用于固定隧道的拨号地址。
|
||||
// 只做解析,不返回任何凭据。
|
||||
func hostPortOf(dsn string) (string, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(dsn))
|
||||
if err != nil || parsed.Hostname() == "" {
|
||||
return "", fmt.Errorf("%w: DSN has no host to dial", ErrUnavailable)
|
||||
}
|
||||
port := parsed.Port()
|
||||
if port == "" {
|
||||
port = "5432"
|
||||
}
|
||||
return parsed.Hostname() + ":" + port, nil
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 生产只读**组合验证**:Go 客户端 + 最小只读账号 + 经批准的 SSH 通路,真读生产数据。
|
||||
//
|
||||
// 只在前两项都显式给出时运行(默认跳过,绝不在 CI 或误操作下碰生产):
|
||||
//
|
||||
// KG_DOBOTAI_PROD_VERIFY=1 \
|
||||
// KG_DOBOTAI_PROD_DSN_FILE=~/.config/knowledge-governance/secrets/dobotai_ops_ro.env \
|
||||
// KG_DOBOTAI_PROD_SSH_TARGET=weknora-prod \
|
||||
// go test ./internal/dobotaiops/ -run TestProductionReadOnlyCombinedVerification -v
|
||||
//
|
||||
// 纪律:只用只读账号;只 SELECT;证据里**不打印**正文、员工姓名或任何凭据。
|
||||
func TestProductionReadOnlyCombinedVerification(t *testing.T) {
|
||||
if strings.TrimSpace(os.Getenv("KG_DOBOTAI_PROD_VERIFY")) != "1" {
|
||||
t.Skip("KG_DOBOTAI_PROD_VERIFY≠1:跳过生产组合验证")
|
||||
}
|
||||
dsnFile := expandHome(strings.TrimSpace(os.Getenv("KG_DOBOTAI_PROD_DSN_FILE")))
|
||||
sshTarget := strings.TrimSpace(os.Getenv("KG_DOBOTAI_PROD_SSH_TARGET"))
|
||||
tenantKey := strings.TrimSpace(os.Getenv("KG_DOBOTAI_PROD_TENANT"))
|
||||
if dsnFile == "" || sshTarget == "" || tenantKey == "" {
|
||||
// 租户键必须由调用方给出:查询本身就是"按租户"的,猜一个默认值等于自欺。
|
||||
t.Skip("KG_DOBOTAI_PROD_DSN_FILE / KG_DOBOTAI_PROD_SSH_TARGET / KG_DOBOTAI_PROD_TENANT 未设置:跳过")
|
||||
}
|
||||
dsn, err := ReadDSNFile(dsnFile)
|
||||
if err != nil {
|
||||
t.Fatalf("读只读 secret 失败:%v", err)
|
||||
}
|
||||
parsed, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := parsed.Port()
|
||||
if port == "" {
|
||||
port = "5432"
|
||||
}
|
||||
// 拨号地址由 DSN 派生(不写死主机),并经 SSH 通路到达:
|
||||
address := parsed.Hostname() + ":" + port
|
||||
t.Logf("经 SSH 目标 %s 拨号到 %s(只读账号 %s)", sshTarget, address, parsed.User.Username())
|
||||
|
||||
// 关键:DialMode=ssh ⇒ 走 SSHDialer(socketpair + ssh -W),不是直连。
|
||||
client, err := Build(context.Background(), Config{
|
||||
DSNFile: dsnFile,
|
||||
GovernanceDatabaseURL: "postgres://governance@not-this-host:5432/governance",
|
||||
DialMode: "ssh",
|
||||
SSHTarget: sshTarget,
|
||||
ConnectTimeout: 10 * time.Second,
|
||||
QueryTimeout: 8 * time.Second,
|
||||
MaxConns: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Build()(经 SSH 通路 + 只读账号)失败:%v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
|
||||
report := client.ACL()
|
||||
t.Logf("ACL 报告:role=%s super=%v createrole=%v createdb=%v bypassrls=%v replication=%v schema_create=%v db_create=%v "+
|
||||
"memberships=%d set_role=%d owned_rel=%d owned_schema=%d secdef_exec=%d write_privs=%d missing_selects=%d",
|
||||
report.Role, report.Super, report.CreateRole, report.CreateDB, report.BypassRLS, report.Replication,
|
||||
report.SchemaCreate, report.DatabaseCreate, report.RoleMemberships, report.SetRoleCandidates,
|
||||
report.OwnedRelations, report.OwnedSchemas, report.ExecutableSecDefFns,
|
||||
len(report.WritePrivileges), len(report.MissingSelects))
|
||||
|
||||
now := time.Now().UTC()
|
||||
window, err := NewWindow(tenantKey, now.Add(-14*24*time.Hour).Format(time.RFC3339), now.Add(-30*time.Minute).Format(time.RFC3339), 90*24*time.Hour, now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWindow() error = %v", err)
|
||||
}
|
||||
counts, err := client.QueryCounts(ctx, window, Filter{})
|
||||
if err != nil {
|
||||
t.Fatalf("QueryCounts() error = %v", err)
|
||||
}
|
||||
t.Logf("窗口 %s → %s:turns=%d 状态=%v 渠道=%v", window.Start.Format(time.RFC3339), window.End.Format(time.RFC3339), counts.Total, counts.ByStatus, counts.ByChannel)
|
||||
|
||||
coverage, err := client.QueryRuleCoverage(ctx, window)
|
||||
if err != nil {
|
||||
t.Fatalf("QueryRuleCoverage() error = %v", err)
|
||||
}
|
||||
byVersion := map[string]int64{}
|
||||
for _, group := range coverage.Groups {
|
||||
byVersion[group.EvaluatorVersion+"|"+group.Verdict] += group.Turns
|
||||
}
|
||||
t.Logf("rule_coverage:成功 turn=%d 缺决策=%d 分组(版本|verdict=%d):%v", coverage.SucceededTurns, coverage.SucceededWithoutDecision, len(coverage.Groups), byVersion)
|
||||
|
||||
page, err := client.ListTurnMetadata(ctx, window, "", 5)
|
||||
if err != nil {
|
||||
t.Fatalf("ListTurnMetadata() error = %v", err)
|
||||
}
|
||||
missingDepartment, missingRegion, linkedNonZero := 0, 0, 0
|
||||
for _, item := range page.Items {
|
||||
if item.DepartmentMissing {
|
||||
missingDepartment++
|
||||
}
|
||||
if item.RegionMissing {
|
||||
missingRegion++
|
||||
}
|
||||
if item.LinkedMessages > 0 {
|
||||
linkedNonZero++
|
||||
}
|
||||
}
|
||||
t.Logf("元数据首页:%d 条(HasMore=%v)|关联消息>0 的 %d 条|部门缺失 %d|区域缺失 %d", len(page.Items), page.HasMore, linkedNonZero, missingDepartment, missingRegion)
|
||||
if len(page.Items) == 0 {
|
||||
t.Fatal("窗口内没有 turn:窗口选错了")
|
||||
}
|
||||
|
||||
// 人员关联回归:用真实 turn 走授权读取,检查关联是否真的命中(关联字段错就会全空)。
|
||||
// 生产形态:一个 turn 的 request(入站)消息带 actor_id,answer(出站)不带 ⇒
|
||||
// 入站必须关联到 actor,出站未关联属正常事实(用 ActorLinked 区分,不混为一谈)。
|
||||
inboundLinked, inboundUnlinked, outboundUnlinked := 0, 0, 0
|
||||
for _, item := range page.Items {
|
||||
detail, err := client.GetTurnForAuthorizedRead(ctx, window.TenantKey, item.ID, func(string) error { return nil })
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, message := range detail.Messages {
|
||||
switch {
|
||||
case message.Direction == "inbound" && message.ActorLinked && message.ActorType != "":
|
||||
inboundLinked++
|
||||
case message.Direction == "inbound":
|
||||
inboundUnlinked++
|
||||
case !message.ActorLinked:
|
||||
outboundUnlinked++
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Logf("人员关联(channel_actors.id = messages.actor_id):入站已关联 %d / 入站未关联 %d / 出站无 actor %d",
|
||||
inboundLinked, inboundUnlinked, outboundUnlinked)
|
||||
if inboundLinked == 0 {
|
||||
t.Fatal("人员关联一处都没命中:关联字段或通路有问题")
|
||||
}
|
||||
if inboundUnlinked > 0 {
|
||||
t.Fatalf("有 %d 条入站消息没关联到 actor:", inboundUnlinked)
|
||||
}
|
||||
|
||||
// 只读边界:ACL 函数自证(不执行任何写语句)。
|
||||
for _, table := range RequiredTables {
|
||||
if !strings.Contains(fmt.Sprint(report.CheckedTableList), table) {
|
||||
t.Fatalf("自检没覆盖 %s", table)
|
||||
}
|
||||
}
|
||||
if err := client.Available(ctx); err != nil {
|
||||
t.Fatalf("可用性探测失败:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func expandHome(path string) string {
|
||||
if strings.HasPrefix(path, "~/") {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
return home + path[1:]
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QualityScope struct {
|
||||
Keys []QualityKey
|
||||
AsOf time.Time
|
||||
}
|
||||
|
||||
func (c *RecordsRepository) ReadQualityScope(ctx context.Context, query RecordQuery) (QualityScope, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
if query.Cursor != "" {
|
||||
return QualityScope{}, ErrInvalidQuery
|
||||
}
|
||||
pattern, err := recordKeywordPattern(query.Keyword)
|
||||
if err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
result := QualityScope{Keys: []QualityKey{}}
|
||||
err = c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if c.readAsOf(ctx, q, &result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
scopeSQL := c.baseSQL + ` SELECT id,quality_hash,strpos(payload->>'answer',$5)>0,(payload->'source_coverage')::text FROM records WHERE `
|
||||
if c.qualityScopeSQL != "" {
|
||||
scopeSQL = c.qualityScopeSQL
|
||||
}
|
||||
rows, err := q.Query(ctx, scopeSQL+recordFilterSQL+` ORDER BY id LIMIT 5001`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern, noPublishedMarker)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var key QualityKey
|
||||
var raw string
|
||||
if rows.Scan(&key.ID, &key.InputHash, &key.Marker, &raw) != nil || json.Unmarshal([]byte(raw), &key.Source) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(result.Keys) >= 5000 {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
key.ObservedAt = result.AsOf
|
||||
result.Keys = append(result.Keys, key)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RecordQuerier and RecordTransaction keep the projection identical while an
|
||||
// explicitly selected reader supplies either source-ACL or local-snapshot transactions.
|
||||
type RecordRow = rowScanner
|
||||
type RecordQuerier = querier
|
||||
type RecordTransaction func(context.Context, func(context.Context, RecordQuerier) error) error
|
||||
type RecordsRepositoryOptions struct {
|
||||
BaseSQL string
|
||||
SummarySQL string
|
||||
QualityScopeSQL string
|
||||
Transaction RecordTransaction
|
||||
ValidateWindow func(Window) error
|
||||
ReadAsOf func(context.Context, RecordQuerier, *time.Time) error
|
||||
TenantKey string
|
||||
}
|
||||
type RecordsRepository struct {
|
||||
baseSQL string
|
||||
summarySQL string
|
||||
qualityScopeSQL string
|
||||
transact RecordTransaction
|
||||
validateQueryWindow func(Window) error
|
||||
readAsOf func(context.Context, RecordQuerier, *time.Time) error
|
||||
tenant string
|
||||
}
|
||||
|
||||
func NewRecordsRepository(o RecordsRepositoryOptions) *RecordsRepository {
|
||||
asOf := o.ReadAsOf
|
||||
if asOf == nil {
|
||||
asOf = func(ctx context.Context, q RecordQuerier, t *time.Time) error {
|
||||
return q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(t)
|
||||
}
|
||||
}
|
||||
return &RecordsRepository{summarySQL: o.SummarySQL, qualityScopeSQL: o.QualityScopeSQL, baseSQL: o.BaseSQL, transact: o.Transaction, validateQueryWindow: o.ValidateWindow, readAsOf: asOf, tenant: o.TenantKey}
|
||||
}
|
||||
func (c *RecordsRepository) WithSummarySQL(sql string) *RecordsRepository {
|
||||
out := *c
|
||||
out.summarySQL = sql
|
||||
return &out
|
||||
}
|
||||
func (c *Client) recordRepository() *RecordsRepository {
|
||||
return NewRecordsRepository(RecordsRepositoryOptions{BaseSQL: recordsBaseSQL, Transaction: c.withReadOnlyTx, ValidateWindow: c.validateQueryWindow})
|
||||
}
|
||||
func (c *Client) ListRecords(ctx context.Context, q RecordQuery) (RecordPage, error) {
|
||||
return c.recordRepository().ListRecords(ctx, q)
|
||||
}
|
||||
func (c *Client) GetRecord(ctx context.Context, tenant, id string) (Record, error) {
|
||||
return c.recordRepository().GetRecord(ctx, tenant, id)
|
||||
}
|
||||
func (c *Client) ReadUsageGroups(ctx context.Context, q RecordQuery) (UsageGroups, error) {
|
||||
return c.recordRepository().ReadUsageGroups(ctx, q)
|
||||
}
|
||||
func (c *Client) ReadQualityScope(ctx context.Context, q RecordQuery) (QualityScope, error) {
|
||||
return c.recordRepository().ReadQualityScope(ctx, q)
|
||||
}
|
||||
|
||||
// DecodeMirrorPayload accepts only the source adapter's fixed safe projection;
|
||||
// credentials and arbitrary source tables are never part of this protocol.
|
||||
func DecodeMirrorPayload(raw string) (Record, error) { return decodeRecord(raw) }
|
||||
@@ -0,0 +1,335 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const CoverageRuleVersion = "governance-answer-substring-v1"
|
||||
const noPublishedMarker = "暂无已发布"
|
||||
|
||||
// The master follows the explicitly approved v2 policy; legacy/source checks stay immutable.
|
||||
func CheckMasterCoverage(answer string, available bool) CoverageCheck {
|
||||
result := CoverageCheck{State: "pending", RuleVersion: "master-answer-substring-v2"}
|
||||
if !available || strings.TrimSpace(answer) == "" {
|
||||
return result
|
||||
}
|
||||
result.State = "checked"
|
||||
result.Verdict = "covered"
|
||||
if strings.Contains(answer, noPublishedMarker) {
|
||||
result.Verdict = "uncovered"
|
||||
result.MatchedText = noPublishedMarker
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
var ErrRecordNotFound = errors.New("qa record not found")
|
||||
|
||||
type CoverageCheck struct {
|
||||
Verdict string `json:"verdict,omitempty"`
|
||||
State string `json:"state"`
|
||||
RuleVersion string `json:"rule_version"`
|
||||
MatchedText string `json:"matched_text,omitempty"`
|
||||
}
|
||||
|
||||
// Absence of this exact substring is not evidence that knowledge covers a question.
|
||||
func CheckAnswerCoverage(answer string) CoverageCheck {
|
||||
return CheckMarkerCoverage(strings.Contains(answer, noPublishedMarker))
|
||||
}
|
||||
func CheckMarkerCoverage(matched bool) CoverageCheck {
|
||||
result := CoverageCheck{State: "pending", RuleVersion: CoverageRuleVersion}
|
||||
if matched {
|
||||
result.State = "checked"
|
||||
result.Verdict = "uncovered"
|
||||
result.MatchedText = noPublishedMarker
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
type SourceCoverage struct {
|
||||
Verdict string `json:"verdict"`
|
||||
ReasonCode string `json:"reason_code"`
|
||||
EvaluatorVersion string `json:"evaluator_version"`
|
||||
}
|
||||
|
||||
type RecordFeedback struct {
|
||||
AskerValue string `json:"asker_value"`
|
||||
Up int64 `json:"up"`
|
||||
Down int64 `json:"down"`
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
ContentProjection string `json:"content_projection,omitempty"`
|
||||
FieldEditRevision int64 `json:"field_edit_revision,omitempty"`
|
||||
BackgroundTasks json.RawMessage `json:"background_tasks,omitempty"`
|
||||
RecordOrigin string `json:"record_origin,omitempty"`
|
||||
MasterFields map[string]string `json:"master_fields,omitempty"`
|
||||
QualityObservedAt time.Time `json:"-"`
|
||||
QualityInputHash string `json:"-"`
|
||||
Quality json.RawMessage `json:"quality,omitempty"`
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Organization *RecordOrganization `json:"organization,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
}
|
||||
|
||||
type RecordQuery struct {
|
||||
Summary bool
|
||||
Filters map[string]string
|
||||
MatchIDs []string
|
||||
MatchVersion string
|
||||
Window Window
|
||||
Keyword string
|
||||
Cursor string
|
||||
Limit int
|
||||
}
|
||||
|
||||
type QualityKey struct {
|
||||
ObservedAt time.Time `json:"-"`
|
||||
Marker bool `json:"marker"`
|
||||
Source SourceCoverage `json:"source"`
|
||||
ID string `json:"id"`
|
||||
InputHash string `json:"input_hash"`
|
||||
}
|
||||
type RecordPage struct {
|
||||
LocalRevision int64 `json:"local_revision,omitempty"`
|
||||
ScopeQuality []QualityKey `json:"-"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
}
|
||||
|
||||
type recordCursor struct {
|
||||
AskedAt time.Time `json:"at"`
|
||||
ID string `json:"id"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
// A single inbound-message join controls names/time. Feedback is preaggregated;
|
||||
// joining each feedback row directly would multiply the business event count.
|
||||
const actorIdentitySQL = `jsonb_build_object('actor_id',COALESCE(a.id,''),'staff_id',COALESCE(a.external_actor_id,''),'union_id',COALESCE(m.actor_union_id_snapshot,''))`
|
||||
const qualityHashSQL = `encode(sha256(convert_to(jsonb_build_array('quality-input-v1',t.id,t.status,t.question,t.answer,t.references_json,COALESCE(m.media_json,'[]'::jsonb))::text,'UTF8')),'hex')`
|
||||
const recordsBaseSQL = `
|
||||
WITH records AS (
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity,` + qualityHashSQL + ` AS quality_hash,
|
||||
jsonb_build_object(
|
||||
'_identity',` + actorIdentitySQL + `, '_quality_hash',` + qualityHashSQL + `,'_quality_observed_at',transaction_timestamp(),
|
||||
'id',t.id,'status',t.status,'question',t.question,'answer',t.answer,
|
||||
'asked_at',COALESCE(m.created_at,t.created_at),
|
||||
'time_source',CASE WHEN m.id IS NULL THEN 'turn.created_at' ELSE 'request_message.created_at' END,
|
||||
'asker',COALESCE(NULLIF(m.actor_name_snapshot,''),a.display_name,''),
|
||||
'trigger_person',COALESCE(m.trigger_person_snapshot,''),
|
||||
'department',COALESCE(m.department_snapshot,''),'region',COALESCE(m.region_snapshot,''),
|
||||
'references',t.references_json,'media',COALESCE(m.media_json,'[]'::jsonb),
|
||||
'source_coverage',jsonb_build_object('verdict',COALESCE(c.verdict,''),'reason_code',COALESCE(c.reason_code,''),'evaluator_version',COALESCE(c.evaluator_version,'')),
|
||||
'feedback',jsonb_build_object('asker_value',COALESCE(f.asker_value,''),'up',f.up_count,'down',f.down_count)
|
||||
) AS payload
|
||||
FROM public.turns t
|
||||
LEFT JOIN public.messages m ON m.id=t.request_message_id AND m.tenant_key=t.tenant_key AND m.channel=t.channel AND m.direction='inbound'
|
||||
LEFT JOIN public.channel_actors a ON a.id=m.actor_id AND a.tenant_key=t.tenant_key AND a.channel=t.channel
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT verdict,reason_code,evaluator_version FROM public.coverage_decisions c
|
||||
WHERE c.turn_id=t.id AND c.tenant_key=t.tenant_key AND c.channel=t.channel
|
||||
ORDER BY c.created_at DESC,c.evaluator_version DESC LIMIT 1
|
||||
) c ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT count(*) FILTER(WHERE value='up') AS up_count,count(*) FILTER(WHERE value='down') AS down_count,
|
||||
max(value) FILTER(WHERE actor_id=m.actor_id) AS asker_value
|
||||
FROM public.answer_feedback f
|
||||
WHERE f.turn_id=t.id AND f.answer_message_id=t.answer_message_id AND f.tenant_key=t.tenant_key AND f.channel=t.channel
|
||||
) f ON true
|
||||
WHERE t.tenant_key=$1 AND t.channel='dingtalk'
|
||||
)`
|
||||
|
||||
const recordFilterSQL = ` asked_at >= $2 AND asked_at < $3 AND ($4='' OR question ILIKE $4 ESCAPE '\')`
|
||||
|
||||
// Availability is over the entire filtered result, not just the current page.
|
||||
const recordColumnsSQL = `SELECT count(*),jsonb_build_object(
|
||||
'answer',COALESCE(bool_or(payload->>'answer'<>''),false),
|
||||
'coverage',COALESCE(bool_or(strpos(payload->>'answer',$5)>0),false),
|
||||
'asked_at',count(*)>0,
|
||||
'asker',COALESCE(bool_or(payload->>'asker'<>''),false),
|
||||
'question',COALESCE(bool_or(question<>''),false),
|
||||
'trigger_person',COALESCE(bool_or(payload->>'trigger_person'<>''),false),
|
||||
'department',COALESCE(bool_or(payload->>'department'<>''),false),
|
||||
'region',COALESCE(bool_or(payload->>'region'<>''),false),
|
||||
'feedback',COALESCE(bool_or(payload->'feedback'->>'asker_value'<>'' OR
|
||||
(payload->'feedback'->>'up')::bigint>0 OR (payload->'feedback'->>'down')::bigint>0),false)
|
||||
)::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text,COALESCE(jsonb_agg(jsonb_build_object('id',id,'input_hash',quality_hash,'marker',strpos(payload->>'answer',$5)>0,'source',payload->'source_coverage')),'[]'::jsonb)::text FROM records WHERE `
|
||||
|
||||
var recordColumnOrder = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
|
||||
func recordKeywordPattern(keyword string) (string, error) {
|
||||
if !utf8.ValidString(keyword) || utf8.RuneCountInString(keyword) > 200 || strings.ContainsRune(keyword, 0) {
|
||||
return "", ErrInvalidQuery
|
||||
}
|
||||
if keyword == "" {
|
||||
return "", nil
|
||||
}
|
||||
return "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(keyword) + "%", nil
|
||||
}
|
||||
|
||||
func (c *RecordsRepository) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return RecordPage{}, err
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > 100 || len(query.Cursor) > 2048 {
|
||||
return RecordPage{}, fmt.Errorf("%w: invalid record filters", ErrInvalidQuery)
|
||||
}
|
||||
scopeBytes, _ := json.Marshal([]string{query.Window.TenantKey, query.Window.Start.UTC().Format(time.RFC3339Nano), query.Window.End.UTC().Format(time.RFC3339Nano), query.Keyword})
|
||||
if len(query.Filters) > 0 {
|
||||
if query.MatchIDs == nil {
|
||||
return RecordPage{}, ErrInvalidQuery
|
||||
}
|
||||
extra, _ := json.Marshal(struct {
|
||||
Filters map[string]string
|
||||
Version string
|
||||
}{query.Filters, query.MatchVersion})
|
||||
scopeBytes = append(scopeBytes, extra...)
|
||||
}
|
||||
scopeSum := sha256.Sum256(scopeBytes)
|
||||
scope := hex.EncodeToString(scopeSum[:])
|
||||
var cursor recordCursor
|
||||
var before any
|
||||
if query.Cursor != "" {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(query.Cursor)
|
||||
if err != nil || json.Unmarshal(decoded, &cursor) != nil || cursor.Scope != scope || cursor.ID == "" || len(cursor.ID) > 256 || cursor.AskedAt.Before(query.Window.Start) || !cursor.AskedAt.Before(query.Window.End) {
|
||||
return RecordPage{}, fmt.Errorf("%w: invalid or mismatched cursor", ErrInvalidQuery)
|
||||
}
|
||||
before = cursor.AskedAt
|
||||
}
|
||||
pattern, patternErr := recordKeywordPattern(query.Keyword)
|
||||
if patternErr != nil {
|
||||
return RecordPage{}, patternErr
|
||||
}
|
||||
args := []any{query.Window.TenantKey, query.Window.Start, query.Window.End, pattern}
|
||||
page := RecordPage{Items: make([]Record, 0), Columns: make([]string, 0)}
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := c.readAsOf(ctx, q, &page.AsOf); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var rawColumns, rawActors, rawQuality string
|
||||
summarySQL := c.baseSQL + recordColumnsSQL
|
||||
if c.summarySQL != "" {
|
||||
summarySQL = c.summarySQL
|
||||
}
|
||||
summaryFilter := recordFilterSQL
|
||||
summaryArgs := append(append([]any{}, args...), noPublishedMarker)
|
||||
if query.MatchIDs != nil {
|
||||
summaryFilter += " AND id=ANY($6::text[])"
|
||||
summaryArgs = append(summaryArgs, query.MatchIDs)
|
||||
}
|
||||
if err := q.QueryRow(ctx, summarySQL+summaryFilter, summaryArgs...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
|
||||
return fmt.Errorf("%w: record count failed", ErrUnavailable)
|
||||
}
|
||||
if json.Unmarshal([]byte(rawQuality), &page.ScopeQuality) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
for i := range page.ScopeQuality {
|
||||
page.ScopeQuality[i].ObservedAt = page.AsOf
|
||||
}
|
||||
var available map[string]bool
|
||||
if json.Unmarshal([]byte(rawActors), &page.ScopeActors) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if err := json.Unmarshal([]byte(rawColumns), &available); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
for _, column := range recordColumnOrder {
|
||||
if available[column] {
|
||||
page.Columns = append(page.Columns, column)
|
||||
}
|
||||
}
|
||||
listFilter := recordFilterSQL
|
||||
listArgs := append(append([]any{}, args...), before, cursor.ID, query.Limit+1)
|
||||
if query.MatchIDs != nil {
|
||||
listFilter += " AND id=ANY($8::text[])"
|
||||
listArgs = append(listArgs, query.MatchIDs)
|
||||
}
|
||||
rows, err := q.Query(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE `+listFilter+`
|
||||
AND ($5::timestamptz IS NULL OR (asked_at,id)<($5,$6)) ORDER BY asked_at DESC,id DESC LIMIT $7`, listArgs...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: record list failed", ErrUnavailable)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
item, err := decodeRecord(raw)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
page.Items = append(page.Items, item)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
if err != nil {
|
||||
return RecordPage{}, err
|
||||
}
|
||||
if len(page.Items) > query.Limit {
|
||||
page.HasMore = true
|
||||
page.Items = page.Items[:query.Limit]
|
||||
last := page.Items[len(page.Items)-1]
|
||||
raw, err := json.Marshal(recordCursor{AskedAt: last.AskedAt, ID: last.ID, Scope: scope})
|
||||
if err != nil {
|
||||
return RecordPage{}, ErrUnavailable
|
||||
}
|
||||
page.NextCursor = base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (c *RecordsRepository) GetRecord(ctx context.Context, tenantKey, id string) (Record, error) {
|
||||
if strings.TrimSpace(tenantKey) == "" || (c.tenant != "" && tenantKey != c.tenant) || id == "" || len(id) > 256 || strings.ContainsRune(id, 0) {
|
||||
return Record{}, ErrInvalidQuery
|
||||
}
|
||||
var item Record
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
var raw string
|
||||
err := q.QueryRow(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE id=$2`, tenantKey, id).Scan(&raw)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrRecordNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
item, err = decodeRecord(raw)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
return item, err
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func qaRecordsFixture(t *testing.T, pool *pgxpool.Pool) string {
|
||||
t.Helper()
|
||||
dsn := buildFixture(t, pool)
|
||||
execFixture(t, pool,
|
||||
`ALTER TABLE messages ADD COLUMN actor_name_snapshot text NOT NULL DEFAULT '', ADD COLUMN trigger_person_snapshot text NOT NULL DEFAULT '', ADD COLUMN media_json jsonb NOT NULL DEFAULT '[]'`,
|
||||
`DROP TABLE IF EXISTS answer_feedback`,
|
||||
`CREATE TABLE answer_feedback(id text PRIMARY KEY,tenant_key text,channel text,turn_id text,answer_message_id text,actor_id text,value text)`,
|
||||
`GRANT SELECT ON answer_feedback TO kg_ro_fixture`,
|
||||
`UPDATE messages SET actor_name_snapshot='测试人员',trigger_person_snapshot='回调昵称' WHERE id='msg-req-3'`,
|
||||
`UPDATE turns SET answer='根据引用,当前暂无已发布的权威知识,暂不建议操作。' WHERE id='turn-3'`,
|
||||
`INSERT INTO answer_feedback VALUES ('fb1','default','dingtalk','turn-3','msg-ans-3','actor-row-1','up'),('fb2','default','dingtalk','turn-3','msg-ans-3','another-person','down'),('fb3','other-tenant','dingtalk','turn-3','msg-ans-3','actor-row-1','down')`,
|
||||
)
|
||||
return dsn
|
||||
}
|
||||
|
||||
func TestQARecordSearchPreservesSourceAndDoesNotMultiplyFeedback(t *testing.T) {
|
||||
pool := fixturePool(t)
|
||||
client := buildReadOnlyClient(t, qaRecordsFixture(t, pool))
|
||||
window := Window{TenantKey: "default", Start: time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC), End: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)}
|
||||
query := RecordQuery{Window: window, Keyword: "第三", Limit: 20}
|
||||
page, err := client.ListRecords(context.Background(), query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if page.Total != 1 || len(page.Items) != 1 {
|
||||
t.Fatalf("feedback multiplied turns: total=%d rows=%d", page.Total, len(page.Items))
|
||||
}
|
||||
item := page.Items[0]
|
||||
if item.ID != "turn-3" || item.Question != "第三问(正文)" || item.Asker != "测试人员" || item.TriggerPerson != "回调昵称" {
|
||||
t.Fatalf("explicit field mapping failed: %+v", item)
|
||||
}
|
||||
if item.Coverage.Verdict != "uncovered" || item.SourceCoverage.Verdict != "covered" {
|
||||
t.Fatalf("governance must override reference-prioritized source without rewriting it: %+v", item)
|
||||
}
|
||||
if item.Feedback.AskerValue != "up" || item.Feedback.Up != 1 || item.Feedback.Down != 1 {
|
||||
t.Fatalf("asker and aggregate feedback were conflated: %+v", item.Feedback)
|
||||
}
|
||||
query.Keyword = "%"
|
||||
page, err = client.ListRecords(context.Background(), query)
|
||||
if err != nil || page.Total != 0 {
|
||||
t.Fatalf("keyword wildcard must be literal: total=%d err=%v", page.Total, err)
|
||||
}
|
||||
query.Keyword = ""
|
||||
query.Limit = 1
|
||||
page, err = client.ListRecords(context.Background(), query)
|
||||
if err != nil || page.Total != 4 || len(page.Items) != 1 || !page.HasMore || page.NextCursor == "" {
|
||||
t.Fatalf("invalid first page: %+v %v", page, err)
|
||||
}
|
||||
firstID := page.Items[0].ID
|
||||
foundFeedback := false
|
||||
for _, column := range page.Columns {
|
||||
if column == "feedback" {
|
||||
foundFeedback = true
|
||||
}
|
||||
}
|
||||
if !foundFeedback {
|
||||
t.Fatal("a populated column elsewhere in the filtered result must not be hidden by an empty first page")
|
||||
}
|
||||
query.Cursor = page.NextCursor
|
||||
next, err := client.ListRecords(context.Background(), query)
|
||||
if err != nil || len(next.Items) != 1 || next.Items[0].ID == firstID {
|
||||
t.Fatalf("invalid cursor page: %+v %v", next, err)
|
||||
}
|
||||
query.Keyword = "changed"
|
||||
if _, err := client.ListRecords(context.Background(), query); !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("cursor must be scoped to its filters: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Explicit opt-in only. This test executes catalog/SELECT queries, never
|
||||
// migrations, permission changes, fixture helpers or business writes.
|
||||
func TestProductionQAQueryReadOnlyVerification(t *testing.T) {
|
||||
if os.Getenv("KG_DOBOTAI_PROD_VERIFY") != "1" {
|
||||
t.Skip("explicit production read verification is disabled")
|
||||
}
|
||||
path, target := os.Getenv("KG_DOBOTAI_PROD_DSN_FILE"), os.Getenv("KG_DOBOTAI_PROD_SSH_TARGET")
|
||||
if path == "" || target == "" {
|
||||
t.Fatal("approved source credential file and SSH target required")
|
||||
}
|
||||
client, err := Build(context.Background(), Config{DSNFile: path, GovernanceDatabaseURL: "postgres://governance@not-this-source/governance", DialMode: "ssh", SSHTarget: target, ConnectTimeout: 10 * time.Second, QueryTimeout: 12 * time.Second, MaxConns: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("dedicated read source blocked: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
now := time.Now().UTC()
|
||||
start, end := now.Add(-14*24*time.Hour), now.Add(-30*time.Minute)
|
||||
tenant := os.Getenv("KG_DOBOTAI_PROD_TENANT")
|
||||
if tenant == "" {
|
||||
// Discover, never guess: refuse if this approved source is not single-tenant.
|
||||
var tenants int
|
||||
err = client.withReadOnlyTx(context.Background(), func(ctx context.Context, q querier) error {
|
||||
return q.QueryRow(ctx, `SELECT count(DISTINCT tenant_key),COALESCE(min(tenant_key),'') FROM public.turns WHERE channel='dingtalk' AND created_at >= $1 AND created_at < $2`, start, end).Scan(&tenants, &tenant)
|
||||
})
|
||||
if err != nil || tenants != 1 || tenant == "" {
|
||||
t.Fatal("source does not identify one authorized tenant; explicit scope is required")
|
||||
}
|
||||
}
|
||||
query := RecordQuery{Window: Window{TenantKey: tenant, Start: start, End: end}, Limit: 5}
|
||||
page, err := client.ListRecords(context.Background(), query)
|
||||
if err != nil {
|
||||
t.Fatalf("real query implementation failed: %v", err)
|
||||
}
|
||||
if page.Total < 1 || len(page.Items) < 1 {
|
||||
t.Fatal("no real source data in the bounded window")
|
||||
}
|
||||
detail, err := client.GetRecord(context.Background(), tenant, page.Items[0].ID)
|
||||
if err != nil || detail.Question != page.Items[0].Question || detail.Answer != page.Items[0].Answer {
|
||||
t.Fatal("source list/detail content mismatch")
|
||||
}
|
||||
if _, err := client.GetRecord(context.Background(), "qaops-not-authorized-tenant", page.Items[0].ID); !errors.Is(err, ErrRecordNotFound) {
|
||||
t.Fatal("tenant isolation failed")
|
||||
}
|
||||
if page.HasMore {
|
||||
query.Cursor = page.NextCursor
|
||||
next, err := client.ListRecords(context.Background(), query)
|
||||
if err != nil {
|
||||
t.Fatalf("real cursor page failed: %v", err)
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
for _, item := range page.Items {
|
||||
ids[item.ID] = true
|
||||
}
|
||||
for _, item := range next.Items {
|
||||
if ids[item.ID] {
|
||||
t.Fatal("cursor pagination repeated a turn")
|
||||
}
|
||||
}
|
||||
}
|
||||
safety := client.Safety()
|
||||
if output := os.Getenv("KG_DOBOTAI_PROD_SCOPE_FILE"); output != "" {
|
||||
// Optional local browser-harness handoff: one tenant key only, never
|
||||
// credentials/employee data, outside Git, exclusive creation and 0600.
|
||||
if !strings.HasPrefix(filepath.Clean(output), filepath.Clean(os.TempDir())+string(os.PathSeparator)) {
|
||||
t.Fatal("scope handoff must stay inside the scratch directory")
|
||||
}
|
||||
file, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create private scope handoff")
|
||||
}
|
||||
_, writeErr := file.WriteString(tenant)
|
||||
closeErr := file.Close()
|
||||
if writeErr != nil || closeErr != nil {
|
||||
t.Fatal("private scope handoff failed")
|
||||
}
|
||||
}
|
||||
t.Logf("REAL_SOURCE_READ_VERIFIED total=%d first_page=%d cursor=%t columns=%v as_of=%s tables_audited=%d effective_table_writes=%d column_writes=%d sequence_writes=%d schema_creates=%d temp=%t ssl=%t; no content or identity logged", page.Total, len(page.Items), page.HasMore, page.Columns, page.AsOf.UTC().Format(time.RFC3339), safety.TablesChecked, safety.TableWrites, safety.ColumnWrites, safety.SequenceWrites, safety.SchemaCreates, safety.DatabaseTemp, safety.SSL)
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 本阶段只读查询模块(工单第 4 项)。纪律:
|
||||
// - 一律绑定参数;列固定;不拼接调用方给的 SQL/排序字段;
|
||||
// - 时间统一半开区间 created_at >= $start AND created_at < $end;
|
||||
// - 按 turn 计次;跨租户/渠道的连接同时校验 tenant_key 与 channel;
|
||||
// - 只走 REPEATABLE READ + READ ONLY 事务,口径固定在同一个 as_of 上。
|
||||
|
||||
const countsTotalSQL = `
|
||||
SELECT count(*)::bigint
|
||||
FROM turns
|
||||
WHERE tenant_key = $1 AND created_at >= $2 AND created_at < $3
|
||||
AND ($4 = '' OR channel = $4) AND ($5 = '' OR status = $5)`
|
||||
|
||||
const countsBySQL = `
|
||||
SELECT %s, count(*)::bigint
|
||||
FROM turns
|
||||
WHERE tenant_key = $1 AND created_at >= $2 AND created_at < $3
|
||||
AND ($4 = '' OR channel = $4) AND ($5 = '' OR status = $5)
|
||||
GROUP BY 1
|
||||
ORDER BY 1`
|
||||
|
||||
// QueryCounts 返回某租户在窗口内的问答总量与状态/渠道分组(按 turn 计次)。
|
||||
func (c *Client) QueryCounts(ctx context.Context, window Window, filter Filter) (CountsResult, error) {
|
||||
if err := filter.Validate(); err != nil {
|
||||
return CountsResult{}, err
|
||||
}
|
||||
if err := c.validateQueryWindow(window); err != nil {
|
||||
return CountsResult{}, err
|
||||
}
|
||||
result := CountsResult{TenantKey: window.TenantKey, Start: window.Start, End: window.End,
|
||||
ByStatus: map[string]int64{}, ByChannel: map[string]int64{}}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := q.QueryRow(ctx, countsTotalSQL, window.TenantKey, window.Start, window.End, filter.Channel, filter.Status).
|
||||
Scan(&result.Total); err != nil {
|
||||
return fmt.Errorf("%w: total count failed", ErrUnavailable)
|
||||
}
|
||||
statusRows, err := q.Query(ctx, fmt.Sprintf(countsBySQL, "status"), window.TenantKey, window.Start, window.End, filter.Channel, filter.Status)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: status grouping failed", ErrUnavailable)
|
||||
}
|
||||
defer statusRows.Close()
|
||||
for statusRows.Next() {
|
||||
var status string
|
||||
var count int64
|
||||
if err := statusRows.Scan(&status, &count); err != nil {
|
||||
return fmt.Errorf("%w: status grouping failed", ErrUnavailable)
|
||||
}
|
||||
result.ByStatus[status] = count
|
||||
}
|
||||
channelRows, err := q.Query(ctx, fmt.Sprintf(countsBySQL, "channel"), window.TenantKey, window.Start, window.End, filter.Channel, filter.Status)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: channel grouping failed", ErrUnavailable)
|
||||
}
|
||||
defer channelRows.Close()
|
||||
for channelRows.Next() {
|
||||
var channel string
|
||||
var count int64
|
||||
if err := channelRows.Scan(&channel, &count); err != nil {
|
||||
return fmt.Errorf("%w: channel grouping failed", ErrUnavailable)
|
||||
}
|
||||
result.ByChannel[channel] = count
|
||||
}
|
||||
if err := statusRows.Err(); err != nil {
|
||||
return fmt.Errorf("%w: status grouping failed", ErrUnavailable)
|
||||
}
|
||||
return channelRows.Err()
|
||||
})
|
||||
if err != nil {
|
||||
return CountsResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
const coverageByVersionSQL = `
|
||||
SELECT c.evaluator_version, c.verdict, c.reason_code, count(DISTINCT c.turn_id)::bigint
|
||||
FROM coverage_decisions c
|
||||
JOIN turns t ON t.id = c.turn_id AND t.tenant_key = c.tenant_key AND t.channel = c.channel
|
||||
WHERE t.tenant_key = $1 AND t.created_at >= $2 AND t.created_at < $3
|
||||
GROUP BY 1, 2, 3
|
||||
ORDER BY 1, 2, 3`
|
||||
|
||||
const succeededTurnStatsSQL = `
|
||||
SELECT count(*)::bigint,
|
||||
count(*) FILTER (
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM coverage_decisions c
|
||||
WHERE c.turn_id = t.id AND c.tenant_key = t.tenant_key AND c.channel = t.channel
|
||||
)
|
||||
)::bigint
|
||||
FROM turns t
|
||||
WHERE t.tenant_key = $1 AND t.status = 'succeeded' AND t.created_at >= $2 AND t.created_at < $3`
|
||||
|
||||
// QueryRuleCoverage 返回规则覆盖分组与"成功 turn 缺决策"量。
|
||||
// 注意:这是 rule_coverage(规则决策),**不是** AI 正确率或正式知识覆盖率;
|
||||
// 不同 evaluator_version 的口径不会混算。
|
||||
func (c *Client) QueryRuleCoverage(ctx context.Context, window Window) (CoverageResult, error) {
|
||||
if err := c.validateQueryWindow(window); err != nil {
|
||||
return CoverageResult{}, err
|
||||
}
|
||||
result := CoverageResult{NotAnAccuracyMeasure: "rule_coverage 只是规则决策覆盖;v5 的 covered 含非知识响应/纯视觉识别,不能当 AI 正确率或正式知识覆盖率"}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
rows, err := q.Query(ctx, coverageByVersionSQL, window.TenantKey, window.Start, window.End)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: coverage grouping failed", ErrUnavailable)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var group CoverageGroup
|
||||
if err := rows.Scan(&group.EvaluatorVersion, &group.Verdict, &group.ReasonCode, &group.Turns); err != nil {
|
||||
return fmt.Errorf("%w: coverage grouping failed", ErrUnavailable)
|
||||
}
|
||||
result.Groups = append(result.Groups, group)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("%w: coverage grouping failed", ErrUnavailable)
|
||||
}
|
||||
if err := q.QueryRow(ctx, succeededTurnStatsSQL, window.TenantKey, window.Start, window.End).
|
||||
Scan(&result.SucceededTurns, &result.SucceededWithoutDecision); err != nil {
|
||||
return fmt.Errorf("%w: succeeded turn stats failed", ErrUnavailable)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return CoverageResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
const listTurnMetadataSQL = `
|
||||
SELECT t.id, t.created_at, t.status, t.channel, t.agent_id, t.knowledge_searched,
|
||||
CASE WHEN jsonb_typeof(t.references_json) = 'array' THEN jsonb_array_length(t.references_json) ELSE 0 END,
|
||||
linked.total,
|
||||
COALESCE(linked.department_missing, TRUE),
|
||||
COALESCE(linked.region_missing, TRUE)
|
||||
FROM turns t
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT count(*)::int AS total,
|
||||
bool_and(COALESCE(m.department_snapshot, '') = '') AS department_missing,
|
||||
bool_and(COALESCE(m.region_snapshot, '') = '') AS region_missing
|
||||
FROM messages m
|
||||
WHERE m.tenant_key = t.tenant_key AND m.channel = t.channel
|
||||
AND m.id = ANY(array_remove(ARRAY[t.request_message_id, t.answer_message_id], NULL))
|
||||
) linked ON TRUE
|
||||
WHERE t.tenant_key = $1 AND t.created_at >= $2 AND t.created_at < $3
|
||||
AND ($4::timestamptz IS NULL OR (t.created_at, t.id) < ($4::timestamptz, $5::text))
|
||||
ORDER BY t.created_at DESC, t.id DESC
|
||||
LIMIT $6`
|
||||
|
||||
// ListTurnMetadata 用 (created_at, id) 游标稳定翻页(倒序);limit 硬上限 100。
|
||||
// 返回的是元数据:不含正文、不含员工个人值;部门/区域快照为空如实标记为 missing。
|
||||
func (c *Client) ListTurnMetadata(ctx context.Context, window Window, cursor string, limit int) (TurnMetadataPage, error) {
|
||||
if err := c.validateQueryWindow(window); err != nil {
|
||||
return TurnMetadataPage{}, err
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > c.config.MaxPageSize {
|
||||
return TurnMetadataPage{}, fmt.Errorf("%w: limit exceeds %d", ErrInvalidQuery, c.config.MaxPageSize)
|
||||
}
|
||||
var decoded Cursor
|
||||
var cursorTime *time.Time
|
||||
if strings.TrimSpace(cursor) != "" {
|
||||
value, err := DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return TurnMetadataPage{}, err
|
||||
}
|
||||
decoded = value
|
||||
cursorTime = &decoded.CreatedAt
|
||||
}
|
||||
page := TurnMetadataPage{}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
rows, err := q.Query(ctx, listTurnMetadataSQL, window.TenantKey, window.Start, window.End, cursorTime, decoded.ID, limit+1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: turn listing failed", ErrUnavailable)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var item TurnMetadata
|
||||
if err := rows.Scan(&item.ID, &item.CreatedAt, &item.Status, &item.Channel, &item.AgentID,
|
||||
&item.KnowledgeSearched, &item.ReferenceCount, &item.LinkedMessages,
|
||||
&item.DepartmentMissing, &item.RegionMissing); err != nil {
|
||||
return fmt.Errorf("%w: turn listing failed", ErrUnavailable)
|
||||
}
|
||||
page.Items = append(page.Items, item)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
if err != nil {
|
||||
return TurnMetadataPage{}, err
|
||||
}
|
||||
if len(page.Items) > limit {
|
||||
// 多取一条只为判断是否还有下一页;游标必须指向**最后一条真正返回的行**,
|
||||
// 否则下一页会跳过那一条(集成测试专门钉这个边界)。
|
||||
page.Items = page.Items[:limit]
|
||||
page.HasMore = true
|
||||
tail := page.Items[len(page.Items)-1]
|
||||
page.NextCursor = EncodeCursor(Cursor{CreatedAt: tail.CreatedAt.UTC(), ID: tail.ID})
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
const authorizedTurnSQL = `
|
||||
SELECT t.id, t.created_at, t.status, t.channel, t.agent_id, t.question, t.answer,
|
||||
COALESCE(t.references_json::text, '[]'), t.error_message
|
||||
FROM turns t
|
||||
WHERE t.tenant_key = $1 AND t.id = $2`
|
||||
|
||||
const authorizedMessagesSQL = `
|
||||
SELECT m.id, m.created_at, m.direction, m.role, m.message_type, m.status, m.text_content,
|
||||
a.id IS NOT NULL,
|
||||
COALESCE(a.actor_type, '')
|
||||
FROM messages m
|
||||
LEFT JOIN channel_actors a
|
||||
-- 关联字段必须是 channel_actors.id:生产 FK 是 messages.actor_id → channel_actors(id)。
|
||||
-- 用 external_actor_id 关联在生产对拍里命中 0 行(正确关联 2234 行)。
|
||||
ON a.tenant_key = m.tenant_key AND a.channel = m.channel AND a.id = m.actor_id
|
||||
WHERE m.tenant_key = $1 AND m.channel = $2
|
||||
AND m.id = ANY(array_remove(ARRAY[$3, $4], NULL))
|
||||
ORDER BY m.created_at, m.id`
|
||||
|
||||
// GetTurnForAuthorizedRead 按租户 + turn_id 读取正文/引用(必要时)。
|
||||
// **必须**传入授权回调(返回错误即拒绝);本函数不提供"默认放行",测试输出也不应打印原文或员工个人值。
|
||||
func (c *Client) GetTurnForAuthorizedRead(ctx context.Context, tenantKey, turnID string, authorize func(turnID string) error) (TurnDetail, error) {
|
||||
if authorize == nil {
|
||||
return TurnDetail{}, fmt.Errorf("%w: an explicit authorization callback is required", ErrInvalidQuery)
|
||||
}
|
||||
if strings.TrimSpace(tenantKey) == "" || strings.TrimSpace(turnID) == "" {
|
||||
return TurnDetail{}, fmt.Errorf("%w: tenant and turn id are required", ErrInvalidQuery)
|
||||
}
|
||||
if err := authorize(turnID); err != nil {
|
||||
return TurnDetail{}, fmt.Errorf("%w: turn read is not authorized", ErrInvalidQuery)
|
||||
}
|
||||
detail := TurnDetail{}
|
||||
var references string
|
||||
var requestID, answerID *string
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := q.QueryRow(ctx, authorizedTurnSQL, tenantKey, turnID).Scan(
|
||||
&detail.ID, &detail.CreatedAt, &detail.Status, &detail.Channel, &detail.AgentID,
|
||||
&detail.Question, &detail.Answer, &references, &detail.ErrorCode); err != nil {
|
||||
return fmt.Errorf("%w: turn could not be read", ErrUnavailable)
|
||||
}
|
||||
detail.ReferencesJSON = []byte(references)
|
||||
if !json.Valid(detail.ReferencesJSON) {
|
||||
detail.ReferencesJSON = []byte("[]")
|
||||
}
|
||||
// request/answer 两条消息 id 需要一起取:单独查一次拿 id 列表,避免把正文带进列表接口。
|
||||
if err := q.QueryRow(ctx, `SELECT request_message_id, answer_message_id FROM turns WHERE tenant_key = $1 AND id = $2`, tenantKey, turnID).
|
||||
Scan(&requestID, &answerID); err != nil {
|
||||
return fmt.Errorf("%w: turn could not be read", ErrUnavailable)
|
||||
}
|
||||
rows, err := q.Query(ctx, authorizedMessagesSQL, tenantKey, detail.Channel, requestID, answerID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: turn messages could not be read", ErrUnavailable)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var message TurnMessage
|
||||
if err := rows.Scan(&message.ID, &message.CreatedAt, &message.Direction, &message.Role,
|
||||
&message.MessageType, &message.Status, &message.Text, &message.ActorLinked, &message.ActorType); err != nil {
|
||||
return fmt.Errorf("%w: turn messages could not be read", ErrUnavailable)
|
||||
}
|
||||
detail.Messages = append(detail.Messages, message)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
if err != nil {
|
||||
return TurnDetail{}, err
|
||||
}
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
// validateQueryWindow 是仓储入口的**完整**校验:不能只靠 NewWindow —— 调用方完全可以
|
||||
// 自己拼一个 Window 结构体绕过它(独立探测已证明)。这里把租户、半开区间、跨度上限
|
||||
// 与"不允许未来窗口"全部落实在每次查询上。
|
||||
func (c *Client) validateQueryWindow(window Window) error {
|
||||
if strings.TrimSpace(window.TenantKey) == "" {
|
||||
return fmt.Errorf("%w: tenant key is required", ErrInvalidQuery)
|
||||
}
|
||||
if window.Start.IsZero() || window.End.IsZero() || !window.Start.Before(window.End) {
|
||||
return fmt.Errorf("%w: window is invalid", ErrInvalidQuery)
|
||||
}
|
||||
limit := c.config.MaxWindow
|
||||
if limit <= 0 {
|
||||
limit = 90 * 24 * time.Hour
|
||||
}
|
||||
if window.End.Sub(window.Start) > limit {
|
||||
return fmt.Errorf("%w: window exceeds the %s limit", ErrInvalidQuery, limit)
|
||||
}
|
||||
now := time.Now()
|
||||
if c.config.Now != nil {
|
||||
now = c.config.Now()
|
||||
}
|
||||
if window.End.After(now.Add(5 * time.Minute)) {
|
||||
return fmt.Errorf("%w: window end is in the future", ErrInvalidQuery)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// 这些用例只在 TEST_DATABASE_URL 指向**一次性/隔离**数据库时运行(CI 默认跳过)。
|
||||
// 它们**绝不**指向生产:fixture 表、隔离角色、临时 DSN 文件都在这个库内建/删。
|
||||
// 生产侧的真实验证另有入口(纯目录/SELECT,见工单与 runbook)。
|
||||
func fixturePool(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
// 先过隔离环境护栏(会建表/建角色):未声明就跳过,声明了但不像一次性库就直接失败。
|
||||
fixtureEnvironment(t)
|
||||
dsn := strings.TrimSpace(os.Getenv("TEST_DATABASE_URL"))
|
||||
pool, err := pgxpool.New(context.Background(), dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
// dropRoleIfExists 先解掉授权依赖再删角色(临时库里可重复运行)。
|
||||
func dropRoleIfExists(t *testing.T, pool *pgxpool.Pool, role string) {
|
||||
t.Helper()
|
||||
var exists bool
|
||||
if err := pool.QueryRow(context.Background(), `SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = $1)`, role).Scan(&exists); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
execFixture(t, pool, fmt.Sprintf(`DROP OWNED BY %s`, quoteIdent(role)), fmt.Sprintf(`DROP ROLE %s`, quoteIdent(role)))
|
||||
}
|
||||
|
||||
func execFixture(t *testing.T, pool *pgxpool.Pool, statements ...string) {
|
||||
t.Helper()
|
||||
for _, statement := range statements {
|
||||
if _, err := pool.Exec(context.Background(), statement); err != nil {
|
||||
t.Fatalf("fixture 语句失败(%s):%v", strings.SplitN(statement, "\n", 2)[0], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func randomSecret(t *testing.T) string {
|
||||
t.Helper()
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.NewReplacer("+", "A", "/", "B", "=", "C").Replace(base64.URLEncoding.EncodeToString(buf))
|
||||
}
|
||||
|
||||
func writeSecretFile(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "dobotai_ops_ro.env")
|
||||
if err := os.WriteFile(path, []byte(content+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// buildFixture 建表 + 灌数据 + 建一个镜像生产授权面的最小只读角色,返回只读 DSN。
|
||||
func buildFixture(t *testing.T, pool *pgxpool.Pool) string {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
execFixture(t, pool,
|
||||
`DROP TABLE IF EXISTS messages, coverage_decisions, channel_actors, turns CASCADE`,
|
||||
`CREATE TABLE turns (id text PRIMARY KEY, tenant_key text NOT NULL, channel text NOT NULL,
|
||||
status text NOT NULL, agent_id text NOT NULL DEFAULT '', knowledge_searched boolean NOT NULL DEFAULT false,
|
||||
references_json jsonb NOT NULL DEFAULT '[]'::jsonb, request_message_id text, answer_message_id text,
|
||||
question text NOT NULL DEFAULT '', answer text NOT NULL DEFAULT '', error_message text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL)`,
|
||||
`CREATE TABLE messages (id text PRIMARY KEY, tenant_key text NOT NULL, channel text NOT NULL, actor_id text,
|
||||
department_snapshot text NOT NULL DEFAULT '', region_snapshot text NOT NULL DEFAULT '', actor_union_id_snapshot text NOT NULL DEFAULT '',
|
||||
direction text NOT NULL DEFAULT '', role text NOT NULL DEFAULT '', message_type text NOT NULL DEFAULT '',
|
||||
status text NOT NULL DEFAULT '', text_content text NOT NULL DEFAULT '', created_at timestamptz NOT NULL)`,
|
||||
`CREATE TABLE coverage_decisions (id text PRIMARY KEY, tenant_key text NOT NULL, channel text NOT NULL,
|
||||
turn_id text NOT NULL, evaluator_version text NOT NULL, verdict text NOT NULL, reason_code text NOT NULL DEFAULT '',
|
||||
reference_count integer NOT NULL DEFAULT 0, created_at timestamptz NOT NULL,
|
||||
UNIQUE (tenant_key, channel, turn_id))`,
|
||||
`CREATE TABLE channel_actors (id text PRIMARY KEY, tenant_key text NOT NULL, channel text NOT NULL,
|
||||
external_actor_id text NOT NULL, actor_type text NOT NULL, display_name text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL)`,
|
||||
`INSERT INTO turns (id, tenant_key, channel, status, agent_id, knowledge_searched, references_json,
|
||||
request_message_id, answer_message_id, question, answer, created_at) VALUES
|
||||
('turn-4', 'default', 'dingtalk', 'succeeded', 'agent-a', false, '[]',
|
||||
'msg-req-4', 'msg-ans-4', '第四问(无规则决策)', '第四答', '2026-10-14T04:00:00Z'),
|
||||
('turn-3', 'default', 'dingtalk', 'succeeded', 'agent-a', true, '[{"doc":"x"},{"doc":"y"}]',
|
||||
'msg-req-3', 'msg-ans-3', '第三问(正文)', '第三答(正文)', '2026-10-14T03:00:00Z'),
|
||||
('turn-2', 'default', 'dingtalk', 'succeeded', 'agent-a', false, '[]',
|
||||
'msg-req-2', 'msg-ans-2', '第二问', '第二答', '2026-10-14T02:00:00Z'),
|
||||
('turn-1', 'default', 'dingtalk', 'failed', 'agent-b', true, '[]',
|
||||
NULL, NULL, '第一问', '', '2026-10-14T01:00:00Z')`,
|
||||
`INSERT INTO messages (id, tenant_key, channel, actor_id, department_snapshot, region_snapshot,
|
||||
direction, role, message_type, status, text_content, created_at) VALUES
|
||||
('msg-req-3', 'default', 'dingtalk', 'actor-row-1', '', '', 'inbound', 'user', 'text', 'ok', '第三问原文', '2026-10-14T03:00:00Z'),
|
||||
('msg-ans-3', 'default', 'dingtalk', 'actor-row-1', '研发部', '华南', 'outbound', 'assistant', 'text', 'ok', '第三答原文', '2026-10-14T03:00:01Z'),
|
||||
('msg-req-2', 'default', 'dingtalk', 'actor-row-1', '', '', 'inbound', 'user', 'text', 'ok', '第二问原文', '2026-10-14T02:00:00Z'),
|
||||
('msg-req-4', 'default', 'dingtalk', 'actor-row-1', '', '', 'inbound', 'user', 'text', 'ok', '第四问原文', '2026-10-14T04:00:00Z'),
|
||||
('msg-ans-4', 'default', 'dingtalk', 'actor-row-1', '', '', 'outbound', 'assistant', 'text', 'ok', '第四答原文', '2026-10-14T04:00:01Z')`,
|
||||
// 真实关系:messages.actor_id 引用 channel_actors(id);external_actor_id 是另一个
|
||||
// 唯一键(tenant_key, channel, external_actor_id)。夹具必须照这个来 —— 用
|
||||
// external_actor_id 关联就会命中 0 行(生产对拍实测:错 0 / 对 2234)。
|
||||
`INSERT INTO channel_actors (id, tenant_key, channel, external_actor_id, actor_type, display_name, created_at)
|
||||
VALUES ('actor-row-1', 'default', 'dingtalk', 'ext-actor-1', 'employee', '不应外泄的姓名', '2026-10-14T00:00:00Z')`,
|
||||
// 另一个租户的数据:所有查询都必须把它挡在外面(跨租户隔离)。
|
||||
`INSERT INTO turns (id, tenant_key, channel, status, agent_id, created_at)
|
||||
VALUES ('turn-other-tenant', 'another-tenant', 'dingtalk', 'succeeded', 'agent-x', '2026-10-14T03:30:00Z')`,
|
||||
`INSERT INTO coverage_decisions (id, tenant_key, channel, turn_id, evaluator_version, verdict, reason_code, reference_count, created_at)
|
||||
VALUES ('cov-other-tenant', 'another-tenant', 'dingtalk', 'turn-other-tenant', 'v5', 'covered', '', 0, '2026-10-14T03:30:02Z')`,
|
||||
// 生产上 (tenant_key, channel, turn_id) 是唯一的:一个 turn 只会有一条决策,
|
||||
// 不同 turn 才可能来自不同 evaluator_version —— fixture 照生产形态来。
|
||||
`INSERT INTO coverage_decisions (id, tenant_key, channel, turn_id, evaluator_version, verdict, reason_code, reference_count, created_at)
|
||||
VALUES ('cov-1', 'default', 'dingtalk', 'turn-3', 'v5', 'covered', '', 2, '2026-10-14T03:00:02Z'),
|
||||
('cov-2', 'default', 'dingtalk', 'turn-1', 'v5', 'uncovered', 'no_source', 0, '2026-10-14T01:00:02Z'),
|
||||
('cov-3', 'default', 'dingtalk', 'turn-2', 'v4', 'covered', '', 0, '2026-10-14T02:00:02Z')`,
|
||||
)
|
||||
password := randomSecret(t)
|
||||
// 角色在同一个临时库里可能已经存在(多个用例复用):先删再建,保持用例可重复运行。
|
||||
dropRoleIfExists(t, pool, "kg_ro_fixture")
|
||||
execFixture(t, pool,
|
||||
fmt.Sprintf(`CREATE ROLE kg_ro_fixture LOGIN PASSWORD '%s' CONNECTION LIMIT 4`, password),
|
||||
`ALTER ROLE kg_ro_fixture SET default_transaction_read_only = on`,
|
||||
)
|
||||
// 当前库名(避免写死)
|
||||
var databaseName string
|
||||
if err := pool.QueryRow(ctx, `SELECT current_database()`).Scan(&databaseName); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
execFixture(t, pool,
|
||||
fmt.Sprintf(`GRANT CONNECT ON DATABASE %s TO kg_ro_fixture`, quoteIdent(databaseName)),
|
||||
`GRANT USAGE ON SCHEMA public TO kg_ro_fixture`,
|
||||
`GRANT SELECT ON TABLE public.turns, public.messages, public.coverage_decisions, public.channel_actors TO kg_ro_fixture`,
|
||||
)
|
||||
// 用与生产一致的写法拼只读 DSN:主机/端口/库名从 TEST_DATABASE_URL 派生
|
||||
//(容器内 inet_server_addr 从宿主机不可路由),口令在测试内不打印。
|
||||
return dsnWithCredentials(t, "kg_ro_fixture", password)
|
||||
}
|
||||
|
||||
// dsnWithCredentials 把 TEST_DATABASE_URL 里的用户/口令换掉,其余(主机、端口、库、查询串)保持。
|
||||
func dsnWithCredentials(t *testing.T, user, password string) string {
|
||||
t.Helper()
|
||||
parsed, err := url.Parse(strings.TrimSpace(os.Getenv("TEST_DATABASE_URL")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsed.User = url.UserPassword(user, password)
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
func quoteIdent(value string) string {
|
||||
return `"` + strings.ReplaceAll(value, `"`, `""`) + `"`
|
||||
}
|
||||
|
||||
func buildReadOnlyClient(t *testing.T, roDSN string) *Client {
|
||||
t.Helper()
|
||||
client, err := Build(context.Background(), Config{
|
||||
DSNFile: writeSecretFile(t, "DOBOTAI_OPS_READ_DSN="+roDSN),
|
||||
GovernanceDatabaseURL: "postgres://governance@elsewhere:5432/governance",
|
||||
DialMode: "direct",
|
||||
ConnectTimeout: 5 * time.Second,
|
||||
QueryTimeout: 5 * time.Second,
|
||||
MaxConns: 2,
|
||||
// 固定"当前时间":仓储入口会拒未来窗口,夹具的时间窗必须相对一个确定时刻来判。
|
||||
Now: func() time.Time { return time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC) },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Build() 失败:%v", err)
|
||||
}
|
||||
t.Cleanup(client.Close)
|
||||
return client
|
||||
}
|
||||
|
||||
func TestReadOnlyRepositoryAgainstFixtureDatabase(t *testing.T) {
|
||||
pool := fixturePool(t)
|
||||
roDSN := buildFixture(t, pool)
|
||||
client := buildReadOnlyClient(t, roDSN)
|
||||
ctx := context.Background()
|
||||
window, err := NewWindow("default", "2026-10-14T00:00:00Z", "2026-10-15T00:00:00Z", 90*24*time.Hour, time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// ACL 自检报告必须干净(这是"账号确实最小只读"的机器证据)。
|
||||
report := client.ACL()
|
||||
if report.Role != "kg_ro_fixture" || report.Super || report.SchemaCreate || len(report.WritePrivileges) != 0 || len(report.MissingSelects) != 0 {
|
||||
t.Fatalf("ACL 报告不干净:%+v", report)
|
||||
}
|
||||
|
||||
counts, err := client.QueryCounts(ctx, window, Filter{})
|
||||
if err != nil {
|
||||
t.Fatalf("QueryCounts() error = %v", err)
|
||||
}
|
||||
if counts.Total != 4 || counts.ByStatus["succeeded"] != 3 || counts.ByStatus["failed"] != 1 || counts.ByChannel["dingtalk"] != 4 {
|
||||
t.Fatalf("counts = %+v", counts)
|
||||
}
|
||||
filtered, err := client.QueryCounts(ctx, window, Filter{Channel: "dingtalk", Status: "succeeded"})
|
||||
if err != nil || filtered.Total != 3 {
|
||||
t.Fatalf("过滤计数 = %+v (%v)", filtered, err)
|
||||
}
|
||||
if _, err := client.QueryCounts(ctx, window, Filter{Status: "nope"}); !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("未知状态应被拒:%v", err)
|
||||
}
|
||||
|
||||
coverage, err := client.QueryRuleCoverage(ctx, window)
|
||||
if err != nil {
|
||||
t.Fatalf("QueryRuleCoverage() error = %v", err)
|
||||
}
|
||||
if len(coverage.Groups) != 3 {
|
||||
t.Fatalf("覆盖分组 = %+v", coverage.Groups)
|
||||
}
|
||||
if coverage.SucceededTurns != 3 || coverage.SucceededWithoutDecision != 1 {
|
||||
t.Fatalf("成功 turn 统计 = %+v", coverage)
|
||||
}
|
||||
for _, group := range coverage.Groups {
|
||||
if group.EvaluatorVersion == "v5" && group.Verdict == "uncovered" && group.ReasonCode != "no_source" {
|
||||
t.Fatalf("reason_code 未保留:%+v", group)
|
||||
}
|
||||
}
|
||||
|
||||
first, err := client.ListTurnMetadata(ctx, window, "", 2)
|
||||
if err != nil {
|
||||
t.Fatalf("ListTurnMetadata() error = %v", err)
|
||||
}
|
||||
if len(first.Items) != 2 || !first.HasMore || first.NextCursor == "" {
|
||||
t.Fatalf("第一页 = %+v", first)
|
||||
}
|
||||
if first.Items[0].ID != "turn-4" || first.Items[1].ID != "turn-3" {
|
||||
t.Fatalf("倒序不对:%+v", first.Items)
|
||||
}
|
||||
if first.Items[1].ReferenceCount != 2 || first.Items[1].LinkedMessages != 2 {
|
||||
t.Fatalf("引用/关联消息计数不对:%+v", first.Items[1])
|
||||
}
|
||||
// turn-3:一条关联消息部门/区域为空、一条有值 ⇒ 不该标 missing;turn-4:两条都为空 ⇒ 如实标 missing。
|
||||
if first.Items[1].DepartmentMissing || first.Items[1].RegionMissing {
|
||||
t.Fatalf("有值的关联消息不该标 missing:%+v", first.Items[1])
|
||||
}
|
||||
if !first.Items[0].DepartmentMissing || !first.Items[0].RegionMissing {
|
||||
t.Fatalf("快照为空的关联消息必须如实标 missing:%+v", first.Items[0])
|
||||
}
|
||||
second, err := client.ListTurnMetadata(ctx, window, first.NextCursor, 2)
|
||||
if err != nil {
|
||||
t.Fatalf("第二页 error = %v", err)
|
||||
}
|
||||
if len(second.Items) != 2 || second.Items[0].ID != "turn-2" || second.Items[1].ID != "turn-1" || second.HasMore {
|
||||
t.Fatalf("第二页 = %+v", second)
|
||||
}
|
||||
if _, err := client.ListTurnMetadata(ctx, window, "不是游标", 10); !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("非法游标应被拒:%v", err)
|
||||
}
|
||||
if _, err := client.ListTurnMetadata(ctx, window, "", 101); !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("超过分页上限应被拒:%v", err)
|
||||
}
|
||||
// 跨租户隔离:另一个租户的 turn 不能出现在任何结果里(计数、覆盖、列表都一样)。
|
||||
otherTenant, err := NewWindow("another-tenant", "2026-10-14T00:00:00Z", "2026-10-15T00:00:00Z", 90*24*time.Hour, time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
otherCounts, err := client.QueryCounts(ctx, otherTenant, Filter{})
|
||||
if err != nil || otherCounts.Total != 1 {
|
||||
t.Fatalf("另一个租户应只看到自己的 1 条:%+v (%v)", otherCounts, err)
|
||||
}
|
||||
for _, item := range append(first.Items, second.Items...) {
|
||||
if item.ID == "turn-other-tenant" {
|
||||
t.Fatalf("跨租户泄漏:%+v", item)
|
||||
}
|
||||
}
|
||||
if _, err := client.GetTurnForAuthorizedRead(ctx, "default", "turn-other-tenant", func(string) error { return nil }); !errors.Is(err, ErrUnavailable) {
|
||||
// default 租户下没有这个 turn ⇒ 读不到(不是"读到了别人的")
|
||||
t.Fatalf("跨租户 turn 不该在 default 下可读:%v", err)
|
||||
}
|
||||
|
||||
// 授权读取:没有授权回调一律拒绝(不提供"默认放行")。
|
||||
if _, err := client.GetTurnForAuthorizedRead(ctx, "default", "turn-3", nil); !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("缺授权回调必须拒绝:%v", err)
|
||||
}
|
||||
if _, err := client.GetTurnForAuthorizedRead(ctx, "default", "turn-3", func(string) error { return errors.New("no") }); !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Fatalf("授权回调拒绝时必须拒绝:%v", err)
|
||||
}
|
||||
detail, err := client.GetTurnForAuthorizedRead(ctx, "default", "turn-3", func(string) error { return nil })
|
||||
if err != nil {
|
||||
t.Fatalf("授权读取 error = %v", err)
|
||||
}
|
||||
if detail.Question != "第三问(正文)" || detail.Answer != "第三答(正文)" || len(detail.Messages) != 2 {
|
||||
t.Fatalf("授权读取内容不对:%+v", detail)
|
||||
}
|
||||
// 关联回归:即使夹具里 id 与 external_actor_id 不同,也必须靠正确的字段命中 actor_type。
|
||||
for _, message := range detail.Messages {
|
||||
if message.ActorType != "employee" {
|
||||
t.Fatalf("人员关联没命中(关联字段必须是 channel_actors.id):%+v", message)
|
||||
}
|
||||
}
|
||||
if strings.Contains(detail.Messages[0].ActorType, "不应外泄") {
|
||||
t.Fatalf("只应带 actor_type,不应带员工姓名:%+v", detail.Messages[0])
|
||||
}
|
||||
_ = client.Available(ctx)
|
||||
}
|
||||
|
||||
func TestBuildRefusesUnsafeAccountsAndTargets(t *testing.T) {
|
||||
pool := fixturePool(t)
|
||||
roDSN := buildFixture(t, pool)
|
||||
ctx := context.Background()
|
||||
password := randomSecret(t)
|
||||
dropRoleIfExists(t, pool, "kg_writer_fixture")
|
||||
execFixture(t, pool,
|
||||
fmt.Sprintf(`CREATE ROLE kg_writer_fixture LOGIN PASSWORD '%s'`, password),
|
||||
`GRANT USAGE ON SCHEMA public TO kg_writer_fixture`,
|
||||
`GRANT SELECT, INSERT ON TABLE public.turns TO kg_writer_fixture`,
|
||||
`GRANT SELECT ON TABLE public.messages, public.coverage_decisions, public.channel_actors TO kg_writer_fixture`,
|
||||
)
|
||||
writerDSN := dsnWithCredentials(t, "kg_writer_fixture", password)
|
||||
|
||||
// 有写权限的账号:fail closed(不是"能读就算过")。
|
||||
_, err := Build(ctx, Config{
|
||||
DSNFile: writeSecretFile(t, writerDSN), DialMode: "direct",
|
||||
GovernanceDatabaseURL: "postgres://governance@elsewhere:5432/governance",
|
||||
ConnectTimeout: 5 * time.Second, QueryTimeout: 5 * time.Second})
|
||||
if !errors.Is(err, ErrNotReadOnly) {
|
||||
t.Fatalf("可写账号必须被拒为 ErrNotReadOnly:%v", err)
|
||||
}
|
||||
// 指向治理主库的 DSN:拒绝(防"误配后读写治理库")。
|
||||
_, err = Build(ctx, Config{
|
||||
DSNFile: writeSecretFile(t, roDSN), DialMode: "direct", GovernanceDatabaseURL: roDSN,
|
||||
ConnectTimeout: 5 * time.Second, QueryTimeout: 5 * time.Second})
|
||||
if !errors.Is(err, ErrNotReadOnly) {
|
||||
t.Fatalf("指向治理库必须被拒:%v", err)
|
||||
}
|
||||
// secret 文件缺失:ErrUnavailable(按"未启用"处理,不拖垮治理)。
|
||||
_, err = Build(ctx, Config{DSNFile: filepath.Join(t.TempDir(), "missing.env"), DialMode: "direct",
|
||||
ConnectTimeout: time.Second, QueryTimeout: time.Second})
|
||||
if !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("缺 secret 应为 ErrUnavailable:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// SourceSafety records effective privileges, not only grants on queried tables.
|
||||
// TEMP and transport are disclosed independently: this probe never changes them.
|
||||
type SourceSafety struct {
|
||||
Database string `json:"database"`
|
||||
ConnectionLimit int `json:"connection_limit"`
|
||||
TablesChecked int `json:"tables_checked"`
|
||||
TableWrites int `json:"table_writes"`
|
||||
ColumnWrites int `json:"column_writes"`
|
||||
SequenceWrites int `json:"sequence_writes"`
|
||||
SchemaCreates int `json:"schema_creates"`
|
||||
DatabaseTemp bool `json:"database_temp"`
|
||||
SSL bool `json:"ssl"`
|
||||
MissingColumns []string `json:"missing_columns"`
|
||||
}
|
||||
|
||||
const sourceSafetySQL = `
|
||||
WITH relations AS (
|
||||
SELECT c.oid,c.relkind FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
|
||||
WHERE n.nspname NOT LIKE 'pg_%' AND n.nspname<>'information_schema'
|
||||
), required(table_name,column_name,type_name) AS (VALUES
|
||||
('turns','id','text'),('turns','tenant_key','text'),('turns','channel','text'),
|
||||
('turns','question','text'),('turns','answer','text'),('turns','created_at','timestamptz'),
|
||||
('turns','references_json','jsonb'),('turns','knowledge_searched','bool'),
|
||||
('turns','request_message_id','text'),('turns','answer_message_id','text'),
|
||||
('messages','id','text'),('messages','actor_id','text'),('messages','department_snapshot','text'),
|
||||
('messages','region_snapshot','text'),('messages','actor_union_id_snapshot','text'),('channel_actors','id','text'),('channel_actors','external_actor_id','text'),
|
||||
('coverage_decisions','turn_id','text'),('coverage_decisions','verdict','text')
|
||||
)
|
||||
SELECT jsonb_build_object(
|
||||
'database',current_database(),
|
||||
'connection_limit',(SELECT rolconnlimit FROM pg_roles WHERE rolname=current_user),
|
||||
'tables_checked',(SELECT count(*) FROM relations WHERE relkind IN ('r','p','v','m','f')),
|
||||
'table_writes',(SELECT count(*) FROM relations WHERE relkind IN ('r','p','v','m','f') AND (
|
||||
has_table_privilege(oid,'INSERT') OR has_table_privilege(oid,'UPDATE') OR has_table_privilege(oid,'DELETE') OR
|
||||
has_table_privilege(oid,'TRUNCATE') OR has_table_privilege(oid,'REFERENCES') OR has_table_privilege(oid,'TRIGGER') OR
|
||||
CASE WHEN current_setting('server_version_num')::int>=170000 THEN has_table_privilege(oid,'MAINTAIN') ELSE false END)),
|
||||
'column_writes',(SELECT count(*) FROM relations WHERE relkind IN ('r','p','v','m','f') AND (
|
||||
has_any_column_privilege(oid,'INSERT') OR has_any_column_privilege(oid,'UPDATE') OR has_any_column_privilege(oid,'REFERENCES'))),
|
||||
'sequence_writes',(SELECT count(*) FROM relations WHERE relkind='S' AND (has_sequence_privilege(oid,'USAGE') OR has_sequence_privilege(oid,'UPDATE'))),
|
||||
'schema_creates',(SELECT count(*) FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname<>'information_schema' AND has_schema_privilege(oid,'CREATE')),
|
||||
'database_temp',has_database_privilege(current_database(),'TEMP'),
|
||||
'ssl',COALESCE((SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()),false),
|
||||
'missing_columns',(SELECT COALESCE(jsonb_agg(table_name||'.'||column_name),'[]'::jsonb) FROM required r WHERE NOT EXISTS(
|
||||
SELECT 1 FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace
|
||||
WHERE n.nspname='public' AND c.relname=r.table_name AND a.attname=r.column_name AND a.attnum>0 AND NOT a.attisdropped AND a.atttypid=to_regtype(r.type_name))))::text`
|
||||
|
||||
func AuditSourceSafety(ctx context.Context, q rowQuerier) (SourceSafety, error) {
|
||||
var raw string
|
||||
if err := q.QueryRow(ctx, sourceSafetySQL).Scan(&raw); err != nil {
|
||||
return SourceSafety{}, fmt.Errorf("%w: extended safety probe failed", ErrUnavailable)
|
||||
}
|
||||
var report SourceSafety
|
||||
if err := json.Unmarshal([]byte(raw), &report); err != nil || report.Database == "" || report.TablesChecked < 4 || report.ConnectionLimit <= 0 {
|
||||
return SourceSafety{}, fmt.Errorf("%w: incomplete safety report or unlimited source connections", ErrNotReadOnly)
|
||||
}
|
||||
if report.TableWrites > 0 || report.ColumnWrites > 0 || report.SequenceWrites > 0 || report.SchemaCreates > 0 {
|
||||
return report, fmt.Errorf("%w: effective write or maintenance privileges detected", ErrNotReadOnly)
|
||||
}
|
||||
if len(report.MissingColumns) > 0 {
|
||||
return report, fmt.Errorf("%w: source schema contract mismatch", ErrUnavailable)
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSourceRechecksEffectivePrivilegesBeforeEveryQuery(t *testing.T) {
|
||||
pool := fixturePool(t)
|
||||
roDSN := buildFixture(t, pool)
|
||||
client := buildReadOnlyClient(t, roDSN)
|
||||
execFixture(t, pool, `CREATE TABLE acl_other_surface(id text)`, `GRANT INSERT ON acl_other_surface TO kg_ro_fixture`)
|
||||
t.Cleanup(func() { execFixture(t, pool, `DROP TABLE IF EXISTS acl_other_surface`) })
|
||||
window := Window{TenantKey: "default", Start: time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC), End: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)}
|
||||
if _, err := client.QueryCounts(context.Background(), window, Filter{}); !errors.Is(err, ErrNotReadOnly) {
|
||||
t.Fatalf("unexpected privilege escalation outside legacy tables was not blocked: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtendedAuditRejectsWritesOutsideTheFourLegacyTables(t *testing.T) {
|
||||
for _, key := range []string{"table_writes", "column_writes", "sequence_writes", "schema_creates"} {
|
||||
report := map[string]any{"database": "source_test", "connection_limit": 4, "tables_checked": 19, "table_writes": 0, "column_writes": 0, "sequence_writes": 0, "schema_creates": 0, "database_temp": true, "ssl": false, "missing_columns": []string{}}
|
||||
report[key] = 1
|
||||
raw, _ := json.Marshal(report)
|
||||
_, err := AuditSourceSafety(context.Background(), fakeQuerier{row: fakeRow{values: []any{string(raw)}}})
|
||||
if !errors.Is(err, ErrNotReadOnly) {
|
||||
t.Fatalf("%s must block source: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtendedAuditReportsTransportTempAndSchemaContract(t *testing.T) {
|
||||
raw := `{"database":"source_test","connection_limit":4,"tables_checked":19,"table_writes":0,"column_writes":0,"sequence_writes":0,"schema_creates":0,"database_temp":true,"ssl":false,"missing_columns":[]}`
|
||||
report, err := AuditSourceSafety(context.Background(), fakeQuerier{row: fakeRow{values: []any{raw}}})
|
||||
if err != nil || !report.DatabaseTemp || report.SSL || report.ConnectionLimit != 4 {
|
||||
t.Fatalf("audit missing security disclosures: %+v %v", report, err)
|
||||
}
|
||||
raw = `{"database":"source_test","connection_limit":4,"tables_checked":19,"missing_columns":["turns.question"]}`
|
||||
if _, err := AuditSourceSafety(context.Background(), fakeQuerier{row: fakeRow{values: []any{raw}}}); err == nil {
|
||||
t.Fatal("missing schema contract must block source")
|
||||
}
|
||||
for _, raw := range []string{"{}", "not json"} {
|
||||
if _, err := AuditSourceSafety(context.Background(), fakeQuerier{row: fakeRow{values: []any{raw}}}); err == nil {
|
||||
t.Fatal("incomplete audit must not pass")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Settings contains only backend configuration. A source error must not stop
|
||||
// the governance main database or its unrelated workflows from starting.
|
||||
type Settings struct {
|
||||
Enabled bool
|
||||
TenantKey string
|
||||
Connection Config
|
||||
Problem string
|
||||
}
|
||||
|
||||
func LoadSettings(getenv func(string) string, governanceDSN string) Settings {
|
||||
s := Settings{}
|
||||
raw := strings.TrimSpace(getenv("DOBOTAI_OPS_READ_ENABLED"))
|
||||
if raw == "" {
|
||||
return s
|
||||
}
|
||||
enabled, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
s.Problem = "DOBOTAI_OPS_READ_ENABLED is invalid"
|
||||
return s
|
||||
}
|
||||
if !enabled {
|
||||
return s
|
||||
}
|
||||
s.Enabled = true
|
||||
s.TenantKey = strings.TrimSpace(getenv("DOBOTAI_OPS_TENANT_KEY"))
|
||||
c := Config{DSNFile: strings.TrimSpace(getenv("DOBOTAI_OPS_READ_DSN_FILE")), GovernanceDatabaseURL: governanceDSN,
|
||||
DialMode: strings.TrimSpace(getenv("DOBOTAI_OPS_DIAL_MODE")), SSHTarget: strings.TrimSpace(getenv("DOBOTAI_OPS_SSH_TARGET")),
|
||||
ConnectTimeout: 5 * time.Second, QueryTimeout: 4 * time.Second, MaxConns: 2, MinConns: 0}
|
||||
if c.DialMode == "" {
|
||||
c.DialMode = "direct"
|
||||
}
|
||||
for _, item := range []struct {
|
||||
key string
|
||||
target *time.Duration
|
||||
}{
|
||||
{"DOBOTAI_OPS_CONNECT_TIMEOUT", &c.ConnectTimeout}, {"DOBOTAI_OPS_QUERY_TIMEOUT", &c.QueryTimeout},
|
||||
} {
|
||||
if raw := getenv(item.key); raw != "" {
|
||||
value, err := time.ParseDuration(raw)
|
||||
if err != nil {
|
||||
s.Problem = item.key + " is invalid"
|
||||
return s
|
||||
}
|
||||
*item.target = value
|
||||
}
|
||||
}
|
||||
for _, item := range []struct {
|
||||
key string
|
||||
target *int32
|
||||
}{
|
||||
{"DOBOTAI_OPS_MAX_CONNS", &c.MaxConns}, {"DOBOTAI_OPS_MIN_CONNS", &c.MinConns},
|
||||
} {
|
||||
if raw := getenv(item.key); raw != "" {
|
||||
value, err := strconv.ParseInt(raw, 10, 32)
|
||||
if err != nil {
|
||||
s.Problem = item.key + " is invalid"
|
||||
return s
|
||||
}
|
||||
*item.target = int32(value)
|
||||
}
|
||||
}
|
||||
if s.TenantKey == "" || len(s.TenantKey) > 128 {
|
||||
s.Problem = "DOBOTAI_OPS_TENANT_KEY is required and must be at most 128 bytes"
|
||||
return s
|
||||
}
|
||||
if !filepath.IsAbs(c.DSNFile) || filepath.Clean(c.DSNFile) != c.DSNFile {
|
||||
s.Problem = "DOBOTAI_OPS_READ_DSN_FILE must be an absolute clean path"
|
||||
return s
|
||||
}
|
||||
if err := c.Validate(); err != nil {
|
||||
s.Problem = "external read configuration is invalid"
|
||||
return s
|
||||
}
|
||||
s.Connection = c.withDefaults()
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLoadSettingsConsumesIndependentConnectionLimits(t *testing.T) {
|
||||
env := map[string]string{
|
||||
"DOBOTAI_OPS_READ_ENABLED": "true", "DOBOTAI_OPS_READ_DSN_FILE": "/run/secrets/source",
|
||||
"DOBOTAI_OPS_TENANT_KEY": "approved-tenant", "DOBOTAI_OPS_DIAL_MODE": "ssh", "DOBOTAI_OPS_SSH_TARGET": "approved-hop",
|
||||
"DOBOTAI_OPS_CONNECT_TIMEOUT": "7s", "DOBOTAI_OPS_QUERY_TIMEOUT": "3s",
|
||||
"DOBOTAI_OPS_MAX_CONNS": "3", "DOBOTAI_OPS_MIN_CONNS": "1",
|
||||
}
|
||||
s := LoadSettings(func(k string) string { return env[k] }, "postgres://governance@elsewhere/governance")
|
||||
if !s.Enabled || s.Problem != "" || s.TenantKey != "approved-tenant" {
|
||||
t.Fatalf("settings were not loaded: %+v", s)
|
||||
}
|
||||
if s.Connection.ConnectTimeout != 7*time.Second || s.Connection.QueryTimeout != 3*time.Second || s.Connection.MaxConns != 3 || s.Connection.MinConns != 1 {
|
||||
t.Fatalf("environment overrides ignored: %+v", s.Connection)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSettingsIsDisabledByDefaultAndContainsInvalidSourceConfiguration(t *testing.T) {
|
||||
if s := LoadSettings(func(string) string { return "" }, ""); s.Enabled || s.Problem != "" {
|
||||
t.Fatalf("not disabled by default: %+v", s)
|
||||
}
|
||||
for _, key := range []string{"DOBOTAI_OPS_READ_ENABLED", "DOBOTAI_OPS_CONNECT_TIMEOUT", "DOBOTAI_OPS_QUERY_TIMEOUT", "DOBOTAI_OPS_MAX_CONNS", "DOBOTAI_OPS_MIN_CONNS"} {
|
||||
env := map[string]string{"DOBOTAI_OPS_READ_ENABLED": "true", "DOBOTAI_OPS_READ_DSN_FILE": "/run/secrets/source", "DOBOTAI_OPS_TENANT_KEY": "approved-tenant"}
|
||||
env[key] = "invalid-sensitive-value"
|
||||
s := LoadSettings(func(k string) string { return env[k] }, "postgres://governance@elsewhere/governance")
|
||||
if s.Problem == "" || strings.Contains(s.Problem, "invalid-sensitive-value") {
|
||||
t.Fatalf("%s must fail closed without echoing its value: %+v", key, s)
|
||||
}
|
||||
}
|
||||
s := LoadSettings(func(k string) string {
|
||||
if k == "DOBOTAI_OPS_READ_ENABLED" {
|
||||
return "true"
|
||||
}
|
||||
return ""
|
||||
}, "")
|
||||
if s.Problem == "" {
|
||||
t.Fatal("missing secret and tenant must block source access")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretReaderDoesNotSelectAnUnrelatedDatabaseURL(t *testing.T) {
|
||||
unrelated := testDSN("writer", "not"+"a-secret", "other", "other_db")
|
||||
wanted := testDSN("reader", "fixture"+"only", "source", "source_db")
|
||||
got, ok := parseDSNLine("DATABASE_URL=" + unrelated + "\nDOBOTAI_OPS_READ_DSN=" + wanted)
|
||||
if !ok || got != wanted {
|
||||
t.Fatal("must select only the dedicated read DSN key")
|
||||
}
|
||||
if _, ok := parseDSNLine("DATABASE_URL=" + unrelated); ok {
|
||||
t.Fatal("must not borrow another application's credential")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedGovernanceDSNDoesNotDisableIdentityGuard(t *testing.T) {
|
||||
err := GuardGovernanceDatabase("postgres://reader@source/dobotai_prod", "invalid-main-dsn")
|
||||
if !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("malformed main identity must fail closed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SSHDialer 复用既有的 SSH direct-tcpip 能力:`ssh -W <host>:<port> <target>` ——
|
||||
// 由 SSH 侧完成到目标库的 TCP 连接,本机**不新增监听、不改 SSH/NPS/systemd/Docker 网络**。
|
||||
//
|
||||
// 实现用 socketpair:Go 侧拿到的是 fd 支撑的真实 net.Conn(支持 SetDeadline,
|
||||
// pgx 的连接/查询超时才能在拨号阶段生效),ssh 子进程的 stdin/stdout 指向同一对端的另一端。
|
||||
//
|
||||
// context 语义(刻意区分两段):
|
||||
// - **拨号阶段**尊重 ctx:ctx 已取消就不再创建连接、不再启动子进程;
|
||||
// - **连接建立之后不绑定这个 ctx** —— pgx 在连接成功后就会取消拨号 ctx,
|
||||
// 若把连接生命周期挂上去,健康连接会被立刻掐断。连接生命周期绑定在
|
||||
// "连接关闭 ⇄ 子进程回收" 这对关系上(见 tunnelConn.Close)。
|
||||
//
|
||||
// 依赖:运行环境里必须有 ssh 客户端与已批准的密钥/known_hosts。容器内 localhost 不等于
|
||||
// 宿主机 —— 容器没有 ssh 能力时返回 ErrUnavailable;**不擅自复制私钥、不放宽 known_hosts、
|
||||
// 不改 network_mode**。
|
||||
// dialAddress 是**配置里 DSN 的主机:端口**。为什么必须用它、而不是 pgx 传进来的 addr:
|
||||
// pgx 会先在**本机**解析域名,本机若开了 Clash/mihomo 之类的 Fake-IP(198.18.0.0/15)或
|
||||
// 其他 DNS 劫持,解析结果是假地址;把假地址交给 ssh 去连必然挂住(实测:20s 超时)。
|
||||
// 固定审批的隧道应当让**远端**解析并连接配置里的主机名 —— 这也是"不接受任意主机"的同一原则。
|
||||
func SSHDialer(target, dialAddress string) (func(ctx context.Context, network, addr string) (net.Conn, error), error) {
|
||||
if target == "" {
|
||||
return nil, fmt.Errorf("%w: ssh target is required", ErrUnavailable)
|
||||
}
|
||||
if strings.TrimSpace(dialAddress) == "" {
|
||||
return nil, fmt.Errorf("%w: dial address is required", ErrUnavailable)
|
||||
}
|
||||
if _, err := exec.LookPath("ssh"); err != nil {
|
||||
return nil, fmt.Errorf("%w: ssh client is not available in this environment", ErrUnavailable)
|
||||
}
|
||||
return func(ctx context.Context, _ string, _ string) (net.Conn, error) {
|
||||
addr := dialAddress
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("%w: ssh dial cancelled before start", ErrUnavailable)
|
||||
}
|
||||
fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: cannot create a socketpair for the ssh tunnel", ErrUnavailable)
|
||||
}
|
||||
localEnd := os.NewFile(uintptr(fds[0]), "kg-ssh-tunnel-local")
|
||||
remoteEnd := os.NewFile(uintptr(fds[1]), "kg-ssh-tunnel-child")
|
||||
conn, err := net.FileConn(localEnd)
|
||||
_ = localEnd.Close()
|
||||
if err != nil {
|
||||
_ = remoteEnd.Close()
|
||||
return nil, fmt.Errorf("%w: cannot wrap the ssh tunnel in a connection", ErrUnavailable)
|
||||
}
|
||||
command := exec.Command("ssh",
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "ExitOnForwardFailure=yes",
|
||||
"-o", "ServerAliveInterval=15",
|
||||
"-W", addr, target)
|
||||
command.Stdin = remoteEnd
|
||||
command.Stdout = remoteEnd
|
||||
// ssh 自身的 stderr 一律丢弃:里面可能带主机名/路径;失败统一上抛 ErrUnavailable。
|
||||
command.Stderr = io.Discard
|
||||
if err := command.Start(); err != nil {
|
||||
_ = remoteEnd.Close()
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("%w: cannot start the ssh tunnel", ErrUnavailable)
|
||||
}
|
||||
_ = remoteEnd.Close()
|
||||
// reaped 必须先初始化:reap() 会在子进程退出时 close 它(nil channel 会 panic)。
|
||||
tunnel := &tunnelConn{Conn: conn, command: command, reaped: make(chan struct{})}
|
||||
go tunnel.reap()
|
||||
return tunnel, nil
|
||||
}, nil
|
||||
}
|
||||
|
||||
// tunnelConn 把"连接关闭 ⇄ 子进程回收"显式绑定起来:
|
||||
// - 连接被关(pgx 归还/释放连接、或对端断开)⇒ 子进程收到终止信号并回收,不留孤儿;
|
||||
// - 子进程自己退出(隧道断/认证失败)⇒ Go 侧连接立刻关掉,让 pgx 马上感知断开;
|
||||
// - Close 幂等,且不阻塞在等待子进程上(最多等一个短宽限期)。
|
||||
type tunnelConn struct {
|
||||
net.Conn
|
||||
command *exec.Cmd
|
||||
closeOnce sync.Once
|
||||
reaped chan struct{}
|
||||
}
|
||||
|
||||
func (t *tunnelConn) reap() {
|
||||
if t.command != nil {
|
||||
_ = t.command.Wait()
|
||||
}
|
||||
if t.reaped != nil {
|
||||
close(t.reaped)
|
||||
}
|
||||
// 子进程退出 ⇒ 连接必然无用,主动关掉让调用方立刻看到 EOF。
|
||||
_ = t.Conn.Close()
|
||||
}
|
||||
|
||||
func (t *tunnelConn) Close() error {
|
||||
var err error
|
||||
t.closeOnce.Do(func() {
|
||||
err = t.Conn.Close()
|
||||
// 连接关闭后 ssh 通常自行退出;这里补一刀保证它不会挂着不退。
|
||||
if t.command.Process != nil {
|
||||
_ = t.command.Process.Signal(syscall.SIGTERM)
|
||||
}
|
||||
select {
|
||||
case <-t.Exited():
|
||||
case <-time.After(2 * time.Second):
|
||||
if t.command.Process != nil {
|
||||
_ = t.command.Process.Kill()
|
||||
}
|
||||
}
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// Exited 让测试/运维能确认子进程已经回收(不暴露任何连接信息)。
|
||||
func (t *tunnelConn) Exited() <-chan struct{} {
|
||||
if t.reaped == nil {
|
||||
closed := make(chan struct{})
|
||||
close(closed)
|
||||
return closed
|
||||
}
|
||||
return t.reaped
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 只有在显式给出"已批准的 SSH 目标 + 一个可达的只读端点"时才跑:CI 默认跳过。
|
||||
// 目的:证明 `ssh -W` + socketpair 的拨号在 Go 侧是一个**支持 deadline 的真实 net.Conn**
|
||||
// (pgx 的连接/查询超时能在拨号阶段生效),且经这条通道发出的请求真的能到达目标。
|
||||
//
|
||||
// KG_SSH_DIAL_TARGET=weknora-prod KG_SSH_DIAL_ADDR=127.0.0.1:8090 // go test ./internal/dobotaiops/ -run TestSSHDialerTransportsRealTraffic -v
|
||||
func TestSSHDialerTransportsRealTraffic(t *testing.T) {
|
||||
target := strings.TrimSpace(os.Getenv("KG_SSH_DIAL_TARGET"))
|
||||
address := strings.TrimSpace(os.Getenv("KG_SSH_DIAL_ADDR"))
|
||||
if target == "" || address == "" {
|
||||
t.Skip("KG_SSH_DIAL_TARGET / KG_SSH_DIAL_ADDR 未设置:跳过(CI 默认不跑)")
|
||||
}
|
||||
dialer, err := SSHDialer(target, address)
|
||||
if err != nil {
|
||||
t.Fatalf("SSHDialer() error = %v", err)
|
||||
}
|
||||
conn, err := dialer(context.Background(), "tcp", address)
|
||||
if err != nil {
|
||||
t.Fatalf("dial error = %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
// 真实 deadline 必须可用(否则 pgx 的连接超时形同虚设)。
|
||||
if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil {
|
||||
t.Fatalf("socketpair 连接必须支持 deadline:%v", err)
|
||||
}
|
||||
if _, err := fmt.Fprintf(conn, "GET /version HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", address); err != nil {
|
||||
t.Fatalf("write error = %v", err)
|
||||
}
|
||||
response, err := http.ReadResponse(bufio.NewReader(conn), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("read error = %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d", response.StatusCode)
|
||||
}
|
||||
buf := make([]byte, 256)
|
||||
n, _ := response.Body.Read(buf)
|
||||
if !strings.Contains(string(buf[:n]), "commit_sha") {
|
||||
t.Fatalf("经 SSH 通道取到的响应不像版本接口:%q", string(buf[:n]))
|
||||
}
|
||||
var _ net.Conn = conn
|
||||
}
|
||||
|
||||
// 取消的 context 不得创建连接、不得启动子进程(独立探测曾证明旧实现照样建连)。
|
||||
func TestSSHDialerRespectsCancelledContext(t *testing.T) {
|
||||
dialer, err := SSHDialer("definitely-not-a-real-ssh-alias", "127.0.0.1:5432")
|
||||
if err != nil {
|
||||
t.Fatalf("SSHDialer() error = %v", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
conn, err := dialer(ctx, "tcp", "127.0.0.1:1")
|
||||
if err == nil || conn != nil {
|
||||
t.Fatalf("ctx 已取消时不得建连:conn=%v err=%v", conn, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "cancelled") {
|
||||
t.Fatalf("应明确说明是取消:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭连接必须回收子进程(不阻塞、幂等);顺带证明 GetDeadline/SetDeadline 是真实能力。
|
||||
func TestSSHTunnelCloseReapsChild(t *testing.T) {
|
||||
target := strings.TrimSpace(os.Getenv("KG_SSH_DIAL_TARGET"))
|
||||
if target == "" {
|
||||
t.Skip("KG_SSH_DIAL_TARGET 未设置:跳过(需要有已批准目标才能起 ssh 子进程)")
|
||||
}
|
||||
dialer, err := SSHDialer(target, "127.0.0.1:1") // 目标端口不通也没关系:本轮只看生命周期
|
||||
if err != nil {
|
||||
t.Fatalf("SSHDialer() error = %v", err)
|
||||
}
|
||||
conn, err := dialer(context.Background(), "tcp", "127.0.0.1:1")
|
||||
if err != nil {
|
||||
t.Skipf("无法在本机建立隧道(%v)—— 该用例只在有 ssh 能力的环境有意义", err)
|
||||
}
|
||||
tunnel, ok := conn.(*tunnelConn)
|
||||
if !ok {
|
||||
t.Fatalf("返回值应绑定子进程生命周期:%T", conn)
|
||||
}
|
||||
if err := tunnel.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
if err := tunnel.Close(); err != nil {
|
||||
t.Fatalf("Close() 必须幂等:%v", err)
|
||||
}
|
||||
select {
|
||||
case <-tunnel.Exited():
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("关闭连接后 ssh 子进程没有被回收")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Window 是一次只读统计/列举的时间范围,语义固定为**半开区间**:
|
||||
// created_at >= Start AND created_at < End(工单要求)。
|
||||
type Window struct {
|
||||
TenantKey string
|
||||
Start time.Time
|
||||
End time.Time
|
||||
}
|
||||
|
||||
// NewWindow 解析并校验调用方给的租户与时间范围:
|
||||
// - 租户非空、长度受限(不做任何 SQL 拼接,只作为绑定参数);
|
||||
// - 时间是 RFC3339(允许带时区),必须有 start < end;
|
||||
// - 窗口跨度不超过上限(默认 90 天)、不允许跑到未来太远。
|
||||
func NewWindow(tenantKey, startRaw, endRaw string, limit time.Duration, now time.Time) (Window, error) {
|
||||
tenantKey = strings.TrimSpace(tenantKey)
|
||||
if tenantKey == "" || len(tenantKey) > 128 {
|
||||
return Window{}, fmt.Errorf("%w: tenant key is required", ErrInvalidQuery)
|
||||
}
|
||||
start, err := parseInstant(startRaw)
|
||||
if err != nil {
|
||||
return Window{}, err
|
||||
}
|
||||
end, err := parseInstant(endRaw)
|
||||
if err != nil {
|
||||
return Window{}, err
|
||||
}
|
||||
if !start.Before(end) {
|
||||
return Window{}, fmt.Errorf("%w: start must be before end", ErrInvalidQuery)
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 90 * 24 * time.Hour
|
||||
}
|
||||
if end.Sub(start) > limit {
|
||||
return Window{}, fmt.Errorf("%w: window exceeds the %s limit", ErrInvalidQuery, limit)
|
||||
}
|
||||
if end.After(now.Add(5 * time.Minute)) {
|
||||
return Window{}, fmt.Errorf("%w: end is in the future", ErrInvalidQuery)
|
||||
}
|
||||
return Window{TenantKey: tenantKey, Start: start.UTC(), End: end.UTC()}, nil
|
||||
}
|
||||
|
||||
func parseInstant(raw string) (time.Time, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return time.Time{}, fmt.Errorf("%w: time is required", ErrInvalidQuery)
|
||||
}
|
||||
parsed, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("%w: time must be RFC3339 (with offset)", ErrInvalidQuery)
|
||||
}
|
||||
return parsed.UTC(), nil
|
||||
}
|
||||
|
||||
// Cursor 是 (created_at, id) 复合游标:与工单要求一致 —— 稳定、确定性、翻页不漏不重。
|
||||
type Cursor struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
|
||||
// EncodeCursor / DecodeCursor 只做无损编解码,不做业务判断;非法游标一律报 ErrInvalidQuery。
|
||||
func EncodeCursor(cursor Cursor) string {
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(cursor.CreatedAt.UTC().Format(time.RFC3339Nano) + "|" + cursor.ID))
|
||||
}
|
||||
|
||||
func DecodeCursor(raw string) (Cursor, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return Cursor{}, fmt.Errorf("%w: cursor is not valid", ErrInvalidQuery)
|
||||
}
|
||||
parts := strings.SplitN(string(decoded), "|", 2)
|
||||
if len(parts) != 2 || parts[1] == "" {
|
||||
return Cursor{}, fmt.Errorf("%w: cursor is not valid", ErrInvalidQuery)
|
||||
}
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
return Cursor{}, fmt.Errorf("%w: cursor is not valid", ErrInvalidQuery)
|
||||
}
|
||||
return Cursor{CreatedAt: createdAt.UTC(), ID: parts[1]}, nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Development headings cannot replace the formal release baseline.
|
||||
func ExtractDevelopmentNotes(changelog, version string) string {
|
||||
return developmentNotes(changelog, version, "")
|
||||
}
|
||||
func ExtractDevelopmentNotesForCommit(changelog, version, sha string) string {
|
||||
return developmentNotes(changelog, version, sha)
|
||||
}
|
||||
func developmentNotes(changelog, version, sha string) string {
|
||||
if !SemverValid(version) {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(changelog, "\n")
|
||||
prefix := "## 开发快照 snapshot/v" + version + " - "
|
||||
for i, line := range lines {
|
||||
if strings.HasPrefix(line, prefix) {
|
||||
end := len(lines)
|
||||
for j := i + 1; j < len(lines); j++ {
|
||||
if strings.HasPrefix(lines[j], "## ") {
|
||||
end = j
|
||||
break
|
||||
}
|
||||
}
|
||||
body := strings.TrimSpace(strings.Join(lines[i+1:end], "\n"))
|
||||
if sha == "" {
|
||||
return body
|
||||
}
|
||||
for _, field := range lines[i+1 : end] {
|
||||
if strings.TrimSpace(field) == "目标提交:"+sha {
|
||||
return body
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -15,7 +15,7 @@ type CatalogSource struct {
|
||||
LastRefreshDurationMS int64 `json:"last_refresh_duration_ms"`
|
||||
// ScanProgress / ScanMessage 只在 SnapshotStatus == "scanning" 时有值:新来源在首次扫描
|
||||
// 完成前也出现在「来源与目录」里,带着百分比与进度文案,不必等到快照落地才看得见。
|
||||
ScanProgress int `json:"scan_progress,omitempty"`
|
||||
ScanProgress int `json:"scan_progress"`
|
||||
ScanMessage string `json:"scan_message,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQueuedCatalogSourceIncludesNumericZeroProgress(t *testing.T) {
|
||||
source := CatalogSource{SnapshotStatus: "scanning", ScanProgress: 0}
|
||||
body, err := json.Marshal(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var decoded map[string]any
|
||||
if err = json.Unmarshal(body, &decoded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value, ok := decoded["scan_progress"]; !ok || value != float64(0) {
|
||||
t.Fatalf("queued source must satisfy the frontend numeric progress contract: %s", body)
|
||||
}
|
||||
}
|
||||
@@ -99,9 +99,12 @@ func isAuthEndpoint(method, path string) bool {
|
||||
|
||||
// classify maps a request to the minimum role required.
|
||||
func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/source-connections/audit" {
|
||||
return roleAdmin
|
||||
}
|
||||
// The member roster exposes account identities and roles: admin-only for
|
||||
// every method, checked before the read shortcut below.
|
||||
if strings.HasPrefix(path, "/api/v1/users") {
|
||||
if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") {
|
||||
return roleAdmin
|
||||
}
|
||||
if method == http.MethodGet {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
// 钉盘的根是 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)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), nil, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")); ok {
|
||||
t.Fatal("without a lister nothing can resolve")
|
||||
}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, "not-a-space-url"); ok {
|
||||
t.Fatal("a URL without a space id must not resolve")
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,11 @@ 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 {
|
||||
@@ -136,7 +141,7 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
|
||||
return
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(),
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(), Actor: actorFor(r),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
@@ -239,3 +244,76 @@ 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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dwsMetadataReader interface {
|
||||
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
|
||||
}
|
||||
|
||||
func readDWSCredentials(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
reader, ok := config.DingtalkSources.(dwsMetadataReader)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "DWS credential status not configured"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
result, err := reader.ReadDWSMetadata(ctx)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "无法读取 DWS 凭证状态"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": result})
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// 「整库版本」只读视图:把已经封存的候选产物(artifact-acceptance-v1)如实列出来。
|
||||
//
|
||||
// 边界(刻意不做的事):
|
||||
// - 不触发封存、不停/起写入者:封存需要维护窗口与来源凭据,只能由运维命令
|
||||
// scripts/library-capture.sh 在目标主机执行;
|
||||
// - 不把完整性当发布:候选证明"这一份内容被完整、可核验地封存了"(A04 口径),
|
||||
// 而授权与生产同步是另外的、需要独立授权的步骤(A06 效果测试已由用户取消);
|
||||
// - 归档根没接线时返回可用性=false 与原因,不返回空表冒充"没有快照"。
|
||||
type librarySnapshotPart struct {
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Count int64 `json:"count"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
type librarySnapshotView struct {
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Scope string `json:"scope"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ValidationPolicy string `json:"validation_policy"`
|
||||
Format string `json:"format"`
|
||||
Compatibility librarysnapshot.Compatibility `json:"compatibility"`
|
||||
Parts []librarySnapshotPart `json:"parts"`
|
||||
LogicalBytes int64 `json:"logical_bytes"`
|
||||
UniqueBytes int64 `json:"unique_bytes"`
|
||||
SharedBytes int64 `json:"shared_bytes"`
|
||||
Totals map[string]int64 `json:"totals"`
|
||||
}
|
||||
|
||||
type librarySnapshotList struct {
|
||||
Available bool `json:"available"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
ArchiveRoot string `json:"archive_root,omitempty"`
|
||||
Snapshots []librarySnapshotView `json:"snapshots"`
|
||||
// 归档级口径:ContentBytes 是**跨版本去重后、被版本引用的内容字节**。
|
||||
// 它不是磁盘占用(清单、未引用 blob、块对齐与元数据都不在里面),
|
||||
// 更不是可回收空间——清理需要保留策略、依赖保护与在线作业引用。
|
||||
Versions int `json:"versions"`
|
||||
ContentBytes int64 `json:"content_bytes"`
|
||||
BlobFileBytes int64 `json:"blob_file_bytes"`
|
||||
BlobAllocatedBytes int64 `json:"blob_allocated_bytes"`
|
||||
UnreferencedBlobs int `json:"unreferenced_blobs"`
|
||||
UnreferencedBytes int64 `json:"unreferenced_bytes"`
|
||||
ManifestFileBytes int64 `json:"manifest_file_bytes"`
|
||||
ManifestAllocatedBytes int64 `json:"manifest_allocated_bytes"`
|
||||
// 页面必须能说清"封存由谁执行",不能让人以为页面上有个没实现的按钮。
|
||||
CaptureNote string `json:"capture_note"`
|
||||
}
|
||||
|
||||
const libraryCaptureNote = "封存由运维命令 scripts/library-capture.sh capture -scope internal|external 在目标主机执行(停写入者→导出→恢复)。页面只读展示已封存的完整版本:它通过了数据完整性检查(身份、双向正文覆盖、生成问题、资源与摘要),这已满足封版所需的完整性口径;授权与生产同步仍是独立步骤。"
|
||||
|
||||
func librarySnapshotsList(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
view, err := readLibrarySnapshots(config.LibraryArchiveRoot)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, librarySnapshotList{Available: false,
|
||||
Reason: "归档不可读:" + err.Error(), Snapshots: []librarySnapshotView{}, CaptureNote: libraryCaptureNote})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
func librarySnapshotDetail(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshot id required"})
|
||||
return
|
||||
}
|
||||
if config.LibraryArchiveRoot == "" {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": false,
|
||||
"reason": "未接线:LIBRARY_ARCHIVE_ROOT 未配置,本平台没有整库归档可读"})
|
||||
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(id)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "快照不存在或校验失败"})
|
||||
return
|
||||
}
|
||||
usage, err := archive.Usage()
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "归档用量不可读"})
|
||||
return
|
||||
}
|
||||
view, ok := librarySnapshotViewOf(id, manifest, usage)
|
||||
if !ok {
|
||||
view = librarySnapshotViewOfNoUsage(id, manifest)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": true, "snapshot": view, "capture_note": libraryCaptureNote})
|
||||
}
|
||||
|
||||
func readLibrarySnapshots(root string) (librarySnapshotList, error) {
|
||||
view := librarySnapshotList{Snapshots: []librarySnapshotView{}, CaptureNote: libraryCaptureNote}
|
||||
if root == "" {
|
||||
view.Reason = "未接线:LIBRARY_ARCHIVE_ROOT 未配置,本平台没有整库归档可读"
|
||||
return view, nil
|
||||
}
|
||||
view.ArchiveRoot = root
|
||||
archive, err := librarysnapshot.Open(root, 256*1024*1024)
|
||||
if err != nil {
|
||||
return view, errors.New("归档根不可用")
|
||||
}
|
||||
defer archive.Close()
|
||||
usage, err := archive.Usage()
|
||||
if err != nil {
|
||||
return view, errors.New("归档用量不可读")
|
||||
}
|
||||
// Per-version UniqueBytes deduplicates only inside one version, so summing it
|
||||
// over versions over-reports shared blobs. The archive-wide accounting below
|
||||
// deduplicates across versions and keeps filesystem facts separate.
|
||||
total, err := archive.ContentUsage()
|
||||
if err != nil {
|
||||
return view, errors.New("归档用量不可读")
|
||||
}
|
||||
view.Versions = total.Versions
|
||||
view.ContentBytes = total.ContentBytes
|
||||
view.BlobFileBytes = total.BlobFileBytes
|
||||
view.BlobAllocatedBytes = total.BlobAllocatedBytes
|
||||
view.UnreferencedBlobs = total.UnreferencedBlobs
|
||||
view.UnreferencedBytes = total.UnreferencedBytes
|
||||
view.ManifestFileBytes = total.ManifestFileBytes
|
||||
view.ManifestAllocatedBytes = total.ManifestAllocatedBytes
|
||||
byID := map[string]librarysnapshot.Usage{}
|
||||
for _, item := range usage {
|
||||
byID[item.VersionID] = item
|
||||
}
|
||||
for id, item := range byID {
|
||||
manifest, loadErr := archive.Load(id)
|
||||
if loadErr != nil {
|
||||
return view, errors.New("归档快照校验失败")
|
||||
}
|
||||
snapshot, ok := librarySnapshotViewOf(id, manifest, []librarysnapshot.Usage{item})
|
||||
if !ok {
|
||||
snapshot = librarySnapshotViewOfNoUsage(id, manifest)
|
||||
}
|
||||
view.Snapshots = append(view.Snapshots, snapshot)
|
||||
}
|
||||
sort.Slice(view.Snapshots, func(i, j int) bool {
|
||||
if view.Snapshots[i].CreatedAt.Equal(view.Snapshots[j].CreatedAt) {
|
||||
return view.Snapshots[i].SnapshotID > view.Snapshots[j].SnapshotID
|
||||
}
|
||||
return view.Snapshots[i].CreatedAt.After(view.Snapshots[j].CreatedAt)
|
||||
})
|
||||
view.Available = true
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func librarySnapshotViewOf(id string, manifest librarysnapshot.Manifest, usage []librarysnapshot.Usage) (librarySnapshotView, bool) {
|
||||
snapshot := librarySnapshotViewOfNoUsage(id, manifest)
|
||||
for _, item := range usage {
|
||||
if item.VersionID == id {
|
||||
snapshot.LogicalBytes = item.LogicalBytes
|
||||
snapshot.UniqueBytes = item.UniqueBytes
|
||||
snapshot.SharedBytes = item.SharedBytes
|
||||
return snapshot, true
|
||||
}
|
||||
}
|
||||
return snapshot, false
|
||||
}
|
||||
|
||||
func librarySnapshotViewOfNoUsage(id string, manifest librarysnapshot.Manifest) librarySnapshotView {
|
||||
snapshot := librarySnapshotView{SnapshotID: id, Scope: manifest.Scope, KnowledgeBaseID: manifest.KnowledgeBaseID,
|
||||
TenantID: manifest.TenantID, CreatedAt: manifest.CreatedAt, ValidationPolicy: manifest.ValidationPolicy,
|
||||
Format: manifest.Format, Compatibility: manifest.Compatibility, Parts: make([]librarySnapshotPart, 0, len(manifest.Parts)),
|
||||
Totals: map[string]int64{}}
|
||||
for _, part := range manifest.Parts {
|
||||
snapshot.Parts = append(snapshot.Parts, librarySnapshotPart{Kind: part.Kind, Name: part.Name,
|
||||
SHA256: part.SHA256, Count: part.Count, Bytes: part.Bytes})
|
||||
snapshot.LogicalBytes += part.Bytes
|
||||
// 汇总按"数量字段"给出人看得懂的四个数字:文档/分块/索引/资源/Wiki 页。
|
||||
switch part.Name {
|
||||
case "knowledges":
|
||||
snapshot.Totals["documents"] = part.Count
|
||||
case "chunks":
|
||||
if part.Kind == "database" {
|
||||
snapshot.Totals["chunks"] = part.Count
|
||||
} else {
|
||||
snapshot.Totals["index_documents"] = part.Count
|
||||
}
|
||||
case "resources":
|
||||
snapshot.Totals["resources"] = part.Count
|
||||
case "wiki_pages":
|
||||
snapshot.Totals["wiki_pages"] = part.Count
|
||||
case "wiki_folders":
|
||||
snapshot.Totals["wiki_folders"] = part.Count
|
||||
}
|
||||
}
|
||||
sort.Slice(snapshot.Parts, func(i, j int) bool {
|
||||
if snapshot.Parts[i].Kind == snapshot.Parts[j].Kind {
|
||||
return snapshot.Parts[i].Name < snapshot.Parts[j].Name
|
||||
}
|
||||
return snapshot.Parts[i].Kind < snapshot.Parts[j].Kind
|
||||
})
|
||||
return snapshot
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// The 整库版本 page reads a sealed archive through this exact function. A
|
||||
// synthetic archive keeps the assertion about what the page shows independent of
|
||||
// whether a real capture has run on this host.
|
||||
func TestReadLibrarySnapshotsReportsSealedTotals(t *testing.T) {
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kglib-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(root)
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := librarysnapshot.Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The archive re-derives row counts from the stored bytes, so the bodies must
|
||||
// carry exactly the declared number of rows.
|
||||
rows := func(count int) string {
|
||||
if count == 0 {
|
||||
return "[]"
|
||||
}
|
||||
items := make([]string, count)
|
||||
for i := range items {
|
||||
items[i] = fmt.Sprintf(`{"id":"00000000-0000-4000-8000-%012d"}`, i)
|
||||
}
|
||||
return "[" + strings.Join(items, ",") + "]"
|
||||
}
|
||||
parts := []struct {
|
||||
kind, name string
|
||||
count int64
|
||||
body string
|
||||
}{
|
||||
{"database", "knowledges", 4, rows(4)},
|
||||
{"database", "chunks", 38, rows(38)},
|
||||
{"database", "resources", 21, rows(21)},
|
||||
{"database", "resource_bindings", 4, rows(4)},
|
||||
{"database", "knowledge_tags", 0, rows(0)},
|
||||
{"database", "knowledge_tag_relations", 0, rows(0)},
|
||||
{"index", "chunks", 122, rows(122)},
|
||||
{"wiki", "wiki_pages", 31, rows(31)},
|
||||
{"wiki", "wiki_folders", 21, rows(21)},
|
||||
{"wiki", "wiki_page_issues", 0, rows(0)},
|
||||
{"wiki", "wiki_log_entries", 11, rows(11)},
|
||||
}
|
||||
// Every resource row must have its own archived object: the archive refuses a
|
||||
// snapshot whose resource dependencies are incomplete.
|
||||
for i := 0; i < 21; i++ {
|
||||
parts = append(parts, struct {
|
||||
kind, name string
|
||||
count int64
|
||||
body string
|
||||
}{"resource", fmt.Sprintf("00000000-0000-4000-8000-%012d", i), 1, fmt.Sprintf("object-%d", i)})
|
||||
}
|
||||
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy,
|
||||
Format: librarysnapshot.Format, Scope: "internal", TenantID: 10000,
|
||||
KnowledgeBaseID: "0c84a098-d3ed-4b82-a165-e6de9691d6a8", CreatedAt: time.Now().UTC(),
|
||||
Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
|
||||
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024,
|
||||
IndexMappingSHA256: "137cde2965f3b56521f5fb722b4e0617f46d0e509e571b217fe01e090d5e4d01"}}
|
||||
for _, part := range parts {
|
||||
stored, err := archive.Put(bytes.NewReader([]byte(part.body)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored.Kind, stored.Name, stored.Count = part.kind, part.name, part.count
|
||||
manifest.Parts = append(manifest.Parts, stored)
|
||||
}
|
||||
snapshotID, err := archive.Seal(manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = archive.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list, err := readLibrarySnapshots(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !list.Available || len(list.Snapshots) != 1 || list.Snapshots[0].SnapshotID != snapshotID {
|
||||
t.Fatalf("unexpected list %+v", list)
|
||||
}
|
||||
snapshot := list.Snapshots[0]
|
||||
want := map[string]int64{"documents": 4, "chunks": 38, "index_documents": 122, "resources": 21, "wiki_pages": 31}
|
||||
for key, value := range want {
|
||||
if snapshot.Totals[key] != value {
|
||||
t.Fatalf("total %s = %d, want %d", key, snapshot.Totals[key], value)
|
||||
}
|
||||
}
|
||||
// The archive-wide content figure deduplicates blobs across versions, so it
|
||||
// can be smaller than a version's logical sum but never larger.
|
||||
if snapshot.LogicalBytes <= 0 || list.ContentBytes <= 0 || list.ContentBytes > snapshot.LogicalBytes {
|
||||
t.Fatalf("bytes not reported: logical=%d content=%d", snapshot.LogicalBytes, list.ContentBytes)
|
||||
}
|
||||
if list.BlobAllocatedBytes < list.BlobFileBytes || list.ManifestFileBytes <= 0 {
|
||||
t.Fatalf("filesystem facts not separated: %+v", list)
|
||||
}
|
||||
if snapshot.Compatibility.EmbeddingDimension != 1024 || snapshot.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
|
||||
t.Fatalf("contract not reported: %+v", snapshot)
|
||||
}
|
||||
if list.CaptureNote == "" {
|
||||
t.Fatal("page must explain who runs the capture")
|
||||
}
|
||||
if _, err = os.Stat(filepath.Join(root, "versions", snapshotID+".json")); err != nil {
|
||||
t.Fatalf("sealed manifest missing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLibrarySnapshotsWithoutArchiveIsExplicitlyUnwired(t *testing.T) {
|
||||
list, err := readLibrarySnapshots("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list.Available || list.Reason == "" || len(list.Snapshots) != 0 {
|
||||
t.Fatalf("empty configuration must be reported as unwired, got %+v", list)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type monitorRemovalRetrier interface {
|
||||
RetryMonitorRemoval(context.Context, string, string, time.Time) error
|
||||
}
|
||||
|
||||
func retryMonitorRemoval(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if identity.Role != roleEngineer && identity.Role != roleAdmin {
|
||||
writeJSON(w, 403, map[string]string{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "monitor-removal-retry" {
|
||||
writeJSON(w, 403, map[string]string{"error": "write intent required"})
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" || len(id) > 128 {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid publication"})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(monitorRemovalRetrier)
|
||||
if !ok {
|
||||
writeJSON(w, 501, map[string]string{"error": "removal retry not configured"})
|
||||
return
|
||||
}
|
||||
err := store.RetryMonitorRemoval(r.Context(), id, actorFor(r), time.Now().UTC())
|
||||
if errors.Is(err, postgresstore.ErrPublicationStateConflict) {
|
||||
writeJSON(w, 409, map[string]string{"error": "状态或治理规则已变化,不能重复提交"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, 500, map[string]string{"error": "测试库移除重试失败"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, map[string]string{"status": "accepted"})
|
||||
}
|
||||
|
||||
type monitorTaskReader interface {
|
||||
ListMonitorTasks(context.Context, postgresstore.MonitorTaskFilter) (postgresstore.MonitorTaskPage, error)
|
||||
}
|
||||
|
||||
func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
f := postgresstore.MonitorTaskFilter{Search: q.Get("q"), Source: q.Get("source"), Scope: q.Get("scope"), Action: q.Get("action"), Status: q.Get("status"), Stage: q.Get("stage"), ID: q.Get("id"), Target: q.Get("target"), Since: q.Get("since"), Until: q.Get("until"), Limit: 20}
|
||||
for k, p := range map[string]*int{"limit": &f.Limit, "offset": &f.Offset} {
|
||||
if q.Get(k) != "" {
|
||||
n, e := strconv.Atoi(q.Get(k))
|
||||
if e != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid pagination"})
|
||||
return
|
||||
}
|
||||
*p = n
|
||||
}
|
||||
}
|
||||
if f.Limit < 1 || f.Limit > 100 || f.Offset < 0 || len(f.Search) > 512 || len(f.Source) > 128 || len(f.ID) > 128 {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
|
||||
return
|
||||
}
|
||||
for _, pair := range [][2]string{{f.Scope, "|internal|external"}, {f.Action, "|add|update|remove"}, {f.Status, "|active|waiting|running|retrying|attention|completed|cancelled"}, {f.Stage, "|waiting|fetch|upload|parsing|indexing|removal|finished"}} {
|
||||
if !strings.Contains("|"+pair[1]+"|", "|"+pair[0]+"|") {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, v := range []string{f.Since, f.Until} {
|
||||
if v != "" {
|
||||
if _, e := time.Parse(time.RFC3339, v); e != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid date"})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
store, ok := config.Store.(monitorTaskReader)
|
||||
if !ok {
|
||||
writeJSON(w, 501, map[string]string{"error": "monitor tasks not configured"})
|
||||
return
|
||||
}
|
||||
page, e := store.ListMonitorTasks(r.Context(), f)
|
||||
if e != nil {
|
||||
writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, 200, map[string]any{"data": page})
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type monitorTasksTestStore struct {
|
||||
fakeJobStore
|
||||
filter postgresstore.MonitorTaskFilter
|
||||
}
|
||||
|
||||
func (s *monitorTasksTestStore) ListMonitorTasks(_ context.Context, f postgresstore.MonitorTaskFilter) (postgresstore.MonitorTaskPage, error) {
|
||||
s.filter = f
|
||||
return postgresstore.MonitorTaskPage{Items: []postgresstore.MonitorTask{}, Total: 145, Limit: f.Limit, Offset: f.Offset}, nil
|
||||
}
|
||||
func TestMonitorTasksRoute(t *testing.T) {
|
||||
s := &monitorTasksTestStore{}
|
||||
req := httptest.NewRequest("GET", "/api/v1/monitor/tasks?status=active&limit=20&offset=40", nil)
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleViewer}))
|
||||
w := httptest.NewRecorder()
|
||||
h, err := NewHandler(Config{Store: s})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if s.filter.Status != "active" || s.filter.Offset != 40 {
|
||||
t.Fatalf("filter %#v", s.filter)
|
||||
}
|
||||
for _, query := range []string{"status=garbage", "stage=internal&scope=internal", "limit=101", "offset=-1", "since=bad"} {
|
||||
r := httptest.NewRequest("GET", "/api/v1/monitor/tasks?"+query, nil).WithContext(req.Context())
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, r)
|
||||
if rr.Code != 400 {
|
||||
t.Fatalf("invalid %s: %d", query, rr.Code)
|
||||
}
|
||||
}
|
||||
unauth := httptest.NewRecorder()
|
||||
h.ServeHTTP(unauth, httptest.NewRequest("GET", "/api/v1/monitor/tasks", nil))
|
||||
if unauth.Code != 401 {
|
||||
t.Fatalf("unauthenticated %d", unauth.Code)
|
||||
}
|
||||
removal := httptest.NewRecorder()
|
||||
h.ServeHTTP(removal, httptest.NewRequest("POST", "/api/v1/test-publications/example/removal-retry", nil).WithContext(req.Context()))
|
||||
if removal.Code != 403 {
|
||||
t.Fatalf("viewer removal %d", removal.Code)
|
||||
}
|
||||
}
|
||||
@@ -47,8 +47,31 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
var guardBaseURL func(any, string)
|
||||
guardBaseURL = func(node any, path string) {
|
||||
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" {
|
||||
t.Fatalf("unapproved endpoint exposure at %s", path)
|
||||
}
|
||||
next := key
|
||||
if path != "" {
|
||||
next = path + "." + key
|
||||
}
|
||||
guardBaseURL(child, next)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range value {
|
||||
guardBaseURL(child, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
var tree any
|
||||
_ = json.Unmarshal(contract, &tree)
|
||||
guardBaseURL(tree, "")
|
||||
lower := strings.ToLower(string(contract))
|
||||
for _, forbidden := range []string{"secret_ref", "authorization_code", "manifest_sha256", "knowledge_id", "test_kb_id", "base_url", "download_code", "cookie"} {
|
||||
for _, forbidden := range []string{"secret_ref", "authorization_code", "manifest_sha256", "knowledge_id", "test_kb_id", "download_code", "cookie"} {
|
||||
if strings.Contains(lower, forbidden) {
|
||||
t.Fatalf("OpenAPI contract must not expose %q", forbidden)
|
||||
}
|
||||
@@ -77,7 +100,7 @@ func TestOpenAPICatalogMutationsRequireIdempotencyKeyHeader(t *testing.T) {
|
||||
if !ok || schema["type"] != "string" || schema["minLength"] != float64(1) || schema["maxLength"] != float64(128) {
|
||||
t.Fatalf("IdempotencyKey header schema is unsafe: %#v", parameter["schema"])
|
||||
}
|
||||
for _, path := range []string{"/api/v1/source-catalog/route", "/api/v1/source-catalog/sources/{id}/refresh"} {
|
||||
for _, path := range []string{"/api/v1/qa-ops/organization/sync", "/api/v1/source-catalog/route", "/api/v1/source-catalog/sources/{id}/refresh"} {
|
||||
operation, ok := document.Paths[path]["post"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing POST %s", path)
|
||||
@@ -104,6 +127,46 @@ func TestOpenAPICatalogMutationsRequireIdempotencyKeyHeader(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAAIContractDescribesAllAdministratorPathsAndWriteOnlyCredential(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../api/openapi.yaml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var document struct {
|
||||
Paths map[string]map[string]any `json:"paths"`
|
||||
Components struct {
|
||||
Schemas map[string]map[string]any `json:"schemas"`
|
||||
} `json:"components"`
|
||||
}
|
||||
if json.Unmarshal(raw, &document) != nil {
|
||||
t.Fatal("invalid API document")
|
||||
}
|
||||
for _, route := range []struct{ path, method string }{{"/settings", "get"}, {"/settings", "post"}, {"/settings/test", "post"}, {"/automation", "post"}, {"/previews", "post"}, {"/batches", "post"}, {"/batches/{id}/actions", "post"}, {"/status", "get"}, {"/records/{id}", "get"}} {
|
||||
path := "/api/v1/qa-ops/ai" + route.path
|
||||
op, ok := document.Paths[path][route.method].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing %s %s", route.method, path)
|
||||
}
|
||||
responses, _ := op["responses"].(map[string]any)
|
||||
for _, status := range []string{"400", "401", "403", "500", "503"} {
|
||||
if responses[status] == nil {
|
||||
t.Fatalf("missing %s for %s", status, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
safe := document.Components.Schemas["QAAISafeSettings"]
|
||||
properties, _ := safe["properties"].(map[string]any)
|
||||
if properties["api_key"] != nil || properties["key_ciphertext"] != nil || properties["key_configured"] == nil || safe["additionalProperties"] != false {
|
||||
t.Fatal("safe settings contract exposes secrets or accepts unknown fields")
|
||||
}
|
||||
input := document.Components.Schemas["QAAISaveSettings"]
|
||||
properties, _ = input["properties"].(map[string]any)
|
||||
key, _ := properties["api_key"].(map[string]any)
|
||||
if key["writeOnly"] != true {
|
||||
t.Fatal("API key request property is not write-only")
|
||||
}
|
||||
}
|
||||
|
||||
func stringValue(value any) string {
|
||||
result, _ := value.(string)
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func qaAIError(w http.ResponseWriter, err error) {
|
||||
status, code, message := 503, "qa_ai_unavailable", "问答AI存储或安全配置不可用,请检查独立模型配置与执行器;未将失败伪装为成功或空结果"
|
||||
switch {
|
||||
case errors.Is(err, qaopsai.ErrInvalid):
|
||||
status, code, message = 400, "qa_ai_invalid_request", "参数、正式标签或模型输出校验未通过;更换API地址时须重新录入密钥,不能把旧密钥发送到新地址"
|
||||
case errors.Is(err, qaopsai.ErrConflict):
|
||||
status, code, message = 409, "qa_ai_version_conflict", "配置、输入、人工复核或预览已变化,请刷新;现有结论未被覆盖"
|
||||
default:
|
||||
var remote *qaopsai.RemoteError
|
||||
if errors.As(err, &remote) {
|
||||
status, code, message = 422, "qa_ai_"+remote.Code, "模型服务明确拒绝或未返回合格结果,配置未启用;请核对密钥、模型与JSON输出支持"
|
||||
}
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message, "code": code})
|
||||
}
|
||||
func qaAIReady(w http.ResponseWriter, r *http.Request, c Config) bool {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return false
|
||||
}
|
||||
if r.Method != "GET" && !authorizeQAIntent(w, r, "qa-ai") {
|
||||
return false
|
||||
}
|
||||
if c.QAAI == nil {
|
||||
qaAIError(w, qaopsai.ErrUnavailable)
|
||||
return false
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return false
|
||||
}
|
||||
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
|
||||
}
|
||||
func registerQAAIRoutes(mux *http.ServeMux, c Config) {
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
data, err := c.QAAI.GetSettings(r.Context())
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
for _, test := range []bool{false, true} {
|
||||
path := "POST /api/v1/qa-ops/ai/settings"
|
||||
if test {
|
||||
path += "/test"
|
||||
}
|
||||
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input qaopsai.SaveSettings
|
||||
if decodeQualityJSON(w, r, &input, "base_revision", "base_url", "model", "key_action") != nil {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !qaAISecretTransport(r, c) {
|
||||
writeJSON(w, 400, map[string]string{"code": "qa_ai_secure_transport_required", "error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
var data qaopsai.Settings
|
||||
var err error
|
||||
if test {
|
||||
data, err = c.QAAI.TestSettings(r.Context(), input)
|
||||
} else {
|
||||
data, err = c.QAAI.SaveSettings(r.Context(), input, identity.Username)
|
||||
}
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
}
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/ai/automation", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Kind string `json:"kind"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &input, "kind", "enabled") != nil {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
data, err := c.QAAI.SetAutomation(r.Context(), input.Kind, input.Enabled, identity.Username)
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/ai/previews", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input qaopsai.Scope
|
||||
if decodeQualityJSON(w, r, &input, "kind") != nil {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
data, err := c.QAAI.Preview(r.Context(), input, identity.Username)
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/ai/batches", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
PreviewID string `json:"preview_id"`
|
||||
Nonce string `json:"nonce"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &input, "preview_id", "nonce") != nil {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
data, err := c.QAAI.Start(r.Context(), input.PreviewID, input.Nonce, identity.Username)
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/ai/batches/{id}/actions", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Action string `json:"action"`
|
||||
Nonce string `json:"nonce"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &input, "action", "nonce") != nil || r.Header.Get("Idempotency-Key") != input.Nonce {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
data, err := c.QAAI.ManageBatch(r.Context(), r.PathValue("id"), input.Action, input.Nonce, identity.Username)
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/status", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
data, err := c.QAAI.GetStatus(r.Context())
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/records/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
data, err := c.QAAI.RecordEvidence(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAIUnavailableDoesNotFalselyClaimNoModelCallOccurred(t *testing.T) {
|
||||
response := httptest.NewRecorder()
|
||||
qaAIError(response, qaopsai.ErrUnavailable)
|
||||
if strings.Contains(response.Body.String(), "未调用模型") {
|
||||
t.Fatal("a persistence failure after a model call was reported as no call")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIEndpointsRequireAdminAndExplicitSameOriginWriteIntent(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["fixture-ai-admin"] = "usr-boss"
|
||||
auth.sessions["fixture-ai-viewer"] = "usr-eye"
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, route := range []struct{ method, path, body string }{{"GET", "/api/v1/qa-ops/ai/settings", ""}, {"GET", "/api/v1/qa-ops/ai/status", ""}, {"POST", "/api/v1/qa-ops/ai/settings", `{}`}, {"POST", "/api/v1/qa-ops/ai/settings/test", `{}`}, {"POST", "/api/v1/qa-ops/ai/previews", `{}`}, {"POST", "/api/v1/qa-ops/ai/batches", `{}`}, {"POST", "/api/v1/qa-ops/ai/automation", `{}`}, {"POST", "/api/v1/qa-ops/ai/batches/fixture/actions", `{}`}} {
|
||||
for _, who := range []struct {
|
||||
token string
|
||||
want int
|
||||
}{{"", 401}, {"fixture-ai-viewer", 403}, {"fixture-ai-admin", 503}} {
|
||||
request := httptest.NewRequest(route.method, route.path, strings.NewReader(route.body))
|
||||
if who.token != "" {
|
||||
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: who.token})
|
||||
}
|
||||
request.Header.Set("X-Governance-Action", "qa-ai")
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != who.want {
|
||||
t.Fatalf("%s %s role=%s status=%d want=%d", route.method, route.path, who.token, response.Code, who.want)
|
||||
}
|
||||
}
|
||||
if route.method == "POST" {
|
||||
request := httptest.NewRequest(route.method, route.path, strings.NewReader(route.body))
|
||||
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-ai-admin"})
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != 403 {
|
||||
t.Fatal("write without explicit action was accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errQAOrganization = errors.New("organization attribution unavailable")
|
||||
|
||||
type qaAttributionProvider interface {
|
||||
GetAttribution(context.Context) (*qaopsorg.Attribution, error)
|
||||
}
|
||||
|
||||
func recordAttribution(ctx context.Context, config Config) (*qaopsorg.Attribution, error) {
|
||||
if config.QAOrg == nil {
|
||||
return qaopsorg.BuildAttribution(qaopsorg.State{State: "empty"}, qaopsorg.Directory{})
|
||||
}
|
||||
provider, ok := config.QAOrg.(qaAttributionProvider)
|
||||
if !ok {
|
||||
return nil, errQAOrganization
|
||||
}
|
||||
p, err := provider.GetAttribution(ctx)
|
||||
if err != nil || p == nil {
|
||||
return nil, errQAOrganization
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
func attributionVersion(p *qaopsorg.Attribution) dobotaiops.OrganizationVersion {
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory", RegionNames: p.Metadata.RegionLabels()}
|
||||
}
|
||||
func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) {
|
||||
trigger := item.TriggerPerson
|
||||
if raw, ok := item.MasterFields["trigger_person"]; ok {
|
||||
trigger = raw
|
||||
}
|
||||
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID, item.Asker, trigger)
|
||||
o := &dobotaiops.RecordOrganization{Version: attributionVersion(p), State: person.State, Departments: person.Departments, Region: person.Region, SourceDepartment: item.Department, SourceRegion: item.Region, DepartmentOrigin: "unavailable", RegionOrigin: "unavailable"}
|
||||
if item.Department != "" {
|
||||
o.DepartmentOrigin = "source_snapshot"
|
||||
} else if len(person.Departments) > 0 {
|
||||
item.Department = strings.Join(person.Departments, ";")
|
||||
o.DepartmentOrigin = "current_directory"
|
||||
}
|
||||
if item.Region != "" {
|
||||
o.RegionOrigin = "source_snapshot"
|
||||
} else if person.Region != "" {
|
||||
item.Region = person.Region
|
||||
o.RegionOrigin = "current_directory"
|
||||
}
|
||||
item.Organization = o
|
||||
}
|
||||
func enrichQAPage(page *dobotaiops.RecordPage, p *qaopsorg.Attribution) {
|
||||
version := attributionVersion(p)
|
||||
page.Organization = &version
|
||||
for i := range page.Items {
|
||||
enrichQARecord(&page.Items[i], p)
|
||||
}
|
||||
for _, actor := range page.ScopeActors {
|
||||
person := p.Resolve(actor.StaffID, actor.UnionID)
|
||||
if len(person.Departments) > 0 {
|
||||
dobotaiops.AddRecordColumns(page, "department")
|
||||
}
|
||||
if person.Region != "" {
|
||||
dobotaiops.AddRecordColumns(page, "region")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type qaUsageReader interface {
|
||||
ReadUsageGroups(context.Context, dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error)
|
||||
}
|
||||
type qaUsageRow struct {
|
||||
Key string `json:"key"`
|
||||
Questions int64 `json:"questions"`
|
||||
Succeeded int64 `json:"succeeded"`
|
||||
Failed int64 `json:"failed"`
|
||||
Other int64 `json:"other"`
|
||||
Users *int `json:"users"`
|
||||
RosterPeople *int `json:"roster_people"`
|
||||
}
|
||||
type qaUsage struct {
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
Questions int64 `json:"questions"`
|
||||
IdentifiedUsers int `json:"identified_users"`
|
||||
Rows []qaUsageRow `json:"rows"`
|
||||
}
|
||||
|
||||
func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, query dobotaiops.RecordQuery) qaUsage {
|
||||
result := qaUsage{Organization: attributionVersion(p), AsOf: groups.AsOf, Start: query.Window.Start, End: query.Window.End, Keyword: query.Keyword, Rows: []qaUsageRow{}}
|
||||
keys := append(append([]string{}, p.Metadata.RegionLabels()...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
rows := map[string]*qaUsageRow{}
|
||||
members := map[string]map[string]bool{}
|
||||
all := map[string]bool{}
|
||||
for _, key := range keys {
|
||||
row := &qaUsageRow{Key: key}
|
||||
if p.Metadata.State == "ready" {
|
||||
var n int
|
||||
valid := true
|
||||
switch key {
|
||||
case "unassigned":
|
||||
n = p.Metadata.View.UnassignedPeople
|
||||
case "cross_region":
|
||||
n = p.Metadata.View.ConflictingPeople
|
||||
default:
|
||||
var ok bool
|
||||
for _, region := range p.Metadata.RegionDefinitions() {
|
||||
if region.Name == key {
|
||||
n, ok = p.Metadata.View.Regions[region.ID]
|
||||
break
|
||||
}
|
||||
}
|
||||
valid = ok
|
||||
}
|
||||
if valid {
|
||||
row.RosterPeople = &n
|
||||
row.Users = new(int)
|
||||
}
|
||||
}
|
||||
rows[key] = row
|
||||
members[key] = map[string]bool{}
|
||||
}
|
||||
for _, group := range groups.Groups {
|
||||
person := p.Resolve(group.Identity.StaffID, group.Identity.UnionID)
|
||||
key := person.State
|
||||
if person.Region != "" {
|
||||
key = person.Region
|
||||
}
|
||||
row := rows[key]
|
||||
if row == nil {
|
||||
continue
|
||||
}
|
||||
row.Questions += group.Total
|
||||
row.Succeeded += group.Succeeded
|
||||
row.Failed += group.Failed
|
||||
row.Other += group.Total - group.Succeeded - group.Failed
|
||||
result.Questions += group.Total
|
||||
if person.PersonID != "" {
|
||||
members[key][person.PersonID] = true
|
||||
all[person.PersonID] = true
|
||||
}
|
||||
}
|
||||
for _, key := range keys {
|
||||
row := rows[key]
|
||||
if row.Users != nil {
|
||||
*row.Users = len(members[key])
|
||||
}
|
||||
result.Rows = append(result.Rows, *row)
|
||||
}
|
||||
result.IdentifiedUsers = len(all)
|
||||
return result
|
||||
}
|
||||
func qaOpsUsage(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
reader, ok := config.QAOps.(qaUsageReader)
|
||||
if !ok || config.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
values := r.URL.Query()
|
||||
for key, items := range values {
|
||||
if (key != "start" && key != "end" && key != "keyword") || len(items) != 1 {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
window, err := dobotaiops.NewWindow(config.QAOpsTenantKey, values.Get("start"), values.Get("end"), 90*24*time.Hour, config.Now())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
p, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
query := dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword")}
|
||||
groups, err := reader.ReadUsageGroups(r.Context(), query)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": summarizeQAUsage(groups, p, query)})
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type attributionOrgSpy struct {
|
||||
orgSpy
|
||||
projection *qaopsorg.Attribution
|
||||
}
|
||||
|
||||
func (s *attributionOrgSpy) GetAttribution(context.Context) (*qaopsorg.Attribution, error) {
|
||||
return s.projection, s.err
|
||||
}
|
||||
|
||||
type attributedReader struct{}
|
||||
|
||||
func (*attributedReader) Available(context.Context) error { return nil }
|
||||
func (*attributedReader) Safety() dobotaiops.SourceSafety { return dobotaiops.SourceSafety{SSL: true} }
|
||||
func (*attributedReader) ListRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{{ID: "anonymous"}}, ScopeActors: []dobotaiops.ActorIdentity{{StaffID: "fixture-private-staff"}}, Columns: []string{"question"}, Total: 3}, nil
|
||||
}
|
||||
func (*attributedReader) GetRecord(context.Context, string, string) (dobotaiops.Record, error) {
|
||||
return dobotaiops.Record{ID: "one", Department: "历史部门", Region: "历史区域", Identity: dobotaiops.ActorIdentity{StaffID: "fixture-private-staff"}}, nil
|
||||
}
|
||||
func (*attributedReader) ReadUsageGroups(context.Context, dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) {
|
||||
return dobotaiops.UsageGroups{AsOf: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC), Groups: []dobotaiops.UsageGroup{{Identity: dobotaiops.ActorIdentity{StaffID: "fixture-private-staff"}, Total: 3, Succeeded: 2, Failed: 1}, {Identity: dobotaiops.ActorIdentity{UnionID: "fixture-private-union"}, Total: 2, Succeeded: 2}, {Identity: dobotaiops.ActorIdentity{StaffID: "unmatched"}, Total: 2}}}, nil
|
||||
}
|
||||
func attributionHandler(t *testing.T) (http.Handler, *attributionOrgSpy) {
|
||||
t.Helper()
|
||||
projection, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "directory-v1", RevisionID: "region-v1", Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "APAC"}}}, qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "测试公司"}}, People: []qaopsorg.Person{{ID: "fixture-private-staff", UnionID: "fixture-private-union", DepartmentIDs: []string{"root"}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
org := &attributionOrgSpy{projection: projection}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["attribution-admin"] = "usr-boss"
|
||||
auth.sessions["attribution-viewer"] = "usr-eye"
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: &attributedReader{}, QAOpsTenantKey: "fixed", QAOrg: org, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h, org
|
||||
}
|
||||
func attributionRequest(h http.Handler, path, token string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
const attributionFilter = "?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z"
|
||||
|
||||
func TestQAAttributionUsesWholeFilterAndPreservesHistoricalSnapshots(t *testing.T) {
|
||||
h, org := attributionHandler(t)
|
||||
w := attributionRequest(h, "/api/v1/qa-ops/records"+attributionFilter, "attribution-admin")
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
var page struct{ Data dobotaiops.RecordPage }
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &page)
|
||||
if !strings.Contains(strings.Join(page.Data.Columns, ","), "department,region") {
|
||||
t.Fatal("organization column hidden because first page is anonymous", w.Body.String())
|
||||
}
|
||||
w = attributionRequest(h, "/api/v1/qa-ops/records/one", "attribution-admin")
|
||||
var detail struct{ Data dobotaiops.Record }
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &detail)
|
||||
if detail.Data.Department != "历史部门" || detail.Data.Region != "历史区域" || detail.Data.Organization == nil || detail.Data.Organization.Region != "APAC" {
|
||||
t.Fatal("source snapshot overwritten or current attribution missing", w.Body.String())
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "fixture-private") {
|
||||
t.Fatal("identity keys exposed")
|
||||
}
|
||||
org.err = qaopsorg.ErrUnavailable
|
||||
w = attributionRequest(h, "/api/v1/qa-ops/records"+attributionFilter, "attribution-admin")
|
||||
if w.Code != 503 || !strings.Contains(w.Body.String(), "organization_unavailable") {
|
||||
t.Fatal("permission/storage failure hidden as empty", w.Body.String())
|
||||
}
|
||||
}
|
||||
func TestQAUsageIsAdminScopedDeduplicatedAndNotPerformance(t *testing.T) {
|
||||
h, _ := attributionHandler(t)
|
||||
path := "/api/v1/qa-ops/usage" + attributionFilter
|
||||
for _, tc := range []struct {
|
||||
token string
|
||||
status int
|
||||
}{{"", 401}, {"attribution-viewer", 403}, {"attribution-admin", 200}} {
|
||||
w := attributionRequest(h, path, tc.token)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("usage guard got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if tc.status == 200 {
|
||||
var result struct {
|
||||
Data struct {
|
||||
Questions int64 `json:"questions"`
|
||||
IdentifiedUsers int `json:"identified_users"`
|
||||
Rows []struct {
|
||||
Key string
|
||||
Questions int64
|
||||
Users *int
|
||||
}
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &result) != nil || result.Data.Questions != 7 || result.Data.IdentifiedUsers != 1 {
|
||||
t.Fatal("events/people not deduplicated", w.Body.String())
|
||||
}
|
||||
for _, row := range result.Data.Rows {
|
||||
if row.Key == "APAC" && (row.Questions != 5 || row.Users == nil || *row.Users != 1) {
|
||||
t.Fatal("regional user double-counted")
|
||||
}
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "fixture-private") || strings.Contains(w.Body.String(), "performance") {
|
||||
t.Fatal("private identity or performance verdict leaked")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, extra := range []string{"&tenant=forged", "&limit=1", "&cursor=forged", "&start=duplicate"} {
|
||||
if w := attributionRequest(h, path+extra, "attribution-admin"); w.Code != 400 {
|
||||
t.Fatal("usage accepted client scope or pagination")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type qaDashboardReader interface {
|
||||
ReadMasterDashboard(context.Context, dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error)
|
||||
}
|
||||
|
||||
func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-dashboard") {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
Filters map[string]string `json:"filters,omitempty"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request, "start", "end") != nil {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(qaDashboardReader)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
window, e := dobotaiops.NewWindow(c.QAOpsTenantKey, request.Start, request.End, 90*24*time.Hour, c.Now())
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters})
|
||||
if e != nil {
|
||||
if errors.Is(e, qaopsquality.ErrConflict) {
|
||||
writeQualityError(w, e)
|
||||
return
|
||||
}
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": dashboard})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dashboardReaderSpy struct {
|
||||
attributedReader
|
||||
calls int
|
||||
masterCalls int
|
||||
query dobotaiops.RecordQuery
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *dashboardReaderSpy) ReadDashboard(_ context.Context, q dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error) {
|
||||
s.calls++
|
||||
s.query = q
|
||||
return qaopsmirror.Dashboard{TotalIssues: 7, NewThisWeek: 2}, s.err
|
||||
}
|
||||
func (s *dashboardReaderSpy) ReadMasterDashboard(ctx context.Context, q dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error) {
|
||||
s.masterCalls++
|
||||
return s.ReadDashboard(ctx, q)
|
||||
}
|
||||
func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
|
||||
reader := &dashboardReaderSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["dash-admin"] = "usr-boss"
|
||||
auth.sessions["dash-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: reader, QAOpsTenantKey: "fixed-dashboard-tenant", Now: func() time.Time { return time.Date(2026, 10, 18, 12, 0, 0, 0, time.UTC) }, Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
good := `{"start":"2026-10-05T00:00:00+08:00","end":"2026-10-12T00:00:00+08:00","keyword":"100%_"}`
|
||||
for _, c := range []struct {
|
||||
token, action, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"", "qa-dashboard", "", good, 401}, {"dash-viewer", "qa-dashboard", "", good, 403}, {"dash-admin", "", "", good, 403}, {"dash-admin", "qa-dashboard", "https://untrusted.invalid", good, 403},
|
||||
{"dash-admin", "qa-dashboard", "", `null`, 400}, {"dash-admin", "qa-dashboard", "", `{"start":null,"end":"2026-10-12T00:00:00+08:00"}`, 400},
|
||||
{"dash-admin", "qa-dashboard", "", `{"tenant":"other","start":"2026-10-05T00:00:00+08:00","end":"2026-10-12T00:00:00+08:00"}`, 400},
|
||||
{"dash-admin", "qa-dashboard", "", good, 200},
|
||||
} {
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(c.body))
|
||||
if c.token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token})
|
||||
}
|
||||
r.Header.Set("X-Governance-Action", c.action)
|
||||
r.Header.Set("Origin", c.origin)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.status {
|
||||
t.Fatalf("dashboard status=%d want=%d", w.Code, c.status)
|
||||
}
|
||||
if w.Code == 200 && w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("private dashboard response may be cached")
|
||||
}
|
||||
}
|
||||
if reader.masterCalls != 1 || reader.calls != 1 || reader.query.Window.TenantKey != "fixed-dashboard-tenant" || reader.query.Keyword != "100%_" {
|
||||
t.Fatal("rejected requests reached the reader or browser controlled the tenant")
|
||||
}
|
||||
reader.err = qaopsquality.ErrConflict
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(good))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "dash-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-dashboard")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("quality input drift status=%d want409", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type departmentStatisticsReader interface {
|
||||
ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error)
|
||||
}
|
||||
|
||||
func qaDepartmentStatistics(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-department-statistics") {
|
||||
return
|
||||
}
|
||||
var q qaopsmirror.DepartmentStatisticsQuery
|
||||
if r.URL.RawQuery != "" || decodeQualityJSON(w, r, &q, "period") != nil {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
now := c.Now()
|
||||
if _, _, e := q.Bounds(now); e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(departmentStatisticsReader)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
data, e := reader.ReadDepartmentStatistics(r.Context(), q, now)
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if data.State == "pending" {
|
||||
status = http.StatusAccepted
|
||||
w.Header().Set("Retry-After", "1")
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"data": data})
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type departmentStatisticsFixture struct {
|
||||
masterFixtureReader
|
||||
reads int
|
||||
}
|
||||
|
||||
func (f *departmentStatisticsFixture) ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error) {
|
||||
f.reads++
|
||||
return qaopsmirror.DepartmentStatisticsResult{State: "pending", RetryAfter: 1}, nil
|
||||
}
|
||||
func TestDepartmentStatisticsRouteIsAsynchronousStrictAndAdminOnly(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["dept-fixture-admin"] = "usr-boss"
|
||||
auth.sessions["dept-fixture-viewer"] = "usr-eye"
|
||||
reader := &departmentStatisticsFixture{}
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixture-tenant", Now: func() time.Time { return time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
body, token, intent, site string
|
||||
want int
|
||||
}{
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 202},
|
||||
{`{"period":"month","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "same-origin", 202},
|
||||
{`{"period":"all"}`, "", "qa-department-statistics", "", 401},
|
||||
{`{"period":"all"}`, "dept-fixture-viewer", "qa-department-statistics", "", 403},
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "", "", 403},
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "cross-site", 403},
|
||||
{`{"period":"all","tenant":"other"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"all","period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`null`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"month","month":"2027-01"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"all","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
} {
|
||||
r := httptest.NewRequest("POST", "/api/v1/qa-ops/departments/statistics", strings.NewReader(c.body))
|
||||
if c.token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token})
|
||||
}
|
||||
if c.intent != "" {
|
||||
r.Header.Set("X-Governance-Action", c.intent)
|
||||
}
|
||||
if c.site != "" {
|
||||
r.Header.Set("Sec-Fetch-Site", c.site)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.want {
|
||||
t.Fatalf("department statistics got %d want %d", w.Code, c.want)
|
||||
}
|
||||
if w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("employee department stats became publicly cacheable")
|
||||
}
|
||||
}
|
||||
if reader.reads != 2 {
|
||||
t.Fatal("malformed or unauthorized request reached aggregation", reader.reads)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func masterNoStore(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/master/") || strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/departments/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Master reads and reviews own their state; no source client is accepted as fallback.
|
||||
type qaMasterStore interface {
|
||||
ListMasterRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error)
|
||||
GetMasterRecord(context.Context, string, string) (dobotaiops.Record, error)
|
||||
ReadMasterQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error)
|
||||
MasterQualityStore() *qaopsquality.Store
|
||||
}
|
||||
type qaMasterReader struct {
|
||||
QAOpsReader
|
||||
master qaMasterStore
|
||||
}
|
||||
|
||||
func (s qaMasterReader) ListRecords(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
return s.master.ListMasterRecords(ctx, q)
|
||||
}
|
||||
func (s qaMasterReader) GetRecord(ctx context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
return s.master.GetMasterRecord(ctx, tenant, id)
|
||||
}
|
||||
func (s qaMasterReader) ReadQualityScope(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return s.master.ReadMasterQualityScope(ctx, q)
|
||||
}
|
||||
func (s qaMasterReader) ReadStoredQuality(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
if reader, ok := s.master.(interface {
|
||||
ReadMasterQualityViews(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
|
||||
}); ok {
|
||||
return reader.ReadMasterQualityViews(ctx, keys)
|
||||
}
|
||||
return s.master.MasterQualityStore().ReadViews(ctx, keys)
|
||||
}
|
||||
func withQAMaster(w http.ResponseWriter, r *http.Request, c Config, handler func(http.ResponseWriter, *http.Request, Config)) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
master, ok := c.QAOps.(qaMasterStore)
|
||||
if !ok {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
c.QAOps = qaMasterReader{QAOpsReader: c.QAOps, master: master}
|
||||
c.QAQuality = master.MasterQualityStore()
|
||||
if master.MasterQualityStore() == nil {
|
||||
c.QAQuality = nil
|
||||
}
|
||||
handler(w, r, c)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type downvoteSnapshotReader struct {
|
||||
QAOpsReader
|
||||
view qaopsquality.View
|
||||
}
|
||||
|
||||
func (s downvoteSnapshotReader) ReadStoredQuality(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
return map[string]qaopsquality.View{"fixture-feedback-race": s.view}, nil
|
||||
}
|
||||
|
||||
func TestMasterQualityEnrichmentUsesOneFeedbackDecisionEvenWhenVoteChangesBetweenReads(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
old, current dobotaiops.RecordFeedback
|
||||
label, correctness, rule string
|
||||
}{
|
||||
{"new-downvote", dobotaiops.RecordFeedback{}, dobotaiops.RecordFeedback{Down: 1}, "否", "incorrect", "downvote-is-incorrect-v1"},
|
||||
{"withdrawn-current-vote", dobotaiops.RecordFeedback{Down: 1}, dobotaiops.RecordFeedback{}, "是", "correct", ""},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
view := qaopsquality.View{EffectiveSource: "master-effective-fields-v1", FeedbackRule: test.rule, Effective: qaopsquality.Fields{Correctness: test.correctness}, MasterFeedback: &test.current}
|
||||
c := Config{QAOps: downvoteSnapshotReader{view: view}, QAQuality: &qualityFake{}}
|
||||
item := dobotaiops.Record{ID: "fixture-feedback-race", RecordOrigin: "dobotai_2_0", Feedback: test.old, MasterFields: map[string]string{"is_correct": "待确认"}}
|
||||
if err := enrichQAQualityRecord(context.Background(), c, &item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if item.Feedback != test.current || item.MasterFields["is_correct"] != test.label {
|
||||
t.Fatal("detail combines an old feedback snapshot with a newer quality decision")
|
||||
}
|
||||
page := dobotaiops.RecordPage{Items: []dobotaiops.Record{{ID: item.ID, RecordOrigin: item.RecordOrigin, Feedback: test.old, MasterFields: map[string]string{"is_correct": "待确认"}}}}
|
||||
// The common projection must be shared by the list and detail enrichment paths.
|
||||
if err := enrichQAQualityPage(context.Background(), c, &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if page.Items[0].Feedback != test.current || page.Items[0].MasterFields["is_correct"] != test.label {
|
||||
t.Fatal("list combines an old feedback snapshot with a newer quality decision")
|
||||
}
|
||||
var quality map[string]any
|
||||
if json.Unmarshal(item.Quality, &quality) != nil {
|
||||
t.Fatal("quality response missing")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsfields"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type masterFieldWriter interface {
|
||||
PatchMasterFields(context.Context, string, qaopsmirror.MasterFieldPatch, string) (qaopsmirror.MasterFieldReceipt, error)
|
||||
}
|
||||
|
||||
func qaMasterFieldOptions(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, 200, map[string]any{"data": map[string]any{"version": "qa-master-options-v1", "fields": qaopsfields.EditableOptions()}})
|
||||
}
|
||||
func qaMasterFieldPatch(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-master-fields") {
|
||||
return
|
||||
}
|
||||
var q qaopsmirror.MasterFieldPatch
|
||||
if decodeQualityJSON(w, r, &q, "input_hash", "input_epoch", "base_revision", "base_review_revision", "nonce", "fields") != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "字段选项或编辑参数无效"})
|
||||
return
|
||||
}
|
||||
writer, ok := c.QAOps.(masterFieldWriter)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
result, err := writer.PatchMasterFields(r.Context(), r.PathValue("id"), q, identity.Username)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, qaopsquality.ErrDownvoted):
|
||||
writeJSON(w, 409, map[string]string{"error": "问题已点踩,是否正确固定为否;未保存冲突选择,请重新读取"})
|
||||
case errors.Is(err, qaopsquality.ErrConflict):
|
||||
writeJSON(w, 409, map[string]string{"error": "字段或问答版本已变化,请重新读取后修改;未覆盖其他人的内容"})
|
||||
case errors.Is(err, dobotaiops.ErrInvalidQuery):
|
||||
writeJSON(w, 400, map[string]string{"error": "字段选项无效,未保存;请选择主表允许的内容"})
|
||||
default:
|
||||
qaOpsError(w, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type masterFixtureReader struct {
|
||||
calls int
|
||||
tenant string
|
||||
}
|
||||
|
||||
func (f *masterFixtureReader) ListRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
panic("master must never fall back to replaceable mirror/source reads")
|
||||
}
|
||||
func (f *masterFixtureReader) GetRecord(context.Context, string, string) (dobotaiops.Record, error) {
|
||||
panic("master must never fetch the production source")
|
||||
}
|
||||
func (f *masterFixtureReader) Available(context.Context) error { return nil }
|
||||
func (f *masterFixtureReader) Safety() dobotaiops.SourceSafety { return dobotaiops.SourceSafety{} }
|
||||
func (f *masterFixtureReader) MasterQualityStore() *qaopsquality.Store { return nil }
|
||||
func (f *masterFixtureReader) ListMasterRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
f.calls++
|
||||
f.tenant = q.Window.TenantKey
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{}, Columns: []string{"question"}, AsOf: time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC), LocalRevision: 3}, nil
|
||||
}
|
||||
func (f *masterFixtureReader) GetMasterRecord(_ context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
f.calls++
|
||||
f.tenant = tenant
|
||||
return dobotaiops.Record{ID: id, Question: "fixture master"}, nil
|
||||
}
|
||||
func (f *masterFixtureReader) ReadMasterQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return dobotaiops.QualityScope{}, nil
|
||||
}
|
||||
func TestQAMasterUsesFixedTenantAndNeverSourceFallback(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["fixture-master-admin"] = "usr-boss"
|
||||
reader := &masterFixtureReader{}
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixed-master-tenant", Now: func() time.Time { return time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
base := "/api/v1/qa-ops/master/records"
|
||||
for _, c := range []struct {
|
||||
path string
|
||||
cookie bool
|
||||
status int
|
||||
}{{base + "?start=2026-10-05T00:00:00Z&end=2026-10-12T00:00:00Z", true, 200}, {base + "/fixture-id", true, 200}, {base + "?tenant=other", true, 400}, {base, false, 401}} {
|
||||
r := httptest.NewRequest(http.MethodGet, c.path, nil)
|
||||
if c.cookie {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-master-admin"})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.status {
|
||||
t.Fatalf("master route %s: got %d, wanted %d", c.path, w.Code, c.status)
|
||||
}
|
||||
if w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("master employee data was cacheable")
|
||||
}
|
||||
}
|
||||
if reader.calls != 2 || reader.tenant != "fixed-master-tenant" {
|
||||
t.Fatal("master fixed-tenant read path missing")
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPost, base+"/fixture-id/reviews", strings.NewReader(`{}`))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-master-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("master review lacked explicit same-origin intent gate", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type mirroredQualitySource struct {
|
||||
qualitySource
|
||||
reads int
|
||||
}
|
||||
|
||||
func (s *mirroredQualitySource) ReadStoredQuality(_ context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
s.reads++
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, key := range keys {
|
||||
out[key.ID] = qaopsquality.Project(key.InputHash, 1, 0, qaopsquality.Check{Result: dobotaiops.CheckMarkerCoverage(true)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func TestMirroredQualityQueriesDoNotRepeatObservationWrites(t *testing.T) {
|
||||
source := &mirroredQualitySource{qualitySource: qualitySource{record: dobotaiops.Record{ID: "fixture-turn", Question: "fixture", Answer: "暂无已发布"}}}
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
source.record.QualityInputHash = e.Hash
|
||||
legacy := &qualityFake{fail: true}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["quality-admin"] = "usr-boss"
|
||||
h, e2 := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: source, QAOpsTenantKey: "fixed", QAQuality: legacy, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if e2 != nil {
|
||||
t.Fatal(e2)
|
||||
}
|
||||
for _, q := range []struct{ method, path, body string }{{"GET", "/api/v1/qa-ops/records/fixture-turn", ""}, {"GET", "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", ""}, {"POST", "/api/v1/qa-ops/quality/query", `{"start":"2026-10-14T00:00:00Z","end":"2026-10-15T00:00:00Z","keyword":""}`}} {
|
||||
w := qualityRequest(h, q.method, q.path, "quality-admin", q.body)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatal("local mirror read went back through observation writes", q.path, w.Code)
|
||||
}
|
||||
}
|
||||
if source.reads != 3 || legacy.calls != 0 {
|
||||
t.Fatal("batched stored projection not used", source.reads, legacy.calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type qaMirrorSyncStore interface {
|
||||
GetSyncStatus(context.Context) (qaopsmirror.Status, error)
|
||||
EnqueueSync(context.Context, string, string) (qaopsmirror.SyncReceipt, bool, error)
|
||||
}
|
||||
|
||||
func qaRecordsSync(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步入口不接受查询参数"})
|
||||
return
|
||||
}
|
||||
store, ok := c.QAOps.(qaMirrorSyncStore)
|
||||
if !ok || !c.QAOpsEnabled {
|
||||
writeJSON(w, 503, map[string]string{"error": "本地问答同步未接线,未创建任务"})
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
state, e := store.GetSyncStatus(r.Context())
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": state})
|
||||
return
|
||||
}
|
||||
if !authorizeQAIntent(w, r, "qa-records-sync") {
|
||||
return
|
||||
}
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if key == "" || len(key) > 128 || strings.TrimSpace(key) != key {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求需要有效 Idempotency-Key,重试须复用原标识"})
|
||||
return
|
||||
}
|
||||
var body *struct{}
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&body) != nil || body == nil || d.Decode(&struct{}{}) != io.EOF {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求体必须是空对象"})
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, replayed, e := store.EnqueueSync(r.Context(), key, identity.Username)
|
||||
if e != nil {
|
||||
status := 503
|
||||
message := "同步未成功入队,已有本地数据保持不变"
|
||||
if errors.Is(e, qaopsmirror.ErrInvalid) {
|
||||
status = 400
|
||||
message = "同步请求标识无效"
|
||||
}
|
||||
if errors.Is(e, qaopsmirror.ErrConflict) {
|
||||
status = 409
|
||||
message = "同步标识已用于另一操作,请重新发起"
|
||||
}
|
||||
if errors.Is(e, qaopsmirror.ErrWorkerUnavailable) {
|
||||
message = "问答同步执行器未在线,未创建任务"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
return
|
||||
}
|
||||
operation := "created"
|
||||
if replayed {
|
||||
operation = "replayed"
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"data": receipt, "operation": operation})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type mirrorSyncSpy struct {
|
||||
qaOpsSpy
|
||||
syncCalls int
|
||||
key, actor string
|
||||
}
|
||||
|
||||
func (s *mirrorSyncSpy) GetSyncStatus(context.Context) (qaopsmirror.Status, error) {
|
||||
return qaopsmirror.Status{Mode: "local", IntervalSeconds: 300, WorkerReady: true}, nil
|
||||
}
|
||||
func (s *mirrorSyncSpy) EnqueueSync(_ context.Context, key, actor string) (qaopsmirror.SyncReceipt, bool, error) {
|
||||
s.syncCalls++
|
||||
s.key = key
|
||||
s.actor = actor
|
||||
return qaopsmirror.SyncReceipt{JobID: "fixture-mirror-job"}, false, nil
|
||||
}
|
||||
func TestQAMirrorSyncRequiresSessionIntentAndIdempotency(t *testing.T) {
|
||||
spy := &mirrorSyncSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["mirror-admin"] = "usr-boss"
|
||||
auth.sessions["mirror-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsEnabled: true, QAOpsTenantKey: "fixture-tenant", Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
method, token, key, intent, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"GET", "", "", "", "", "", 401}, {"GET", "mirror-viewer", "", "", "", "", 403}, {"GET", "mirror-admin", "", "", "", "", 200},
|
||||
{"POST", "mirror-admin", "op-one", "", "", "{}", 403}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "https://foreign.invalid", "{}", 403},
|
||||
{"POST", "mirror-admin", "", "qa-records-sync", "", "{}", 400}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "", "null", 400},
|
||||
{"POST", "mirror-admin", "op-one", "qa-records-sync", "", `{"tenant":"forged"}`, 400}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "", "{}", 202},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, "/api/v1/qa-ops/sync", strings.NewReader(tc.body))
|
||||
if tc.token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
|
||||
}
|
||||
req.Header.Set("Idempotency-Key", tc.key)
|
||||
req.Header.Set("X-Governance-Action", tc.intent)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("%s %s got %d want %d: %s", tc.method, tc.body, w.Code, tc.status, w.Body.String())
|
||||
}
|
||||
}
|
||||
if spy.syncCalls != 1 || spy.key != "op-one" || spy.actor == "" {
|
||||
t.Fatal("invalid sync reached store or operator was not session-stamped")
|
||||
}
|
||||
req := httptest.NewRequest("GET", "/api/v1/qa-ops/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "mirror-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
var body struct {
|
||||
Data struct {
|
||||
Cache *qaopsmirror.Status `json:"cache"`
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &body) != nil || body.Data.Cache == nil || body.Data.Cache.Mode != "local" {
|
||||
t.Fatal("local serving mode missing from status")
|
||||
}
|
||||
}
|
||||
func TestQAMirrorSyncNamespaceCannotBypassEntry(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["mirror-admin"] = "usr-boss"
|
||||
h, _ := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
|
||||
req := httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(`{"type":"qaops.records.sync.fixture","payload":{},"idempotency_key":"bypass"}`))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "mirror-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("generic jobs endpoint bypassed mirror sync admission", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
_ "time/tzdata"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type monthlyFilter struct {
|
||||
Month, Region, Department, Activity, Search string
|
||||
Start, End, MonthEnd time.Time
|
||||
Page, Limit int
|
||||
}
|
||||
type monthlyPerson struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
Region string `json:"region"`
|
||||
Departments []string `json:"departments"`
|
||||
Questions int64 `json:"questions"`
|
||||
Succeeded int64 `json:"succeeded"`
|
||||
Failed int64 `json:"failed"`
|
||||
Other int64 `json:"other"`
|
||||
}
|
||||
type monthlyDepartment struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
type monthlyPeople struct {
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
Source string `json:"source"`
|
||||
Timezone string `json:"timezone"`
|
||||
Month string `json:"month"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
MonthEnd time.Time `json:"month_end"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
Partial bool `json:"partial"`
|
||||
Questions int64 `json:"questions"`
|
||||
LinkedQuestions int64 `json:"linked_questions"`
|
||||
UnresolvedQuestions int64 `json:"unresolved_questions"`
|
||||
RosterPeople int `json:"roster_people"`
|
||||
UsedPeople int `json:"used_people"`
|
||||
ZeroPeople int `json:"zero_people"`
|
||||
MissingNames int `json:"missing_names"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
HasMore bool `json:"has_more"`
|
||||
Rows []monthlyPerson `json:"rows"`
|
||||
DepartmentOptions []monthlyDepartment `json:"department_options"`
|
||||
}
|
||||
|
||||
func parseMonthlyFilter(values url.Values, now time.Time) (monthlyFilter, error) {
|
||||
f := monthlyFilter{Month: values.Get("month"), Region: values.Get("region"), Department: values.Get("department_id"), Activity: values.Get("activity"), Search: values.Get("search"), Page: 1, Limit: 30}
|
||||
allowed := map[string]bool{"month": true, "cutoff": true, "region": true, "department_id": true, "activity": true, "search": true, "page": true, "limit": true, "directory_id": true, "revision_id": true}
|
||||
for key, v := range values {
|
||||
if !allowed[key] || len(v) != 1 {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
}
|
||||
loc, err := time.LoadLocation("Asia/Shanghai")
|
||||
if err != nil {
|
||||
return f, dobotaiops.ErrUnavailable
|
||||
}
|
||||
f.Start, err = time.ParseInLocation("2006-01", f.Month, loc)
|
||||
if err != nil || len(f.Month) != 7 || f.Start.Year() < 1 || f.Start.Format("2006-01") != f.Month || !f.Start.Before(now) {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
f.MonthEnd = f.Start.AddDate(0, 1, 0)
|
||||
f.End = f.MonthEnd
|
||||
if now.Before(f.End) {
|
||||
f.End = now.In(loc)
|
||||
}
|
||||
if raw := values.Get("cutoff"); raw != "" {
|
||||
cutoff, e := time.Parse(time.RFC3339Nano, raw)
|
||||
if e != nil || !cutoff.After(f.Start) || cutoff.After(f.MonthEnd) || cutoff.After(now) {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
f.End = cutoff.In(loc)
|
||||
}
|
||||
if f.Activity == "" {
|
||||
f.Activity = "all"
|
||||
}
|
||||
if f.Activity != "all" && f.Activity != "used" && f.Activity != "zero" {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !utf8.ValidString(f.Region) || len(f.Region) > 256 || strings.TrimSpace(f.Region) != f.Region || strings.ContainsAny(f.Region, "\x00\r\n") {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !utf8.ValidString(f.Search) || utf8.RuneCountInString(f.Search) > 100 || strings.ContainsRune(f.Search, 0) {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
for key, target := range map[string]*int{"page": &f.Page, "limit": &f.Limit} {
|
||||
if raw := values.Get(key); raw != "" {
|
||||
n, e := strconv.Atoi(raw)
|
||||
if e != nil || n < 1 || n > 100000 {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
*target = n
|
||||
}
|
||||
}
|
||||
if f.Limit > 100 || f.Page > 1 && (!values.Has("directory_id") || !values.Has("revision_id")) {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
func monthlyHasDepartment(person qaopsorg.PersonAttribution, department string, parents map[string]string) bool {
|
||||
if department == "" {
|
||||
return true
|
||||
}
|
||||
for _, id := range person.DepartmentIDs {
|
||||
for cur := id; cur != ""; cur = parents[cur] {
|
||||
if cur == department {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func monthlyResult(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, f monthlyFilter) monthlyPeople {
|
||||
result := monthlyPeople{Organization: attributionVersion(p), Source: "2.0", Timezone: "Asia/Shanghai", Month: f.Month, Start: f.Start, End: f.End, MonthEnd: f.MonthEnd, AsOf: groups.AsOf, Partial: f.End.Before(f.MonthEnd), Page: f.Page, Limit: f.Limit, Rows: []monthlyPerson{}, DepartmentOptions: []monthlyDepartment{}}
|
||||
totals := map[string]dobotaiops.UsageGroup{}
|
||||
for _, group := range groups.Groups {
|
||||
result.Questions += group.Total
|
||||
person := p.Resolve(group.Identity.StaffID, group.Identity.UnionID)
|
||||
if person.PersonID == "" {
|
||||
result.UnresolvedQuestions += group.Total
|
||||
continue
|
||||
}
|
||||
n := totals[person.PersonID]
|
||||
n.Total += group.Total
|
||||
n.Succeeded += group.Succeeded
|
||||
n.Failed += group.Failed
|
||||
totals[person.PersonID] = n
|
||||
result.LinkedQuestions += group.Total
|
||||
}
|
||||
parents := map[string]string{}
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
parents[d.ID] = d.ParentID
|
||||
result.DepartmentOptions = append(result.DepartmentOptions, monthlyDepartment{ID: d.ID, Path: d.Path})
|
||||
}
|
||||
rows := []monthlyPerson{}
|
||||
people := p.Members()
|
||||
result.RosterPeople = len(people)
|
||||
search := strings.ToLower(f.Search)
|
||||
for _, person := range people {
|
||||
n := totals[person.PersonID]
|
||||
if n.Total > 0 {
|
||||
result.UsedPeople++
|
||||
} else {
|
||||
result.ZeroPeople++
|
||||
}
|
||||
if person.Name == "" {
|
||||
result.MissingNames++
|
||||
}
|
||||
if f.Region != "" && f.Region != person.Region && f.Region != person.State {
|
||||
continue
|
||||
}
|
||||
if !monthlyHasDepartment(person, f.Department, parents) {
|
||||
continue
|
||||
}
|
||||
if f.Activity == "used" && n.Total == 0 || f.Activity == "zero" && n.Total > 0 {
|
||||
continue
|
||||
}
|
||||
if search != "" && !strings.Contains(strings.ToLower(person.Name), search) && !strings.Contains(strings.ToLower(strings.Join(person.Departments, ";")), search) {
|
||||
continue
|
||||
}
|
||||
// This is a stable row key, not an anonymisation claim or a new user identifier.
|
||||
sum := sha256.Sum256([]byte(p.Metadata.DirectoryID + "\x00" + person.PersonID))
|
||||
rows = append(rows, monthlyPerson{Key: "person-" + hex.EncodeToString(sum[:]), Name: person.Name, State: person.State, Region: person.Region, Departments: person.Departments, Questions: n.Total, Succeeded: n.Succeeded, Failed: n.Failed, Other: n.Total - n.Succeeded - n.Failed})
|
||||
}
|
||||
sort.Slice(rows, func(i, j int) bool {
|
||||
a, b := rows[i], rows[j]
|
||||
if a.Name == "" && b.Name != "" {
|
||||
return false
|
||||
}
|
||||
if a.Name != "" && b.Name == "" {
|
||||
return true
|
||||
}
|
||||
if a.Name != b.Name {
|
||||
return a.Name < b.Name
|
||||
}
|
||||
return a.Key < b.Key
|
||||
})
|
||||
result.Total = len(rows)
|
||||
start := (f.Page - 1) * f.Limit
|
||||
if start < len(rows) {
|
||||
end := min(start+f.Limit, len(rows))
|
||||
result.Rows = rows[start:end]
|
||||
result.HasMore = end < len(rows)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Names remain in the bounded read-query body, not URLs/access logs. The source
|
||||
// reader and governance store are still strictly read-only on this route.
|
||||
func monthlyRequestValues(w http.ResponseWriter, r *http.Request) (url.Values, error) {
|
||||
values := url.Values{}
|
||||
if r.URL.RawQuery != "" || r.Header.Get("X-Governance-Action") != "qa-usage-read" {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8192))
|
||||
token, err := decoder.Token()
|
||||
if err != nil || token != json.Delim('{') {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
for decoder.More() {
|
||||
token, err = decoder.Token()
|
||||
key, ok := token.(string)
|
||||
if err != nil || !ok || values.Has(key) {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
var raw json.RawMessage
|
||||
if decoder.Decode(&raw) != nil || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if key == "page" || key == "limit" {
|
||||
var n int
|
||||
if json.Unmarshal(raw, &n) != nil {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
values.Set(key, strconv.Itoa(n))
|
||||
} else {
|
||||
var text string
|
||||
if json.Unmarshal(raw, &text) != nil {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
values.Set(key, text)
|
||||
}
|
||||
}
|
||||
if _, err = decoder.Token(); err != nil {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
var extra any
|
||||
if decoder.Decode(&extra) != io.EOF {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
func qaMonthlyPeople(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
values, err := monthlyRequestValues(w, r)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
f, err := parseMonthlyFilter(values, config.Now())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
p, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
if p.Metadata.State != "ready" {
|
||||
writeJSON(w, 409, map[string]string{"code": "directory_missing", "error": "尚无完整通讯录,请先从区域使用页同步;不能生成零记录人员名单"})
|
||||
return
|
||||
}
|
||||
|
||||
if values.Has("directory_id") || values.Has("revision_id") {
|
||||
if !values.Has("directory_id") || !values.Has("revision_id") {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
if values.Get("directory_id") != p.Metadata.DirectoryID || values.Get("revision_id") != p.Metadata.RevisionID {
|
||||
writeJSON(w, 409, map[string]string{"code": "organization_changed", "error": "通讯录或区域配置已变化,请重新查询个人月明细"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Region != "" && f.Region != "unassigned" && f.Region != "cross_region" {
|
||||
found := false
|
||||
for _, name := range p.Metadata.RegionLabels() {
|
||||
found = found || f.Region == name
|
||||
}
|
||||
if !found {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Department != "" {
|
||||
found := false
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
found = found || d.ID == f.Department
|
||||
}
|
||||
if !found {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
reader, ok := config.QAOps.(qaUsageReader)
|
||||
if !ok || config.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
groups, err := reader.ReadUsageGroups(r.Context(), dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: config.QAOpsTenantKey, Start: f.Start, End: f.End}})
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": monthlyResult(groups, p, f)})
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type monthlyReaderSpy struct {
|
||||
attributedReader
|
||||
query dobotaiops.RecordQuery
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *monthlyReaderSpy) ReadUsageGroups(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) {
|
||||
s.calls++
|
||||
s.query = q
|
||||
return s.attributedReader.ReadUsageGroups(ctx, q)
|
||||
}
|
||||
func monthlyRequest(h http.Handler, path, token string) *httptest.ResponseRecorder {
|
||||
u, _ := url.Parse(path)
|
||||
body := map[string]any{}
|
||||
for k, v := range u.Query() {
|
||||
if len(v) != 1 {
|
||||
body[k] = v
|
||||
continue
|
||||
}
|
||||
if k == "page" || k == "limit" {
|
||||
if n, e := strconv.Atoi(v[0]); e == nil {
|
||||
body[k] = n
|
||||
} else {
|
||||
body[k] = v[0]
|
||||
}
|
||||
} else {
|
||||
body[k] = v[0]
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(body)
|
||||
r := httptest.NewRequest(http.MethodPost, u.Path, bytes.NewReader(raw))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("X-Governance-Action", "qa-usage-read")
|
||||
if token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func monthlyHandler(t *testing.T) (http.Handler, *attributionOrgSpy, *monthlyReaderSpy) {
|
||||
t.Helper()
|
||||
d := qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "示例根"}, {ID: "child", ParentID: "root", Name: "子部门"}}, People: []qaopsorg.Person{{ID: "fixture-private-staff", Name: "同名示例", UnionID: "fixture-private-union", DepartmentIDs: []string{"root"}}, {ID: "private-zero", Name: "同名示例", DepartmentIDs: []string{"child"}}, {ID: "private-cross", Name: "跨区域示例", DepartmentIDs: []string{"root", "child"}}, {ID: "private-unnamed", DepartmentIDs: []string{"child"}}}}
|
||||
now := time.Date(2026, 10, 17, 8, 0, 0, 0, time.UTC)
|
||||
p, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "monthly-directory", DirectorySource: "weekly_report_live", DirectorySyncedAt: &now, RevisionID: "monthly-regions", Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "国内工业"}, {DepartmentID: "child", Region: "APAC"}}}, d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
org := &attributionOrgSpy{projection: p}
|
||||
reader := &monthlyReaderSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["attribution-admin"] = "usr-boss"
|
||||
auth.sessions["attribution-viewer"] = "usr-eye"
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixed", QAOrg: org, Now: func() time.Time { return now }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h, org, reader
|
||||
}
|
||||
func TestQAMonthlyPeopleIncludesZeroUseAndKeepsUnresolvedEvents(t *testing.T) {
|
||||
h, _, reader := monthlyHandler(t)
|
||||
path := "/api/v1/qa-ops/usage/people?month=2026-10&limit=2"
|
||||
w := monthlyRequest(h, path, "attribution-admin")
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
var result struct {
|
||||
Data struct {
|
||||
Month string
|
||||
Timezone string
|
||||
Partial bool
|
||||
Questions int64
|
||||
LinkedQuestions int64 `json:"linked_questions"`
|
||||
UnresolvedQuestions int64 `json:"unresolved_questions"`
|
||||
RosterPeople int `json:"roster_people"`
|
||||
UsedPeople int `json:"used_people"`
|
||||
ZeroPeople int `json:"zero_people"`
|
||||
MissingNames int `json:"missing_names"`
|
||||
Total int
|
||||
HasMore bool `json:"has_more"`
|
||||
Rows []struct {
|
||||
Key string
|
||||
Name string
|
||||
Questions int64
|
||||
State string
|
||||
}
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
||||
t.Fatal("invalid monthly JSON")
|
||||
}
|
||||
v := result.Data
|
||||
if v.Month != "2026-10" || v.Timezone != "Asia/Shanghai" || !v.Partial || v.Questions != 7 || v.LinkedQuestions != 5 || v.UnresolvedQuestions != 2 || v.RosterPeople != 4 || v.UsedPeople != 1 || v.ZeroPeople != 3 || v.MissingNames != 1 || v.Total != 4 || len(v.Rows) != 2 || !v.HasMore {
|
||||
t.Fatal("monthly roster, zero count or alias dedup wrong", w.Body.String())
|
||||
}
|
||||
if reader.query.Window.TenantKey != "fixed" || reader.query.Window.Start.Format(time.RFC3339) != "2026-10-01T00:00:00+08:00" || reader.query.Window.End.Format(time.RFC3339) != "2026-10-17T16:00:00+08:00" {
|
||||
t.Fatal("month was not normalized to the named timezone")
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "private-") || strings.Contains(w.Body.String(), "performance") || strings.Contains(w.Body.String(), "staff_id") {
|
||||
t.Fatal("raw identities or unapproved verdict exposed")
|
||||
}
|
||||
page2 := monthlyRequest(h, path+"&page=2&directory_id=monthly-directory&revision_id=monthly-regions", "attribution-admin")
|
||||
if page2.Code != 200 {
|
||||
t.Fatal(page2.Body.String())
|
||||
}
|
||||
for _, extra := range []string{"&activity=zero", "®ion=cross_region", "&department_id=child", "&search=" + url.QueryEscape("子部门")} {
|
||||
r := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2026-10"+extra, "attribution-admin")
|
||||
if r.Code != 200 {
|
||||
t.Fatal("valid monthly filter failed", r.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestQAMonthlyScopeAndVersionFailClosed(t *testing.T) {
|
||||
h, org, reader := monthlyHandler(t)
|
||||
base := "/api/v1/qa-ops/usage/people?month=2026-10"
|
||||
for _, tc := range []struct {
|
||||
suffix, token string
|
||||
status int
|
||||
}{{"", "", 401}, {"", "attribution-viewer", 403}, {"&tenant=forged", "attribution-admin", 400}, {"&threshold=5", "attribution-admin", 400}, {"&month=duplicate", "attribution-admin", 400}, {"&page=0", "attribution-admin", 400}, {"&limit=101", "attribution-admin", 400}, {"&activity=under5", "attribution-admin", 400}, {"®ion=invalid", "attribution-admin", 400}, {"&department_id=invalid", "attribution-admin", 400}, {"&page=2", "attribution-admin", 400}, {"&page=2&directory_id=changed&revision_id=monthly-regions", "attribution-admin", 409}, {"&cutoff=2026-11-01T00:00:00Z", "attribution-admin", 400}} {
|
||||
w := monthlyRequest(h, base+tc.suffix, tc.token)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("monthly %s: %d want %d", tc.suffix, w.Code, tc.status)
|
||||
}
|
||||
}
|
||||
for _, month := range []string{"2026-1", " 2026-10", "2026-13", "0000-01", "2026-11"} {
|
||||
r := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month="+url.QueryEscape(month), "attribution-admin")
|
||||
if r.Code != 400 {
|
||||
t.Fatal("invalid/future month accepted")
|
||||
}
|
||||
}
|
||||
if reader.calls != 0 {
|
||||
t.Fatal("invalid or unauthorized monthly request reached source")
|
||||
}
|
||||
org.projection, _ = qaopsorg.BuildAttribution(qaopsorg.State{State: "empty"}, qaopsorg.Directory{})
|
||||
if w := monthlyRequest(h, base, "attribution-admin"); w.Code != 409 {
|
||||
t.Fatal("no roster presented as zero-use list")
|
||||
}
|
||||
org.err = qaopsorg.ErrUnavailable
|
||||
if w := monthlyRequest(h, base, "attribution-admin"); w.Code != 503 {
|
||||
t.Fatal("store failure hidden as empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAMonthlyPersonFiltersDoNotGuessNamesOrDuplicateDescendantMembers(t *testing.T) {
|
||||
h, _, _ := monthlyHandler(t)
|
||||
for _, tc := range []struct {
|
||||
filter string
|
||||
total int
|
||||
}{{"&activity=used", 1}, {"&activity=zero", 3}, {"®ion=cross_region", 1}, {"®ion=APAC", 2}, {"&department_id=child", 3}, {"&department_id=root", 4}, {"&search=" + url.QueryEscape("同名示例"), 2}, {"&search=" + url.QueryEscape("子部门"), 3}, {"&search=%25_", 0}} {
|
||||
w := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2026-10"+tc.filter, "attribution-admin")
|
||||
var payload struct{ Data monthlyPeople }
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &payload) != nil || payload.Data.Total != tc.total || payload.Data.Questions != 7 {
|
||||
t.Fatal("person-scope filter did not preserve source totals or person dedup", tc.filter)
|
||||
}
|
||||
for _, r := range payload.Data.Rows {
|
||||
if tc.filter == "&activity=zero" && r.Questions != 0 {
|
||||
t.Fatal("used member labeled zero")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestQAMonthlyReadBodyRejectsDuplicateNullTrailingAndOversizedInput(t *testing.T) {
|
||||
h, _, reader := monthlyHandler(t)
|
||||
for _, body := range []string{`{"month":"2026-10","month":"2026-10"}`, `{"month":"2026-10","search":null}`, `{"month":"2026-10","page":"1"}`, `{"month":"2026-10"}{}`, `[]`, `{"month":"2026-10","search":"` + strings.Repeat("x", 9000) + `"}`} {
|
||||
r := httptest.NewRequest("POST", "/api/v1/qa-ops/usage/people", strings.NewReader(body))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "attribution-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-usage-read")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("invalid read body reached source", w.Code)
|
||||
}
|
||||
}
|
||||
for _, method := range []string{"POST", "GET"} {
|
||||
r := httptest.NewRequest(method, "/api/v1/qa-ops/usage/people?search=sensitive-example", strings.NewReader(`{"month":"2026-10"}`))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "attribution-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 400 && w.Code != 405 {
|
||||
t.Fatal("URL-based name query accepted")
|
||||
}
|
||||
}
|
||||
if reader.calls != 0 {
|
||||
t.Fatal("invalid body read production source")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAMonthlyPastLeapMonthUsesClosedCalendarWindow(t *testing.T) {
|
||||
h, _, reader := monthlyHandler(t)
|
||||
w := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2024-02", "attribution-admin")
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
if reader.query.Window.End.Format(time.RFC3339) != "2024-03-01T00:00:00+08:00" || reader.query.Window.End.Sub(reader.query.Window.Start) != 29*24*time.Hour {
|
||||
t.Fatal("leap month boundary incorrect")
|
||||
}
|
||||
var raw struct{ Data struct{ Partial bool } }
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &raw)
|
||||
if raw.Data.Partial {
|
||||
t.Fatal("past natural month mislabeled as current progress")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
)
|
||||
|
||||
// No raw SQL, source credential, arbitrary tenant or write method crosses this boundary.
|
||||
type QAOpsReader interface {
|
||||
ListRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error)
|
||||
GetRecord(context.Context, string, string) (dobotaiops.Record, error)
|
||||
Available(context.Context) error
|
||||
Safety() dobotaiops.SourceSafety
|
||||
}
|
||||
|
||||
func authorizeQAOps(w http.ResponseWriter, r *http.Request) bool {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "问答运营需要登录后访问"})
|
||||
return false
|
||||
}
|
||||
// Until the employee-data visibility scope is approved, do not widen access
|
||||
// to all pre-existing viewers/engineers merely because this endpoint is GET.
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "尚未配置员工问答可见范围,当前仅管理员可访问"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func qaOpsStatus(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
state := "disabled"
|
||||
code := "source_not_configured"
|
||||
warnings := []string{}
|
||||
if config.QAOpsEnabled {
|
||||
state = "unavailable"
|
||||
code = "source_unavailable"
|
||||
}
|
||||
if config.QAOpsProblem != "" {
|
||||
state = "blocked"
|
||||
code = "source_configuration_invalid"
|
||||
}
|
||||
if config.QAOps != nil && config.QAOps.Available(r.Context()) == nil {
|
||||
state = "connected"
|
||||
code = ""
|
||||
safety := config.QAOps.Safety()
|
||||
if safety.DatabaseTemp {
|
||||
warnings = append(warnings, "database_temp_enabled")
|
||||
}
|
||||
if !safety.SSL {
|
||||
warnings = append(warnings, "database_transport_unencrypted")
|
||||
}
|
||||
}
|
||||
data := map[string]any{"state": state, "code": code, "warnings": warnings, "read_only": true, "source_version": "2.0", "channel": "dingtalk"}
|
||||
if mirror, ok := config.QAOps.(qaMirrorSyncStore); ok {
|
||||
cache, err := mirror.GetSyncStatus(r.Context())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
data["cache"] = cache
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": data})
|
||||
}
|
||||
|
||||
func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if config.QAOps == nil || config.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
values := r.URL.Query()
|
||||
allowed := map[string]bool{"start": true, "end": true, "keyword": true, "cursor": true, "limit": true, "projection": true}
|
||||
for _, key := range dobotaiops.QualityFilterKeys {
|
||||
allowed[key] = true
|
||||
}
|
||||
for key, items := range values {
|
||||
if !allowed[key] || len(items) != 1 {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
window, err := dobotaiops.NewWindow(config.QAOpsTenantKey, values.Get("start"), values.Get("end"), 90*24*time.Hour, config.Now())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
limit := 20
|
||||
if raw := values.Get("limit"); raw != "" {
|
||||
limit, err = strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > 100 {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
filters := map[string]string{}
|
||||
for _, key := range dobotaiops.QualityFilterKeys {
|
||||
if value := values.Get(key); value != "" {
|
||||
filters[key] = value
|
||||
}
|
||||
}
|
||||
if !dobotaiops.ValidQualityFilters(filters) {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
mode := values.Get("projection")
|
||||
if mode != "" && mode != "summary" && mode != "full" {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
projection, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
page, err := config.QAOps.ListRecords(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword"), Cursor: values.Get("cursor"), Limit: limit, Summary: mode == "summary", Filters: filters})
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
enrichQAPage(&page, projection)
|
||||
if err := enrichQAQualityPage(r.Context(), config, &page); err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
if mode == "summary" {
|
||||
for i := range page.Items {
|
||||
page.Items[i] = qaRecordPreview(page.Items[i])
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": page})
|
||||
}
|
||||
|
||||
func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if config.QAOps == nil || config.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
projection, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
item, err := config.QAOps.GetRecord(r.Context(), config.QAOpsTenantKey, r.PathValue("id"))
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
enrichQARecord(&item, projection)
|
||||
if err := enrichQAQualityRecord(r.Context(), config, &item); err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": item})
|
||||
}
|
||||
|
||||
func qaOpsError(w http.ResponseWriter, err error) {
|
||||
status := http.StatusServiceUnavailable
|
||||
code := "source_unavailable"
|
||||
message := "问答记录当前不可用;本地模式请检查同步状态,原有知识治理功能不受影响"
|
||||
if errors.Is(err, errQAOrganization) {
|
||||
code = "organization_unavailable"
|
||||
message = "通讯录或区域配置读取失败,未将不可用数据伪装成空列,请重试"
|
||||
}
|
||||
if errors.Is(err, dobotaiops.ErrInvalidQuery) {
|
||||
status = http.StatusBadRequest
|
||||
code = "invalid_query"
|
||||
message = "查询参数无效:请检查时间范围、关键词长度或重新查询后翻页"
|
||||
}
|
||||
if errors.Is(err, dobotaiops.ErrNotReadOnly) {
|
||||
code = "source_not_read_only"
|
||||
message = "问答连接权限校验未通过,已阻止读取,请联系管理员"
|
||||
}
|
||||
if errors.Is(err, dobotaiops.ErrRecordNotFound) {
|
||||
status = http.StatusNotFound
|
||||
code = "record_not_found"
|
||||
message = "未找到当前授权范围内的问答记录"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message, "code": code})
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type qaOpsSpy struct {
|
||||
query dobotaiops.RecordQuery
|
||||
tenant, id string
|
||||
calls int
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *qaOpsSpy) ListRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
s.query = q
|
||||
s.calls++
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{}}, s.err
|
||||
}
|
||||
func (s *qaOpsSpy) GetRecord(_ context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
s.tenant = tenant
|
||||
s.id = id
|
||||
s.calls++
|
||||
return dobotaiops.Record{}, s.err
|
||||
}
|
||||
func (s *qaOpsSpy) Available(context.Context) error { return s.err }
|
||||
func (s *qaOpsSpy) Safety() dobotaiops.SourceSafety {
|
||||
return dobotaiops.SourceSafety{DatabaseTemp: true, SSL: false}
|
||||
}
|
||||
|
||||
func TestQAOperationsRequireExplicitSessionAndServerSelectedTenant(t *testing.T) {
|
||||
spy := &qaOpsSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
for token, user := range map[string]string{"admin-qa-fixture": "usr-boss", "viewer-qa-fixture": "usr-eye", "engineer-qa-fixture": "usr-eng"} {
|
||||
auth.sessions[token] = user
|
||||
}
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsEnabled: true, QAOpsTenantKey: "approved-tenant", Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z"
|
||||
for _, tc := range []struct {
|
||||
token, path string
|
||||
status int
|
||||
}{
|
||||
{"", base, http.StatusUnauthorized}, {"viewer-qa-fixture", base, http.StatusForbidden}, {"engineer-qa-fixture", base, http.StatusForbidden},
|
||||
{"admin-qa-fixture", base + "&tenant_key=another-tenant", http.StatusBadRequest},
|
||||
{"admin-qa-fixture", base + "&limit=0", http.StatusBadRequest},
|
||||
{"admin-qa-fixture", base + "&keyword=a&keyword=b", http.StatusBadRequest},
|
||||
{"admin-qa-fixture", base + "&keyword=test", http.StatusOK},
|
||||
} {
|
||||
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
|
||||
if tc.token != "" {
|
||||
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != tc.status {
|
||||
t.Fatalf("status=%d want=%d body=%s", response.Code, tc.status, response.Body.String())
|
||||
}
|
||||
}
|
||||
if spy.calls != 1 || spy.query.Window.TenantKey != "approved-tenant" || spy.query.Keyword != "test" {
|
||||
t.Fatalf("unauthorized/invalid reads reached source: %+v", spy)
|
||||
}
|
||||
spy.err = errors.New("sensitive-driver-detail-not-for-browser")
|
||||
request := httptest.NewRequest(http.MethodGet, base, nil)
|
||||
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusServiceUnavailable || strings.Contains(response.Body.String(), "sensitive-driver-detail") {
|
||||
t.Fatalf("source failure leaked or became empty success: %s", response.Body.String())
|
||||
}
|
||||
if response.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("employee answers must not be cached")
|
||||
}
|
||||
unauth, _ := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsTenantKey: "approved-tenant"})
|
||||
response = httptest.NewRecorder()
|
||||
unauth.ServeHTTP(response, httptest.NewRequest(http.MethodGet, base, nil))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatal("auth-disabled governance must not expose production answers")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAOperationsRoleGatePrecedesGenericGETShortcut(t *testing.T) {
|
||||
for _, path := range []string{"/api/v1/qa-ops/status", "/api/v1/qa-ops/records", "/api/v1/qa-ops/records/some-id"} {
|
||||
if role := classifyRole(http.MethodGet, path); role != roleAdmin {
|
||||
t.Fatalf("QA employee data route classified as %s, must require admin: %s", role, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAOperationsFailClosedWithoutBreakingGovernance(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["admin-qa-fixture"] = "usr-boss"
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", nil)
|
||||
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("unconfigured source must not be an empty list: status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
health := httptest.NewRecorder()
|
||||
handler.ServeHTTP(health, httptest.NewRequest(http.MethodGet, "/livez", nil))
|
||||
if health.Code != http.StatusOK {
|
||||
t.Fatalf("external source must not stop governance liveness: %d", health.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type QAOrgStore interface {
|
||||
GetView(context.Context) (qaopsorg.State, error)
|
||||
PreviewRules(context.Context, qaopsorg.SaveRequest) (qaopsorg.State, error)
|
||||
SaveRules(context.Context, qaopsorg.SaveRequest, string) (qaopsorg.State, error)
|
||||
}
|
||||
|
||||
func qaOrganization(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if config.QAOrg == nil {
|
||||
writeOrgError(w, qaopsorg.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
var result qaopsorg.State
|
||||
var err error
|
||||
if r.Method == http.MethodGet {
|
||||
result, err = config.QAOrg.GetView(r.Context())
|
||||
} else {
|
||||
if !authorizeQAOrganizationWrite(w, r) {
|
||||
return
|
||||
}
|
||||
var request qaopsorg.SaveRequest
|
||||
raw, readErr := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
var fields map[string]json.RawMessage
|
||||
var extra any
|
||||
invalidJSON := readErr != nil || json.Unmarshal(raw, &fields) != nil || fields == nil || fields["base_revision"] == nil || walkQualityJSON(check) != nil || check.Decode(&extra) != io.EOF
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if invalidJSON || decoder.Decode(&request) != nil || decoder.Decode(&extra) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
result, err = config.QAOrg.PreviewRules(r.Context(), request)
|
||||
} else {
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
result, err = config.QAOrg.SaveRules(r.Context(), request, identity.Username)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
}
|
||||
func writeOrgError(w http.ResponseWriter, err error) {
|
||||
status, message := 503, "通讯录或区域配置存储不可用,未展示为空数据"
|
||||
switch {
|
||||
case errors.Is(err, qaopsorg.ErrInvalid):
|
||||
status, message = 400, "部门树或区域配置无效,请核对重复、缺失路径及区域"
|
||||
case errors.Is(err, qaopsorg.ErrConflict):
|
||||
status, message = 409, "通讯录或区域配置已变化,请重新读取后预览"
|
||||
case errors.Is(err, qaopsorg.ErrNoDirectory):
|
||||
status, message = 409, "尚无完整通讯录快照,不能保存区域配置"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAOrganizationSameOriginThroughReverseProxy(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["org-proxy-admin"] = "usr-boss"
|
||||
spy := &orgSpy{}
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, QAOrg: spy, Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
site string
|
||||
status int
|
||||
}{{"same-origin", 200}, {"cross-site", 403}, {"same-site", 403}} {
|
||||
req := httptest.NewRequest("PUT", "http://internal-api:8080/api/v1/qa-ops/organization/regions", strings.NewReader(`{"directory_id":"d","base_revision":"","rules":[]}`))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "org-proxy-admin"})
|
||||
req.Header.Set("X-Governance-Action", "qa-organization")
|
||||
req.Header.Set("Origin", "http://frontend:8088")
|
||||
req.Header.Set("Sec-Fetch-Site", tc.site)
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
if res.Code != tc.status {
|
||||
t.Fatalf("proxy fetch site %s got %d want %d", tc.site, res.Code, tc.status)
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user