Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0cc3cac837 | |||
| e4342fa05b | |||
| 040b7285d7 |
@@ -1,82 +0,0 @@
|
||||
name: deploy-production
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
action:
|
||||
description: deploy 或 writeback
|
||||
required: true
|
||||
default: deploy
|
||||
sha:
|
||||
description: 验收过的完整提交 SHA
|
||||
required: true
|
||||
bundle:
|
||||
description: release.json 的完整 SHA256
|
||||
required: true
|
||||
task:
|
||||
description: 对应的 HiFox 任务 UUID
|
||||
required: true
|
||||
confirm:
|
||||
description: deploy-production 或 retry-writeback
|
||||
required: true
|
||||
approval_event:
|
||||
description: HiFox 自动触发填写的状态事件 UUID
|
||||
required: false
|
||||
acceptance_digest:
|
||||
description: HiFox 自动触发填写的验收记录摘要
|
||||
required: false
|
||||
|
||||
concurrency:
|
||||
group: cloud-test-governance-main-production
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
guard:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: 核对手动入口及发布输入
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
test "$GITHUB_REF" = refs/heads/main
|
||||
case "$GITHUB_SERVER_URL" in
|
||||
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
git init -q .
|
||||
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
|
||||
git checkout -q --detach "$GITHUB_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
python3 scripts/production_cd.py guard --event "$GITHUB_EVENT_PATH"
|
||||
|
||||
publish:
|
||||
needs: [guard]
|
||||
runs-on: kg-production-cd
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- name: 取同一提交的控制端代码
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
test "$GITHUB_REF" = refs/heads/main
|
||||
case "$GITHUB_SERVER_URL" in
|
||||
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
git init -q .
|
||||
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
|
||||
git checkout -q --detach "$GITHUB_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
- name: 调用云主站受限发布入口并读回回执
|
||||
env:
|
||||
KG_CD_SSH_KEY: ${{ secrets.KG_CD_SSH_KEY }}
|
||||
KG_CD_KNOWN_HOSTS: ${{ secrets.KG_CD_KNOWN_HOSTS }}
|
||||
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
|
||||
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
|
||||
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
|
||||
@@ -1,80 +0,0 @@
|
||||
name: prepare-candidate
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
plan:
|
||||
description: 'Release task UUID, exact SHA, baseline, requirement PRs and additional reviewed commits (JSON)'
|
||||
required: true
|
||||
mode:
|
||||
description: 'verify or prepare'
|
||||
required: true
|
||||
default: verify
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: knowledge-governance-candidate
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
guard:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Verify release scope and CI
|
||||
env:
|
||||
KG_CANDIDATE_READ_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
case "$GITHUB_SERVER_URL" in
|
||||
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
case "$GITHUB_REF" in refs/heads/*) ;; *) exit 1 ;; esac
|
||||
git init -q .
|
||||
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
|
||||
auth() { git -c credential.helper='!f() { printf "username=x-access-token\npassword=%s\n" "$KG_CANDIDATE_READ_TOKEN"; }; f' "$@"; }
|
||||
auth fetch -q origin "$GITHUB_REF" +refs/heads/main:refs/remotes/origin/main
|
||||
git checkout --detach -q "$GITHUB_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
export KG_CANDIDATE_FORGE="$GITHUB_SERVER_URL"
|
||||
python3 scripts/candidate_release.py guard --event "$GITHUB_EVENT_PATH" --repo .
|
||||
|
||||
prepare:
|
||||
if: ${{ inputs.mode == 'prepare' && gitea.ref == 'refs/heads/main' }}
|
||||
needs: [guard]
|
||||
runs-on: kg-candidate
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Build and deploy isolated candidate
|
||||
env:
|
||||
KG_CANDIDATE_ACCESS: ${{ secrets.KG_CANDIDATE_ACCESS }}
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REF" = refs/heads/main
|
||||
test -n "$KG_CANDIDATE_ACCESS"
|
||||
python3 - <<'PY'
|
||||
import json, os, sys
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import ProxyHandler, Request, build_opener
|
||||
with open(os.environ['GITHUB_EVENT_PATH']) as source:
|
||||
event = json.load(source)
|
||||
if event.get('inputs', {}).get('mode') != 'prepare':
|
||||
sys.exit('candidate workflow mode is not prepare')
|
||||
data = json.dumps({'run': os.environ['GITHUB_RUN_ID'], 'plan': json.loads(event['inputs']['plan'])}).encode()
|
||||
request = Request('http://127.0.0.1:38984/prepare', data=data, headers={
|
||||
'Authorization': 'Bearer ' + os.environ['KG_CANDIDATE_ACCESS'], 'Content-Type': 'application/json'})
|
||||
opener = build_opener(ProxyHandler({}))
|
||||
try:
|
||||
with opener.open(request, timeout=2540) as response:
|
||||
print(response.read(65536).decode())
|
||||
except HTTPError as exc:
|
||||
print(exc.read(4096).decode(), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
PY
|
||||
+2
-45
@@ -1,48 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.399(系统设置分区调整:AI 模型连接 / 知识库映射)
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
|
||||
- 原「系统设置 → 服务配置」改名为「AI 模型连接」,只保留问答四字段分析与中文翻译共用的
|
||||
模型连接(地址、模型、密钥操作、测试连接、保存),不再混放 WeKnora 连接。
|
||||
- WeKnora 测试/生产地址、生产租户与知识库 ID 迁到「知识库映射」,与测试入库、封存源、
|
||||
生产目标同屏;两个 ID 收进「生产核验参数」,并注明只用于核验、不决定发布写入目标。
|
||||
- 连接配置在独立组件内维护自己的草稿:保存只提交连接的四项,刷新参数取服务器当前值;
|
||||
保存刷新策略也不会带上未保存的连接地址。
|
||||
- 凭据仍是服务器文件引用,连接卡只报状态,页面不提供 API Key 录入。
|
||||
- 同步更新 README、运维手册、验收清单中的入口路径。
|
||||
|
||||
## 开发快照 0.1.384(系统设置审查修复:能力心跳、封存源对照、分区合并)
|
||||
|
||||
### Added
|
||||
|
||||
- `GET /api/v1/system/worker-capabilities`:读取 worker 认领记录里的 job_types,
|
||||
页面据此显示“执行器已启用/已停用/无认领”,不再把 readiness 当成可接单。
|
||||
- 测试知识库绑定接口返回整库封存源与一致性状态,设置页同屏对照“入库目标 / 封存源”。
|
||||
|
||||
### Changed
|
||||
|
||||
- 系统设置分区合并为“知识库映射”(测试入库 + 生产目标 + 封存源对照)。
|
||||
- 服务卡片分三行:地址可达、凭据与库读取、执行器能力。
|
||||
|
||||
## 开发快照 0.1.383(发布管理精简 + 系统设置审查修复)
|
||||
|
||||
### Changed
|
||||
|
||||
- 发布管理:顶部改为「状态卡 + 下一步」,一个主按钮(启动同步/查看任务)+ 一个准备按钮
|
||||
(封存/基线/签发授权);启动条件、检查清单、恢复验证收进「发布前检查」;
|
||||
目标维护、差异明细、来源身份收进「高级与历史」。去掉重复的版本入口与说明。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 服务配置与刷新策略各自保存边界:保存一方不再夹带另一方未保存的草稿(F03)。
|
||||
- 系统设置分区独立加载:监控/目录失败不再挡住成员与备份入口;保存后重新探测服务状态(F09)。
|
||||
- 解析停滞阈值接入活动配置(worker 60 秒内生效),收尾超时仍只保存并在页面标注未接入(F02)。
|
||||
- 重置密码改为受控遮罩对话框,不再用浏览器 prompt(F11)。
|
||||
- 生产绑定:文档级旧配置收进折叠区,凭据缺失时说明不影响整库执行器(F05/F06)。
|
||||
- 备份:主机未接通时明确「当前计划不会执行」,无运行记录时失败库显示未知(F07)。
|
||||
- 文案统一:生产租户 ID、备份执行主机、收尾超时告警;技术细节不再占据主视图(F10)。
|
||||
- 发布管理按封存、授权、同步与查看任务切换主操作,合并重复入口;变更明细、完整性和恢复验证按需展开,维护占用与失败作业保持可见。流程说明见 [发布管理流程与页面精简](docs/release-ui-flow.md)。
|
||||
|
||||
## 开发快照 0.1.382(采集 agent 允许显式 peer uid)
|
||||
|
||||
@@ -2399,11 +2361,6 @@
|
||||
|
||||
### Added
|
||||
|
||||
- 数据源配置新增 PP API 地址、账号与密码更新、真实登录及目录连接检查;配置校验通过才生效,临时故障保留待验证修改,扫描与取件共用生效配置。
|
||||
- 钉钉添加来源统一使用 DWS 官方授权,增加真实空间校验、中途失效恢复与账号变化保护,取消登记自动回落旧扫码侧车;认证操作接入既有审计。
|
||||
|
||||
- 数据源配置新增 DWS 登录与重新授权入口,使用钉钉官方设备授权;成功后刷新账号并独立检查目录访问权限。支持取消、过期和重试,授权仅限发起的管理员会话。[操作说明](docs/DWS_LOGIN.md)
|
||||
|
||||
- 新增解析监控统一工作台:顶部运行指标与依赖卡片、下方单一文件处理表;来源文件与目标测试库归并最新版本,动作、阶段、状态分列,后端统一筛选、计数及分页。支持单条/跨页勾选重试和版本、失败、重试详情;测试库移除重试独立核验治理规则,不误走上传流程。取消六分页和手动开始入口,生产授权仍在发布管理;本次不改变后台自动调度策略,自动处理闭环需另行端到端验收。
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
+1
-2
@@ -51,7 +51,6 @@ RUN set -eux; \
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/ /app/
|
||||
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/dws_dingtalk_scan.py \
|
||||
scripts/pp_client.py scripts/artifact_fetch.py scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
|
||||
RUN chmod 0644 /app/scripts/*.py
|
||||
scripts/artifact_fetch.py scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
|
||||
USER 65532:65532
|
||||
CMD ["/app/api"]
|
||||
|
||||
@@ -27,14 +27,6 @@ BUILD_TIME ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
verify:
|
||||
$(PY) scripts/ci_checks.py
|
||||
|
||||
.PHONY: qa qa-doctor qa-self-test
|
||||
qa:
|
||||
$(PY) scripts/qa_env.py run
|
||||
qa-doctor:
|
||||
$(PY) scripts/qa_env.py doctor
|
||||
qa-self-test:
|
||||
$(PY) -m unittest discover -s scripts -p test_qa_env.py -v
|
||||
|
||||
# 清单:哪些是必需项、在哪个档案(local / ci)下必需
|
||||
list:
|
||||
$(PY) scripts/ci_checks.py --list
|
||||
|
||||
@@ -52,9 +52,9 @@ Knowledge Adapter / DobotAI 网关
|
||||
|
||||
| 来源 | 当前接入方式 | 参考文档 |
|
||||
| --- | --- | --- |
|
||||
| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [登录授权](docs/DWS_LOGIN.md) · [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) |
|
||||
| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) |
|
||||
| AList | 来源目录与资料获取,依赖指定连接和凭据 | [用户操作流程](docs/OPERATIONS_RUNBOOK.md) |
|
||||
| PP(资料门户) | 页面管理 API 与认证配置;真实校验、只读扫描及取件 | [认证配置](docs/SOURCE_AUTH_CONFIGURATION.md) · [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) |
|
||||
| PP(资料门户) | 本地清单、历史账本接管与只读扫描 | [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) |
|
||||
|
||||
IT、行政等是待扩展的业务资料范围,不是已经完成的新连接器。接入敏感资料前,需要先确认 Owner、有效版本、可见范围与知识库路由。
|
||||
|
||||
@@ -71,16 +71,15 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
|
||||
|
||||
## 访问与部署
|
||||
|
||||
### 运行架构与访问入口
|
||||
### 已部署环境
|
||||
|
||||
| 组件 | 职责 | 接手时从这里看 |
|
||||
|---|---|---|
|
||||
| React/Vite + Web Nginx | 提供静态页面,同源转发 `/api/` 和 `/health` | [前端开发代理](web/vite.config.ts)、[Compose 的 Nginx 配置](deploy/nginx.conf) |
|
||||
| Go API + 治理 PostgreSQL | 认证、角色、来源、绑定、审核、任务与发布记录。云测试使用独立逻辑库 `knowledge_governance_test` | [API](cmd/api)、[接口契约](api/openapi.yaml) |
|
||||
| 普通 worker + 测试 WeKnora | worker 取件、上传、轮询并记录验收结果。WeKnora 负责解析、切片和索引 | [worker](cmd/worker)、[来源接入](docs/OPERATIONS_RUNBOOK.md#接入外部平台) |
|
||||
| 发布 worker + 生产 WeKnora | 按已锁定的批次和目标执行受控发布与读回。问答端通过下游服务使用已发布知识 | [发布 worker](cmd/release-worker)、[操作手册](docs/OPERATIONS_RUNBOOK.md) |
|
||||
Compose 中网页入口固定映射为 **宿主机 `8088` → Web 容器 `8080`**。网页和 `/api/` 使用同源入口。
|
||||
|
||||
从自己的电脑做系统设置验收,使用 SSH 转发后的 `http://127.0.0.1:28189/`。云测试主控制台使用受限内网入口 `http://100.85.111.121:8088/`。仓内 Compose 则将宿主 `8088` 映射到 Web 容器 `8080`。选择入口时先确认要看的部署。隧道命令、生产 `090` 服务地址和 HTTPS 反代示例见[运维手册](docs/OPERATIONS_RUNBOOK.md#入口与反向代理)。
|
||||
- 本机访问:`http://127.0.0.1:8088/`
|
||||
- 局域网访问:`http://<服务器内网IP>:8088/`
|
||||
- 健康入口:`http://127.0.0.1:8088/health`
|
||||
|
||||
可以由 NAS 反向代理提供 HTTPS 域名入口,目标为平台服务器的 `8088`,保持路径原样转发。公网开放前必须验证鉴权、访问控制及转发头配置,不直接暴露数据库或内部管理接口。
|
||||
|
||||
**平台入口展示当前部署版本,不是每次 CI 的构建预览。** CI 静态预览由独立链路提供;CI 通过不会自动更新运行服务。
|
||||
|
||||
@@ -95,7 +94,13 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
|
||||
- 来源目录、spool 与运行状态挂载;按部署主机调整路径和 UID/GID。
|
||||
- 测试 WeKnora 连接与对内/对外路由;生产发布按独立配置和授权接线。
|
||||
|
||||
仓内 Compose 含 `postgres` 演练服务。云测试和生产使用阿里云 RDS,部署前先核对目标逻辑库、当前迁移版本、待运行的迁移及所用的环境配置。API 和 worker 启动可执行迁移。已有环境先用 `docker compose config --services` 检查服务清单,按该环境的发布手册切换已验证的产物。前端开发可直接使用下面的 Vite 流程。
|
||||
准备完成后,由获授权的操作者执行:
|
||||
|
||||
```bash
|
||||
docker compose up --build -d
|
||||
```
|
||||
|
||||
主机需要提权时,由操作者按本机权限规则执行,不在自动化中默认使用 sudo。停止服务可用 `docker compose down`;**不要执行 `docker compose down -v`,除非明确批准删除数据库卷。**
|
||||
|
||||
## 配置与安全边界
|
||||
|
||||
@@ -109,7 +114,7 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
|
||||
|
||||
## 开发与 CI
|
||||
|
||||
本机和 QA 虚拟机的依赖安装、前后端启动、测试命令及 PostgreSQL 测试库准备见 [开发与测试指南](docs/DEVELOPMENT_AND_TESTING.md)。
|
||||
基础环境:Go 1.26、Node.js 22、npm,以及检查脚本所需的 Python 3 和工具链。依赖以仓库锁文件和实际 CI 配置为准。
|
||||
|
||||
```bash
|
||||
make verify # 完整检查入口:本地与 CI 使用同一套规则
|
||||
@@ -122,7 +127,7 @@ make list # 查看检查清单与适用范围
|
||||
|
||||
## 问答运营模型配置
|
||||
|
||||
管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
管理员在「系统设置 → 服务配置 → 问答评估模型」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
|
||||
API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。
|
||||
|
||||
|
||||
@@ -2682,211 +2682,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/pp-connection": {
|
||||
"get": {
|
||||
"operationId": "getPPConnection",
|
||||
"summary": "管理员读取 PP 配置元数据及最近检查结果",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPConnectionView"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"operationId": "savePPConnection",
|
||||
"summary": "管理员保存并真实校验 PP 配置",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPConnectionView"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PPConnectionDraft"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/pp-connection/test": {
|
||||
"post": {
|
||||
"operationId": "testPPConnection",
|
||||
"summary": "管理员使用草稿真实登录并读取最小目录,不登记来源",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PPConnectionDraft"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/dingtalk-spaces/validate": {
|
||||
"post": {
|
||||
"operationId": "validateDingtalkSourceSpaces",
|
||||
"summary": "管理员用共享 DWS 身份真实检查所选空间可见性",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成"
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"urls"
|
||||
],
|
||||
"properties": {
|
||||
"urls": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/dingtalk-spaces": {
|
||||
"post": {
|
||||
"tags": [
|
||||
@@ -3639,26 +3434,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/system/worker-capabilities": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getWorkerCapabilities",
|
||||
"summary": "读取 worker 能力心跳(执行器是否注册上传/解析链)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/routing-bindings": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -6084,140 +5859,6 @@
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"PPConnectionDraft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"base_url",
|
||||
"username",
|
||||
"revision"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"base_url": {
|
||||
"type": "string",
|
||||
"format": "uri",
|
||||
"description": "HTTPS API 根地址"
|
||||
},
|
||||
"username": {
|
||||
"type": "string",
|
||||
"maxLength": 255
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"writeOnly": true,
|
||||
"maxLength": 8192,
|
||||
"description": "省略或空值保留已存密码"
|
||||
},
|
||||
"revision": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"pending_id": {
|
||||
"type": "string",
|
||||
"description": "继续校验已保存的待验证修改"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPSafeMetadata": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id",
|
||||
"base_url",
|
||||
"username",
|
||||
"password_configured"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"base_url": {
|
||||
"type": "string",
|
||||
"format": "uri"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
},
|
||||
"password_configured": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPObservation": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"state",
|
||||
"message",
|
||||
"checked_at"
|
||||
],
|
||||
"properties": {
|
||||
"state": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"valid",
|
||||
"auth_failed",
|
||||
"permission_denied",
|
||||
"incomplete",
|
||||
"unavailable",
|
||||
"invalid_response"
|
||||
]
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"checked_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPConnectionView": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"revision": {
|
||||
"type": "integer"
|
||||
},
|
||||
"active": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPSafeMetadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"pending": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPSafeMetadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"observation": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"pending_observation": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"QAReportedHistoricalRate": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
|
||||
+1
-16
@@ -21,7 +21,6 @@ import (
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
@@ -94,7 +93,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
// Production WeKnora is probed for liveness only: the console must show the
|
||||
// real state of that endpoint, while credentials and the publish target stay
|
||||
// in the release runtime config (RELEASE_CONFIG_FILE).
|
||||
// 生产 WeKnora 端点:配置入口在网页「系统设置 → 知识库映射」,管理员保存的值是
|
||||
// 生产 WeKnora 端点:配置入口在网页「系统设置 → 服务配置」,管理员保存的值是
|
||||
// 这里的真源;容器 env 只作为未在网页配置时的兜底。凭据与发布目标仍留在
|
||||
// release 运行时配置(RELEASE_CONFIG_FILE)里,不经网页也不落明文。
|
||||
actionStore := postgresstore.NewStore(pool)
|
||||
@@ -194,20 +193,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
return fmt.Errorf("快照搬运接线无效: %w", handoffErr)
|
||||
}
|
||||
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
|
||||
ppStateFile := getenv("PP_AUTH_STATE_FILE")
|
||||
if ppStateFile == "" {
|
||||
ppStateFile = "/data/source-auth/pp/settings.json"
|
||||
}
|
||||
ppPython := getenv("PP_AUTH_PYTHON")
|
||||
if ppPython == "" {
|
||||
ppPython = "/usr/bin/python3"
|
||||
}
|
||||
ppScript := getenv("PP_AUTH_CHECK_SCRIPT")
|
||||
if ppScript == "" {
|
||||
ppScript = "/app/scripts/pp_client.py"
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
PPConnection: &ppauth.Manager{Path: ppStateFile, LegacyPath: getenv("PP_LEGACY_CREDENTIALS_FILE"), Probe: ppauth.CommandProbe(ppPython, ppScript)},
|
||||
LibraryHandoffEnabled: handoffConfigured,
|
||||
QAAI: qaopsai.NewFromEnvironment(pool, getenv, config.DatabaseURL),
|
||||
QAWeeklyMail: qawemail.NewStore(pool, qaSettings.TenantKey, getenv("QA_AI_MASTER_KEY_FILE"), nil),
|
||||
@@ -237,7 +223,6 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
ProductionReleaseAuthorizationToken: releaseAuthorizationToken,
|
||||
// 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。
|
||||
DingtalkSources: dingtalkSourceLister{},
|
||||
DWSLogin: dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{}),
|
||||
DingtalkDocuments: dingtalkSourceLister{},
|
||||
BackupSchedule: postgresstore.NewStore(pool),
|
||||
VersionHistory: versionHistoryStore,
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
// newWeKnoraReadinessResolver 把「探测目标」收敛到与业务同一组真源:
|
||||
// 端点来自网页「知识库映射」保存的连接配置(endpoint 内部已做 env 兜底),知识库来自
|
||||
// 端点来自网页保存的服务配置(endpoint 内部已做 env 兜底),知识库来自
|
||||
// 当前持久化绑定(未绑定才用 env 引导值),凭据每次重新读同一份 key 文件。
|
||||
// 任何一项读取失败都必须显式报错——静默退回旧值正是 F13 的成因。
|
||||
func newWeKnoraReadinessResolver(
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -562,11 +561,6 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
Client: client,
|
||||
PollDelay: config.TestWeKnoraPollInitial,
|
||||
StallAfter: config.TestWeKnoraStalledAfter,
|
||||
// 页面保存的停滞阈值在这里生效;每 60 秒重读一次活动配置,
|
||||
// 读失败保留上一次值,再失败才回落到启动参数。
|
||||
StallAfterSource: func() time.Duration {
|
||||
return activeStalledAfter(context.Background(), store, config.TestWeKnoraStalledAfter)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create test poll handler: %w", err)
|
||||
@@ -598,29 +592,3 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
handlers["test.remove"] = remove.Handle
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
// activeStalledAfter 读取活动 UI 配置里的解析停滞阈值(带 60 秒缓存)。
|
||||
// 页面保存后无需重启 worker 即可生效;“保存即生效”不是文案,而是这里的读取。
|
||||
var stalledAfterCache struct {
|
||||
mu sync.Mutex
|
||||
value time.Duration
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
func activeStalledAfter(ctx context.Context, store *postgresstore.Store, fallback time.Duration) time.Duration {
|
||||
stalledAfterCache.mu.Lock()
|
||||
defer stalledAfterCache.mu.Unlock()
|
||||
if time.Since(stalledAfterCache.fetchedAt) < time.Minute && stalledAfterCache.value > 0 {
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
settings, err := store.GetActiveUISettings(ctx)
|
||||
if err != nil || settings.StalledAfterSeconds <= 0 {
|
||||
if stalledAfterCache.value > 0 {
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
stalledAfterCache.value = time.Duration(settings.StalledAfterSeconds) * time.Second
|
||||
stalledAfterCache.fetchedAt = time.Now()
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
# 知识治理候选和批次验收
|
||||
|
||||
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
|
||||
## 发起候选
|
||||
|
||||
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
|
||||
|
||||
````markdown
|
||||
```kg-release-v1
|
||||
{"task":"<发布任务 UUID>","base":"<当前主站 SHA>","sha":"<候选 SHA>","items":[{"task":"<业务任务 UUID>","pr":123}],"extra":[]}
|
||||
```
|
||||
````
|
||||
|
||||
2. Agent 执行 `candidate_coordinator.py prepare <发布任务 UUID>`。Gitea 核对候选 SHA 的 CI、每个 PR 的落地提交和完整主干范围。需准备候选时,独立 Runner 通过回环入口调度本机执行器。执行器复查发布负责人评论、Gitea 作业证明和当前主站 SHA 后,从准确提交构建镜像并封存。
|
||||
3. 执行器在独立验收数据库上启动同份归档,核验 API 提交、三个运行镜像、迁移账本、Web 入口及归档摘要。在发布任务和业务任务回填候选版本与地址。对「待测试」业务任务,由执行器转「测试中」。本地候选地址绑定回环,验收 Agent 应和执行器同机,或使用经工程侧验证的私有转发。
|
||||
4. `candidate_coordinator.py status <发布任务 UUID>` 读取候选回执或对应 Gitea 运行链接。遇到调度结果不明,先从 Gitea 读回运行再决定恢复路径。
|
||||
|
||||
## 登记验收
|
||||
|
||||
业务验收报告分别放在原业务任务,批次共享功能回归报告放在发布任务。保持测试角色原有输出,使用获授权的验收人或测试 Agent 在对应任务评论追加以下结构化结论。报告应保留用例明细和原始证据链接。该段的 `required` 是本轮登记的必测用例数。
|
||||
|
||||
````markdown
|
||||
```kg-qa-v1
|
||||
{"sha":"<完整提交 SHA>","bundle":"<归档清单 SHA256>","url":"<候选地址>","verdict":"passed","required":3,"passed":3,"failed":0,"blocked":0}
|
||||
```
|
||||
````
|
||||
|
||||
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
|
||||
|
||||
运维按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)将已验收归档传到主站只读收件目录并核对摘要。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
|
||||
## 执行器配置
|
||||
|
||||
- 版本管理机使用 Python 3.11 及以上、Docker Compose、HiFox CLI 和已有 Gitea 凭据。候选执行器通过 `candidate_worker.py <仓库工作树> <访问文件>` 绑定 `127.0.0.1:38984`,仓库工作树允许读取 `origin/main`。执行器通过现有 Gitea 凭据读取作业与日志。运行账户需能以 `weknora-test` 执行只读版本检查。
|
||||
- 为候选执行器单独配置 `kg-candidate` Runner。作业使用同机回环网络,通过仓库 Secrets 的 `KG_CANDIDATE_ACCESS` 访问执行器。访问文件由执行器用户持有,内容为独立 64 位十六进制随机凭据。候选作业使用的容器须无宿主 Docker socket 和生产密钥挂载。
|
||||
- 业务验收使用 `~/.config/knowledge-governance/{qa.json,qa.pgpass,rds-ca.pem}`。复用 `qa_env.py` 的专用 `kg_qa_` RDS 库和角色校验。验收使用专用账号与测试数据。需要验证外部系统的用例须先准备各自的隔离资源。
|
||||
- 候选执行器采用单验收槽。新批次启动前由运维确认前一批验收结束,按上一批 `ready.json` 中的容器身份停止其 Compose 项目,归档原有配置和回执后释放槽位。保留已验收的归档及审批记录。
|
||||
|
||||
## 演练和当前环境
|
||||
|
||||
`prepare-candidate.yml` 的 `verify` 模式校验 Gitea 范围与 CI。可在评审分支验证。`prepare` 模式只接受 `main` 的调度。`candidate_release.py build` 和 `candidate_runtime.py <bundle>` 可在隔离开发机演练打包及冒烟。后者使用临时 Docker 数据库,退出后停止演练容器。
|
||||
|
||||
主站当前运行的提交必须在候选的 `main` 主干历史内。若现有主站来自分叉的现场分支,先评审并同步运行基线,再以新提交打包。现有临时候选所用的 RDS 库需要先核验身份,主站数据库不用于候选业务验收。
|
||||
@@ -1,131 +0,0 @@
|
||||
# 知识治理平台开发与测试
|
||||
|
||||
以下命令从仓库根目录运行。日常开发可在 Ubuntu 宿主进行,指定提交的回归在 `hifox-qa` 的独立检出中运行。部署到阿里云测试服后的验收按 [操作 Runbook](OPERATIONS_RUNBOOK.md) 和 [用户流程验收](USER_FLOWS_ACCEPTANCE.md) 执行。
|
||||
|
||||
## QA 虚拟机一键回归
|
||||
|
||||
在 `hifox-qa` 检出提测提交后,运行下列入口。将 SHA 占位值换成提测记录里的完整提交 SHA。
|
||||
|
||||
```bash
|
||||
make qa-doctor
|
||||
KG_QA_SHA='<完整提交 SHA>' make qa
|
||||
```
|
||||
|
||||
`make qa-doctor` 检查工具链、HiFox 机器在线状态、OMP 模型调用、测试库身份和已安装的迁移。`make qa` 安装锁定依赖,在专用测试库上通过 API 初始化和迁移,随后核对完整迁移序列、API 就绪状态、Web 首页及 Vite 健康代理。通过后执行 Go 和 Vitest 测试,结束时关闭本次启动的服务。每次运行的服务日志保存在 `~/.local/state/knowledge-governance/qa/`。需要提交前完整门禁时执行 `make verify`。
|
||||
|
||||
初次配置由负责人在 QA 虚拟机准备 `~/.config/knowledge-governance/`。以下示例使用虚构的 RDS 主机名。
|
||||
|
||||
| 文件 | 内容 |
|
||||
| --- | --- |
|
||||
| `qa.json` | 当前用户所有、权限 `0600`,字段 `host`、`port`、`database`、`user` |
|
||||
| `qa.pgpass` | 当前用户所有、权限 `0600`,填写与 `qa.json` 匹配的口令条目 |
|
||||
| `rds-ca.pem` | 对应实例的 CA 证书,用于校验 RDS 主机名 |
|
||||
|
||||
```json
|
||||
{"host":"rds.example.test","port":5432,"database":"kg_qa_app","user":"kg_qa_app"}
|
||||
```
|
||||
|
||||
专用非生产 RDS 库和角色以 `kg_qa_` 开头,权限和网络准备见第 2 节。首次运行接受空库,后续运行接受与当前提交兼容的迁移序列。缺库、认证失败、迁移不兼容和端口冲突均会使命令非零退出。浏览器业务 E2E 和专用集成库的 Go 测试按第 4 节执行。
|
||||
|
||||
## 1. 检出代码与安装依赖
|
||||
|
||||
准备 Git、Make、Python 3、Go 1.26(含同一工具链的 `gofmt`)、Node.js 22 和 npm。数据库检查另需 PostgreSQL 客户端 `psql`。首次安装依赖需要能访问 Go 和 npm 的依赖源。
|
||||
|
||||
```bash
|
||||
# QA 在独立克隆中拉取提测分支,使用提测记录里的完整提交 SHA
|
||||
export KG_TARGET_BRANCH='<提测分支名>' KG_TARGET_SHA='<完整提交 SHA>'
|
||||
git fetch origin "$KG_TARGET_BRANCH" && git switch --detach "$KG_TARGET_SHA" &&
|
||||
test "$(git rev-parse HEAD)" = "$KG_TARGET_SHA" && test -z "$(git status --porcelain)"
|
||||
# 上面的命令链若失败,先解决检出或工作区问题再继续
|
||||
|
||||
# 检查当前 shell 的工具链,非交互任务也应设置相同的 PATH
|
||||
export PATH="$(go env GOROOT)/bin:$PATH"
|
||||
go version
|
||||
command -v gofmt
|
||||
node --version
|
||||
npm --version
|
||||
python3 --version
|
||||
make deps-install
|
||||
```
|
||||
|
||||
`make deps-install` 通过 `go mod download` 和 `npm ci` 安装依赖。Go 依赖由 `go.mod` / `go.sum` 约束,前端由 `web/package-lock.json` 锁定。依赖安装失败时先检查工具链、依赖源和锁文件,避免临时改写清单来绕过问题。
|
||||
|
||||
## 2. 准备开发和测试数据库
|
||||
|
||||
无库检查可直接跳到第 4 节。启动 API 或执行真库测试前,由数据库管理员在**非生产 PostgreSQL RDS** 上预建专用空库和登录角色。建议分配 `kg_qa_app` 给应用冒烟,`kg_qa_it` 给 Go 集成测试,各用独立角色。开发宿主另用开发专用库,避免与 QA 共享数据。库未分配时先申请,启动流程以库已存在为前提。
|
||||
|
||||
| 用途 | 所需权限 | 数据初始化 |
|
||||
| --- | --- | --- |
|
||||
| 应用启动与 UI 冒烟 | `CONNECT`,以及目标 schema 内的 `USAGE`、`CREATE` 和对应用对象的读写权限。迁移角色须能修改自己创建的对象。 | 首次 API 启动执行仓库内嵌迁移。用户表为空时创建初始管理员,首次登录必须修改密码。初始口令通过测试环境负责人交接。 |
|
||||
| Go PostgreSQL 集成测试 | `CONNECT` 和目标测试库的 `CREATE` 权限,用于建立各用例自己的 schema。 | 用例创建隔离 schema、执行迁移、写入测试数据并清理。相同测试不要并发指向同一个库,避免固定 schema 名冲突。 |
|
||||
|
||||
两类角色均只授予对应非生产库所需的权限。使用空库和合成数据。密码由操作者在目标机配置到权限为 `0600` 的 PostgreSQL passfile,条目按 `host:port:database:user:password` 填写。使用 RDS CA 校验证书。以下命令先读回实际数据库、角色与 TLS 状态,核对三者再启动 API 或运行真库测试。
|
||||
|
||||
```bash
|
||||
# 用获准的 RDS 主机名、端口、库名、角色和文件路径替换示例值
|
||||
export PGHOST='<非生产 RDS 主机名>' PGPORT=5432
|
||||
export PGDATABASE=kg_qa_app PGUSER=kg_qa_app
|
||||
export PGPASSFILE="$HOME/.config/knowledge-governance/qa.pgpass"
|
||||
export PGSSLROOTCERT="$HOME/.config/knowledge-governance/rds-ca.pem"
|
||||
export PGSSLMODE=verify-full PGCONNECT_TIMEOUT=5
|
||||
psql -X -v ON_ERROR_STOP=1 -c \
|
||||
'SELECT current_database(), current_user, ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid();'
|
||||
```
|
||||
|
||||
如果是云厂商提供的私网地址,先确认执行机通过获准的网络路径可访问 RDS。库名、角色、TLS、连接权限或迁移权限有问题时,先交由环境负责人核对配置。实例上已有数据的库不能当作空库初始化。
|
||||
|
||||
## 3. 启动后端和前端
|
||||
|
||||
**终端 A,启动 API。** 在干净 shell 中执行第 2 节的应用库配置和连通性检查。使用独立测试配置,不加载现网 `.env`。
|
||||
|
||||
```bash
|
||||
export DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5"
|
||||
export APP_ADDR=127.0.0.1:8088
|
||||
export TEST_WEKNORA_ENABLED=false PP_SCAN_ENABLED=false
|
||||
export RELEASE_WORKER_ENABLED=false PRODUCTION_RELEASE_REQUESTS_ENABLED=false
|
||||
export DOBOTAI_OPS_READ_ENABLED=false DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED=false
|
||||
go run ./cmd/api
|
||||
```
|
||||
|
||||
API 会在监听前连接 PostgreSQL、应用迁移并初始化管理员。Web 页面和同步 API 联调只需运行 API 与 Vite。需要验证后台队列时,另用相同的隔离应用库配置启动普通 worker(`go run ./cmd/worker`)。涉及取件或来源刷新的任务还依赖容器内 `/app/scripts` 及获准的来源接线,按部署说明准备。发布 worker 无需启动。
|
||||
|
||||
Vite 通过 `localhost:8088` 转发 `/api` 和健康检查。如果 `8088` 已被其他部署占用,使用端口空闲的 QA 虚拟机运行本节。仅改前端时,可复用一个获准联调的测试 API,但需要先确认 `localhost:8088/health` 可达,并核对该地址指向的环境。
|
||||
|
||||
**终端 B,启动 Web。**
|
||||
|
||||
```bash
|
||||
npm --prefix web run dev -- --host 127.0.0.1 --port 5173 --strictPort
|
||||
```
|
||||
|
||||
在运行服务的机器打开 `http://127.0.0.1:5173/`。另开终端检查 API 与前端代理,再复查迁移记录。最后一条命令需要第 2 节的应用库配置。
|
||||
|
||||
```bash
|
||||
curl --fail --silent --show-error http://127.0.0.1:8088/health
|
||||
curl --fail --silent --show-error http://127.0.0.1:5173/health
|
||||
psql -X -v ON_ERROR_STOP=1 -c \
|
||||
'SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1;'
|
||||
```
|
||||
|
||||
空库首次启动后,用专用测试账号登录,按当次验收标准验证页面及接口。联调结束在两个终端按 `Ctrl+C` 停服务,数据库由环境管理员按测试数据保留规则管理。
|
||||
|
||||
## 4. 选择测试命令
|
||||
|
||||
| 目的 | 命令 |
|
||||
| --- | --- |
|
||||
| 查看检查及适用范围 | `make list` |
|
||||
| 后端包测试 | `make tests-go` |
|
||||
| 单个 Go 包及相关子包 | `go test -count=1 ./internal/httpapi/...` |
|
||||
| 前端 Vitest 套件 | `make tests-web` |
|
||||
| 单个前端测试文件 | `npm --prefix web test -- src/App.test.tsx` |
|
||||
| 完整提交前检查,与 CI 共用入口 | `make verify` |
|
||||
|
||||
`make verify` 包含安装、格式、静态检查、构建、测试、版本和安全检查,并写出 `ci-report.json`。在未导入真库测试配置的 shell 中运行。若检出时用了 `--no-tags`,先执行 `git fetch --tags origin`,以便版本检查读取正式标签对应的提交。依赖安装与安全检查需要相应网络或缓存。允许跳过的外部依赖用例见 [test-scope.json](../scripts/test-scope.json),真库测试应单独执行并记录结果。
|
||||
|
||||
在应用冒烟之外验证真实 PostgreSQL 行为时,重新按第 2 节切换并核对 **集成测试库和角色**,然后执行目标用例。下面以 UI 设置版本切换用例为例。
|
||||
|
||||
```bash
|
||||
TEST_DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5" \
|
||||
go test -count=1 -v ./internal/platform/postgres -run '^TestUISettingsActivationRetiresPreviousRevisionIntegration$'
|
||||
```
|
||||
|
||||
检查输出出现目标用例的 `PASS`。用例被跳过或没有匹配时,应补齐配置或纠正用例名后重跑。前端 Vitest 负责组件与业务逻辑检查,浏览器 E2E 应单独执行并按 Feature 保存证据。提测记录至少包括完整提交 SHA、执行命令、退出码,以及失败用例的日志或浏览器截图。
|
||||
@@ -1,44 +0,0 @@
|
||||
# DWS 登录授权
|
||||
|
||||
管理员入口:系统设置 → 数据源配置 → 钉钉账号(DWS)。
|
||||
|
||||
- 未登录时点击“登录授权”,在弹窗中打开钉钉官方授权页,由本人选择账号与组织并确认。
|
||||
- 平台等待设备授权完成。成功后自动刷新账号、组织和续期凭证有效期,并检查知识库、钉盘目录访问。
|
||||
- “重新授权”采用同一流程;授权中可取消,失败或过期后可重新发起。
|
||||
- “检查连接”只列目录与读取登录元数据,不登记来源、不扫描已有来源、不发起入库或生产发布。
|
||||
- 登录成功与目录可用分开显示;部分范围无权限时保留其他已成功范围,并展示原因。
|
||||
|
||||
## 服务端接线
|
||||
|
||||
API 直接管理 `dws auth login --device --no-browser --format json` 子进程,不复用旧浏览器扫码侧车。
|
||||
CLI 负责官方 OAuth 协议、组织 CLI 权限校验及凭据加密持久化。平台只解析官方设备授权链接、用户授权码、有效期与状态;原始输出、access token、refresh token不进入接口或日志。
|
||||
|
||||
API 与 worker 必须使用相同 UID,以及同一组可写挂载:
|
||||
|
||||
| 配置 | 用途 |
|
||||
|---|---|
|
||||
| `DWS_BIN` | 固定版本的 DWS 程序 |
|
||||
| `DWS_CONFIG_DIR` | 共享的 DWS 状态目录 |
|
||||
| `DWS_HOME` | 共享 home,包含 `.local/share/dws-cli` 文件型密钥存储 |
|
||||
| `DWS_DISABLE_KEYCHAIN=1` | 容器使用文件型凭据存储 |
|
||||
|
||||
子进程 HOME 由 DWS_HOME 指定,只透传所需环境。禁止把认证状态复制成多份,避免轮换令牌互相失效。
|
||||
|
||||
## 接口与生命周期
|
||||
|
||||
- `POST /api/v1/dws-login`:立即返回 starting,后台生成设备授权;同一浏览器管理员会话重复请求复用在途授权。
|
||||
- `GET /api/v1/dws-login/{id}`:读取本人发起的授权。
|
||||
- `DELETE /api/v1/dws-login/{id}`:取消并等待旧 CLI 退出,清除授权链接与用户码。
|
||||
- 上述接口均为管理员专用;授权绑定管理员及其登录会话,另一会话无法读取或取消。
|
||||
- 创建和取消要求同源操作意图;响应禁止缓存。仅允许 `https://login.dingtalk.com/oauth2/device/verify.htm` 官方链接。
|
||||
- 每次只运行一个授权,防止覆盖共享状态。服务重启会结束在途授权;页面提示重新发起。
|
||||
- CLI 成功退出后必须再次读到有效本地凭据才显示登录成功;真实目录访问另行检查。
|
||||
|
||||
## 添加来源
|
||||
|
||||
添加来源向导与账号卡共用官方 DWS 授权;列举、校验、登记使用同一身份。来源登记不再自动回落旧扫码侧车。保存中授权失效时保留已成功项并恢复剩余项;换账号或组织后需重新确认范围。详细交互、认证审计与 PP 接线见 [数据源认证配置](SOURCE_AUTH_CONFIGURATION.md)。
|
||||
|
||||
## 验证边界
|
||||
|
||||
自动回归覆盖授权生成、成功后状态更新、目录访问失败与部分可用、取消与进程退出、过期、重试、跨管理员/会话隔离、同源限制、官方链接校验及元数据脱敏。
|
||||
真实本人授权需要管理员在钉钉官方页面确认;自动测试与生成真实授权链接不替代本人授权,也不证明其公司目录权限。
|
||||
@@ -3,95 +3,14 @@
|
||||
按"实际干活顺序"排列的**现在的**操作流程。标注:**【新】**本期新增(含本次会话与 `f4e1ecc/6496ee3/9155bd3` 的 dws 取件)|**【变】**既有流程本期有改动|**【既有】**未变,仍照旧走。
|
||||
逐条验收证据请看 `docs/USER_FLOWS_ACCEPTANCE.md`;细节规则看各自专题文档。
|
||||
|
||||
管理员配置连接和发布授权,文档工程师维护资料,只读成员查看进度。先确定要操作的环境,再按下面的接线与验收步骤进入业务流程。
|
||||
|
||||
云测试治理主站自身的应用升级见[主站应用 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
|
||||
## 入口与反向代理
|
||||
|
||||
| 请求从哪里发出 | 地址或路径 | 实际目的地 |
|
||||
|---|---|---|
|
||||
| 已接入内网的运维电脑 | `http://100.85.111.121:8088/` | 云测试治理主站 |
|
||||
| 开发电脑的浏览器 | `http://127.0.0.1:28189/` | SSH 转发到测试机回环 `28189`,由候选 Web 提供静态资源 |
|
||||
| 测试候选 Nginx(host 网络) | `/api/`、`/health` | 测试机 `127.0.0.1:18099` 候选 API |
|
||||
| 同一候选 Nginx | `/api/v1/qa-ops/ai/` | 测试机 `127.0.0.1:18098` 现用治理 API,负责模型配置和连接验证 |
|
||||
| 标准 Compose Web(容器网络) | `/api/`、`/health` | Docker DNS 解析 `api:8080`。静态资源和 SPA 回退由同一 Web 提供 |
|
||||
|
||||
**在开发电脑恢复验收入口。** 前提是 SSH 别名 `weknora-test` 能登录测试机。先查远端服务,再查本机监听。本机端口空闲且远端正常时,在独立终端运行第三条命令,保留该终端。在另一终端执行最后一条并用浏览器打开同一地址。
|
||||
|
||||
```bash
|
||||
ssh weknora-test 'curl -fsS --max-time 5 http://127.0.0.1:28189/health'
|
||||
ss -ltn 'sport = :28189'
|
||||
ssh -NT -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 127.0.0.1:28189:127.0.0.1:28189 weknora-test
|
||||
curl -fsS --max-time 5 http://127.0.0.1:28189/health
|
||||
```
|
||||
|
||||
**为内网域名配置 HTTPS。** 在能访问测试主站的受信任反代机上配置证书、内部 DNS 和访问范围。以下片段放入已有 HTTPS `server`,完整保留 URI、Host 和会话 Cookie。上游应选治理 Web 入口,使 `/assets/`、`/api/`、`/health` 走同一域名。若该入口的内层代理也设置 `X-Forwarded-Proto`,联调时检查其保留受信任 TLS 终止层的协议值以及登录回调的实际 URL。
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
proxy_pass http://100.85.111.121:8088;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
```
|
||||
|
||||
在反代机执行 `nginx -t` 校验待应用配置。入口启用后,通过该域名验证登录、一次 `/api/` 请求和首页实际引用的 JS/CSS。`index.html` 应重新校验,带哈希的资源可长期缓存,缺失的 JS 返回 404。候选切换前后分别记录通用上游和 AI 专用上游。现场可在测试机用以下只读命令查看,容器名以当时部署为准。仓内同源配置见 [deploy/nginx.conf](../deploy/nginx.conf)。
|
||||
|
||||
```bash
|
||||
docker exec kg-test-storage-ui-6444814 nginx -T 2>&1 | grep -E 'listen .*28189|location /api/v1/qa-ops/ai/|set \$(api|health)_upstream|proxy_pass http://127[.]0[.]0[.]1:18098'
|
||||
docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage-ui-6444814 kg-accept-090-api
|
||||
```
|
||||
|
||||
**现场版本与回退。** 本次在测试机读到 Web 标签 `4b615abe534b`、API 标签 `341c3154ac91`。完整候选包的 `current` 链接位于 `/opt/knowledge-governance/acceptance/090/current`,单独切换的 Web 位于同级 `web-only/4b615abe534b/dist`,实际反代配置位于 `integration/28189.conf`。切换前记录这三处、容器标签与旧 Web 名称。静态页回退时恢复上次的 Web 资源和对应代理配置。完整候选回退按同批装配工具的 `deploy/accept-090/README.md` 执行。回退后用浏览器重新验证首页资源、模型连接和列库。数据库迁移另按备份与恢复方案处理。
|
||||
|
||||
本次已核实共享测试治理库到 `000082`。对内、对外独立启用的实现依赖 `000083`,待独立库联调或共享库迁移获准后,再验证单侧暂停、保存和刷新。生产 `070` 不在该套验收范围。
|
||||
|
||||
下文系统设置中的绑定、盘点和模型连接步骤适用于上表的测试候选版本。根据现场标签选择对应版本的代码和交付物。
|
||||
|
||||
## 接入外部平台
|
||||
|
||||
| 平台与用途 | 管理员或运维怎样接 | 接通的证据 |
|
||||
|---|---|---|
|
||||
| 钉钉知识库,取目录和文件 | 系统设置 → 数据源配置 → 钉钉授权。用 DWS 设备授权,以来源账号选择组织、空间和范围。API 与 worker 使用部署约定的 DWS 身份目录 | 登录后读回预期空间,选一个有权限的目录校验。登记来源、扫描完成和文件取件分别核验。 |
|
||||
| AList,取工业或教育资料 | 按来源登记服务根地址和允许的目录。普通 worker 读取专用令牌文件。目录接口 `POST /api/fs/list` 使用 `X-Gateway-Token` | 在来源页扫描已知根目录,对照一个子目录和一份文件。下载遵循来源签名链接,凭据和签名 URL 仅留在受控运行环境。[目录与取件](SOURCE_CATALOG_LIVE_ROUTING_ACCEPTANCE.md) |
|
||||
| PP 资料门户 | 在数据源配置填写 HTTPS 根地址和来源账号,点「测试连接」后「保存并校验」。API 和 worker 共享 `PP_AUTH_STATE_FILE` 所在目录 | 真实登录并读取一条目录记录,刷新后核对生效配置。超时或限流时查看待验证状态。 |
|
||||
| WeKnora 测试 090,处理与验收 | 系统设置 → 知识库绑定 → 测试 090。当前测试 API 地址 `http://127.0.0.1:8092`,由治理服务器访问。输入该实例的专用 Key 或使用已配置凭据 | 「验证并读取知识库」能列出预期库。核对名称和 ID,为对内、对外选择不同的目标,保存后刷新读回 |
|
||||
| WeKnora 生产 090,列库与映射 | 在同页切到生产 090,使用下节的转发入口与生产专用 Key。新连接的安全存储由 `WEKNORA_BINDING_MASTER_KEY_FILE` 提供 | 读取生产目录并核对两个目标 ID,保存后重新进入生产页核实。执行发布另按 §5–6 授权 |
|
||||
| 问答 AI 模型 | 系统设置 → AI 模型连接,填写 OpenAI 兼容基础地址(含服务要求的 `/v1`)、模型名及专用 Key。API 与普通 worker 使用同一 `QA_AI_MASTER_KEY_FILE` | 点「测试连接」等待成功,需生效时再保存并刷新检查模型名。存储密钥、权限与 DNS 配置见 [README](../README.md#问答运营模型配置) |
|
||||
|
||||
**生产 090 的两段地址。** 生产机私网 IP 为 `172.29.151.11`,其 WeKnora API 对宿主回环发布 `127.0.0.1:18092`。测试治理机上已有 SSH 本地转发,治理 API 使用 host 网络,故页面的生产服务地址填写 **`http://127.0.0.1:18092`**。请求从治理 API 发出,经测试机的回环监听到生产机的回环 API。浏览器所在电脑的 `127.0.0.1:28189` 则用于打开治理页面。迁到 bridge 网络时要从新 API 容器重新验证上游可达性。
|
||||
|
||||
在**测试治理机**上检验已有通道。`/health` 返回 200 证明转发可用,无凭据列库返回 401 表明请求已到认证层。接着在治理页面安全输入该实例的 Key 并验证真实库列表。本次核验时,生产通道探活成功,匿名列库返回 401。带生产凭据列库和保存映射仍待验收。
|
||||
|
||||
```bash
|
||||
ss -ltnp 'sport = :18092'
|
||||
curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'health %{http_code}\n' http://127.0.0.1:18092/health
|
||||
curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'catalog %{http_code}\n' http://127.0.0.1:18092/api/v1/knowledge-bases
|
||||
```
|
||||
|
||||
## 开发测试和现场验收
|
||||
|
||||
1. 在开发机运行 `make list` 查看门禁,`make verify` 做整套检查。以 `ci-report.json` 的 `commit_sha` 对照 `git rev-parse HEAD`,记录失败或跳过项。前端启动和组件测试见 [开发与 CI](../README.md#开发与-ci)。
|
||||
2. 针对后端改动,在独立测试逻辑库核对 `SELECT current_database(), max(version) FROM schema_migrations;` 与候选版本的迁移目录。云端多个候选可能共用治理 RDS。只改静态页面时单独切换 Web,保留原资源和代理配置供回滚。
|
||||
3. 在指定入口以真实账号分别验证。来源页读取一条已知记录,模型页测试到成功终态,知识库绑定在正确环境列库,保存后刷新核对。存储页按最近批次和子库目录分别与 `du -sB1 -- <目录>` 对账。记录入口、Web/API 提交、时间和结果。
|
||||
4. 候选备份页读取宿主采集的 `metadata.json`,API 只读挂载输出目录。「重新盘点」只重读文件。超过 `BACKUP_HOST_METADATA_MAX_AGE` 时,目录、占盘和预测转为未知。宿主重新采集后核对采集时间是否前进、批次是否恢复。测试现场使用按次采集、15 分钟有效期。采集脚本和挂载参数以同批测试候选交付物为准。
|
||||
|
||||
| 症状 | 第一步怎么查 | 如何判定 |
|
||||
|---|---|---|
|
||||
| 浏览器连接被拒 | 对照本机 `28189` 监听和测试机 `/health` | 远端正常、本机无监听时恢复本机 SSH 转发 |
|
||||
| 页面打开,某个 API 404 或 502 | 查浏览器请求路径、Nginx 生效上游及对应 API 版本 | 404 先查路由是否存在,502 先查上游是否可达。AI 页单独核对 `18098` |
|
||||
| 能探活,列库仍灰或返回 401 | 核对选中环境、凭据配置状态、容器运行 UID 与凭据文件可读性 | 用该环境的专用身份实际列库。检查过程只记录状态码和可读性 |
|
||||
| 历史可读,计划或配额显示未知 | 核对快照年龄、执行主机连接与配额字段 | 盘点、SSH 计划、配额分别验证。只有主机实际读回 cron 才能报告下一次执行时间 |
|
||||
统一入口 **http://127.0.0.1:8088/**(测试栈,右侧面板可直接操作)。角色:管理员 / 文档工程师 / 只读。
|
||||
|
||||
---
|
||||
|
||||
## 0. 开工前:环境与凭据自检
|
||||
| 项 | 怎么做 | 成功标志 |
|
||||
|---|---|---|
|
||||
| 测试/生产 WeKnora | 系统设置 → 知识库映射 → WeKnora 连接 | 生产端"已启用 · 可提交生产请求";测试端探测正常 |
|
||||
| 测试/生产 WeKnora | 系统设置 → 服务配置 | 生产端"已启用 · 可提交生产请求";测试端探测正常 |
|
||||
| 钉钉取件凭据 **【新】** | 容器内 `HOME=/data/home dws auth status --readonly -f json` | `authenticated:true`、`refresh_token_valid:true`(**必须带 `HOME=/data/home`,否则误报未登录**) |
|
||||
| 备份主机接线 | 系统设置 → 存储与备份 | "目标主机 weknora-test · 已连接" |
|
||||
|
||||
@@ -161,7 +80,7 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
|
||||
|
||||
| 分区 | 谁 | 现在要管什么 |
|
||||
|---|---|---|
|
||||
| 知识库映射 → WeKnora 连接 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) |
|
||||
| 服务配置 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) |
|
||||
| 测试知识库绑定 | 管理员 | 标注往哪个测试库路由(对内 ≠ 对外) |
|
||||
| 生产知识库绑定 | 管理员 | 源库 → 目标库映射(发布写哪个生产库) |
|
||||
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
# 云测试治理主站应用 CD
|
||||
|
||||
正式入口为 `http://100.85.111.121:8088/`。云端 Compose 项目为 `knowledge-governance-cloud-test`,工作目录 `/opt/knowledge-governance`,当前配置链为 `compose.json`,服务为 `api`、`web`、`worker`。Web 容器提供 `8088`,通过挂载的 nginx 配置代理 API 的 `127.0.0.1:18098`。应用 CD 与知识库内容发布各自保留原有授权流程。
|
||||
|
||||
## 建立验收产物
|
||||
|
||||
1. 从干净检出的完整提交构建一次 API、worker、web 镜像。构建调用方对三个镜像都注入 `org.opencontainers.image.revision=<完整 SHA>`。API 构建身份沿用 `scripts/version.py --identity` 输出,传给 Dockerfile 的版本、提交和构建时间参数。API 与 worker 各自记录镜像 ID,即使它们来自同一个 Dockerfile。
|
||||
2. 封存后用同一份归档部署到隔离验收环境。输出目录必须是新路径,父目录应已存在。三个 `--api/--web/--worker` 参数是本地镜像的完整 ID。
|
||||
|
||||
```bash
|
||||
python3 scripts/production_cd.py pack --sha "$SHA" --task "$TASK_UUID" \
|
||||
--api "$API_ID" --web "$WEB_ID" --worker "$WORKER_ID" --output "$BUNDLE_DIR"
|
||||
docker load -i "$BUNDLE_DIR/api.tar"
|
||||
docker load -i "$BUNDLE_DIR/web.tar"
|
||||
docker load -i "$BUNDLE_DIR/worker.tar"
|
||||
```
|
||||
|
||||
3. 用验收环境自身的 Compose 和数据库启动这些镜像。用下面的命令读回验收环境运行身份。此处三个服务参数是实际的**测试容器名**。在业务验收入口执行实际用例并将输出、结果与报告链接放在同一份验收记录里。
|
||||
|
||||
```bash
|
||||
python3 scripts/production_cd.py attest --sha "$SHA" --task "$TASK_UUID" \
|
||||
--api "$QA_API" --web "$QA_WEB" --worker "$QA_WORKER" --test-url "$QA_URL" --directory "$BUNDLE_DIR"
|
||||
BUNDLE_SHA=$(sha256sum "$BUNDLE_DIR/release.json" | cut -d' ' -f1)
|
||||
```
|
||||
|
||||
4. 由验收人使用获授权的 HiFox CLI 登记业务结论,读回任务、验收字段和状态。`cd_acceptance` 是 JSON 字符串类型的 metadata,其解析结果为 `{"verdict":"passed","sha":"…","bundle":"…","evidence":"https://…"}`。录入人应先核对真实报告与运行身份。自动发布时,`evidence` 使用同一 HiFox 任务的验收报告评论链接(带 `#comment-<UUID>`)。评论须正文包含完整提交和归档清单摘要,并在发布人确认前完成。用 `task view --output json` 核对实际任务 UUID、空间、状态和验收字段。验收登记重试复用原归档摘要与原记录。以当前版本只接受一个任务,多个任务分别验收。
|
||||
5. 在首次发布前,由运维把四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
|
||||
|
||||
## 在 HiFox 确认发布
|
||||
|
||||
验收、登记、上传归档都完成后,由发布人把原任务移入「待发布」。HiFox 的「知识治理|待发布自动执行 CD」把任务 UUID 交给专用发布 Agent,Agent 调用白名单内的 `scripts/hifox_release_trigger.py`。桥接脚本读取 HiFox 时间线,校验最近一次状态变更的操作者、状态、同任务验收报告及产物摘要,随后调度 Gitea `deploy-production@main`。Gitea 仍只开放 `workflow_dispatch`。目标控制器按完整输入校验 Gitea 运行,并在切换前复查 HiFox 状态和验收摘要。
|
||||
|
||||
相同状态事件复用已记录的 Gitea 运行。如果调度结果未知,核查对应 Gitea 运行与本机调度记录后再处理。旧任务已处于「待发布」时,在验收登记完成后重新进入该状态可发起新确认。
|
||||
|
||||
也可由发布人使用 Gitea Actions 中原有人工入口应急。分支选 `main`,使用 `action=deploy`、完整 `sha`、`bundle`、任务 UUID `task` 和 `confirm=deploy-production`,仅 HiFox Agent 填写 `approval_event` 和 `acceptance_digest`。
|
||||
|
||||
主站侧从 Gitea 读取运行、操作者和通过的校验作业,并验证输入摘要及工作流代码。候选代码可来自仓库内的任务分支,以实际验收 SHA 为准。切换前还核验必需 CI 状态、HiFox 验收记录、三份归档、线上源代码血缘及数据库迁移账本。切换复用 `scripts/deploy-api-web.sh`,仅更换三项 Compose `image`;保留原配置字节以备回滚。切换后自动读回三镜像、API 二进制 SHA、主站健康、API readiness 及实际提供的前端资源。HiFox 回写包含原始运行 URL、完整提交、摘要、镜像 ID 及核验证据。任务评论另含主站登录地址和已核验的运行版本,带 OCI 版本标签时显示其值,其余镜像显示完整提交。
|
||||
|
||||
目标机已有的 `schema_migrations` 必须与候选完全相同,API 与 worker 的库连接均须核对。应用会在启动时检查迁移。新增或改变的迁移先按独立流程审查、备份、执行并复验;CD 自身只读迁移账本。发布时运营方应保留 prior tag,保障用原 Compose 字节回滚。
|
||||
|
||||
## 失败恢复
|
||||
|
||||
- `rolled_back` 表示自动恢复了原 Compose、旧的镜像 ID、API SHA 与站点健康。`rollback_failed` 或 `cutover_started` 要求巡检现场、按回执恢复并复验。目标机互斥锁覆盖切换及回写。Gitea 的取消记录只能说明流水线结束,回滚以目标机回执和运行时读回为准。
|
||||
- `DEPLOYED_HIFOX_PENDING` 表示镜像切换和核验已经完成。以同一 `sha`、`bundle`、`task` 人工发起 `action=writeback`、`confirm=retry-writeback`。脚本先读原目标回执并复验仍在运行的版本,随后补写 HiFox,保留原部署链接。状态与 metadata 的当前值以 HiFox 读回为准。重复调用核对记录后结束。
|
||||
- 目标回执 `/opt/knowledge-governance/cd/receipts/<bundle>.json`,镜像切换前的 Compose 保存为同名 `.compose.backup`。SSH 超时或强制中断后,先读回执和当前运行态。已存在未决或失败回执时,重复部署被拒。保留原回执作为事故证据。
|
||||
|
||||
## 一次性配置与权限
|
||||
|
||||
- 目标机安装仓库 `scripts/{production_cd.py,cd_migration_probe.py,deploy-api-web.sh,production-cd-ssh.sh}` 到 `/opt/knowledge-governance/cd/bin/`。创建私有 `receipts/`、`bundles/`、`hifox-home/`,初始化 `source.git` 为 bare Git 仓,并将 `.gitea/required-contexts.txt` 安装到该目录。仅发布运维可更新这些文件。
|
||||
- 填写目标机 `/opt/knowledge-governance/cd/deploy-production.yml`,内容与 Gitea 主分支的工作流逐字节相同。控制器用 Gitea 发布人账号 ID 和只读日志验证确认。目标端 `authorized_keys` 为 CI 单独公钥设置 `restrict,command="/opt/knowledge-governance/cd/bin/production-cd-ssh.sh"`。校验云主机 SSH host key 后将其按 `kg-governance-cd` 别名写入 `KG_CD_KNOWN_HOSTS`。对应独立 SSH 私钥保存在 `KG_CD_SSH_KEY`。Runner 标签为 `kg-production-cd`,使用 `KG_CD_SSH_HOST` 和 `KG_CD_SSH_PORT` 接入批准的 Tailscale 或本机 IPv6 隧道。
|
||||
- 将受控 HiFox CLI 安装至 `bin/hifox`,由账号持有人在目标主机使用 `hifox-home` 对应的私有配置目录完成登录。身份须能读取指定空间的任务、写 `cd_release` metadata 并完成对应状态迁移。状态绑定前分别读回组织状态和实际任务类型,复用原有待发布、已发布 ID,保留其余工作流配置。
|
||||
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
|
||||
- 常规 push CI 负责验证和静态预览。这个 workflow 的唯一事件是 `workflow_dispatch`。`make verify` 的 `contracts` 子项运行 CD 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
|
||||
@@ -3,7 +3,7 @@
|
||||
> 这份文档是**破坏性变化与数据迁移步骤的落脚点**:`CHANGELOG.md` 里以 `**破坏性**` 开头的条目
|
||||
> **必须**链接到本文(或本文的某个小节)。发布记录本身仍在 `CHANGELOG.md` —— 本文不维护第二份变更列表。
|
||||
>
|
||||
> 常规 CI 负责检查、构建与静态预览。版本 tag 与 Release 由人批准后执行。主站应用部署使用独立的[人工确认 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
> 本仓 CI **只做 CI**:不打 tag、不发 Release、不部署。发布与部署都是**独立的人工审批动作**。
|
||||
|
||||
## 一、正式发布(由人批准后执行)
|
||||
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
# 数据源认证配置
|
||||
|
||||
管理员入口:系统设置 → 数据源配置。PP 连接位于钉钉账号卡旁;添加来源向导使用同一组账号与配置。
|
||||
|
||||
## PP 连接
|
||||
|
||||
- API 地址填写 HTTPS 根地址;后台沿用 `/admin/login/token`、`/potal/file/back/page` 接口路径。`potal` 是上游真实路径,不能改写。
|
||||
- 账号允许修改。密码只显示已配置/未配置;点击“更新密码”录入新值。省略或留空保留既有密码,不回显原值。
|
||||
- “测试连接”使用当前表单,真实登录并读取一条目录记录;合法空目录也可通过。它不保存配置、不登记来源、不启动扫描。
|
||||
- “保存并校验”在后端重新检查本次提交。通过后切换生效;明确的认证拒绝、权限拒绝、接口不兼容阻止生效。
|
||||
- 超时、限流或服务临时故障可保存为待验证修改;缺少凭据可保存未完成配置。两者都不会替换当前生效配置;需要再次保存并校验,通过后才切换。
|
||||
- 草稿测试结果与当前生效配置状态分开;每次修改字段会使原草稿测试结果作废。检查失败时保留上次观测及时间,不能把网络失败当成退出登录。
|
||||
- 后续目录扫描和远程取件读取同一生效配置;验证过的本地文件仍按既有内容校验逻辑复用。配置保存不恢复暂停的计划、不触发入库或发布。
|
||||
|
||||
## PP 服务端接线
|
||||
|
||||
| 参数 | 默认与用途 |
|
||||
|---|---|
|
||||
| `PP_AUTH_STATE_FILE` | `/data/source-auth/pp/settings.json`;API 和 worker 必须读同一份原子配置文件 |
|
||||
| `PP_AUTH_PYTHON` | `/usr/bin/python3`;API 连接检查使用的解释器 |
|
||||
| `PP_AUTH_CHECK_SCRIPT` | `/app/scripts/pp_client.py`;与扫描、取件共享的只读协议实现 |
|
||||
| `PP_LEGACY_CREDENTIALS_FILE` | 可选,只用于首次迁移;有效状态文件存在后不再回落旧文件 |
|
||||
|
||||
配置目录及状态文件分别使用 0700 和 0600。API/worker 使用相同 UID,将宿主凭据目录挂载为共享目录,不能绑定单个文件:单文件 bind mount 会在原子 rename 后继续指向旧 inode。迁移时从目标机既有凭据文件直接读取,禁止通过聊天、命令行参数或仓库传递密码。
|
||||
|
||||
状态文件持有生效配置、待验证修改、最近检查及认证审计,包含密码,因此必须按密钥文件保护,不能进普通配置备份、版本记录或日志。更新使用跨进程文件锁、临时文件、fsync 和原子 rename。配置修订采用乐观并发控制;旧请求不能覆盖新修订。worker 的迟到检查只能更新自身生效配置 ID 对应的观测。
|
||||
|
||||
PP 检查子进程只从 stdin 接收本次凭据,stdout 只返回白名单检查结论。GET 接口仅返回配置元数据和是否存在密码;密码输入字段只可写。
|
||||
|
||||
| 接口 | 用途 |
|
||||
|---|---|
|
||||
| `GET /api/v1/pp-connection` | 管理员读取安全元数据、待验证修改与检查状态 |
|
||||
| `POST /api/v1/pp-connection/test` | 测试当前草稿,不激活 |
|
||||
| `PUT /api/v1/pp-connection` | 校验并保存;携带当前 `revision` |
|
||||
|
||||
使用已保存的待验证密码继续校验时携带 `pending_id`,避免空密码误用旧生效密码。修改请求验证管理员、同源操作意图和输入大小;响应禁止缓存。
|
||||
|
||||
## 钉钉添加向导
|
||||
|
||||
保留 类型 → 授权 → 范围 → 校验 → 保存 五步;授权步骤复用钉钉账号卡的官方 DWS 设备授权流程。
|
||||
|
||||
- 可见范围、校验和登记都使用共享 DWS 身份;登记不再自动回落旧扫码侧车。DWS 无法定位的历史空间返回明确原因。
|
||||
- `POST /api/v1/dingtalk-spaces/validate` 真实读取并检查所选空间。失败、权限不足、部分范围不完整与合法空列表分别展示。
|
||||
- 已接入空间按稳定空间身份标记,历史连接也从其存储的空间标识识别,不靠名称去重。
|
||||
- 保存中授权失效:保留已成功项及待处理项,在向导内重新授权;同账号恢复后继续剩余项,复用操作标识,首次扫描按连接身份去重。
|
||||
- 取消或失败后保留选择并停止自动提交;再次恢复失败不循环弹授权。
|
||||
- 授权后换账号/组织:重新加载范围并清除旧选择,要求重新确认。客户端提交身份指纹,后端在列举前后确认身份,变化时拒绝登记。
|
||||
- 只有已点击保存的操作才会在重新授权后继续登记;账号登录、刷新和连接检查本身不创建来源或扫描任务。
|
||||
- 登记成功和首次扫描入队分别反馈,不能用登记成功冒充扫描已运行。
|
||||
|
||||
其他历史入口若仍调用旧扫码侧车,保留其原行为;本功能不删除整个侧车服务。
|
||||
|
||||
## 审计与验证
|
||||
|
||||
PP 配置/密码更新、连接检查及 DWS 授权结果,复用现有数据源操作审计页面。凭据事件与配置在同一文件内原子提交,并与数据库原有事件按时间合并分页;不把密码写入 SQL。DWS 终态审计按授权 ID 与状态去重,轮询不刷记录。
|
||||
|
||||
回归覆盖真实协议请求、空目录、认证拒绝、权限与限流、密码保留/替换、待验证密码重校验、并发修订冲突、响应脱敏、同源及角色限制、无意外任务、审计分页、DWS 部分成功恢复与换账号保护。协议与消费者测试使用隔离的本机 HTTP 服务;运行环境可用性需另行通过真实页面检查,不能用这些用例替代。
|
||||
@@ -255,8 +255,8 @@
|
||||
|
||||
## D. 系统设置
|
||||
|
||||
### D1 知识库映射 → WeKnora 连接(测试 / 生产端点与 ID)
|
||||
- 入口:**系统设置 → 知识库映射 → WeKnora 连接**(管理员)
|
||||
### D1 服务配置(测试 / 生产端点与 ID)
|
||||
- 入口:**系统设置 → 服务配置**(管理员)
|
||||
- 规则:只配四项(测试地址、生产地址、生产 ID、知识库 ID);**保存时真探测**,无效才拒;凭据只写不读
|
||||
- 状态:✅(见 `P41/P42` 与 `ui_settings_*` 测试)
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# 发布管理流程与页面精简
|
||||
|
||||
## 目标与边界
|
||||
|
||||
现有整库发布页面同时呈现日常发布、维护诊断、恢复演练与历史快照,且封存操作位于页面底部,版本入口重复。此次优化聚焦 `ReleaseTargets` 的信息层级和操作位置,沿用现有 API、权限、授权绑定、维护所有者与恢复确认。
|
||||
|
||||
基线采用云测试站当前前端对应的工作树 `cbc6b98`;该提交的 web 与部署版本 `0b753e5` 相同。并行主干及其他工作树不合并、不覆盖。
|
||||
|
||||
## 操作者主流程
|
||||
|
||||
| 顺序 | 页面操作 | 后台行为 | 完成边界 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 选择对内或对外知识库 | 读取该范围 overview、快照、作业及维护窗口 | 目标身份与版本来自所选范围;读取失败不当作空库 |
|
||||
| 2 | 封存测试版本 | POST `/api/v1/library/captures`,由队列及执行器捕获测试整库版本 | 投递不等于完成,以作业与登记快照为准;此步不发布生产 |
|
||||
| 3 | 查看变更及发布条件 | 展开变更、备份与恢复验证;若缺基线或恢复证据,沿用对应管理员入口 | 逐条呈现服务端阻塞原因,不删除发布门槛 |
|
||||
| 4 | 签发同步授权 | 管理员调用 `/api/v1/library/authorizations`,绑定目标与当前快照 | 有效期内仍需单独点击启动;不自动执行同步 |
|
||||
| 5 | 启动同步 | 沿用现有同步请求与执行链:固定版本、生产预备份、同步、校验及收尾 | 只在接口条件允许时可执行;运行中主按钮改为查看任务 |
|
||||
| 6 | 查看结果 | 自动刷新作业进度,终态按真实记录呈现 | 失败显示原始原因;维护占用不被其他作业成功覆盖 |
|
||||
| 异常 | 从版本与快照选择恢复点 | 继续执行独立恢复授权、影响确认和恢复条件校验 | 恢复整套目标知识状态,不回退测试知识库 |
|
||||
|
||||
封存、签发授权、启动同步三个动作保持独立,不将其合并为一键生产写入。
|
||||
|
||||
## 页面保留规则
|
||||
|
||||
- 顶栏:唯一的「版本与快照」入口和刷新。
|
||||
- 主工作区:实际目标身份、当前生产版本、候选测试版本、紧凑变更统计、当前主动作与一份阻塞原因。
|
||||
- 已有封存时提供次级「重新封存」;运行时不提供重复封存、授权或同步入口。
|
||||
- 「查看变更明细」「发布准备与恢复验证」「封存完整性」默认折叠;原有详情和验证回调继续存在。
|
||||
- 目标维护正常时折叠,持有维护窗口时自动展开;仍按窗口持有作业展示恢复信息。
|
||||
- 最近作业仅在有记录时展示,正常完成默认折叠,失败默认展开;运行中保留主进度,分项明细按需展开。
|
||||
- 版本抽屉保留历史筛选、分页、校验记录、恢复授权和影响确认,移除重复的封存按钮。
|
||||
- 发布管理页面移除旧文档级发布及历史来源关联区域,只展示整库发布流程。
|
||||
|
||||
## 验收清单
|
||||
|
||||
- [x] 前端生产构建通过。
|
||||
- [x] 原发布、恢复、维护所有者和刷新/切库回归通过。
|
||||
- [x] 同一挂载下依次切换封存、授权、同步,点击只调用对应动作。
|
||||
- [x] 折叠与展开、打开历史不触发业务写入。
|
||||
- [x] 运行时主操作只查看任务,不调用封存、授权或同步。
|
||||
- [x] 正常维护折叠、持有时展开、释放后折叠;切库重置明细展开状态。
|
||||
- [x] 无作业不画空进度;失败原因默认可见。
|
||||
- [x] 只读角色和读取失败时禁止主动作。
|
||||
|
||||
浏览器验收使用本地候选构建,GET/HEAD 通过已有 SSH 通道读取云测试 API;代理拒绝所有写请求。界面验收与真实封存、生产同步及恢复演练分开记录;本任务不执行这些业务写入。完整仓库门禁和云端部署结论以实际运行结果为准,不用上述前端检查替代。
|
||||
@@ -2,22 +2,16 @@ package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// CredentialStatus contains metadata only, never credential values.
|
||||
type CredentialStatus struct {
|
||||
Identity string `json:"identity,omitempty"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at,omitempty"`
|
||||
CorpName string `json:"corp_name,omitempty"`
|
||||
UserName string `json:"user_name,omitempty"`
|
||||
StatusKnown bool `json:"status_known"`
|
||||
}
|
||||
|
||||
func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, error) {
|
||||
@@ -26,23 +20,13 @@ func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus,
|
||||
return CredentialStatus{}, errors.New("could not read DWS credential status")
|
||||
}
|
||||
var decoded struct {
|
||||
CorpID json.RawMessage `json:"corp_id"`
|
||||
UserID json.RawMessage `json:"user_id"`
|
||||
Authenticated *bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at"`
|
||||
CorpName string `json:"corp_name"`
|
||||
UserName string `json:"user_name"`
|
||||
Reason string `json:"reason"`
|
||||
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")
|
||||
}
|
||||
identity := ""
|
||||
if len(decoded.CorpID) > 0 && len(decoded.UserID) > 0 && string(decoded.CorpID) != "null" && string(decoded.UserID) != "null" {
|
||||
sum := sha256.Sum256(append(append(decoded.CorpID, 0), decoded.UserID...))
|
||||
identity = hex.EncodeToString(sum[:])
|
||||
}
|
||||
return CredentialStatus{Identity: identity, Authenticated: *decoded.Authenticated, RefreshTokenValid: decoded.RefreshTokenValid, ExpiresAt: decoded.ExpiresAt, RefreshExpiresAt: decoded.RefreshExpiresAt, CorpName: decoded.CorpName, UserName: decoded.UserName, StatusKnown: decoded.Reason == ""}, nil
|
||||
return CredentialStatus{*decoded.Authenticated, decoded.RefreshTokenValid, decoded.ExpiresAt, decoded.RefreshExpiresAt}, nil
|
||||
}
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrLoginBusy = errors.New("another DWS authorization is active")
|
||||
var ErrLoginNotFound = errors.New("DWS authorization not found")
|
||||
|
||||
// DeviceLoginView contains only the user-facing challenge. Tokens remain in the
|
||||
// CLI's shared credential store; command output is never logged or returned.
|
||||
type DeviceLoginView struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
VerificationURL string `json:"verification_url,omitempty"`
|
||||
UserCode string `json:"user_code,omitempty"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type deviceLogin struct {
|
||||
view DeviceLoginView
|
||||
owner string
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
type DeviceLoginManager struct {
|
||||
ctx context.Context
|
||||
runner ExecRunner
|
||||
mu sync.Mutex
|
||||
sessions map[string]*deviceLogin
|
||||
}
|
||||
|
||||
func NewDeviceLoginManager(ctx context.Context, runner ExecRunner) *DeviceLoginManager {
|
||||
return &DeviceLoginManager{ctx: ctx, runner: runner, sessions: make(map[string]*deviceLogin)}
|
||||
}
|
||||
|
||||
func loginActive(state string) bool {
|
||||
return state == "starting" || state == "waiting" || state == "verifying"
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Start(owner string) (DeviceLoginView, error) {
|
||||
if owner == "" {
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for id, s := range m.sessions {
|
||||
if s.view.State == "cancelled" || s.view.State == "expired" {
|
||||
select {
|
||||
case <-s.done:
|
||||
default:
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
}
|
||||
if loginActive(s.view.State) {
|
||||
if s.owner == owner {
|
||||
return s.view, nil
|
||||
}
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
if time.Since(s.view.ExpiresAt) > 30*time.Minute || len(m.sessions) >= 16 {
|
||||
delete(m.sessions, id)
|
||||
}
|
||||
}
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return DeviceLoginView{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(m.ctx, 20*time.Minute)
|
||||
s := &deviceLogin{view: DeviceLoginView{ID: hex.EncodeToString(b[:]), State: "starting", ExpiresAt: time.Now().UTC().Add(20 * time.Minute)}, owner: owner, cancel: cancel, done: make(chan struct{})}
|
||||
m.sessions[s.view.ID] = s
|
||||
go m.run(ctx, s)
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Get(owner, id string) (DeviceLoginView, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s := m.sessions[id]
|
||||
if s == nil || s.owner != owner {
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
if loginActive(s.view.State) && !time.Now().Before(s.view.ExpiresAt) {
|
||||
s.cancel()
|
||||
finishLogin(s, "expired", "授权已过期,请重新发起。")
|
||||
}
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Cancel(owner, id string) (DeviceLoginView, error) {
|
||||
m.mu.Lock()
|
||||
s := m.sessions[id]
|
||||
if s == nil || s.owner != owner {
|
||||
m.mu.Unlock()
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
if loginActive(s.view.State) {
|
||||
s.cancel()
|
||||
finishLogin(s, "cancelled", "")
|
||||
}
|
||||
m.mu.Unlock()
|
||||
// Do not acknowledge cancellation while the old CLI could still write tokens.
|
||||
timer := time.NewTimer(7 * time.Second)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-s.done:
|
||||
case <-timer.C:
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func finishLogin(s *deviceLogin, state, message string) {
|
||||
s.view.State = state
|
||||
s.view.Error = message
|
||||
s.view.VerificationURL = ""
|
||||
s.view.UserCode = ""
|
||||
}
|
||||
|
||||
var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;]*[A-Za-z]`)
|
||||
var challengeCode = regexp.MustCompile(`(?:授权码|User code|User Code)\s*[::]\s*([A-Za-z0-9-]{4,32})`)
|
||||
var challengeExpiry = regexp.MustCompile(`(?:将在\s*|expires in\s*)([0-9]+)\s*(?:秒|seconds)`)
|
||||
|
||||
func safeDeviceURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && u.Scheme == "https" && u.Host == "login.dingtalk.com" && u.User == nil && u.Fragment == "" && u.Path == "/oauth2/device/verify.htm"
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) observe(s *deviceLogin, line string) {
|
||||
line = strings.TrimSpace(ansiEscape.ReplaceAllString(line, ""))
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if match := challengeCode.FindStringSubmatch(line); len(match) == 2 {
|
||||
s.view.UserCode = match[1]
|
||||
}
|
||||
if match := challengeExpiry.FindStringSubmatch(line); len(match) == 2 {
|
||||
seconds, _ := strconv.Atoi(match[1])
|
||||
if seconds > 0 && seconds <= 1800 {
|
||||
s.view.ExpiresAt = time.Now().UTC().Add(time.Duration(seconds) * time.Second)
|
||||
}
|
||||
}
|
||||
if safeDeviceURL(line) {
|
||||
u, _ := url.Parse(line)
|
||||
if s.view.VerificationURL == "" || u.Query().Get("user_code") != "" {
|
||||
s.view.VerificationURL = line
|
||||
}
|
||||
}
|
||||
if s.view.State == "starting" && s.view.UserCode != "" && s.view.VerificationURL != "" {
|
||||
s.view.State = "waiting"
|
||||
}
|
||||
if strings.Contains(line, "Step 3:") {
|
||||
s.view.State = "verifying"
|
||||
}
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) run(ctx context.Context, s *deviceLogin) {
|
||||
defer close(s.done)
|
||||
defer s.cancel()
|
||||
command, err := m.runner.command(ctx, "auth", "login", "--device", "--no-browser", "--format", "json")
|
||||
if err != nil {
|
||||
m.failed(s, "DWS 登录程序不可用,请联系管理员检查服务配置。")
|
||||
return
|
||||
}
|
||||
command.Env = append(command.Env, "DWS_LANG=zh", "NO_COLOR=1", "TERM=dumb")
|
||||
command.Stdout = io.Discard
|
||||
stderr, err := command.StderrPipe()
|
||||
if err != nil {
|
||||
m.failed(s, "无法启动 DWS 授权,请重试。")
|
||||
return
|
||||
}
|
||||
if err = command.Start(); err != nil {
|
||||
m.failed(s, "无法启动 DWS 授权,请检查凭据目录权限。")
|
||||
return
|
||||
}
|
||||
scanner := bufio.NewScanner(stderr)
|
||||
scanner.Buffer(make([]byte, 4096), 64*1024)
|
||||
for scanner.Scan() {
|
||||
m.observe(s, scanner.Text())
|
||||
}
|
||||
if scanner.Err() != nil {
|
||||
s.cancel()
|
||||
}
|
||||
err = command.Wait()
|
||||
m.mu.Lock()
|
||||
active := loginActive(s.view.State)
|
||||
m.mu.Unlock()
|
||||
if !active {
|
||||
return
|
||||
}
|
||||
if err != nil || ctx.Err() != nil {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) || !time.Now().Before(s.view.ExpiresAt) {
|
||||
finishLogin(s, "expired", "授权已过期,请重新发起。")
|
||||
} else {
|
||||
finishLogin(s, "failed", "DWS 授权未完成,请重试;若组织未开通 CLI 数据权限,请联系钉钉管理员。")
|
||||
}
|
||||
return
|
||||
}
|
||||
// A process exit alone is not proof that usable credentials were persisted.
|
||||
checkCtx, cancel := context.WithTimeout(m.ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
status, statusErr := ReadCredentialStatus(checkCtx, m.runner)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if statusErr != nil || !status.Authenticated || !status.RefreshTokenValid || !status.StatusKnown {
|
||||
finishLogin(s, "failed", "授权结束,但未读到有效 DWS 凭据,请重新授权。")
|
||||
} else {
|
||||
finishLogin(s, "succeeded", "")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) failed(s *deviceLogin, message string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if loginActive(s.view.State) {
|
||||
finishLogin(s, "failed", message)
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func deviceFixture(t *testing.T) (*DeviceLoginManager, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
binary := filepath.Join(root, "dws")
|
||||
script := `#!/usr/bin/env python3
|
||||
import sys,time,pathlib,json,os
|
||||
root=pathlib.Path(` + strconv.Quote(root) + `)
|
||||
a=sys.argv[1:]
|
||||
if a==['auth','login','--device','--no-browser','--format','json']:
|
||||
(root/'pid').write_text(str(os.getpid()))
|
||||
print(' 授权码: TEST-CODE',file=sys.stderr,flush=True)
|
||||
print('授权码将在 900 秒后过期。',file=sys.stderr,flush=True)
|
||||
print('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE',file=sys.stderr,flush=True)
|
||||
print('https://login.dingtalk.com/oauth2/device/verify.htm',file=sys.stderr,flush=True)
|
||||
print('never-expose-this-marker',file=sys.stderr,flush=True)
|
||||
while not (root/'finish').exists(): time.sleep(.01)
|
||||
if (root/'fail').exists(): sys.exit(1)
|
||||
elif a==['auth','status','--readonly','--format','json']:
|
||||
print(json.dumps({'authenticated':not (root/'invalid').exists(),'refresh_token_valid':True,'corp_name':'测试组织','user_name':'测试账号','access_token':'never-expose-this-marker'}))
|
||||
else: sys.exit(9)
|
||||
`
|
||||
if err := os.WriteFile(binary, []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
return NewDeviceLoginManager(ctx, ExecRunner{Binary: binary}), root
|
||||
}
|
||||
func awaitDevice(t *testing.T, m *DeviceLoginManager, id, state string) DeviceLoginView {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
v, e := m.Get("owner", id)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if v.State == state {
|
||||
return v
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
v, _ := m.Get("owner", id)
|
||||
t.Fatalf("state=%s want=%s error=%s", v.State, state, v.Error)
|
||||
return v
|
||||
}
|
||||
func TestDeviceLoginUsesOfficialChallengeAndSharedCLI(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
initial, err := m.Start("owner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if initial.State != "starting" {
|
||||
t.Fatal(initial)
|
||||
}
|
||||
waiting := awaitDevice(t, m, initial.ID, "waiting")
|
||||
if waiting.UserCode != "TEST-CODE" || !strings.Contains(waiting.VerificationURL, "user_code=TEST-CODE") {
|
||||
t.Fatal("missing complete official challenge")
|
||||
}
|
||||
if _, err = m.Start("other"); !errors.Is(err, ErrLoginBusy) {
|
||||
t.Fatal("parallel logins may overwrite shared credentials")
|
||||
}
|
||||
duplicate, _ := m.Start("owner")
|
||||
if duplicate.ID != initial.ID {
|
||||
t.Fatal("duplicate start was not idempotent")
|
||||
}
|
||||
if _, err = m.Get("other", initial.ID); !errors.Is(err, ErrLoginNotFound) {
|
||||
t.Fatal("challenge leaked to another owner")
|
||||
}
|
||||
if _, err = m.Cancel("other", initial.ID); !errors.Is(err, ErrLoginNotFound) {
|
||||
t.Fatal("foreign cancellation permitted")
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(root, "finish"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := awaitDevice(t, m, initial.ID, "succeeded")
|
||||
raw, _ := json.Marshal(done)
|
||||
if done.UserCode != "" || done.VerificationURL != "" || strings.Contains(string(raw), "never-expose") {
|
||||
t.Fatal("completed session retained sensitive output")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginCancellationClearsChallenge(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
v, _ := m.Start("owner")
|
||||
awaitDevice(t, m, v.ID, "waiting")
|
||||
closed, err := m.Cancel("owner", v.ID)
|
||||
if err != nil || closed.State != "cancelled" || closed.UserCode != "" || closed.VerificationURL != "" {
|
||||
t.Fatal(closed, err)
|
||||
}
|
||||
pidBytes, err := os.ReadFile(filepath.Join(root, "pid"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pid, _ := strconv.Atoi(string(pidBytes))
|
||||
if syscall.Kill(pid, 0) == nil {
|
||||
t.Fatal("cancel returned while credential-writing process was still running")
|
||||
}
|
||||
again, _ := m.Get("owner", v.ID)
|
||||
if again.State != "cancelled" {
|
||||
t.Fatal("late process exit overwrote cancellation")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginRejectsExitWithoutPersistedCredentials(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
os.WriteFile(filepath.Join(root, "invalid"), nil, 0600)
|
||||
os.WriteFile(filepath.Join(root, "finish"), nil, 0600)
|
||||
v, _ := m.Start("owner")
|
||||
done := awaitDevice(t, m, v.ID, "failed")
|
||||
if !strings.Contains(done.Error, "未读到有效") {
|
||||
t.Fatal("successful exit was treated as authenticated")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginFailureIsRedactedAndRetryable(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
os.WriteFile(filepath.Join(root, "fail"), nil, 0600)
|
||||
os.WriteFile(filepath.Join(root, "finish"), nil, 0600)
|
||||
v, _ := m.Start("owner")
|
||||
done := awaitDevice(t, m, v.ID, "failed")
|
||||
if strings.Contains(done.Error, "never-expose") || done.Error == "" {
|
||||
t.Fatal("raw CLI output or missing error")
|
||||
}
|
||||
retry, e := m.Start("owner")
|
||||
if e != nil || retry.ID == v.ID {
|
||||
t.Fatal("cannot retry failed authorization")
|
||||
}
|
||||
}
|
||||
func TestDeviceChallengeRejectsUntrustedLinksAndExpires(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
_ = root
|
||||
s := &deviceLogin{view: DeviceLoginView{State: "starting", ExpiresAt: time.Now().Add(time.Minute)}, cancel: func() {}}
|
||||
m.observe(s, "授权码: TEST-CODE")
|
||||
for _, link := range []string{"http://login.dingtalk.com/oauth2/device/verify.htm", "https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm", "https://user:pass@login.dingtalk.com/oauth2/device/verify.htm", "javascript:alert(1)", "https://login.dingtalk.com/other"} {
|
||||
m.observe(s, link)
|
||||
}
|
||||
if s.view.State != "starting" || s.view.VerificationURL != "" {
|
||||
t.Fatal("untrusted link accepted")
|
||||
}
|
||||
s.view.ID = "test-expired"
|
||||
s.owner = "owner"
|
||||
s.view.ExpiresAt = time.Now().Add(-time.Second)
|
||||
m.sessions[s.view.ID] = s
|
||||
got, e := m.Get("owner", s.view.ID)
|
||||
if e != nil || got.State != "expired" || got.UserCode != "" {
|
||||
t.Fatal("expired challenge retained")
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
|
||||
// KnowledgeBase 是一个钉钉知识库(wiki 空间)。URL 是 alidocs 空间链接,直接可用于登记来源。
|
||||
type KnowledgeBase struct {
|
||||
Registered bool `json:"registered"`
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
SpaceType string `json:"space_type"`
|
||||
@@ -31,7 +30,6 @@ type KnowledgeBase struct {
|
||||
|
||||
// DriveSpace 是一个钉盘空间(我的文件 = mySpace;组织空间 = orgSpace)。
|
||||
type DriveSpace struct {
|
||||
Registered bool `json:"registered"`
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
RootFolderID string `json:"root_folder_id,omitempty"`
|
||||
@@ -40,7 +38,6 @@ type DriveSpace struct {
|
||||
|
||||
// Result 是一次发现的结果。
|
||||
type Result struct {
|
||||
Identity string `json:"identity,omitempty"`
|
||||
KnowledgeBases []KnowledgeBase `json:"knowledge_bases"`
|
||||
DriveSpaces []DriveSpace `json:"drive_spaces"`
|
||||
// KnowledgeNotice / DriveNotice 说明「这一类为什么不全」:权限不足、未登录、或被上限截断。
|
||||
@@ -73,26 +70,21 @@ func SpaceListArgs(spaceType string) []string {
|
||||
// 知识库整体列不出来 → 返回 ErrUnavailable(页面必须提示「列不出来」,不能装成空列表)。
|
||||
// 单独一类失败、钉盘失败、或结果被上限截断 → 只丢那一部分,把原因写进对应的 Notice。
|
||||
func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result := Result{FetchedAt: time.Now().UTC(), KnowledgeBases: []KnowledgeBase{}, DriveSpaces: []DriveSpace{}}
|
||||
successful := 0
|
||||
causes := []error{}
|
||||
result := Result{FetchedAt: time.Now().UTC()}
|
||||
|
||||
failures := make([]string, 0, len(knowledgeSpaceTypes))
|
||||
seenKnowledge := map[string]bool{}
|
||||
for _, spaceType := range knowledgeSpaceTypes {
|
||||
raw, err := runner.RunDWS(ctx, SpaceListArgs(spaceType)...)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, failureCause(raw, err)))
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
continue
|
||||
}
|
||||
bases, notice, err := parseKnowledgeBases(raw, spaceType)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, failureCause(raw, err)))
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
continue
|
||||
}
|
||||
successful++
|
||||
if notice != "" {
|
||||
result.KnowledgeNotice = notice
|
||||
}
|
||||
@@ -104,6 +96,9 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result.KnowledgeBases = append(result.KnowledgeBases, base)
|
||||
}
|
||||
}
|
||||
if len(result.KnowledgeBases) == 0 && len(failures) > 0 {
|
||||
return result, fmt.Errorf("%w: %s", ErrUnavailable, strings.Join(failures, ";"))
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
result.KnowledgeNotice = strings.Join(append([]string{result.KnowledgeNotice}, failures...), ";")
|
||||
}
|
||||
@@ -112,17 +107,14 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
for _, spaceType := range []string{"mySpace", "orgSpace"} {
|
||||
raw, err := runner.RunDWS(ctx, "wiki", "space", "list", "--type", spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限"
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
result.DriveNotice = err.Error()
|
||||
continue
|
||||
}
|
||||
spaces, err := parseDriveSpaces(raw, spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限"
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
result.DriveNotice = err.Error()
|
||||
continue
|
||||
}
|
||||
successful++
|
||||
for _, space := range spaces {
|
||||
if seenDrive[space.SpaceType+":"+space.SpaceID] {
|
||||
continue
|
||||
@@ -131,21 +123,11 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result.DriveSpaces = append(result.DriveSpaces, space)
|
||||
}
|
||||
}
|
||||
if successful == 0 && len(causes) > 0 {
|
||||
return result, fmt.Errorf("%w: %w", ErrUnavailable, errors.Join(causes...))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func describe(scope string, err error) string {
|
||||
reason := "读取失败,请重试"
|
||||
if errors.Is(err, ErrCredentials) {
|
||||
reason = "DWS 授权已失效"
|
||||
}
|
||||
if errors.Is(err, ErrPermission) {
|
||||
reason = "当前范围权限不足"
|
||||
}
|
||||
return scope + ":" + reason
|
||||
return scope + ":" + err.Error()
|
||||
}
|
||||
|
||||
// parseKnowledgeBases 解析 `dws wiki +space-list`:
|
||||
|
||||
@@ -127,7 +127,7 @@ func TestDiscoverKeepsKnowledgeBasesWhenDriveIsDenied(t *testing.T) {
|
||||
if len(result.DriveSpaces) != 0 {
|
||||
t.Fatalf("drive spaces = %d, want 0", len(result.DriveSpaces))
|
||||
}
|
||||
if !strings.Contains(result.DriveNotice, "权限") {
|
||||
if !strings.Contains(result.DriveNotice, "permission denied") {
|
||||
t.Fatalf("drive notice = %q", result.DriveNotice)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,8 @@ type ExecRunner struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// command keeps device login and source reads on one credential environment.
|
||||
func (r ExecRunner) command(ctx context.Context, args ...string) (*exec.Cmd, error) {
|
||||
// RunDWS 运行 `dws <args…>` 并返回 stdout。
|
||||
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
|
||||
binary := r.Binary
|
||||
if binary == "" {
|
||||
binary = os.Getenv("DWS_BIN")
|
||||
@@ -32,24 +32,14 @@ func (r ExecRunner) command(ctx context.Context, args ...string) (*exec.Cmd, err
|
||||
}
|
||||
binary = found
|
||||
}
|
||||
command := exec.CommandContext(ctx, binary, args...)
|
||||
command.Env = dwsEnv()
|
||||
command.WaitDelay = 2 * time.Second
|
||||
return command, nil
|
||||
}
|
||||
|
||||
// RunDWS uses the same executable and credential environment as device login.
|
||||
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
|
||||
timeout := r.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 25 * time.Second
|
||||
}
|
||||
runCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
command, err := r.command(runCtx, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
command := exec.CommandContext(runCtx, binary, args...)
|
||||
command.Env = dwsEnv()
|
||||
var stdout, stderr bytes.Buffer
|
||||
command.Stdout = &stdout
|
||||
command.Stderr = &stderr
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrCredentials = errors.New("DWS authorization required")
|
||||
var ErrPermission = errors.New("DWS directory permission denied")
|
||||
|
||||
// failureCause inspects only structured CLI errors; no upstream text is returned.
|
||||
func failureCause(raw []byte, cause error) error {
|
||||
var v struct {
|
||||
Error struct {
|
||||
Type string `json:"type"`
|
||||
Code any `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(raw, &v) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
text := strings.ToLower(v.Error.Type + " " + fmt.Sprint(v.Error.Code) + " " + v.Error.Message)
|
||||
for _, key := range []string{"permission", "forbidden", "scope", "access denied", "权限", "403"} {
|
||||
if strings.Contains(text, key) {
|
||||
return ErrPermission
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"unauth", "not_logged_in", "not logged", "login_required", "login required", "authentication", "auth_required", "credential", "token_expired", "invalid_token", "token expired", "invalid_grant", "未登录", "授权已过期", "授权失效"} {
|
||||
if strings.Contains(text, key) {
|
||||
return ErrCredentials
|
||||
}
|
||||
}
|
||||
if errors.Is(cause, ErrCredentials) || errors.Is(cause, ErrPermission) {
|
||||
return cause
|
||||
}
|
||||
return ErrUnavailable
|
||||
}
|
||||
@@ -107,9 +107,6 @@ func classifyRole(method, path string) string {
|
||||
if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") {
|
||||
return roleAdmin
|
||||
}
|
||||
if strings.HasPrefix(path, "/api/v1/dws-login") || strings.HasPrefix(path, "/api/v1/pp-connection") || strings.HasPrefix(path, "/api/v1/dingtalk-spaces") || strings.HasPrefix(path, "/api/v1/dingtalk-session") {
|
||||
return roleAdmin
|
||||
}
|
||||
if method == http.MethodGet {
|
||||
return roleViewer
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Credential events are committed with their secret revision in one atomic file.
|
||||
// Merge them into the existing audit view without copying secrets into SQL.
|
||||
func combinedSourceAudit(ctx context.Context, reader sourceAuditReader, manager *ppauth.Manager, limit, offset int) (postgresstore.SourceAuditPage, error) {
|
||||
if manager == nil {
|
||||
return reader.ListSourceAudit(ctx, limit, offset)
|
||||
}
|
||||
events, err := manager.Events(ctx)
|
||||
if err != nil {
|
||||
return postgresstore.SourceAuditPage{}, err
|
||||
}
|
||||
if len(events) == 0 {
|
||||
return reader.ListSourceAudit(ctx, limit, offset)
|
||||
}
|
||||
start := offset - len(events)
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
rows := make([]postgresstore.SourceAuditItem, 0, limit+len(events))
|
||||
total := 0
|
||||
for next := start; len(rows) < limit+len(events); {
|
||||
take := limit + len(events) - len(rows)
|
||||
if take > 100 {
|
||||
take = 100
|
||||
}
|
||||
page, e := reader.ListSourceAudit(ctx, take, next)
|
||||
if e != nil {
|
||||
return postgresstore.SourceAuditPage{}, e
|
||||
}
|
||||
total = page.Total
|
||||
rows = append(rows, page.Items...)
|
||||
next += len(page.Items)
|
||||
if next >= total || len(page.Items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, e := range events {
|
||||
rows = append(rows, postgresstore.SourceAuditItem{ID: e.ID, ConnectionID: "", SourceName: e.SourceName, Action: e.Action, Actor: e.Actor, CreatedAt: e.CreatedAt, Detail: e.Detail})
|
||||
}
|
||||
sort.SliceStable(rows, func(i, j int) bool {
|
||||
if rows[i].CreatedAt.Equal(rows[j].CreatedAt) {
|
||||
return rows[i].ID > rows[j].ID
|
||||
}
|
||||
return rows[i].CreatedAt.After(rows[j].CreatedAt)
|
||||
})
|
||||
skip := offset - start
|
||||
if skip > len(rows) {
|
||||
skip = len(rows)
|
||||
}
|
||||
end := skip + limit
|
||||
if end > len(rows) {
|
||||
end = len(rows)
|
||||
}
|
||||
return postgresstore.SourceAuditPage{Items: rows[skip:end], Total: total + len(events), Limit: limit, Offset: offset}, nil
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -24,16 +25,25 @@ func listDingtalkSources(w http.ResponseWriter, r *http.Request, config Config)
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
identity, _ := requireSessionIdentity(w, r)
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, 403, map[string]string{"error": "需要管理员身份列举数据源"})
|
||||
lister := config.DingtalkSources
|
||||
if lister == nil {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := availableDWS(ctx, config)
|
||||
result, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
|
||||
// 环境问题(dws 未登录 / 权限不足 / 二进制缺失):页面显示"暂时列不出来",
|
||||
// 不是平台故障,也不该把内部错误细节当 500 抛出去。
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"error": "dingtalk_discovery_unavailable",
|
||||
"hint": "dws 未登录或缺少租户目录读权限;请先刷新钉钉会话,或让管理员检查 dws 凭据。",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list dingtalk sources"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": result})
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestListDingtalkSourcesReportsEnvironmentProblemsAsUnavailable(t *testing.T
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("unavailable = %d, want 503 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), "dws_unavailable") {
|
||||
if !strings.Contains(rec.Body.String(), "dingtalk_discovery_unavailable") {
|
||||
t.Fatalf("body = %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,42 +2,59 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
func TestDWSNameConflictIsNotASuccessfulRegistration(t *testing.T) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: postgresstore.ErrDingtalkSpaceNameTaken}
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "wiki", SpaceID: "testspace"}}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", nil)
|
||||
registerDWSOnlySpace(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op")
|
||||
if rec.Code != 409 {
|
||||
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) {
|
||||
result := dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"}}, DriveSpaces: []dingtalkdiscovery.DriveSpace{{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "drive-root"}}}
|
||||
input, err := resolveDWS(result, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q"))
|
||||
if err != nil || input.RootKey != "space-9JOGOLBQndOyaz4Q" || input.Name != "国内技术支持管理" || input.RootID != "9JOGOLBQndOyaz4Q" || input.SpaceID != "9JOGOLBQndOyaz4Q" {
|
||||
t.Fatalf("wiki resolution=%+v %v", input, err)
|
||||
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)
|
||||
}
|
||||
input, err = resolveDWS(result, dingtalkdiscovery.SpaceURL("102571304"))
|
||||
if err != nil || input.RootID != "drive-root" || input.RootKey != "space-102571304" {
|
||||
t.Fatalf("drive resolution=%+v %v", input, err)
|
||||
|
||||
// 钉盘的根是 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 TestResolveDWSRejectsUnknownAndUnwiredWithoutBrowserFallback(t *testing.T) {
|
||||
if _, err := resolveDWS(dingtalkdiscovery.Result{}, dingtalkdiscovery.SpaceURL("unknownspace1")); err == nil {
|
||||
t.Fatal("unknown space resolved")
|
||||
|
||||
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 _, err := availableDWS(context.Background(), Config{}); err == nil {
|
||||
t.Fatal("unwired service resolved")
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), nil, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")); ok {
|
||||
t.Fatal("without a lister nothing can resolve")
|
||||
}
|
||||
if _, err := resolveDWS(dingtalkdiscovery.Result{}, "not-a-space-url"); err == nil {
|
||||
t.Fatal("invalid space resolved")
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, "not-a-space-url"); ok {
|
||||
t.Fatal("a URL without a space id must not resolve")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -10,6 +12,10 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// DingTalk login proxy. The scan-code login itself lives in the
|
||||
@@ -96,15 +102,86 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "url is required"})
|
||||
return
|
||||
}
|
||||
registerDWSOnlySpace(w, r, config, strings.TrimSpace(input.URL), operationID)
|
||||
// dws 已经持有有效凭据(access 自动续期、refresh 一个月),登记也该走它:
|
||||
// 只有 dws 解析不出这个空间时,才回落到老的扫码侧车。
|
||||
if registered, ok := registerSpaceThroughDWS(w, r, config, strings.TrimSpace(input.URL), operationID); ok || registered {
|
||||
return
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"url": strings.TrimSpace(input.URL)})
|
||||
status, data := proxyDingtalk(http.MethodPost, "/spaces/add", payload)
|
||||
if status != http.StatusOK {
|
||||
if status == 0 {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "dingtalk_login_unavailable"})
|
||||
return
|
||||
}
|
||||
// Relay the sidecar's error (login_required / space_not_found /
|
||||
// name_conflict) verbatim; bodies are machine codes, no secrets.
|
||||
writeProxyResult(w, status, data)
|
||||
return
|
||||
}
|
||||
var resolved struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
Root string `json:"root"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &resolved); err != nil || resolved.Key == "" || resolved.Name == "" || resolved.Root == "" {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "invalid sidecar registration response"})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
|
||||
return
|
||||
}
|
||||
spaceID := extractDingtalkSpaceID(input.URL)
|
||||
if spaceID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid space url"})
|
||||
return
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(), Actor: actorFor(r),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_name_conflict",
|
||||
"hint": "已有同名来源仍在使用(未下架):请先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间。",
|
||||
})
|
||||
return
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_identity_conflict",
|
||||
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试;若仍失败,把该来源「去掉来源」后再登记。",
|
||||
})
|
||||
return
|
||||
case err != nil:
|
||||
// 真正的数据库/内部故障不能伪装成"冲突":换个 500 才有人去查日志。
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
|
||||
return
|
||||
}
|
||||
// First scan is enqueued right away: the new connection has no catalog
|
||||
// head yet, so the generic sources/{id}/refresh endpoint would 404 until
|
||||
// the first snapshot exists.
|
||||
if enqueuer, ok := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); ok {
|
||||
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(r.Context(), governance.CatalogSource{
|
||||
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: resolved.Name,
|
||||
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
|
||||
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
|
||||
}
|
||||
}
|
||||
log.Printf("dingtalk space %q registered as connection %s by %s", resolved.Name, connectionID, actorFor(r))
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
|
||||
"connection_id": connectionID, "name": resolved.Name,
|
||||
}})
|
||||
}
|
||||
|
||||
var dingtalkSpacePattern = regexp.MustCompile(`/spaces/([A-Za-z0-9_-]+)`)
|
||||
|
||||
func extractDingtalkSpaceID(raw string) string {
|
||||
if !validDingtalkURL(raw) {
|
||||
return ""
|
||||
}
|
||||
match := dingtalkSpacePattern.FindStringSubmatch(raw)
|
||||
if len(match) == 2 {
|
||||
return match[1]
|
||||
@@ -167,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
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
@@ -124,7 +123,7 @@ func TestDingtalkSpaceRegistrationErrorClassification(t *testing.T) {
|
||||
|
||||
call := func(storeErr error) (int, string) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: storeErr}
|
||||
handler, err := NewHandler(Config{Store: store, DingtalkSources: fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "公司级技术支持知识库", SpaceID: "9JOK9EEOMLMWX4Q"}}}}})
|
||||
handler, err := NewHandler(Config{Store: store})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHandler() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
func registerDWSLoginRoutes(mux *http.ServeMux, config Config) {
|
||||
mux.HandleFunc("POST /api/v1/dws-login", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "start") })
|
||||
mux.HandleFunc("GET /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "get") })
|
||||
mux.HandleFunc("DELETE /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "cancel") })
|
||||
}
|
||||
|
||||
func handleDWSLogin(w http.ResponseWriter, r *http.Request, config Config, action string) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "需要管理员身份才能管理 DWS 授权"})
|
||||
return
|
||||
}
|
||||
if action != "get" {
|
||||
originOK := true
|
||||
if raw := r.Header.Get("Origin"); raw != "" {
|
||||
origin, err := url.Parse(raw)
|
||||
originOK = err == nil && origin.Host == r.Host && (origin.Scheme == "http" || origin.Scheme == "https")
|
||||
}
|
||||
if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != "dws-login" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "请从本平台的数据源配置页发起授权"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if config.DWSLogin == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "DWS 登录服务未接通,请联系管理员"})
|
||||
return
|
||||
}
|
||||
// Bind the challenge to this authenticated administrator and browser session.
|
||||
owner := identity.UserID + "/" + identity.SessionID
|
||||
var view dingtalkdiscovery.DeviceLoginView
|
||||
var err error
|
||||
switch action {
|
||||
case "start":
|
||||
view, err = config.DWSLogin.Start(owner)
|
||||
case "get":
|
||||
view, err = config.DWSLogin.Get(owner, r.PathValue("id"))
|
||||
case "cancel":
|
||||
view, err = config.DWSLogin.Cancel(owner, r.PathValue("id"))
|
||||
}
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, dingtalkdiscovery.ErrLoginNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "授权会话已结束或服务已重启,请重新发起"})
|
||||
case errors.Is(err, dingtalkdiscovery.ErrLoginBusy):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "另一位管理员正在授权,请稍后再试"})
|
||||
default:
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "无法发起 DWS 授权,请重试"})
|
||||
}
|
||||
return
|
||||
}
|
||||
if config.PPConnection != nil && (action != "get" || view.State == "succeeded" || view.State == "failed" || view.State == "expired") {
|
||||
if err := config.PPConnection.AuditOnce(r.Context(), "dws-"+view.ID+"-"+string(view.State), "钉钉账号(DWS)", "dws_authorization", identity.Username, "DWS 授权状态:"+string(view.State)); err != nil {
|
||||
if action == "start" {
|
||||
_, _ = config.DWSLogin.Cancel(owner, view.ID)
|
||||
}
|
||||
writeJSON(w, 503, map[string]string{"error": "授权审计写入失败,请重试"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if action != "get" {
|
||||
log.Printf("DWS authorization action=%s id=%s actor=%s", action, view.ID, identity.Username)
|
||||
}
|
||||
status := http.StatusOK
|
||||
if action == "start" {
|
||||
status = http.StatusAccepted
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"data": view})
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDWSLoginHTTPAuthenticationOwnershipAndOrigin(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
manager := dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{Binary: "/nonexistent/dws"})
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, DWSLogin: manager})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(method, path, role, session, origin, intent string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
if role != "" {
|
||||
r = r.WithContext(context.WithValue(r.Context(), sessionKey{}, sessionIdentity{UserID: "admin-user", Username: "tester", Role: role, SessionID: session}))
|
||||
}
|
||||
r.Header.Set("Origin", origin)
|
||||
r.Header.Set("X-Governance-Action", intent)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
for _, role := range []string{"", roleViewer, roleEngineer} {
|
||||
w := call("POST", "/api/v1/dws-login", role, "s1", "", "dws-login")
|
||||
if w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("role=%q status=%d", role, w.Code)
|
||||
}
|
||||
}
|
||||
for _, input := range [][2]string{{"", ""}, {"https://foreign.invalid", "dws-login"}} {
|
||||
w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", input[0], input[1])
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("origin/intent not enforced: %d", w.Code)
|
||||
}
|
||||
}
|
||||
w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", "", "dws-login")
|
||||
if w.Code != 202 || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("start=%d body=%s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Data dingtalkdiscovery.DeviceLoginView `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Data.ID == "" {
|
||||
t.Fatal("missing session", err)
|
||||
}
|
||||
path := "/api/v1/dws-login/" + body.Data.ID
|
||||
for _, method := range []string{"GET", "DELETE"} {
|
||||
w = call(method, path, roleAdmin, "other-session", "", "dws-login")
|
||||
if w.Code != 404 {
|
||||
t.Fatalf("foreign session %s=%d", method, w.Code)
|
||||
}
|
||||
w = call(method, path, roleEngineer, "s1", "", "dws-login")
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("engineer %s=%d", method, w.Code)
|
||||
}
|
||||
}
|
||||
w = call("GET", path, roleAdmin, "s1", "", "")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("get=%d", w.Code)
|
||||
}
|
||||
w = call("DELETE", path, roleAdmin, "s1", "", "dws-login")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("cancel=%d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDWSLoginRoutesAreAdminOnly(t *testing.T) {
|
||||
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
|
||||
for _, path := range []string{"/api/v1/dws-login", "/api/v1/dws-login/session-id"} {
|
||||
if got := classifyRole(method, path); got != roleAdmin {
|
||||
t.Errorf("%s %s role=%s; authorization artifacts must be admin-only", method, path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dwsSourceError struct {
|
||||
Status int
|
||||
Code, Hint string
|
||||
}
|
||||
|
||||
func (e *dwsSourceError) Error() string { return e.Hint }
|
||||
func writeDWSSourceError(w http.ResponseWriter, err error) {
|
||||
var e *dwsSourceError
|
||||
if errors.As(err, &e) {
|
||||
writeJSON(w, e.Status, map[string]string{"error": e.Code, "hint": e.Hint})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 500, map[string]string{"error": "dws_source_failed", "hint": "读取钉钉来源失败,请重试"})
|
||||
}
|
||||
func availableDWS(ctx context.Context, config Config) (dingtalkdiscovery.Result, error) {
|
||||
identity := ""
|
||||
if config.DingtalkSources == nil {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{501, "dws_unwired", "DWS 来源服务未接通"}
|
||||
}
|
||||
if reader, ok := config.DingtalkSources.(interface {
|
||||
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
|
||||
}); ok {
|
||||
status, err := reader.ReadDWSMetadata(ctx)
|
||||
if err != nil || !status.StatusKnown {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{503, "dws_status_unavailable", "暂时无法读取 DWS 授权状态,请重试"}
|
||||
}
|
||||
identity = status.Identity
|
||||
if !status.Authenticated && !status.RefreshTokenValid {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{401, "dws_login_required", "DWS 未登录或授权已失效,请重新授权"}
|
||||
}
|
||||
}
|
||||
result, err := config.DingtalkSources.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, dingtalkdiscovery.ErrCredentials) {
|
||||
return result, &dwsSourceError{401, "dws_login_required", "DWS 授权已失效,请重新授权"}
|
||||
}
|
||||
if errors.Is(err, dingtalkdiscovery.ErrPermission) {
|
||||
return result, &dwsSourceError{403, "dws_permission_denied", "当前 DWS 账号缺少目录读取权限"}
|
||||
}
|
||||
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
|
||||
return result, &dwsSourceError{503, "dws_unavailable", "DWS 目录暂时无法读取,请检查连接后重试"}
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
if identity != "" {
|
||||
reader := config.DingtalkSources.(interface {
|
||||
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
|
||||
})
|
||||
fresh, e := reader.ReadDWSMetadata(ctx)
|
||||
if e != nil {
|
||||
return result, &dwsSourceError{503, "dws_status_unavailable", "无法确认当前账号,请重试"}
|
||||
}
|
||||
if fresh.Identity != identity {
|
||||
return result, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"}
|
||||
}
|
||||
}
|
||||
result.Identity = identity
|
||||
if config.Store != nil {
|
||||
if page, e := config.Store.ListSourceConnections(ctx); e == nil {
|
||||
seen := map[string]bool{}
|
||||
for _, c := range page.Items {
|
||||
seen[c.ID] = true
|
||||
}
|
||||
for i, kb := range result.KnowledgeBases {
|
||||
in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + kb.SpaceID}
|
||||
result.KnowledgeBases[i].Registered = seen[in.ConnectionID()]
|
||||
}
|
||||
for i, space := range result.DriveSpaces {
|
||||
in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + space.SpaceID}
|
||||
result.DriveSpaces[i].Registered = seen[in.ConnectionID()]
|
||||
}
|
||||
}
|
||||
}
|
||||
if registry, ok := config.Store.(interface {
|
||||
RegisteredDingtalkSpaceIDs(context.Context) (map[string]bool, error)
|
||||
}); ok {
|
||||
ids, e := registry.RegisteredDingtalkSpaceIDs(ctx)
|
||||
if e != nil {
|
||||
return result, &dwsSourceError{503, "dws_registration_state_unavailable", "无法核对已接入空间,请重试"}
|
||||
}
|
||||
for i, kb := range result.KnowledgeBases {
|
||||
result.KnowledgeBases[i].Registered = ids[kb.SpaceID]
|
||||
}
|
||||
for i, space := range result.DriveSpaces {
|
||||
result.DriveSpaces[i].Registered = ids[space.SpaceID]
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func resolveDWS(result dingtalkdiscovery.Result, raw string) (postgresstore.RegisterDingtalkSpaceInput, error) {
|
||||
spaceID := extractDingtalkSpaceID(raw)
|
||||
if spaceID == "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"}
|
||||
}
|
||||
for _, base := range result.KnowledgeBases {
|
||||
if base.SpaceID == spaceID {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: base.Name, RootID: spaceID, SpaceID: spaceID}, nil
|
||||
}
|
||||
}
|
||||
for _, space := range result.DriveSpaces {
|
||||
if space.SpaceID == spaceID && space.RootFolderID != "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: space.Name, RootID: space.RootFolderID, SpaceID: spaceID}, nil
|
||||
}
|
||||
}
|
||||
if result.KnowledgeNotice != "" || result.DriveNotice != "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{503, "dws_scope_incomplete", "当前目录结果不完整,无法确认所选空间;请检查相应目录权限后重试"}
|
||||
}
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{409, "dws_space_not_visible", "当前 DWS 账号已看不到所选空间,请刷新范围或核对账号权限"}
|
||||
}
|
||||
func registerDWSOnlySpace(w http.ResponseWriter, r *http.Request, config Config, raw, operationID string) {
|
||||
if extractDingtalkSpaceID(raw) == "" {
|
||||
writeDWSSourceError(w, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := availableDWS(ctx, config)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity {
|
||||
writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"})
|
||||
return
|
||||
}
|
||||
input, err := resolveDWS(result, raw)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
input.Now = config.Now()
|
||||
input.Actor = actorFor(r)
|
||||
store, ok := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !ok {
|
||||
writeJSON(w, 503, map[string]string{"error": "registration_unavailable"})
|
||||
return
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(ctx, input)
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, 409, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源仍在使用:请核对空间身份,必要时先移除旧连接(原去掉来源操作)"})
|
||||
return
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, 409, map[string]string{"error": "space_identity_conflict", "hint": "登记键已指向另一个空间,请刷新后核对来源"})
|
||||
return
|
||||
case err != nil:
|
||||
writeJSON(w, 500, map[string]string{"error": "space_registration_failed"})
|
||||
return
|
||||
}
|
||||
queued := false
|
||||
if queue, ok := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); ok {
|
||||
_, _, err = queue.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: input.Name}, "dws-source-first:"+connectionID, config.Now().UTC())
|
||||
queued = err == nil
|
||||
}
|
||||
writeJSON(w, 201, map[string]any{"data": map[string]any{"connection_id": connectionID, "name": input.Name, "first_scan_queued": queued}})
|
||||
}
|
||||
func validateDWSSpace(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !credentialAdmin(w, r, "dingtalk-space") {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
URLs []string `json:"urls"`
|
||||
}
|
||||
if decodeJSONStrict(r, &input) != nil || len(input.URLs) == 0 || len(input.URLs) > 100 {
|
||||
writeJSON(w, 400, map[string]string{"error": "请选择有效的空间范围"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := availableDWS(ctx, config)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity {
|
||||
writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"})
|
||||
return
|
||||
}
|
||||
for _, raw := range input.URLs {
|
||||
if _, err := resolveDWS(result, raw); err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": map[string]any{"valid": true, "checked_at": config.Now().UTC(), "count": len(input.URLs)}})
|
||||
}
|
||||
func validDingtalkURL(raw string) bool {
|
||||
if !strings.Contains(raw, "://") {
|
||||
return true
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && u.Scheme == "https" && u.Host == "alidocs.dingtalk.com" && u.User == nil && u.Fragment == ""
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDWSRegistrationNeverFallsBackToBrowserSession(t *testing.T) {
|
||||
calls := 0
|
||||
sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(401) }))
|
||||
defer sidecar.Close()
|
||||
t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL)
|
||||
h, err := NewHandler(Config{Store: &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}}, DingtalkSources: fakeDingtalkSources{err: dingtalkdiscovery.ErrUnavailable}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", strings.NewReader(`{"url":"https://alidocs.dingtalk.com/i/spaces/valid-space-id/overview"}`))
|
||||
req.Header.Set("Idempotency-Key", "op-dws-only")
|
||||
req.Header.Set("X-Governance-Action", "dingtalk-space")
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if calls != 0 || rec.Code != 503 || !strings.Contains(rec.Body.String(), "dws_unavailable") {
|
||||
t.Fatalf("DWS failed: legacy calls=%d status=%d body=%s", calls, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) {
|
||||
switch value := node.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range value {
|
||||
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" {
|
||||
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" {
|
||||
t.Fatalf("unapproved endpoint exposure at %s", path)
|
||||
}
|
||||
next := key
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
func credentialAdmin(w http.ResponseWriter, r *http.Request, action string) bool {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, 403, map[string]string{"error": "需要管理员身份管理来源凭据"})
|
||||
return false
|
||||
}
|
||||
if r.Method != "GET" {
|
||||
originOK := true
|
||||
if raw := r.Header.Get("Origin"); raw != "" {
|
||||
u, err := url.Parse(raw)
|
||||
originOK = err == nil && u.Host == r.Host && (u.Scheme == "http" || u.Scheme == "https")
|
||||
}
|
||||
if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != action {
|
||||
writeJSON(w, 403, map[string]string{"error": "请从本平台的数据源配置页操作"})
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func writePPError(w http.ResponseWriter, err error) {
|
||||
status := http.StatusBadRequest
|
||||
if errors.Is(err, ppauth.ErrConflict) {
|
||||
status = http.StatusConflict
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": err.Error()})
|
||||
}
|
||||
|
||||
func registerPPConnectionRoutes(mux *http.ServeMux, config Config) {
|
||||
for _, pattern := range []string{"GET /api/v1/pp-connection", "PUT /api/v1/pp-connection", "POST /api/v1/pp-connection/test"} {
|
||||
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !credentialAdmin(w, r, "pp-connection") {
|
||||
return
|
||||
}
|
||||
if config.PPConnection == nil {
|
||||
writeJSON(w, 503, map[string]string{"error": "PP 配置服务未接通,请联系管理员"})
|
||||
return
|
||||
}
|
||||
if r.Method == "GET" {
|
||||
v, err := config.PPConnection.View()
|
||||
if err != nil {
|
||||
writeJSON(w, 503, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": v})
|
||||
return
|
||||
}
|
||||
var draft ppauth.Draft
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 16384)
|
||||
if decodeJSONStrict(r, &draft) != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "PP 配置请求格式不正确"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second)
|
||||
defer cancel()
|
||||
if r.Method == "POST" {
|
||||
result, err := config.PPConnection.Test(ctx, draft, actorFor(r))
|
||||
if err != nil {
|
||||
writePPError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
return
|
||||
}
|
||||
result, err := config.PPConnection.Save(ctx, draft, actorFor(r))
|
||||
if err != nil {
|
||||
status := 400
|
||||
if errors.Is(err, ppauth.ErrConflict) {
|
||||
status = 409
|
||||
}
|
||||
if errors.Is(err, ppauth.ErrRejected) {
|
||||
status = 422
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"error": err.Error(), "data": result})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type noPPJobStore struct {
|
||||
*fakeJobStore
|
||||
queued int
|
||||
}
|
||||
|
||||
func (s *noPPJobStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) {
|
||||
s.queued++
|
||||
return s.fakeJobStore.Enqueue(ctx, request, now)
|
||||
}
|
||||
func TestPPHTTPRoundTripRechecksSaveAndNeverEnqueues(t *testing.T) {
|
||||
probes := 0
|
||||
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c ppauth.Credentials) ppauth.Observation {
|
||||
probes++
|
||||
return ppauth.Observation{State: "valid", Message: "认证有效 · 目录可读"}
|
||||
}}
|
||||
store := &noPPJobStore{fakeJobStore: &fakeJobStore{}}
|
||||
h, err := NewHandler(Config{Store: store, PPConnection: m})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(method, path, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("X-Governance-Action", "pp-connection")
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
draft := `{"base_url":"https://api.example.invalid","username":"example","password":"example-private","revision":0}`
|
||||
for _, op := range [][2]string{{"POST", "/api/v1/pp-connection/test"}, {"PUT", "/api/v1/pp-connection"}, {"GET", "/api/v1/pp-connection"}} {
|
||||
rec := call(op[0], op[1], draft)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%s status=%d body=%s", op[0], rec.Code, rec.Body)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "example-private") || strings.Contains(rec.Body.String(), `"password":`) {
|
||||
t.Fatal("credential leaked through response")
|
||||
}
|
||||
}
|
||||
if probes != 2 || store.queued != 0 {
|
||||
t.Fatalf("save must recheck and must not enqueue: checks=%d jobs=%d", probes, store.queued)
|
||||
}
|
||||
rec := call("PUT", "/api/v1/pp-connection", draft)
|
||||
if rec.Code != 409 {
|
||||
t.Fatalf("stale revision accepted: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
func TestPPHTTPRefusesCrossOriginBeforeProbe(t *testing.T) {
|
||||
probes := 0
|
||||
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, _ ppauth.Credentials) ppauth.Observation {
|
||||
probes++
|
||||
return ppauth.Observation{State: "valid"}
|
||||
}}
|
||||
h, _ := NewHandler(Config{Store: &fakeJobStore{}, PPConnection: m})
|
||||
req := httptest.NewRequest("POST", "/api/v1/pp-connection/test", strings.NewReader(`{}`))
|
||||
req.Header.Set("Origin", "https://foreign.example.invalid")
|
||||
req.Header.Set("X-Governance-Action", "pp-connection")
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 403 || probes != 0 {
|
||||
t.Fatal("cross-origin request reached credential probe")
|
||||
}
|
||||
}
|
||||
|
||||
type combinedAuditStore struct {
|
||||
*fakeJobStore
|
||||
items []postgresstore.SourceAuditItem
|
||||
}
|
||||
|
||||
func (s *combinedAuditStore) ListSourceAudit(_ context.Context, limit, offset int) (postgresstore.SourceAuditPage, error) {
|
||||
start := offset
|
||||
if start > len(s.items) {
|
||||
start = len(s.items)
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(s.items) {
|
||||
end = len(s.items)
|
||||
}
|
||||
return postgresstore.SourceAuditPage{Items: s.items[start:end], Total: len(s.items), Limit: limit, Offset: offset}, nil
|
||||
}
|
||||
func TestPPSourceAuditSharesTheExistingPagedView(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json"}
|
||||
if err := os.Mkdir(filepath.Dir(m.Path), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
store := &combinedAuditStore{fakeJobStore: &fakeJobStore{}}
|
||||
expected := []postgresstore.SourceAuditItem{}
|
||||
for i := 0; i < 8; i++ {
|
||||
item := postgresstore.SourceAuditItem{ID: fmt.Sprintf("db-%02d", i), CreatedAt: now.Add(-time.Duration(i*2) * time.Minute), SourceName: "existing source"}
|
||||
store.items = append(store.items, item)
|
||||
expected = append(expected, item)
|
||||
}
|
||||
state := ppauth.State{}
|
||||
for i := 0; i < 4; i++ {
|
||||
event := ppauth.AuditEvent{ID: fmt.Sprintf("auth-%02d", i), CreatedAt: now.Add(-time.Duration(i*2+1) * time.Minute), SourceName: "PP", Action: "credential_test", Actor: "tester", Detail: "只读连接检查"}
|
||||
state.Audit = append(state.Audit, event)
|
||||
expected = append(expected, postgresstore.SourceAuditItem{ID: event.ID, CreatedAt: event.CreatedAt, SourceName: event.SourceName})
|
||||
}
|
||||
raw, _ := json.Marshal(state)
|
||||
if err := os.WriteFile(m.Path, raw, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sort.Slice(expected, func(i, j int) bool { return expected[i].CreatedAt.After(expected[j].CreatedAt) })
|
||||
for offset := 0; offset <= len(expected); offset++ {
|
||||
page, err := combinedSourceAudit(ctx, store, m, 3, offset)
|
||||
if err != nil || page.Total != len(expected) {
|
||||
t.Fatalf("offset=%d total=%d err=%v", offset, page.Total, err)
|
||||
}
|
||||
end := offset + 3
|
||||
if end > len(expected) {
|
||||
end = len(expected)
|
||||
}
|
||||
if len(page.Items) != end-offset {
|
||||
t.Fatalf("wrong page length at %d", offset)
|
||||
}
|
||||
for i, item := range page.Items {
|
||||
if item.ID != expected[offset+i].ID {
|
||||
t.Fatalf("audit order mismatch at offset %d", offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPPAuthRoutesRequireAdminAndFailClosedWhenUnwired(t *testing.T) {
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, method := range []string{"GET", "PUT", "POST"} {
|
||||
path := "/api/v1/pp-connection"
|
||||
if method == "POST" {
|
||||
path += "/test"
|
||||
}
|
||||
for _, role := range []string{"", roleViewer, roleEngineer, roleAdmin} {
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
if role != "" {
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{UserID: "admin", Username: "tester", Role: role, SessionID: "session"}))
|
||||
}
|
||||
req.Header.Set("X-Governance-Action", "pp-connection")
|
||||
res := httptest.NewRecorder()
|
||||
h.ServeHTTP(res, req)
|
||||
want := 403
|
||||
if role == "" {
|
||||
want = 401
|
||||
}
|
||||
if role == roleAdmin {
|
||||
want = 503
|
||||
}
|
||||
if res.Code != want {
|
||||
t.Errorf("%s role=%q status=%d want=%d", method, role, res.Code, want)
|
||||
}
|
||||
}
|
||||
if got := classifyRole(method, path); got != roleAdmin {
|
||||
t.Errorf("%s classified=%q; credential metadata and tests must be admin only", method, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,24 +41,6 @@ type routingBindingView struct {
|
||||
// that had not been uploaded yet. A plain read reports zeros.
|
||||
Replanned int `json:"replanned"`
|
||||
RetiredDuplicates int `json:"retired_duplicates"`
|
||||
// 整库封存源(LIBRARY_SOURCE_KB_*)与“测试入库绑定”是两套配置:
|
||||
// 页面必须同时给出两者,并标明是否一致,避免改绑后名字变了、封存还是旧库。
|
||||
LibrarySourceInternalKB string `json:"library_source_internal_kb"`
|
||||
LibrarySourceExternalKB string `json:"library_source_external_kb"`
|
||||
InternalSourceState string `json:"internal_source_state"`
|
||||
ExternalSourceState string `json:"external_source_state"`
|
||||
}
|
||||
|
||||
// sourceState 只回答“入库目标与封存源是不是同一个库”。
|
||||
func sourceState(binding, source string) string {
|
||||
switch {
|
||||
case source == "":
|
||||
return "unconfigured"
|
||||
case binding == source:
|
||||
return "consistent"
|
||||
default:
|
||||
return "mismatch"
|
||||
}
|
||||
}
|
||||
|
||||
type routingKnowledgeBaseOption struct {
|
||||
@@ -119,11 +101,7 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress
|
||||
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
|
||||
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
|
||||
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
|
||||
LibrarySourceInternalKB: config.LibrarySourceInternalKB,
|
||||
LibrarySourceExternalKB: config.LibrarySourceExternalKB,
|
||||
InternalSourceState: sourceState(internal, config.LibrarySourceInternalKB),
|
||||
ExternalSourceState: sourceState(external, config.LibrarySourceExternalKB),
|
||||
UpdatedBy: updatedBy, WeKnoraConnected: connected,
|
||||
UpdatedBy: updatedBy, WeKnoraConnected: connected,
|
||||
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -15,12 +15,10 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/backuphost"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
@@ -224,8 +222,6 @@ type Config struct {
|
||||
DingtalkSources dingtalkSourcesLister
|
||||
// DingtalkDocuments 列在线文档/表格并校验可读(只读,dws)。
|
||||
DingtalkDocuments dingtalkDocLister
|
||||
DWSLogin *dingtalkdiscovery.DeviceLoginManager
|
||||
PPConnection *ppauth.Manager
|
||||
NewID func() (string, error)
|
||||
Auth *AuthConfig
|
||||
}
|
||||
@@ -260,9 +256,6 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
config.NewID = newID
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
registerDWSLoginRoutes(mux, config)
|
||||
registerPPConnectionRoutes(mux, config)
|
||||
mux.HandleFunc("POST /api/v1/dingtalk-spaces/validate", func(w http.ResponseWriter, r *http.Request) { validateDWSSpace(w, r, config) })
|
||||
registerQAAIRoutes(mux, config)
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })
|
||||
@@ -384,9 +377,6 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
internal, external := config.effectiveRoutingTargets(r.Context())
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"internal_enabled": internal != "", "external_enabled": external != ""}})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/system/worker-capabilities", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleWorkerCapabilities(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/routing-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.RoutingBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "routing bindings storage unavailable"})
|
||||
|
||||
@@ -35,7 +35,7 @@ func listSourceAudit(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, 501, map[string]string{"error": "audit not configured"})
|
||||
return
|
||||
}
|
||||
page, err := combinedSourceAudit(r.Context(), reader, config.PPConnection, limit, offset)
|
||||
page, err := reader.ListSourceAudit(r.Context(), limit, offset)
|
||||
if err != nil {
|
||||
writeJSON(w, 500, map[string]string{"error": "无法读取数据源操作记录"})
|
||||
return
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// workerHeartbeatStore 是队列存活记录的只读视图。页面要回答“执行器在不在”,
|
||||
// 只能看 worker 认领任务时自己写下的 job_types;readiness 只证明接口可达。
|
||||
type workerHeartbeatStore interface {
|
||||
ListWorkerHeartbeats(context.Context) ([]postgresstore.WorkerHeartbeat, error)
|
||||
}
|
||||
|
||||
type workerCapabilityView struct {
|
||||
WorkerID string `json:"worker_id"`
|
||||
JobTypes []string `json:"job_types"`
|
||||
Alive bool `json:"alive"`
|
||||
LastSeenAt string `json:"last_seen_at"`
|
||||
}
|
||||
|
||||
type testUploadCapability struct {
|
||||
State string `json:"state"`
|
||||
Consumers int `json:"consumers"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
// 与 qaopsmirror 的工作就绪判定同一个窗口:2 分钟没有认领记录就当作不在线。
|
||||
const workerHeartbeatTTL = 2 * time.Minute
|
||||
|
||||
const testUploadJobType = "test.upload"
|
||||
|
||||
func testUploadCapabilityOf(workers []postgresstore.WorkerHeartbeat, now time.Time) testUploadCapability {
|
||||
alive, consumers := 0, 0
|
||||
for _, worker := range workers {
|
||||
if now.Sub(worker.LastSeenAt) > workerHeartbeatTTL {
|
||||
continue
|
||||
}
|
||||
alive++
|
||||
if slices.Contains(worker.JobTypes, testUploadJobType) {
|
||||
consumers++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case consumers > 0:
|
||||
return testUploadCapability{State: "enabled", Consumers: consumers,
|
||||
Detail: "上传/解析执行器已注册(认领过 test.upload)"}
|
||||
case alive > 0:
|
||||
return testUploadCapability{State: "disabled", Consumers: 0,
|
||||
Detail: "worker 在线但没有注册 test.upload:上传/解析任务不会被消费"}
|
||||
default:
|
||||
return testUploadCapability{State: "stale", Consumers: 0,
|
||||
Detail: "没有有效的 worker 认领记录:执行器未运行,或从未接单"}
|
||||
}
|
||||
}
|
||||
|
||||
func (config Config) handleWorkerCapabilities(w http.ResponseWriter, r *http.Request) {
|
||||
store, ok := config.Store.(workerHeartbeatStore)
|
||||
if !ok || store == nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"test_upload": testUploadCapability{State: "unknown", Detail: "worker 存活记录不可用"},
|
||||
"workers": []workerCapabilityView{},
|
||||
}})
|
||||
return
|
||||
}
|
||||
workers, err := store.ListWorkerHeartbeats(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"test_upload": testUploadCapability{State: "unknown", Detail: "读取 worker 存活记录失败"},
|
||||
"workers": []workerCapabilityView{},
|
||||
}})
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
views := make([]workerCapabilityView, 0, len(workers))
|
||||
for _, worker := range workers {
|
||||
views = append(views, workerCapabilityView{
|
||||
WorkerID: worker.WorkerID,
|
||||
JobTypes: worker.JobTypes,
|
||||
Alive: now.Sub(worker.LastSeenAt) <= workerHeartbeatTTL,
|
||||
LastSeenAt: worker.LastSeenAt.UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"test_upload": testUploadCapabilityOf(workers, now),
|
||||
"workers": views,
|
||||
}})
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
func TestTestUploadCapabilityReflectsWorkerHeartbeats(t *testing.T) {
|
||||
now := time.Date(2026, time.November, 17, 7, 0, 0, 0, time.UTC)
|
||||
fresh := now.Add(-10 * time.Second)
|
||||
stale := now.Add(-5 * time.Minute)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
workers []postgresstore.WorkerHeartbeat
|
||||
state string
|
||||
consume int
|
||||
}{
|
||||
{"no heartbeats", nil, "stale", 0},
|
||||
{"heartbeat too old", []postgresstore.WorkerHeartbeat{{LastSeenAt: stale, JobTypes: []string{"test.upload"}}}, "stale", 0},
|
||||
{"worker online without upload chain", []postgresstore.WorkerHeartbeat{{LastSeenAt: fresh, JobTypes: []string{"source.scan.dingtalk"}}}, "disabled", 0},
|
||||
{"enabled consumer", []postgresstore.WorkerHeartbeat{{LastSeenAt: fresh, JobTypes: []string{"test.upload", "test.poll"}}}, "enabled", 1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := testUploadCapabilityOf(tc.workers, now)
|
||||
if got.State != tc.state || got.Consumers != tc.consume {
|
||||
t.Fatalf("%s: got state=%s consumers=%d, want %s/%d", tc.name, got.State, got.Consumers, tc.state, tc.consume)
|
||||
}
|
||||
if got.Detail == "" {
|
||||
t.Fatalf("%s: detail must explain the state", tc.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ type RealProviderConfig struct {
|
||||
WeKnoraBaseURL string
|
||||
MinerUBaseURL string
|
||||
// TestWeKnoraResolver reads the test endpoint an admin saved in the web
|
||||
// settings, so 「知识库映射 → WeKnora 连接」is the single place the console probes. The env
|
||||
// settings, so 「服务配置」is the single place the console probes. The env
|
||||
// value above stays the bootstrap fallback for containers wired before the
|
||||
// UI existed.
|
||||
TestWeKnoraResolver func(ctx context.Context) string
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RegisteredDingtalkSpaceIDs also covers historical connections whose root key
|
||||
// predates DWS; a source name is never an identity.
|
||||
func (s *Store) RegisteredDingtalkSpaceIDs(ctx context.Context) (map[string]bool, error) {
|
||||
rows, err := s.db.Query(ctx, "SELECT base_url FROM source_connections WHERE source_type='dingtalk' AND archived_at IS NULL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := map[string]bool{}
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
space := u.Query().Get("space")
|
||||
if space == "" && strings.HasPrefix(u.Path, "spaces/") {
|
||||
space = strings.TrimPrefix(u.Path, "spaces/")
|
||||
}
|
||||
if space != "" {
|
||||
result[space] = true
|
||||
}
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// WorkerHeartbeat 是队列认领时顺手写下的存活记录(P10)。
|
||||
// 它本来就带 job_types:页面用它判断“这个 worker 有没有注册上传/解析链”,
|
||||
// 不需要再开一张表,也不该拿 readiness 或 env 去猜。
|
||||
type WorkerHeartbeat struct {
|
||||
WorkerID string
|
||||
JobTypes []string
|
||||
StartedAt time.Time
|
||||
LastSeenAt time.Time
|
||||
}
|
||||
|
||||
func (s *Store) ListWorkerHeartbeats(ctx context.Context) ([]WorkerHeartbeat, error) {
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT worker_id, job_types, started_at, last_seen_at
|
||||
FROM worker_heartbeats ORDER BY last_seen_at DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []WorkerHeartbeat
|
||||
for rows.Next() {
|
||||
var hb WorkerHeartbeat
|
||||
var types string
|
||||
if err := rows.Scan(&hb.WorkerID, &types, &hb.StartedAt, &hb.LastSeenAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if types != "" {
|
||||
hb.JobTypes = strings.Split(types, ",")
|
||||
}
|
||||
out = append(out, hb)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -1,356 +0,0 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Credentials struct {
|
||||
ID string `json:"id"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
type Draft struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password,omitempty"`
|
||||
PendingID string `json:"pending_id,omitempty"`
|
||||
Revision int `json:"revision"`
|
||||
}
|
||||
type Observation struct {
|
||||
State string `json:"state"`
|
||||
Message string `json:"message"`
|
||||
CheckedAt string `json:"checked_at"`
|
||||
Previous *Observation `json:"previous,omitempty"`
|
||||
}
|
||||
type Metadata struct {
|
||||
ID string `json:"id"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
PasswordConfigured bool `json:"password_configured"`
|
||||
}
|
||||
type View struct {
|
||||
Revision int `json:"revision"`
|
||||
Active *Metadata `json:"active"`
|
||||
Pending *Metadata `json:"pending"`
|
||||
Observation *Observation `json:"observation"`
|
||||
PendingObservation *Observation `json:"pending_observation"`
|
||||
}
|
||||
type AuditEvent struct {
|
||||
ID string `json:"id"`
|
||||
SourceName string `json:"source_name"`
|
||||
Action string `json:"action"`
|
||||
Actor string `json:"actor"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
type State struct {
|
||||
Revision int `json:"revision"`
|
||||
Active *Credentials `json:"active"`
|
||||
Pending *Credentials `json:"pending"`
|
||||
Observation *Observation `json:"observation"`
|
||||
PendingObservation *Observation `json:"pending_observation"`
|
||||
Audit []AuditEvent `json:"audit"`
|
||||
}
|
||||
type Manager struct {
|
||||
Path string
|
||||
LegacyPath string
|
||||
Probe func(context.Context, Credentials) Observation
|
||||
}
|
||||
|
||||
var ErrRejected = errors.New("PP 配置校验未通过,原配置保留")
|
||||
var ErrInvalid = errors.New("API 地址必须为 HTTPS 根地址,且不能包含凭据、查询参数或片段")
|
||||
var ErrConflict = errors.New("配置已被更新,请刷新后重新提交")
|
||||
|
||||
func ValidateBaseURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && len(raw) <= 300 && strings.TrimSpace(raw) == raw && u.Scheme == "https" && u.Host != "" && u.Hostname() != "" && u.Opaque == "" && u.User == nil && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.Contains(raw, "#") && (u.Path == "" || u.Path == "/")
|
||||
}
|
||||
func metadata(c *Credentials) *Metadata {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &Metadata{ID: c.ID, BaseURL: c.BaseURL, Username: c.Username, PasswordConfigured: c.Password != ""}
|
||||
}
|
||||
func view(s State) View {
|
||||
return View{Revision: s.Revision, Active: metadata(s.Active), Pending: metadata(s.Pending), Observation: s.Observation, PendingObservation: s.PendingObservation}
|
||||
}
|
||||
func randomID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic("secure random unavailable")
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
func (m *Manager) locked(ctx context.Context, fn func(*State) (bool, error)) error {
|
||||
if !filepath.IsAbs(m.Path) {
|
||||
return errors.New("PP credential storage path is invalid")
|
||||
}
|
||||
dir := filepath.Dir(m.Path)
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
return errors.New("PP 配置存储不可用")
|
||||
}
|
||||
info, err := os.Lstat(dir)
|
||||
if err != nil || !info.IsDir() || info.Mode().Perm()&0077 != 0 {
|
||||
return errors.New("PP 配置目录权限必须为 0700")
|
||||
}
|
||||
lockPath := m.Path + ".lock"
|
||||
if info, e := os.Lstat(lockPath); e == nil && (info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0077 != 0) {
|
||||
return errors.New("PP 配置锁权限不安全")
|
||||
}
|
||||
lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return errors.New("PP 配置存储不可用")
|
||||
}
|
||||
defer lock.Close()
|
||||
for {
|
||||
err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if err != syscall.EWOULDBLOCK {
|
||||
return errors.New("PP 配置锁不可用")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
|
||||
var s State
|
||||
info, err = os.Lstat(m.Path)
|
||||
if err == nil {
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > 16<<20 {
|
||||
return errors.New("PP 凭据文件权限或格式不安全")
|
||||
}
|
||||
raw, e := os.ReadFile(m.Path)
|
||||
if e != nil || json.Unmarshal(raw, &s) != nil {
|
||||
return errors.New("无法读取 PP 配置")
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return errors.New("无法读取 PP 配置")
|
||||
} else if m.LegacyPath != "" {
|
||||
raw, e := os.ReadFile(m.LegacyPath)
|
||||
if e == nil {
|
||||
var c Credentials
|
||||
if json.Unmarshal(raw, &c) != nil {
|
||||
return errors.New("旧 PP 配置格式不正确")
|
||||
}
|
||||
if c.BaseURL == "" {
|
||||
c.BaseURL = "https://api.dobot.cn"
|
||||
}
|
||||
c.ID = "legacy"
|
||||
s.Active = &c
|
||||
} else if !errors.Is(e, os.ErrNotExist) {
|
||||
return errors.New("无法读取旧 PP 配置")
|
||||
}
|
||||
}
|
||||
changed, err := fn(&s)
|
||||
if err != nil || !changed {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".pp-next-")
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
tmp := f.Name()
|
||||
defer os.Remove(tmp)
|
||||
if err = f.Chmod(0600); err == nil {
|
||||
_, err = f.Write(raw)
|
||||
}
|
||||
if err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
closeErr := f.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp, m.Path)
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
d, e := os.Open(dir)
|
||||
if e != nil {
|
||||
return errors.New("PP 配置持久化未确认")
|
||||
}
|
||||
defer d.Close()
|
||||
if d.Sync() != nil {
|
||||
return errors.New("PP 配置持久化未确认")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m *Manager) View() (v View, err error) {
|
||||
err = m.locked(context.Background(), func(s *State) (bool, error) { v = view(*s); return false, nil })
|
||||
return
|
||||
}
|
||||
func (m *Manager) snapshot(ctx context.Context) (s State, err error) {
|
||||
err = m.locked(ctx, func(state *State) (bool, error) { s = *state; return false, nil })
|
||||
return
|
||||
}
|
||||
func candidate(s State, d Draft) (Credentials, error) {
|
||||
if !ValidateBaseURL(d.BaseURL) {
|
||||
return Credentials{}, ErrInvalid
|
||||
}
|
||||
if len(d.Username) > 255 || strings.ContainsAny(d.Username, "\n\r\x00") || len(d.Password) > 8192 {
|
||||
return Credentials{}, errors.New("账号或密码格式不正确")
|
||||
}
|
||||
c := Credentials{ID: randomID(), BaseURL: strings.TrimRight(d.BaseURL, "/"), Username: strings.TrimSpace(d.Username), Password: d.Password}
|
||||
if c.Password == "" && d.PendingID != "" {
|
||||
if s.Pending == nil || s.Pending.ID != d.PendingID {
|
||||
return Credentials{}, ErrConflict
|
||||
}
|
||||
c.Password = s.Pending.Password
|
||||
} else if c.Password == "" && s.Active != nil {
|
||||
c.Password = s.Active.Password
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
func same(a, b *Credentials) bool {
|
||||
return a != nil && b != nil && a.BaseURL == b.BaseURL && a.Username == b.Username && a.Password == b.Password
|
||||
}
|
||||
func (m *Manager) probe(ctx context.Context, c Credentials) Observation {
|
||||
o := Observation{State: "incomplete", Message: "配置未完成,请填写账号和密码"}
|
||||
if c.Username != "" && c.Password != "" {
|
||||
if m.Probe == nil {
|
||||
o = Observation{State: "unavailable", Message: "PP 检查服务未接通"}
|
||||
} else {
|
||||
o = m.Probe(ctx, c)
|
||||
}
|
||||
}
|
||||
switch o.State {
|
||||
case "valid", "auth_failed", "permission_denied", "incomplete", "unavailable", "invalid_response":
|
||||
default:
|
||||
o = Observation{State: "unavailable", Message: "检查结果不可识别,请重试"}
|
||||
}
|
||||
if o.CheckedAt == "" {
|
||||
o.CheckedAt = time.Now().UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
return o
|
||||
}
|
||||
func addAudit(s *State, source, action, actor, detail string) {
|
||||
s.Audit = append(s.Audit, AuditEvent{ID: "auth-" + randomID(), SourceName: source, Action: action, Actor: actor, CreatedAt: time.Now().UTC(), Detail: detail})
|
||||
}
|
||||
func retainObservation(old *Observation, next Observation) *Observation {
|
||||
if next.State == "unavailable" && old != nil {
|
||||
if old.State == "unavailable" && old.Previous != nil {
|
||||
next.Previous = old.Previous
|
||||
} else {
|
||||
next.Previous = old
|
||||
}
|
||||
}
|
||||
return &next
|
||||
}
|
||||
func (m *Manager) Save(ctx context.Context, d Draft, actor string) (v View, err error) {
|
||||
s, err := m.snapshot(ctx)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if s.Revision != d.Revision {
|
||||
return v, ErrConflict
|
||||
}
|
||||
c, err := candidate(s, d)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
o := m.probe(ctx, c)
|
||||
rejected := o.State == "auth_failed" || o.State == "permission_denied" || o.State == "invalid_response"
|
||||
err = m.locked(ctx, func(current *State) (bool, error) {
|
||||
if current.Revision != s.Revision {
|
||||
return false, ErrConflict
|
||||
}
|
||||
if rejected {
|
||||
if same(current.Active, &c) {
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_rejected", actor, o.Message)
|
||||
v = view(*current)
|
||||
return true, nil
|
||||
}
|
||||
current.Revision++
|
||||
if o.State == "valid" {
|
||||
current.Active = &c
|
||||
current.Pending = nil
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
current.PendingObservation = nil
|
||||
} else {
|
||||
current.Pending = &c
|
||||
current.PendingObservation = &o
|
||||
}
|
||||
detail := "认证配置已保存并生效"
|
||||
if o.State != "valid" {
|
||||
detail = "修改已保存为待验证,未替换生效配置"
|
||||
}
|
||||
if d.Password != "" {
|
||||
detail += ";密码已更新"
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_configured", actor, detail)
|
||||
v = view(*current)
|
||||
return true, nil
|
||||
})
|
||||
if err == nil && rejected {
|
||||
err = fmt.Errorf("%w:%s", ErrRejected, o.Message)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (m *Manager) Test(ctx context.Context, d Draft, actor string) (o Observation, err error) {
|
||||
s, err := m.snapshot(ctx)
|
||||
if err != nil {
|
||||
return o, err
|
||||
}
|
||||
if s.Revision != d.Revision {
|
||||
return o, ErrConflict
|
||||
}
|
||||
c, err := candidate(s, d)
|
||||
if err != nil {
|
||||
return o, err
|
||||
}
|
||||
o = m.probe(ctx, c)
|
||||
err = m.locked(ctx, func(current *State) (bool, error) {
|
||||
if current.Revision != s.Revision {
|
||||
return false, ErrConflict
|
||||
}
|
||||
if same(current.Active, &c) {
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_test", actor, o.Message)
|
||||
return true, nil
|
||||
})
|
||||
return
|
||||
}
|
||||
func (m *Manager) Audit(ctx context.Context, source, action, actor, detail string) error {
|
||||
return m.locked(ctx, func(s *State) (bool, error) { addAudit(s, source, action, actor, detail); return true, nil })
|
||||
}
|
||||
func (m *Manager) AuditOnce(ctx context.Context, id, source, action, actor, detail string) error {
|
||||
return m.locked(ctx, func(s *State) (bool, error) {
|
||||
for _, e := range s.Audit {
|
||||
if e.ID == id {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
addAudit(s, source, action, actor, detail)
|
||||
s.Audit[len(s.Audit)-1].ID = id
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
func (m *Manager) Events(ctx context.Context) (events []AuditEvent, err error) {
|
||||
err = m.locked(ctx, func(s *State) (bool, error) { events = append(events, s.Audit...); return false, nil })
|
||||
return
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSaveValidatesBeforeActivationAndTransientKeepsActive(t *testing.T) {
|
||||
state := "valid"
|
||||
seen := ""
|
||||
manager := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
seen = c.Password
|
||||
return Observation{State: state, Message: state}
|
||||
}}
|
||||
view, err := manager.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-password", Revision: 0}, "tester")
|
||||
if err != nil || view.Active == nil || view.Active.Username != "example" || !view.Active.PasswordConfigured || seen != "example-password" {
|
||||
t.Fatalf("validated save did not activate: %+v %v", view, err)
|
||||
}
|
||||
activeID := view.Active.ID
|
||||
state = "unavailable"
|
||||
view, err = manager.Save(context.Background(), Draft{BaseURL: "https://changed.example.invalid", Username: "changed", Revision: view.Revision}, "tester")
|
||||
if err != nil || view.Active == nil || view.Active.ID != activeID || view.Pending == nil || view.Pending.Username != "changed" || seen != "example-password" {
|
||||
t.Fatalf("transient save replaced active or lost password: %+v %v", view, err)
|
||||
}
|
||||
state = "auth_failed"
|
||||
_, err = manager.Save(context.Background(), Draft{BaseURL: "https://changed.example.invalid", Username: "changed", Password: "bad-example", Revision: view.Revision}, "tester")
|
||||
if !errors.Is(err, ErrRejected) {
|
||||
t.Fatalf("explicit rejection allowed activation: %v", err)
|
||||
}
|
||||
after, _ := manager.View()
|
||||
if after.Active.ID != activeID {
|
||||
t.Fatal("rejection changed active config")
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPendingPasswordSurvivesRevalidationWithoutReturningSecrets(t *testing.T) {
|
||||
state := "valid"
|
||||
seen := ""
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
seen = c.Password
|
||||
return Observation{State: state, Message: state}
|
||||
}}
|
||||
v, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-old"}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state = "unavailable"
|
||||
v, err = m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-new", Revision: v.Revision}, "tester")
|
||||
if err != nil || v.Pending == nil {
|
||||
t.Fatalf("pending save: %v", err)
|
||||
}
|
||||
state = "valid"
|
||||
v, err = m.Save(context.Background(), Draft{BaseURL: v.Pending.BaseURL, Username: v.Pending.Username, PendingID: v.Pending.ID, Revision: v.Revision}, "tester")
|
||||
if err != nil || seen != "example-new" || v.Pending != nil {
|
||||
t.Fatal("saved pending password was not reused")
|
||||
}
|
||||
raw, _ := json.Marshal(v)
|
||||
if strings.Contains(string(raw), "example-new") || strings.Contains(string(raw), `"password":`) {
|
||||
t.Fatal("metadata leaked secret")
|
||||
}
|
||||
info, err := os.Stat(m.Path)
|
||||
if err != nil || info.Mode().Perm() != 0600 {
|
||||
t.Fatal("secret file not mode 0600")
|
||||
}
|
||||
}
|
||||
func TestConcurrentSavesCannotOverwriteANewerRevision(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
barrier := make(chan struct{})
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
if calls.Add(1) == 2 {
|
||||
close(barrier)
|
||||
}
|
||||
<-barrier
|
||||
return Observation{State: "valid", Message: "valid"}
|
||||
}}
|
||||
outcomes := make(chan error, 2)
|
||||
var wg sync.WaitGroup
|
||||
for _, name := range []string{"example-one", "example-two"} {
|
||||
wg.Add(1)
|
||||
go func(user string) {
|
||||
defer wg.Done()
|
||||
_, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: user, Password: "example-password"}, "tester")
|
||||
outcomes <- err
|
||||
}(name)
|
||||
}
|
||||
wg.Wait()
|
||||
close(outcomes)
|
||||
success, conflict := 0, 0
|
||||
for err := range outcomes {
|
||||
if err == nil {
|
||||
success++
|
||||
} else if errors.Is(err, ErrConflict) {
|
||||
conflict++
|
||||
} else {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if success != 1 || conflict != 1 {
|
||||
t.Fatalf("success=%d conflict=%d", success, conflict)
|
||||
}
|
||||
}
|
||||
func TestFailedObservationRetainsPreviousSuccess(t *testing.T) {
|
||||
state := "valid"
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation { return Observation{State: state, Message: state} }}
|
||||
v, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-password"}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state = "unavailable"
|
||||
_, err = m.Test(context.Background(), Draft{BaseURL: v.Active.BaseURL, Username: v.Active.Username, Revision: v.Revision}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, err = m.View()
|
||||
if err != nil || v.Observation.Previous == nil || v.Observation.Previous.State != "valid" {
|
||||
t.Fatal("failed check erased previous successful observation")
|
||||
}
|
||||
}
|
||||
func TestPPPythonProtocolAndConfigurationConsumers(t *testing.T) {
|
||||
command := exec.Command("python3", "-m", "unittest", "discover", "-s", "../../scripts", "-p", "test_pp_client.py", "-v")
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("PP protocol regression: %v\n%s", err, output)
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CommandProbe reuses the worker's read-only PP adapter; secrets travel on stdin.
|
||||
func CommandProbe(python, script string) func(context.Context, Credentials) Observation {
|
||||
return func(ctx context.Context, c Credentials) Observation {
|
||||
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
raw, _ := json.Marshal(c)
|
||||
command := exec.CommandContext(ctx, python, script)
|
||||
command.Stdin = bytes.NewReader(raw)
|
||||
command.Env = []string{"PATH=" + os.Getenv("PATH"), "PYTHONUNBUFFERED=1"}
|
||||
out, err := command.Output()
|
||||
if err != nil || len(out) > 8192 {
|
||||
return Observation{State: "unavailable", Message: "PP 检查服务暂不可用,请重试"}
|
||||
}
|
||||
var o Observation
|
||||
if json.Unmarshal(out, &o) != nil {
|
||||
return Observation{State: "unavailable", Message: "PP 检查结果不可识别"}
|
||||
}
|
||||
return o
|
||||
}
|
||||
}
|
||||
@@ -181,7 +181,7 @@ func NewCommandRunner(pythonPath, scriptPath, spoolRoot, spoolPrefix string, max
|
||||
// ——钉钉取件在真实链路上会整体失败(2026-10-10 端到端验收实测;脚本单跑正常,
|
||||
// 因为那只绕过了这个白名单)。
|
||||
var dwsEnvNames = []string{
|
||||
"ARTIFACT_DINGTALK_FETCHER", "PP_AUTH_STATE_FILE", "PP_LEGACY_CREDENTIALS_FILE", "DWS_BIN", "DWS_CONFIG_DIR", "DWS_HOME", "DWS_DISABLE_KEYCHAIN",
|
||||
"ARTIFACT_DINGTALK_FETCHER", "DWS_BIN", "DWS_CONFIG_DIR", "DWS_HOME", "DWS_DISABLE_KEYCHAIN",
|
||||
}
|
||||
|
||||
func forwardedDWSEnv() []string {
|
||||
|
||||
@@ -35,9 +35,7 @@ type PollHandlerConfig struct {
|
||||
Client PollClient
|
||||
PollDelay time.Duration
|
||||
StallAfter time.Duration
|
||||
// StallAfterSource 可选:返回当前生效的停滞阈值(来自活动 UI 配置)。
|
||||
StallAfterSource func() time.Duration
|
||||
Now func() time.Time
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type PollHandler struct {
|
||||
@@ -45,10 +43,7 @@ type PollHandler struct {
|
||||
client PollClient
|
||||
pollDelay time.Duration
|
||||
stallAfter time.Duration
|
||||
// stallAfterSource 存在时优先于 stallAfter:页面保存的“解析停滞阈值”
|
||||
// 必须真的决定判定,而不是只写进数据库。
|
||||
stallAfterSource func() time.Duration
|
||||
now func() time.Time
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type pollPayload struct {
|
||||
@@ -65,7 +60,7 @@ func NewPollHandler(config PollHandlerConfig) (*PollHandler, error) {
|
||||
}
|
||||
return &PollHandler{
|
||||
store: config.Store, client: config.Client, pollDelay: config.PollDelay,
|
||||
stallAfter: config.StallAfter, stallAfterSource: config.StallAfterSource, now: config.Now,
|
||||
stallAfter: config.StallAfter, now: config.Now,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -108,13 +103,7 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
stall := handler.stallAfter
|
||||
if handler.stallAfterSource != nil {
|
||||
if fromSettings := handler.stallAfterSource(); fromSettings > 0 {
|
||||
stall = fromSettings
|
||||
}
|
||||
}
|
||||
cutoff := now.Add(-stall)
|
||||
cutoff := now.Add(-handler.stallAfter)
|
||||
lastProgress := publication.LastProgressAt
|
||||
if lastProgress == nil {
|
||||
lastProgress = publication.ProcessingStartedAt
|
||||
|
||||
@@ -186,61 +186,3 @@ func (store *pollStoreStub) MarkStalled(_ context.Context, _ string, _ int, cuto
|
||||
store.stalledCutoff = cutoff
|
||||
return nil
|
||||
}
|
||||
|
||||
// F02 验收:停滞判定必须用“活动配置”的阈值,而不是启动时的常量。
|
||||
// 同一条已经停在同一进度上的解析任务:阈值 30 分钟判停,阈值 2 小时不判停。
|
||||
func TestPollHandlerStallThresholdFollowsActiveSettings(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"processing","updated_at":"2026-09-04T03:00:00Z"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: server.URL, APIKey: "test-key", Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Date(2026, time.September, 4, 4, 0, 0, 0, time.UTC)
|
||||
progressAt := now.Add(-45 * time.Minute)
|
||||
makeStore := func() *pollStoreStub {
|
||||
return &pollStoreStub{publication: postgresstore.PublicationForPoll{
|
||||
ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
|
||||
ProcessingState: governance.ProcessingProcessing, PollSequence: 3,
|
||||
LastProgressAt: &progressAt, ProcessingStartedAt: &progressAt,
|
||||
}}
|
||||
}
|
||||
payload := jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":3}`)}
|
||||
|
||||
// 启动常量 30 分钟、活动配置也是 30 分钟:45 分钟没进度 → 判停。
|
||||
store := makeStore()
|
||||
handler, err := NewPollHandler(PollHandlerConfig{
|
||||
Store: store, Client: client, PollDelay: 15 * time.Second,
|
||||
StallAfter: 30 * time.Minute, Now: func() time.Time { return now },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := handler.Handle(context.Background(), payload); err != nil {
|
||||
t.Fatalf("Handle() error = %v", err)
|
||||
}
|
||||
if !store.stalledMarked {
|
||||
t.Fatal("30 分钟阈值下 45 分钟无进度应判停")
|
||||
}
|
||||
|
||||
// 活动配置改成 2 小时:同一条任务不应再判停。
|
||||
store = makeStore()
|
||||
handler, err = NewPollHandler(PollHandlerConfig{
|
||||
Store: store, Client: client, PollDelay: 15 * time.Second,
|
||||
StallAfter: 30 * time.Minute,
|
||||
StallAfterSource: func() time.Duration { return 2 * time.Hour },
|
||||
Now: func() time.Time { return now },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := handler.Handle(context.Background(), payload); err != nil {
|
||||
t.Fatalf("Handle() error = %v", err)
|
||||
}
|
||||
if store.stalledMarked {
|
||||
t.Fatal("活动配置 2 小时阈值下不应判停:阈值没有接入实际判定")
|
||||
}
|
||||
}
|
||||
|
||||
-1
File diff suppressed because one or more lines are too long
@@ -278,7 +278,7 @@ def pp_find_entry(manifest):
|
||||
def pp_download(manifest, max_bytes):
|
||||
entry = pp_find_entry(manifest)
|
||||
if entry is None:
|
||||
entry = {}
|
||||
raise MissingSource("PP ledger entry for this locator no longer exists")
|
||||
# Ledger titles may omit the extension; recover the true file name from the
|
||||
# local path or source URL before type checks run.
|
||||
manifest_name = manifest.setdefault("name", "")
|
||||
@@ -301,23 +301,9 @@ def pp_download(manifest, max_bytes):
|
||||
if expected_hash and len(expected_hash) == 64 and actual != expected_hash:
|
||||
raise FetchError("PP local copy hash mismatch (ledger changed?)", retryable=True, code="local_mismatch")
|
||||
return str(candidate), size, actual, True
|
||||
from pp_client import active_client, record_observation, observation, PPError
|
||||
client = None
|
||||
try:
|
||||
client = active_client()
|
||||
inventory = client.inventory(client.login())
|
||||
record_observation(client.config, observation('valid'))
|
||||
except PPError as error:
|
||||
if client is not None:
|
||||
record_observation(client.config, observation(error.state))
|
||||
raise FetchError(str(error), retryable=error.state == 'unavailable', code='pp_' + error.state) from None
|
||||
locator = manifest.get('locator_hash', '')
|
||||
matches = [row for row in inventory['items'] if row.get('online') == 1 and (row.get('potalGroup') or {}).get('groupName') == '公开' and digest_of(str(row.get('fileUrl') or '').strip()) == locator]
|
||||
if not matches:
|
||||
raise MissingSource('PP file is no longer visible in the configured portal')
|
||||
url = str(matches[0].get('fileUrl') or '').strip()
|
||||
if not pathlib.PurePosixPath(manifest['name']).suffix:
|
||||
manifest['name'] += pathlib.PurePosixPath(urllib.parse.unquote(urllib.parse.urlsplit(url).path)).suffix
|
||||
url = entry.get("url", "")
|
||||
if not url:
|
||||
raise MissingSource("PP ledger entry has no local file and no download URL")
|
||||
path, size, actual = http_get(url, {}, 180, max_bytes)
|
||||
expected_hash = str(entry.get("sha256", "")).lower()
|
||||
if expected_hash and len(expected_hash) == 64 and actual != expected_hash:
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Coordinate candidate preparation and record independently authored QA evidence."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
|
||||
import candidate_release as candidate
|
||||
import candidate_runtime as runtime
|
||||
import hifox_release_trigger as hfx
|
||||
import production_cd as cd
|
||||
|
||||
STATE = Path.home() / '.local/state/kg-candidate-release'
|
||||
CLI = str(Path.home() / '.local/bin/hifox')
|
||||
WORKFLOW = candidate.API + '/actions/workflows/prepare-candidate.yml/dispatches?return_run_details=true'
|
||||
QA_AUTHORS = {cd.RELEASE_OWNER, '62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
|
||||
WAIT_TEST = 'b59c34ee-94f4-41a8-8577-dea73b2c6414'
|
||||
TESTING = 'f8906482-bad7-4af8-9a3b-d52630eff3f7'
|
||||
QA_FENCE = re.compile(r'^```kg-qa-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
|
||||
|
||||
|
||||
def task(task_id):
|
||||
cd.require(cd.matches(cd.UUID, task_id), 'provide the task UUID')
|
||||
obj = hfx.hifox(CLI, 'task', 'view', task_id)
|
||||
if not isinstance(obj, dict) or obj.get('id') != task_id or obj.get('spaceId') != cd.SPACE:
|
||||
raise cd.CDError('task is outside the release space')
|
||||
return obj
|
||||
|
||||
|
||||
def timeline(task_id):
|
||||
rows = hfx.hifox(CLI, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
|
||||
cd.require(isinstance(rows, list), 'task timeline unavailable')
|
||||
return [row for row in rows if row.get('event') == 'commented']
|
||||
|
||||
|
||||
def owner_plan(task_id):
|
||||
task(task_id)
|
||||
matches = [candidate.FENCE.search(row.get('content') or '') for row in reversed(sorted(
|
||||
timeline(task_id), key=lambda row: row.get('createdAt', ''))) if (row.get('actor') or {}).get('id') == cd.RELEASE_OWNER]
|
||||
match = next((row for row in matches if row), None)
|
||||
if match is None:
|
||||
raise cd.CDError('release owner must post a kg-release-v1 plan on the release task')
|
||||
plan = json.loads(match[1])
|
||||
candidate.check_plan(plan)
|
||||
cd.require(plan['task'] == task_id, 'release plan belongs to another task')
|
||||
for item in plan['items']:
|
||||
requirement = task(item['task'])
|
||||
identifier = requirement.get('identifier')
|
||||
pr = candidate.read_forge(candidate.API + f'/pulls/{item["pr"]}')
|
||||
fields = ' '.join(str(v or '') for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
|
||||
cd.require(isinstance(identifier, str) and re.search(rf'(?<![\w-]){re.escape(identifier)}(?!\w)', fields, re.IGNORECASE),
|
||||
f"PR #{item['pr']} does not identify its HiFox requirement")
|
||||
return plan
|
||||
|
||||
|
||||
def queue(task_id):
|
||||
plan = owner_plan(task_id)
|
||||
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
key = cd.acceptance_digest(plan)
|
||||
path = STATE / (key + '.dispatch.json')
|
||||
with cd.deploy_lock(STATE / 'dispatch.lock'):
|
||||
if path.exists():
|
||||
result = cd.read_json(cd.immutable_file(path))
|
||||
cd.require(result['state'] == 'queued', 'candidate dispatch outcome unknown; reconcile Gitea before retry')
|
||||
return result
|
||||
conf = Path.home() / '.config/knowledge-governance/qa.json'
|
||||
runtime.qa_database(conf)
|
||||
cd.record(path, {'state': 'submitting', 'plan': plan})
|
||||
result = hfx.forge('POST', WORKFLOW, {'ref': 'main', 'inputs': {'plan': json.dumps(plan), 'mode': 'prepare'}})
|
||||
run = str(result.get('workflow_run_id', ''))
|
||||
cd.require(cd.matches(hfx.RUN_ID, run), 'missing candidate run ID; reconcile Gitea before retry')
|
||||
receipt = {'state': 'queued', 'plan': plan, 'run': run, 'url': f'{cd.FORGE}/{cd.REPO}/actions/runs/{run}'}
|
||||
cd.record(path, receipt)
|
||||
return receipt
|
||||
|
||||
|
||||
def add_comment(task_id, key, body):
|
||||
marker = f'[KG candidate {key}]'
|
||||
|
||||
def existing():
|
||||
return [row for row in timeline(task_id) if marker in (row.get('content') or '')]
|
||||
|
||||
if not existing():
|
||||
hfx.hifox(CLI, 'task', 'comment', task_id, '--body', f'{marker}\n\n{body}')
|
||||
rows = existing()
|
||||
cd.require(len(rows) == 1 and cd.matches(cd.UUID, rows[0].get('id')) and body in rows[0].get('content', ''),
|
||||
'candidate comment not uniquely verified')
|
||||
return rows[0]['id']
|
||||
|
||||
|
||||
def publish_candidate(plan, receipt, run):
|
||||
body = (f'候选验收地址 {receipt["url"]}\n\n提交 `{receipt["sha"]}`\n\n'
|
||||
f'归档 `{receipt["bundle"]}`\n\n'
|
||||
f'构建记录 {cd.FORGE}/{cd.REPO}/actions/runs/{run}\n\n'
|
||||
f'发布任务 {task(plan["task"])["url"]}')
|
||||
key = 'ready ' + receipt['bundle']
|
||||
add_comment(plan['task'], key, body)
|
||||
for item in plan['items']:
|
||||
item_id = item['task']
|
||||
status = (task(item_id).get('status') or {}).get('id')
|
||||
if status == TESTING:
|
||||
cd.require(any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)),
|
||||
f'{item_id}: another QA round is already in progress')
|
||||
continue
|
||||
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
|
||||
add_comment(item_id, key, body)
|
||||
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
|
||||
f'{item_id}: task status changed during candidate handoff')
|
||||
hfx.hifox(CLI, 'task', 'edit', item_id, '--status', TESTING)
|
||||
cd.require((task(item_id).get('status') or {}).get('id') == TESTING, f'{item_id}: testing status not verified')
|
||||
|
||||
|
||||
def register(task_id):
|
||||
plan = owner_plan(task_id)
|
||||
directory = STATE / cd.acceptance_digest(plan)
|
||||
with cd.deploy_lock(directory / 'registration.lock'):
|
||||
receipt = cd.read_json(cd.immutable_file(directory / 'ready.json'))
|
||||
cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication')
|
||||
runtime.attest(directory / 'bundle', receipt)
|
||||
reports = {}
|
||||
tasks = [item['task'] for item in plan['items']] + [task_id]
|
||||
for item_id in tasks:
|
||||
obj = task(item_id)
|
||||
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
|
||||
for row in rows:
|
||||
match = QA_FENCE.search(row.get('content') or '')
|
||||
if not match or (row.get('actor') or {}).get('id') not in QA_AUTHORS:
|
||||
continue
|
||||
result = json.loads(match[1])
|
||||
if result.get('bundle') == receipt['bundle']:
|
||||
reports[item_id] = (row, result)
|
||||
break
|
||||
if item_id in reports:
|
||||
row = reports[item_id][0]
|
||||
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
|
||||
'invalid QA evidence link')
|
||||
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
|
||||
fresh = owner_plan(task_id)
|
||||
cd.require(fresh == plan, 'release plan changed during registration')
|
||||
rel = task(task_id)
|
||||
cd.require((rel.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED),
|
||||
'register QA before the owner moves the release task to 待发布')
|
||||
sha, bundle = receipt['sha'], receipt['bundle']
|
||||
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks)
|
||||
body = f'批次验收通过\n\n提交 `{sha}`\n\n归档 `{bundle}`\n\n需求验收与批次回归报告\n{links}'
|
||||
comment = add_comment(task_id, 'acceptance ' + bundle, body)
|
||||
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
|
||||
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
|
||||
hfx.hifox(CLI, 'task', 'metadata', 'set', task_id, 'cd_acceptance', json.dumps(json.dumps(acceptance)))
|
||||
cd.require(cd.metadata(task(task_id), 'cd_acceptance') == acceptance, 'acceptance writeback not verified')
|
||||
return acceptance
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('prepare', 'register', 'status'))
|
||||
parser.add_argument('task')
|
||||
args = parser.parse_args()
|
||||
if args.action == 'prepare':
|
||||
result = queue(args.task)
|
||||
elif args.action == 'register':
|
||||
result = register(args.task)
|
||||
else:
|
||||
plan = owner_plan(args.task)
|
||||
key = cd.acceptance_digest(plan)
|
||||
results = [STATE / key / 'ready.json', STATE / (key + '.dispatch.json')]
|
||||
result = next((cd.read_json(cd.immutable_file(p)) for p in results if p.exists()), {'state': 'unprepared'})
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except HTTPError as exc:
|
||||
sys.exit(f'Candidate coordinator: HTTP {exc.code}; reconcile Gitea before retry')
|
||||
except (cd.CDError, runtime.qa_env.QAError, OSError, ValueError) as exc:
|
||||
sys.exit(f'Candidate coordinator: {exc}')
|
||||
@@ -1,203 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate a release batch and build its immutable candidate bundle."""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
|
||||
from urllib.request import Request
|
||||
|
||||
import hifox_release_trigger as integration
|
||||
import production_cd as cd
|
||||
|
||||
API = f'/api/v1/repos/{cd.REPO}'
|
||||
CONTEXTS = Path(__file__).resolve().parents[1] / '.gitea/required-contexts.txt'
|
||||
FENCE = re.compile(r'^```kg-release-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
|
||||
|
||||
|
||||
def read_forge(path):
|
||||
token = os.getenv('KG_CANDIDATE_READ_TOKEN')
|
||||
if not token:
|
||||
return integration.forge('GET', path)
|
||||
from urllib.request import ProxyHandler, build_opener
|
||||
server = os.getenv('KG_CANDIDATE_FORGE', cd.FORGE)
|
||||
cd.require(server in (cd.FORGE, 'http://192.168.50.223:3000'), 'untrusted Gitea origin')
|
||||
request = Request(server + path, headers={'Authorization': 'token ' + token})
|
||||
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=20) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def check_plan(plan):
|
||||
cd.require(isinstance(plan, dict) and set(plan) == {'task', 'sha', 'base', 'items', 'extra'},
|
||||
'invalid release plan fields')
|
||||
cd.require(cd.matches(cd.UUID, plan['task']) and cd.matches(cd.SHA, plan['sha'])
|
||||
and cd.matches(cd.SHA, plan['base']) and plan['base'] != plan['sha'], 'invalid release task or SHA range')
|
||||
items = plan['items']
|
||||
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
|
||||
for item in items:
|
||||
cd.require(isinstance(item, dict) and set(item) == {'task', 'pr'} and cd.matches(cd.UUID, item['task'])
|
||||
and item['task'] != plan['task'] and type(item['pr']) is int and item['pr'] > 0, 'invalid requirement or PR')
|
||||
cd.require(len({i['task'] for i in items}) == len(items) == len({i['pr'] for i in items}),
|
||||
'duplicate requirement or PR')
|
||||
extra = plan['extra']
|
||||
cd.require(isinstance(extra, list) and len(extra) <= 100 and all(cd.matches(cd.SHA, s) for s in extra)
|
||||
and len(set(extra)) == len(extra), 'invalid additional reviewed commits')
|
||||
|
||||
|
||||
def check_scope(plan, read_pr, first_parents):
|
||||
check_plan(plan)
|
||||
required = set(plan['extra'])
|
||||
for item in plan['items']:
|
||||
pr = read_pr(item['pr'])
|
||||
sha = pr.get('merge_commit_sha')
|
||||
cd.require(pr.get('merged') is True and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, sha),
|
||||
f"PR #{item['pr']} must be merged into main")
|
||||
cd.require(sha not in required, 'landed commit is listed in multiple scope entries')
|
||||
required.add(sha)
|
||||
cd.require(required == set(first_parents), 'commits outside the release scope, or planned commits absent from main range')
|
||||
|
||||
|
||||
def instant(value):
|
||||
cd.require(isinstance(value, str) and bool(re.search(r'(Z|[+-]\d\d:\d\d)$', value)), 'invalid QA timestamp')
|
||||
return datetime.datetime.fromisoformat(value.replace('Z', '+00:00'))
|
||||
|
||||
|
||||
def check_qa(plan, receipt, reports, authors):
|
||||
check_plan(plan)
|
||||
tasks = {item['task'] for item in plan['items']} | {plan['task']}
|
||||
cd.require(set(reports) == tasks, 'require reports on every requirement and the release task')
|
||||
cd.require(cd.matches(cd.HASH, receipt.get('bundle')) and receipt.get('sha') == plan['sha'], 'invalid candidate receipt')
|
||||
for task, (comment, report) in reports.items():
|
||||
cd.require((comment.get('actor') or {}).get('id') in authors, f'{task}: require authorized QA report author')
|
||||
cd.require(all(report.get(k) == receipt[k] for k in ('sha', 'bundle', 'url')), f'{task}: report is for a different candidate')
|
||||
cd.require(instant(comment.get('createdAt')) > instant(receipt['ready_at']), f'{task}: report predates candidate')
|
||||
cd.require(not comment.get('updatedAt') or instant(comment['updatedAt']) >= instant(comment['createdAt']),
|
||||
f'{task}: invalid report revision timestamp')
|
||||
values = [report.get(field) for field in ('required', 'passed', 'failed', 'blocked')]
|
||||
cd.require(all(type(v) is int for v in values) and values[0] > 0
|
||||
and values == [values[0], values[0], 0, 0] and report.get('verdict') == 'passed',
|
||||
f'{task}: required QA cases have not passed')
|
||||
|
||||
|
||||
def git(*args, cwd=None):
|
||||
env = dict(os.environ, GIT_TERMINAL_PROMPT='0')
|
||||
return cd.run(['git', *args], 'read candidate source', cwd=cwd, env=env, timeout=120).decode().strip()
|
||||
|
||||
|
||||
def verify_source(plan, repo):
|
||||
main_line = git('rev-list', '--first-parent', 'origin/main', cwd=repo).splitlines()
|
||||
sha, base = plan['sha'], plan['base']
|
||||
cd.require(sha in main_line and base in main_line and main_line.index(sha) < main_line.index(base),
|
||||
'candidate and baseline must be ordered commits on main first-parent history')
|
||||
check_scope(plan, lambda n: read_forge(API + f'/pulls/{n}'),
|
||||
main_line[main_line.index(sha):main_line.index(base)])
|
||||
contexts = {line.split('#', 1)[0].strip() for line in CONTEXTS.read_text().splitlines()} - {''}
|
||||
cd.verify_contexts(read_forge(API + f'/commits/{sha}/status'), contexts)
|
||||
|
||||
|
||||
def build(plan, repo, destination):
|
||||
check_plan(plan)
|
||||
verify_source(plan, repo)
|
||||
sha = plan['sha']
|
||||
destination = destination.resolve()
|
||||
if destination.exists():
|
||||
digest = cd.hash_file(destination / 'release.json')
|
||||
cd.verify_bundle(destination, {'task': plan['task'], 'sha': sha, 'bundle': digest})
|
||||
return digest
|
||||
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
with tempfile.TemporaryDirectory(prefix='kg-candidate-source-') as name:
|
||||
src = Path(name) / 'source'
|
||||
git('clone', '--no-checkout', '--shared', str(repo.resolve()), str(src))
|
||||
git('checkout', '--detach', sha, cwd=src)
|
||||
cd.require(git('rev-parse', 'HEAD', cwd=src) == sha and not git('status', '--porcelain', cwd=src),
|
||||
'candidate checkout differs from selected commit')
|
||||
identity = json.loads(cd.run([sys.executable, 'scripts/version.py', '--identity'], 'read build version', cwd=src))
|
||||
cd.require(identity.get('commit_sha') == sha, 'version script returned another SHA')
|
||||
flags = {'VERSION': identity['release_version'] or 'dev', 'RELEASE_VERSION': identity['release_version'] or '',
|
||||
'BUILD_KIND': identity['build_kind'], 'COMMITS_SINCE_RELEASE': identity['commits_since_release'] or '',
|
||||
'COMMIT_SHA': sha, 'BUILD_TIME': identity['built_at']}
|
||||
common = ['docker', 'build', '--pull=false', '--label', f'{cd.REVISION}={sha}']
|
||||
# Only pass the explicitly configured build proxy, never the agent's inherited credentials.
|
||||
for variable in ('HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY'):
|
||||
value = os.getenv('KG_BUILD_' + variable)
|
||||
if value:
|
||||
cd.require('@' not in value, 'build proxy must not contain credentials')
|
||||
common += ['--build-arg', f'{variable}={value}']
|
||||
tags = {name: f'kg-release-candidate-{name}:{sha}' for name in ('backend', 'web')}
|
||||
for role, dockerfile in (('backend', 'Dockerfile'), ('web', 'Dockerfile.web')):
|
||||
args = common + ['-f', dockerfile, '-t', tags[role]]
|
||||
if role == 'backend':
|
||||
for key, value in flags.items():
|
||||
args += ['--build-arg', f'{key}={value}']
|
||||
subprocess.run(args + ['.'], cwd=src, check=True, timeout=1800)
|
||||
image_ids = {key: cd.image_inspect(tag)['Id'] for key, tag in tags.items()}
|
||||
# pack takes its migration list from this commit and validates the OCI revision and image IDs.
|
||||
original = Path.cwd()
|
||||
try:
|
||||
os.chdir(src)
|
||||
cd.pack(SimpleNamespace(sha=sha, task=plan['task'], api=image_ids['backend'], worker=image_ids['backend'],
|
||||
web=image_ids['web'], output=destination))
|
||||
finally:
|
||||
os.chdir(original)
|
||||
return cd.hash_file(destination / 'release.json')
|
||||
|
||||
|
||||
def event_plan(event, env):
|
||||
cd.require(env.get('GITHUB_EVENT_NAME') == 'workflow_dispatch' and env.get('GITHUB_REPOSITORY') == cd.REPO,
|
||||
'candidate workflow requires an explicit dispatch in the governance repository')
|
||||
inputs = event.get('inputs') or {}
|
||||
mode = inputs.get('mode')
|
||||
cd.require(mode in ('verify', 'prepare'), 'unknown candidate mode')
|
||||
if mode == 'prepare':
|
||||
cd.require(env.get('GITHUB_REF') == 'refs/heads/main', 'prepare requires the workflow from main')
|
||||
plan = json.loads(inputs['plan'])
|
||||
check_plan(plan)
|
||||
return plan, mode
|
||||
|
||||
|
||||
def proof(plan, mode):
|
||||
return 'KG_CANDIDATE_PLAN_V1 ' + cd.acceptance_digest({'plan': plan, 'mode': mode})
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest='action', required=True)
|
||||
guard = sub.add_parser('guard')
|
||||
guard.add_argument('--event', required=True, type=Path)
|
||||
guard.add_argument('--repo', required=True, type=Path)
|
||||
for name in ('verify', 'build'):
|
||||
arg = sub.add_parser(name)
|
||||
arg.add_argument('--plan', required=True, type=Path)
|
||||
arg.add_argument('--repo', required=True, type=Path)
|
||||
if name == 'build':
|
||||
arg.add_argument('--output', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.action == 'guard':
|
||||
plan, mode = event_plan(cd.read_json(args.event), os.environ)
|
||||
verify_source(plan, args.repo)
|
||||
print(proof(plan, mode))
|
||||
return
|
||||
plan = cd.read_json(args.plan)
|
||||
check_plan(plan)
|
||||
if args.action == 'verify':
|
||||
verify_source(plan, args.repo)
|
||||
print(json.dumps({'state': 'verified', 'sha': plan['sha'], 'task': plan['task']}))
|
||||
else:
|
||||
digest = build(plan, args.repo, args.output)
|
||||
print(json.dumps({'state': 'built', 'sha': plan['sha'], 'task': plan['task'], 'bundle': digest}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except cd.CDError as exc:
|
||||
sys.exit(f'Candidate: {exc}')
|
||||
except (OSError, ValueError, KeyError, subprocess.SubprocessError) as exc:
|
||||
sys.exit(f'Candidate: {type(exc).__name__}; check build or release input')
|
||||
@@ -1,151 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the sealed candidate on an isolated acceptance stack."""
|
||||
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import quote
|
||||
|
||||
import production_cd as cd
|
||||
import qa_env
|
||||
|
||||
|
||||
def isolated_subnet(exclude=()):
|
||||
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
|
||||
data = json.loads(cd.run(['docker', 'network', 'inspect', *nets], 'read Docker networks')) if nets else []
|
||||
occupied = [ipaddress.ip_network(row['Subnet']) for net in data for row in net['IPAM']['Config'] or []
|
||||
if row.get('Subnet') and ':' not in row['Subnet']]
|
||||
routes = json.loads(cd.run(['ip', '-j', '-4', 'route'], 'read host routes'))
|
||||
occupied += [ipaddress.ip_network(route['dst'], strict=False) for route in routes if route['dst'] != 'default']
|
||||
occupied += [ipaddress.ip_network(subnet) for subnet in exclude]
|
||||
for subnet in ipaddress.ip_network('10.241.233.0/24').subnets(new_prefix=28):
|
||||
if not any(subnet.overlaps(other) for other in occupied):
|
||||
return str(subnet)
|
||||
raise cd.CDError('no available candidate subnet')
|
||||
|
||||
|
||||
def qa_database(path):
|
||||
db = qa_env.database_config(path)
|
||||
passfile, cert = [path.parent / name for name in ('qa.pgpass', 'rds-ca.pem')]
|
||||
qa_env.private_file(passfile)
|
||||
qa_env.private_file(cert)
|
||||
expected = f"{db['host']}:{db['port']}:{db['database']}:{db['user']}:"
|
||||
entries = [line for line in passfile.read_text().splitlines() if line and not line.startswith('#')]
|
||||
cd.require(len(entries) == 1 and entries[0].startswith(expected), 'pgpass must authorize exactly the dedicated QA database')
|
||||
password = re.sub(r'\\(.)', r'\1', entries[0][len(expected):])
|
||||
cd.require(bool(password), 'dedicated QA database password missing')
|
||||
url = (f"postgresql://{db['user']}:{quote(password, safe='')}@{db['host']}:{db['port']}/{db['database']}"
|
||||
'?sslmode=verify-full&sslrootcert=/run/qa/rds-ca.pem')
|
||||
return url, cert
|
||||
|
||||
|
||||
def ready(directory, bundle, test_database=None):
|
||||
bundle = bundle.resolve()
|
||||
manifest = cd.read_json(bundle / 'release.json')
|
||||
digest = cd.hash_file(bundle / 'release.json')
|
||||
request = {key: manifest[key] for key in ('sha', 'task')}
|
||||
request['bundle'] = digest
|
||||
cd.verify_bundle(bundle, request)
|
||||
project = 'kg-batch-' + digest[:20] + ('-smoke' if test_database is None else '')
|
||||
cf = directory / 'compose.json'
|
||||
receipt_path = directory / 'ready.json'
|
||||
cmd = ['docker', 'compose', '-p', project, '-f', str(cf)]
|
||||
if cf.exists():
|
||||
cd.require(receipt_path.exists(), 'candidate startup is unresolved; inspect its Compose project')
|
||||
receipt = cd.read_json(cd.immutable_file(receipt_path))
|
||||
cd.require(receipt['task'] == request['task'] and receipt['bundle'] == digest, 'candidate already holds another bundle')
|
||||
attest(bundle, receipt)
|
||||
return receipt
|
||||
services = {}
|
||||
env = {'APP_ADDR': '0.0.0.0:8080', 'TEST_WEKNORA_ENABLED': 'false', 'PP_SCAN_ENABLED': 'false',
|
||||
'RELEASE_WORKER_ENABLED': 'false', 'PRODUCTION_RELEASE_REQUESTS_ENABLED': 'false',
|
||||
'DOBOTAI_OPS_READ_ENABLED': 'false', 'DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED': 'false'}
|
||||
if test_database is None:
|
||||
password = secrets.token_hex(24)
|
||||
cd.atomic_write(directory / 'postgres.env', f'POSTGRES_USER=qa\nPOSTGRES_DB=governance\nPOSTGRES_PASSWORD={password}\n'.encode())
|
||||
env['DATA' + 'BASE_URL'] = f'postgres://qa:{password}@postgres:5432/governance?sslmode=disable'
|
||||
services['postgres'] = {'image': 'postgres:17-alpine', 'env_file': [str(directory / 'postgres.env')],
|
||||
'tmpfs': ['/var/lib/postgresql/data'],
|
||||
'healthcheck': {'test': ['CMD', 'pg_isready', '-U', 'qa', '-d', 'governance'],
|
||||
'interval': '2s', 'timeout': '2s', 'retries': 20}}
|
||||
else:
|
||||
url, cert = qa_database(test_database)
|
||||
env['DATA' + 'BASE_URL'] = url
|
||||
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
|
||||
app_env = directory / 'app.env'
|
||||
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
|
||||
names = {role: f'{project}-{role}' for role in cd.ROLES}
|
||||
for role, item in manifest['images'].items():
|
||||
archive = bundle / f'{role}.tar'
|
||||
cd.verify_archive(archive, item['id'])
|
||||
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
|
||||
services[role] = {'image': item['id'], 'container_name': names[role]}
|
||||
for role in ('api', 'worker'):
|
||||
services[role]['env_file'] = [str(app_env)]
|
||||
if test_database is not None:
|
||||
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro']
|
||||
services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'],
|
||||
'interval': '2s', 'timeout': '3s', 'retries': 45}
|
||||
if test_database is None:
|
||||
services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}}
|
||||
services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}})
|
||||
services['web'].update(ports=['127.0.0.1::8080'], depends_on={'api': {'condition': 'service_healthy'}})
|
||||
internal_subnet = isolated_subnet()
|
||||
networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}}
|
||||
if test_database is None:
|
||||
# The private smoke network has no NAT. Only the web container gets an ingress network.
|
||||
networks['ingress'] = {'ipam': {'config': [{'subnet': isolated_subnet([internal_subnet])}]}}
|
||||
services['web']['networks'] = {'default': {}, 'ingress': {}}
|
||||
cd.record(cf, {'services': services, 'networks': networks})
|
||||
try:
|
||||
cd.run(cmd + ['up', '-d', '--no-build', '--pull', 'never'], 'start candidate Compose project', timeout=130)
|
||||
raw_ports = json.loads(cd.run(['docker', 'inspect', '--format', '{{json .NetworkSettings.Ports}}', names['web']],
|
||||
'read candidate web binding'))
|
||||
port = (raw_ports or {}).get('8080/tcp') or []
|
||||
cd.require(len(port) == 1 and port[0].get('HostIp') == '127.0.0.1'
|
||||
and re.fullmatch(r'[1-9][0-9]{0,4}', port[0].get('HostPort', '')),
|
||||
'candidate web has no verified loopback binding')
|
||||
receipt = {**request, 'url': f'http://127.0.0.1:{port[0]["HostPort"]}', 'containers': names,
|
||||
'images': {role: image['id'] for role, image in manifest['images'].items()},
|
||||
'mode': 'smoke' if test_database is None else 'acceptance'}
|
||||
cd.wait_ready(lambda: attest(bundle, receipt), seconds=65)
|
||||
receipt['ready_at'] = cd.stamp()
|
||||
cd.record(receipt_path, receipt)
|
||||
return receipt
|
||||
except Exception:
|
||||
cd.run(cmd + ['down', '--timeout', '3'], 'stop unsuccessful candidate Compose project', timeout=40)
|
||||
raise
|
||||
|
||||
|
||||
def attest(bundle, receipt):
|
||||
cd.require(cd.hash_file(bundle / 'release.json') == receipt['bundle'], 'candidate bundle changed after deployment')
|
||||
cd.attest(SimpleNamespace(sha=receipt['sha'], task=receipt['task'], directory=bundle,
|
||||
test_url=receipt['url'], **receipt['containers']))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('bundle', type=Path)
|
||||
args = parser.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix='kg-candidate-smoke-') as temp:
|
||||
directory = Path(temp)
|
||||
try:
|
||||
print(json.dumps(ready(directory, args.bundle)))
|
||||
finally:
|
||||
if (directory / 'compose.json').exists():
|
||||
digest = cd.hash_file(args.bundle / 'release.json')
|
||||
cmd = ['docker', 'compose', '-p', 'kg-batch-' + digest[:20] + '-smoke', '-f', str(directory / 'compose.json')]
|
||||
cd.run(cmd + ['down', '--timeout', '3'], 'remove disposable rehearsal containers', timeout=45)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (cd.CDError, qa_env.QAError, OSError, ValueError) as exc:
|
||||
sys.exit(f'Candidate runtime: {exc}')
|
||||
@@ -1,115 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local build worker for authenticated Gitea candidate jobs."""
|
||||
|
||||
import hmac
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from urllib.error import URLError
|
||||
|
||||
import candidate_coordinator as coordinator
|
||||
import candidate_release as candidate
|
||||
import candidate_runtime as runtime
|
||||
import production_cd as cd
|
||||
|
||||
|
||||
def verify_job(run_id, plan, repo):
|
||||
cd.require(isinstance(run_id, str) and run_id.isascii() and run_id.isdigit() and 0 < len(run_id) < 16,
|
||||
'invalid candidate workflow run')
|
||||
target = candidate.API + f'/actions/runs/{run_id}'
|
||||
run = candidate.read_forge(target)
|
||||
sha = run.get('head_sha')
|
||||
cd.require(run.get('event') == 'workflow_dispatch' and run.get('path') == 'prepare-candidate.yml@refs/heads/main'
|
||||
and run.get('status') == 'in_progress' and (run.get('actor') or {}).get('id') == 1
|
||||
and cd.matches(cd.SHA, sha), 'untrusted candidate workflow run')
|
||||
file = '.gitea/workflows/prepare-candidate.yml'
|
||||
cd.require(candidate.git('show', f'{sha}:{file}', cwd=repo) == Path(__file__).resolve().parents[1].joinpath(file).read_text().strip(),
|
||||
'candidate workflow differs from locally installed instructions')
|
||||
jobs = candidate.read_forge(target + '/jobs').get('jobs', [])
|
||||
guard = [job for job in jobs if job.get('name') == 'guard' and job.get('conclusion') == 'success']
|
||||
cd.require(len(guard) == 1 and type(guard[0].get('id')) is int, 'candidate guard did not succeed')
|
||||
# Gitea logs are plaintext and may prefix each line with a timestamp.
|
||||
raw = coordinator.hfx.forge('GET', candidate.API + f'/actions/jobs/{guard[0]["id"]}/logs', raw=True)
|
||||
cd.require(len(raw) <= 2**20, 'candidate guard log exceeded the read limit')
|
||||
lines = raw.decode().splitlines()
|
||||
cd.require(sum(line.strip().endswith(candidate.proof(plan, 'prepare')) for line in lines) == 1,
|
||||
'candidate input does not match Gitea guard proof')
|
||||
|
||||
|
||||
def main_site_sha():
|
||||
raw = cd.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=6', 'weknora-test',
|
||||
'docker compose -p knowledge-governance-cloud-test -f /opt/knowledge-governance/compose.json '
|
||||
'exec -T api /app/api --version-record-status'], 'read main site build identity',
|
||||
allowed=(0, 1), timeout=15)
|
||||
sha = json.loads(raw).get('commit_sha')
|
||||
cd.require(cd.matches(cd.SHA, sha), 'main site did not report a full SHA')
|
||||
return sha
|
||||
|
||||
|
||||
def prepare(payload, repo):
|
||||
cd.require(isinstance(payload, dict) and set(payload) == {'run', 'plan'}, 'invalid candidate job payload')
|
||||
plan = payload['plan']
|
||||
candidate.check_plan(plan)
|
||||
key = cd.acceptance_digest(plan)
|
||||
state = coordinator.STATE
|
||||
conf = Path.home() / '.config/knowledge-governance/qa.json'
|
||||
with cd.deploy_lock(state / 'runtime.lock'):
|
||||
cd.require(coordinator.owner_plan(plan['task']) == plan, 'release owner plan changed')
|
||||
runtime.qa_database(conf)
|
||||
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=repo)
|
||||
verify_job(payload['run'], plan, repo)
|
||||
cd.require(main_site_sha() == plan['base'], 'release baseline differs from the live main site')
|
||||
directory = state / key
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
for existing in state.glob('*/compose.json'):
|
||||
cd.require(existing.parent == directory, 'another candidate owns the acceptance slot')
|
||||
candidate.build(plan, repo, directory / 'bundle')
|
||||
cd.require(coordinator.owner_plan(plan['task']) == plan, 'release plan changed after candidate build')
|
||||
receipt = runtime.ready(directory, directory / 'bundle', conf)
|
||||
coordinator.publish_candidate(plan, receipt, payload['run'])
|
||||
return receipt
|
||||
|
||||
|
||||
def serve(repo, access):
|
||||
secret = cd.immutable_file(access).read_text().strip()
|
||||
cd.require(cd.matches(cd.HASH, secret), 'invalid candidate access file')
|
||||
coordinator.STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
def respond(self, status, body):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != '/prepare' or not hmac.compare_digest(self.headers.get('Authorization', ''), 'Bearer ' + secret):
|
||||
self.respond(403, {'error': 'candidate authorization refused'})
|
||||
return
|
||||
try:
|
||||
size = int(self.headers.get('Content-Length', 0))
|
||||
cd.require(0 < size <= 65536, 'invalid candidate payload size')
|
||||
self.connection.settimeout(10)
|
||||
payload = json.loads(self.rfile.read(size))
|
||||
self.connection.settimeout(60)
|
||||
receipt = prepare(payload, repo)
|
||||
self.respond(200, receipt)
|
||||
except (cd.CDError, runtime.qa_env.QAError) as exc:
|
||||
self.respond(409, {'error': str(exc)})
|
||||
except (OSError, KeyError, ValueError, URLError) as exc:
|
||||
self.respond(502, {'error': f'candidate operation failed: {type(exc).__name__}'})
|
||||
|
||||
ThreadingHTTPServer(('127.0.0.1', 38984), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) != 3:
|
||||
sys.exit('usage: candidate_worker.py <source repository> <private access file>')
|
||||
serve(Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve())
|
||||
@@ -1,56 +0,0 @@
|
||||
"""Run inside a governance container. Read the real application DB ledger only."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from urllib.parse import parse_qsl, unquote, urlsplit
|
||||
|
||||
|
||||
def connection_env(env):
|
||||
# Keep only the connection properties actually shared by libpq and pgx.
|
||||
# Unknown DSN options can change the database identity or schema search path.
|
||||
u = urlsplit(env['DATABASE' + '_URL'])
|
||||
if u.scheme not in ('postgres', 'postgresql') or not u.hostname or not u.username or not u.path[1:] or u.fragment:
|
||||
raise ValueError('invalid database URL')
|
||||
query = parse_qsl(u.query, strict_parsing=True, keep_blank_values=True)
|
||||
supported = {'sslmode': 'PGSSLMODE', 'sslrootcert': 'PGSSLROOTCERT', 'sslcert': 'PGSSLCERT', 'sslkey': 'PGSSLKEY'}
|
||||
if len(dict(query)) != len(query) or any(key not in supported or not val for key, val in query):
|
||||
raise ValueError('unknown database connection options')
|
||||
safe = {'PATH': '/usr/bin:/bin', 'HOME': env.get('HOME', '/nonexistent'), 'LC_ALL': 'C',
|
||||
'PGHOST': u.hostname, 'PGPORT': str(u.port or 5432), 'PGDATABASE': unquote(u.path[1:]),
|
||||
'PGUSER': unquote(u.username), 'PGCONNECT_TIMEOUT': '5',
|
||||
'PGOPTIONS': '-c default_transaction_read_only=on -c statement_timeout=5000'}
|
||||
for name in ('PGPASSFILE', 'PGSSLMODE', 'PGSSLROOTCERT', 'PGSSLCERT', 'PGSSLKEY'):
|
||||
if env.get(name):
|
||||
safe[name] = env[name]
|
||||
for name in env:
|
||||
if name.startswith('PG') and name not in safe:
|
||||
raise ValueError('unknown inherited database connection options')
|
||||
safe.update({supported[key]: value for key, value in query})
|
||||
if u.password:
|
||||
safe['PGPASSWORD'] = unquote(u.password)
|
||||
for name in ('PGDATABASE', 'PGUSER'):
|
||||
if any(char in safe[name] for char in '\r\n\x00='):
|
||||
raise ValueError('unsafe database identifier')
|
||||
return safe
|
||||
|
||||
|
||||
def main():
|
||||
env = connection_env(os.environ)
|
||||
sql = """SELECT json_build_object('database', current_database(), 'user', current_user,
|
||||
'read_only', current_setting('transaction_read_only'),
|
||||
'versions', (SELECT json_agg(version ORDER BY version) FROM schema_migrations));"""
|
||||
p = subprocess.run(['psql', '-XAtw', '-v', 'ON_ERROR_STOP=1', '-c', sql],
|
||||
env=env, capture_output=True, timeout=12)
|
||||
if p.returncode:
|
||||
raise ValueError('query failed')
|
||||
data = json.loads(p.stdout)
|
||||
if data['read_only'] != 'on' or data['database'] != env['PGDATABASE'] or data['user'] != env['PGUSER']:
|
||||
raise ValueError('database identity mismatch')
|
||||
print(json.dumps(data['versions']))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, subprocess.TimeoutExpired):
|
||||
raise SystemExit('read-only migration probe failed') from None
|
||||
@@ -172,43 +172,14 @@ def npm_audit(args: list[str]) -> tuple[dict, str | None]:
|
||||
return {}, f"npm audit 输出解析不了(exit={p.returncode}):{(p.stdout or p.stderr)[:300]}"
|
||||
|
||||
|
||||
def advisory_ids(vulns: dict, name: str, seen: set[str] | None = None) -> list[str]:
|
||||
"""收集一个包命中的 GHSA 编号,沿 via 里的依赖链向上追。
|
||||
|
||||
为什么不能只看本包的 via:npm 对 fdir/tinyglobby/vite 这类"由于依赖了有洞的包"
|
||||
的条目,via 里只有依赖名(字符串),直接取 url 会得到空 id;空 id 的发现既没法
|
||||
写进例外表(例外要求 id 非空),也会让排查人以为"没有具体漏洞"。追到链底才是
|
||||
真正要豁免/修复的那条公告。
|
||||
"""
|
||||
seen = seen or set()
|
||||
if name in seen:
|
||||
return []
|
||||
seen.add(name)
|
||||
entry = vulns.get(name)
|
||||
if not isinstance(entry, dict):
|
||||
return []
|
||||
ids: list[str] = []
|
||||
for via in entry.get("via") or []:
|
||||
if isinstance(via, dict) and via.get("url"):
|
||||
ids.append(str(via["url"]).rsplit("/", 1)[-1])
|
||||
elif isinstance(via, str):
|
||||
ids.extend(advisory_ids(vulns, via, seen))
|
||||
# 去重但保持稳定顺序,便于例外表逐字核对
|
||||
out: list[str] = []
|
||||
for item in ids:
|
||||
if item and item not in out:
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def audit_findings(data: dict, scope: str) -> list[dict]:
|
||||
out = []
|
||||
vulns = data.get("vulnerabilities") or {}
|
||||
for name, adv in vulns.items():
|
||||
for name, adv in (data.get("vulnerabilities") or {}).items():
|
||||
if not isinstance(adv, dict):
|
||||
continue
|
||||
sev = str(adv.get("severity") or "").lower()
|
||||
ids = advisory_ids(vulns, name)
|
||||
ids = [v.get("url", "").rsplit("/", 1)[-1]
|
||||
for v in (adv.get("via") or []) if isinstance(v, dict) and v.get("url")]
|
||||
out.append({"tool": "npm-audit", "id": ids[0] if ids else "", "package": name,
|
||||
"severity": sev, "scope": scope,
|
||||
"detail": f"isDirect={adv.get('isDirect')} range={adv.get('range')}"})
|
||||
|
||||
@@ -442,14 +442,6 @@ def cmd_internal_contracts(go: str) -> int:
|
||||
判据同时核三件事:进程退出码、必需测试集合、负例失败归因——
|
||||
缺任意一件,"绿"就可能是别的测试失败/编译错误伪装出来的。
|
||||
"""
|
||||
qa_rc = subprocess.run(py("-m", "unittest", "discover", "-s", "scripts", "-p", "test_qa_env.py", "-v"),
|
||||
cwd=ROOT).returncode
|
||||
if qa_rc:
|
||||
return qa_rc
|
||||
for pattern in ('test_production_cd.py', 'test_candidate_release.py'):
|
||||
cd_rc = subprocess.run(py('-m', 'unittest', 'discover', '-s', 'scripts', '-p', pattern, '-v'), cwd=ROOT).returncode
|
||||
if cd_rc:
|
||||
return cd_rc
|
||||
snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode
|
||||
if snapshot_rc:
|
||||
return 1
|
||||
|
||||
@@ -1,20 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# 重建并上线 governance api + web(本机 docker build 需要宿主代理 + --network host)
|
||||
set -u
|
||||
|
||||
# Share the image-only Compose switch with CD without entering the legacy build path.
|
||||
compose_up() {
|
||||
"${compose[@]}" up -d --no-build --no-deps "$@"
|
||||
}
|
||||
|
||||
if [[ "${1:-}" == --verified-compose ]]; then
|
||||
[[ "$#" == 7 && "$5" == api && "$6" == web && "$7" == worker && "$4" == /* ]] || exit 2
|
||||
cd -- "$2" || exit 1
|
||||
compose=(docker compose -p "$3" -f "$4")
|
||||
compose_up --pull never "$5" "$6" "$7"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1
|
||||
[ -z "$(git status --porcelain --untracked-files=normal)" ] || { printf "%s\n" "REFUSED_DIRTY_SOURCE"; exit 1; }
|
||||
TS=$(date +%Y%m%d-%H%M%S)
|
||||
@@ -117,9 +103,7 @@ if [ "${GATES_PREV}" = "true" ] && [[ "${COMPOSE_FILES_EFFECTIVE}" != *compose.r
|
||||
echo " 确实要关闸:ALLOW_GATE_OFF=1 bash scripts/deploy-api-web.sh"
|
||||
exit 1
|
||||
fi
|
||||
read -r -a compose_file_args <<< "$COMPOSE_FILES_EFFECTIVE"
|
||||
compose=(docker compose "${compose_file_args[@]}")
|
||||
compose_up api web || { echo "UP_FAILED"; exit 1; }
|
||||
docker compose ${COMPOSE_FILES_EFFECTIVE} up -d --no-build --no-deps api web || { echo "UP_FAILED"; exit 1; }
|
||||
|
||||
echo "=== 5. 状态"
|
||||
docker ps --filter name=knowledge-governance-p1 --format '{{.Names}} {{.Status}} {{.Image}}'
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Submit a HiFox-approved release from the designated CD Agent host."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import ProxyHandler, Request, build_opener
|
||||
|
||||
import production_cd as cd
|
||||
|
||||
|
||||
DISPATCH = f'/api/v1/repos/{cd.REPO}/actions/workflows/deploy-production.yml/dispatches?return_run_details=true'
|
||||
PATH = Path.home() / '.local/state/kg-hifox-release'
|
||||
RUN_ID = re.compile('[1-9][0-9]{0,14}')
|
||||
|
||||
|
||||
def forge(method, path, payload=None, *, raw=False):
|
||||
request = Request(cd.FORGE + path, method=method,
|
||||
data=json.dumps(payload).encode() if payload is not None else None)
|
||||
env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0', 'GIT_ASKPASS': '/bin/false'}
|
||||
fields = dict(line.split('=', 1) for line in cd.run(
|
||||
['/usr/bin/git', 'credential', 'fill'], 'read Gitea credential', cwd='/', env=env,
|
||||
input_data=f'url={cd.FORGE}/{cd.REPO}.git\n\n'.encode()).decode().splitlines() if '=' in line)
|
||||
cd.require(fields.get('username') and fields.get('password'), 'Gitea credential unavailable')
|
||||
auth = base64.b64encode(f'{fields["username"]}:{fields["password"]}'.encode()).decode()
|
||||
request.add_header('Authorization', 'Basic ' + auth)
|
||||
request.add_header('Content-Type', 'application/json')
|
||||
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=20) as response:
|
||||
return response.read(2**20 + 1) if raw else json.load(response)
|
||||
|
||||
|
||||
def hifox(cli, *args):
|
||||
env = {'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': str(Path.home()), 'CI': '1'}
|
||||
raw = cd.run([cli, '--organization-id', cd.ORG, *args, '--output', 'json'], 'read HiFox release record', env=env)
|
||||
result = json.JSONDecoder().raw_decode(raw.decode().strip())[0]
|
||||
cd.require(isinstance(result, (dict, list)) and (not isinstance(result, dict)
|
||||
or (result.get('success') is not False and not result.get('error'))), 'HiFox record unavailable')
|
||||
return result
|
||||
|
||||
|
||||
def queue(task_id, cli, base=PATH):
|
||||
cd.require(cd.matches(cd.UUID, task_id), 'use the triggering task UUID')
|
||||
task = hifox(cli, 'task', 'view', task_id)
|
||||
if not isinstance(task, dict) or task.get('id') != task_id or task.get('spaceId') != cd.SPACE:
|
||||
raise cd.CDError('task is outside the release space')
|
||||
acceptance = cd.metadata(task, 'cd_acceptance') or {}
|
||||
cd.require(isinstance(acceptance, dict) and cd.matches(cd.SHA, acceptance.get('sha'))
|
||||
and cd.matches(cd.HASH, acceptance.get('bundle')), 'skip: no registered candidate acceptance')
|
||||
inputs = dict(action='deploy', confirm='deploy-production', sha=acceptance['sha'], bundle=acceptance['bundle'], task=task_id)
|
||||
timeline = hifox(cli, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
|
||||
if not isinstance(timeline, list):
|
||||
raise cd.CDError('HiFox timeline unavailable')
|
||||
binding, approved_at = cd.release_approval(task, timeline, inputs)
|
||||
inputs.update(binding)
|
||||
since = cd.immutable_file(base / 'active-since').read_text().strip()
|
||||
cd.require(re.fullmatch(r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ', since) and approved_at > since,
|
||||
'status approval predates activation; enter 待发布 again after acceptance')
|
||||
|
||||
claim = base / (binding['approval_event'] + '.json')
|
||||
with cd.deploy_lock(base / 'dispatch.lock'):
|
||||
if claim.exists():
|
||||
result = cd.read_json(cd.immutable_file(claim))
|
||||
cd.require(result.get('inputs') == inputs, 'HiFox approval already used for a different release')
|
||||
cd.require(result.get('state') == 'queued', 'dispatch outcome unknown; reconcile Gitea before retry')
|
||||
return result
|
||||
result = {'state': 'submitting', 'inputs': inputs, 'started_at': cd.stamp()}
|
||||
cd.record(claim, result)
|
||||
response = forge('POST', DISPATCH, {'ref': 'main', 'inputs': inputs})
|
||||
run_id = str(response.get('workflow_run_id', ''))
|
||||
cd.require(cd.matches(RUN_ID, run_id), 'dispatch response has no valid run ID; reconcile before retry')
|
||||
result.update(state='queued', run_id=run_id, run_url=f'{cd.FORGE}/{cd.REPO}/actions/runs/{run_id}')
|
||||
cd.record(claim, result)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('task', help='UUID of the task that entered 待发布')
|
||||
args = parser.parse_args()
|
||||
executable = Path.home() / '.local/bin/hifox'
|
||||
try:
|
||||
print(json.dumps(queue(args.task, str(executable)), ensure_ascii=False))
|
||||
except HTTPError as exc:
|
||||
sys.exit(f'CD: Gitea dispatch HTTP {exc.code}; reconcile before retry')
|
||||
except cd.CDError as exc:
|
||||
sys.exit(f'CD: {exc}')
|
||||
except (OSError, KeyError, ValueError, TypeError) as exc:
|
||||
sys.exit(f'CD: {type(exc).__name__}; inspect the dispatch record')
|
||||
@@ -8,7 +8,6 @@ import argparse,csv,io,json,os,pathlib,re,subprocess,sys,tempfile
|
||||
from collections import deque
|
||||
sys.path.insert(0,'/app/scripts')
|
||||
from source_catalog_import import build_alist_source,build_dingtalk_sources,build_pp_live_source,catalog_sql,validate_source
|
||||
from pp_client import active_client,record_observation,observation,PPError
|
||||
class RefreshBlocked(RuntimeError):pass
|
||||
|
||||
_source_name='';_last_directory=''
|
||||
@@ -40,16 +39,12 @@ def run_psql(sql):
|
||||
if result.returncode:raise RuntimeError('catalog activation failed')
|
||||
|
||||
def refresh_pp():
|
||||
sys.path.insert(0,'/sources/pp');from download_scope_a import login,fetch_inventory
|
||||
emit('connecting',10,'正在登录PP资料下载中心')
|
||||
client=None
|
||||
try:
|
||||
client=active_client();token=client.login()
|
||||
emit('scanning',35,'正在实时读取PP公开资料清单')
|
||||
inventory=client.inventory(token)
|
||||
record_observation(client.config,observation('valid'))
|
||||
except PPError as error:
|
||||
if client is not None:record_observation(client.config,observation(error.state))
|
||||
raise RefreshBlocked(str(error)+',请在数据源配置检查PP连接') from error
|
||||
try:token=login('/run/source-secrets/pp_credentials.json')
|
||||
except Exception as error:raise RefreshBlocked('PP登录失败,请在来源链接更新凭据') from error
|
||||
emit('scanning',35,'正在实时读取PP公开资料清单')
|
||||
inventory=fetch_inventory(token)
|
||||
emit('building',75,'正在构建PP八类目录快照',len(inventory.get('items',[])),len(inventory.get('items',[])))
|
||||
manifest={}
|
||||
try:
|
||||
|
||||
@@ -1,213 +0,0 @@
|
||||
"""PP read-only API client; the only PP authentication protocol implementation.
|
||||
|
||||
API checks and new worker tasks load the same atomically activated configuration.
|
||||
Secrets enter the check subprocess on stdin, never through argv or stdout.
|
||||
"""
|
||||
import contextlib
|
||||
import datetime
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_BASE = "https://api.dobot.cn"
|
||||
DEFAULT_STATE = "/data/source-auth/pp/settings.json"
|
||||
MESSAGES = {
|
||||
"valid": "认证有效 · 目录可读",
|
||||
"incomplete": "配置未完成,请填写账号和密码",
|
||||
"auth_failed": "PP 拒绝认证,请检查账号和密码",
|
||||
"permission_denied": "已认证,但目录权限不足",
|
||||
"unavailable": "PP 暂时无法检查,请稍后重试",
|
||||
"invalid_response": "PP 接口地址或返回格式不兼容",
|
||||
}
|
||||
|
||||
class PPError(Exception):
|
||||
def __init__(self, state):
|
||||
self.state = state
|
||||
super().__init__(MESSAGES[state])
|
||||
|
||||
def observation(state):
|
||||
return {"state": state, "message": MESSAGES[state], "checked_at": datetime.datetime.now(datetime.timezone.utc).isoformat()}
|
||||
|
||||
def validate_base(raw, allow_http=False):
|
||||
if not isinstance(raw, str) or len(raw) > 300 or raw.strip() != raw:
|
||||
raise PPError("invalid_response")
|
||||
try:
|
||||
u = urllib.parse.urlsplit(raw)
|
||||
if (u.scheme not in (("https", "http") if allow_http else ("https",))
|
||||
or not u.hostname or u.username is not None or u.password is not None
|
||||
or u.path not in ("", "/") or u.query or u.fragment or "?" in raw or "#" in raw):
|
||||
raise PPError("invalid_response")
|
||||
_ = u.port
|
||||
except ValueError:
|
||||
raise PPError("invalid_response") from None
|
||||
return raw.rstrip("/")
|
||||
|
||||
def load_config(path=None):
|
||||
p = pathlib.Path(path or os.environ.get("PP_AUTH_STATE_FILE") or DEFAULT_STATE)
|
||||
if p.exists():
|
||||
info = p.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) & 0o077:
|
||||
raise PPError("incomplete")
|
||||
state = json.loads(p.read_text(encoding="utf-8"))
|
||||
config = state.get("active")
|
||||
if not isinstance(config, dict):
|
||||
raise PPError("incomplete")
|
||||
else:
|
||||
legacy_path = os.environ.get("PP_LEGACY_CREDENTIALS_FILE")
|
||||
if not legacy_path:
|
||||
raise PPError("incomplete")
|
||||
legacy = pathlib.Path(legacy_path)
|
||||
try:
|
||||
config = json.loads(legacy.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
raise PPError("incomplete") from None
|
||||
config = {**config, "base_url": config.get("base_url") or DEFAULT_BASE, "id": "legacy"}
|
||||
validate_base(config.get("base_url"))
|
||||
if not config.get("username") or not config.get("password"):
|
||||
raise PPError("incomplete")
|
||||
return config
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
class Client:
|
||||
def __init__(self, config, allow_http=False, timeout=20):
|
||||
self.config = dict(config)
|
||||
self.base = validate_base(config.get("base_url"), allow_http)
|
||||
self.timeout = timeout
|
||||
self.opener = urllib.request.build_opener(NoRedirect())
|
||||
|
||||
def request(self, path, token="", body=None, login=False):
|
||||
headers = {"Accept": "application/json", "User-Agent": "KnowledgeGovernance/PPReadOnly"}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/x-www-form-urlencoded"
|
||||
req = urllib.request.Request(self.base + path, data=body, headers=headers)
|
||||
try:
|
||||
with self.opener.open(req, timeout=self.timeout) as response:
|
||||
raw = response.read((8 << 20) + 1)
|
||||
if len(raw) > 8 << 20:
|
||||
raise PPError("invalid_response")
|
||||
payload = json.loads(raw)
|
||||
except urllib.error.HTTPError as error:
|
||||
error.close()
|
||||
if error.code == 401 or (error.code == 403 and login):
|
||||
raise PPError("auth_failed") from None
|
||||
if error.code == 403:
|
||||
raise PPError("permission_denied") from None
|
||||
if error.code in (408, 425, 429) or error.code >= 500:
|
||||
raise PPError("unavailable") from None
|
||||
raise PPError("invalid_response") from None
|
||||
except (TimeoutError, OSError):
|
||||
raise PPError("unavailable") from None
|
||||
except (ValueError, TypeError):
|
||||
raise PPError("invalid_response") from None
|
||||
if not isinstance(payload, dict) or not isinstance(payload.get("code"), int) or isinstance(payload.get("code"), bool):
|
||||
raise PPError("invalid_response")
|
||||
if payload["code"] != 0:
|
||||
code = payload["code"]
|
||||
if code in (408, 429) or 500 <= code < 600:
|
||||
raise PPError("unavailable")
|
||||
if login or code == 401:
|
||||
raise PPError("auth_failed")
|
||||
if code == 403:
|
||||
raise PPError("permission_denied")
|
||||
raise PPError("invalid_response")
|
||||
return payload.get("data")
|
||||
|
||||
def login(self):
|
||||
if not self.config.get("username") or not self.config.get("password"):
|
||||
raise PPError("incomplete")
|
||||
body = urllib.parse.urlencode({"username": self.config["username"], "password": self.config["password"]}).encode()
|
||||
data = self.request("/admin/login/token", body=body, login=True)
|
||||
token = data.get("access_token") if isinstance(data, dict) else None
|
||||
if not isinstance(token, str) or not token:
|
||||
raise PPError("invalid_response")
|
||||
return token
|
||||
|
||||
def page(self, token, current=1, size=200):
|
||||
query = urllib.parse.urlencode({"current": current, "size": size})
|
||||
data = self.request("/potal/file/back/page?" + query, token=token)
|
||||
total = data.get("total") if isinstance(data, dict) else None
|
||||
# PP serializes Java Long counts as canonical decimal strings.
|
||||
if (isinstance(total, str) and len(total) <= 19 and total.isascii() and total.isdecimal()
|
||||
and (total == "0" or not total.startswith("0"))):
|
||||
total = int(total)
|
||||
if (not isinstance(data, dict) or not isinstance(data.get("list"), list)
|
||||
or not isinstance(total, int) or isinstance(total, bool)
|
||||
or total < 0 or not isinstance(data.get("hasNextPage"), bool)):
|
||||
raise PPError("invalid_response")
|
||||
return {**data, "total": total}
|
||||
|
||||
def check(self):
|
||||
try:
|
||||
self.page(self.login(), size=1)
|
||||
return observation("valid")
|
||||
except PPError as error:
|
||||
return observation(error.state)
|
||||
|
||||
def inventory(self, token):
|
||||
items = []
|
||||
for current in range(1, 10001):
|
||||
page = self.page(token, current)
|
||||
items.extend(page["list"])
|
||||
if not page["hasNextPage"]:
|
||||
if len(items) != page["total"]:
|
||||
raise PPError("invalid_response")
|
||||
return {"reported_total": page["total"], "pages": current, "items": items}
|
||||
raise PPError("invalid_response")
|
||||
|
||||
def record_observation(config, result, path=None):
|
||||
"""An old task may update only the observation of its own active revision."""
|
||||
p = pathlib.Path(path or os.environ.get("PP_AUTH_STATE_FILE") or DEFAULT_STATE)
|
||||
if not p.is_file():
|
||||
return
|
||||
with os.fdopen(os.open(str(p) + ".lock", os.O_CREAT | os.O_RDWR, 0o600), "r+", encoding="utf-8") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
state = json.loads(p.read_text(encoding="utf-8"))
|
||||
if not state.get("active") or state["active"].get("id") != config.get("id"):
|
||||
return
|
||||
old = state.get("observation")
|
||||
if result.get("state") == "unavailable" and isinstance(old, dict):
|
||||
result = {**result, "previous": old.get("previous") or old}
|
||||
state["observation"] = result
|
||||
fd, temp = tempfile.mkstemp(prefix=".pp-next-", dir=p.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as out:
|
||||
json.dump(state, out, ensure_ascii=False)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
os.replace(temp, p)
|
||||
directory = os.open(p.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.unlink(temp)
|
||||
|
||||
def active_client():
|
||||
return Client(load_config())
|
||||
|
||||
def main():
|
||||
try:
|
||||
config = json.load(sys.stdin)
|
||||
result = Client(config).check()
|
||||
except PPError as error:
|
||||
result = observation(error.state)
|
||||
except Exception:
|
||||
result = observation("unavailable")
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
umask 077
|
||||
[ "${SSH_ORIGINAL_COMMAND:-}" = kg-cd-v1 ] || exit 1
|
||||
exec /usr/bin/env -i HOME=/opt/knowledge-governance/cd PATH=/usr/bin:/bin LANG=C.UTF-8 \
|
||||
GIT_TERMINAL_PROMPT=0 /usr/bin/python3 -I /opt/knowledge-governance/cd/bin/production_cd.py serve
|
||||
@@ -1,857 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Governance application CD. The installed host copy owns the release boundary."""
|
||||
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
import copy
|
||||
from datetime import datetime, timezone
|
||||
import fcntl
|
||||
import hashlib
|
||||
from html.parser import HTMLParser
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.error import URLError
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener
|
||||
|
||||
REPO = 'Weknora/knowledge-governance'
|
||||
FORGE = 'https://gitea.zheromiku.top'
|
||||
TARGET = 'cloud-test-governance-main'
|
||||
ORG = '169e6f7f-e508-4a1f-9a9b-63d240439a3d'
|
||||
SPACE = '106e05d1-4091-40b9-8c57-f76dc94f7825'
|
||||
READY = '3e15556f-ca19-417c-8bfd-666634ea5d29'
|
||||
PUBLISHED = '16185166-b8e9-4761-9926-845a1f41c96d'
|
||||
RELEASE_OWNER = '39ae59fb-876c-4587-ab5d-a12a841c6c09'
|
||||
LOGIN_URL = 'http://100.85.111.121:8088/'
|
||||
ROLES = ('api', 'web', 'worker')
|
||||
REVISION = 'org.opencontainers.image.revision'
|
||||
DATA = Path('/opt/knowledge-governance/cd')
|
||||
APP = DATA.parent
|
||||
PROJECT = 'knowledge-governance-cloud-test'
|
||||
SHA = re.compile('[0-9a-f]{40}')
|
||||
HASH = re.compile('[0-9a-f]{64}')
|
||||
IMAGE = re.compile('sha256:[0-9a-f]{64}')
|
||||
UUID = re.compile('[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}')
|
||||
GUARD_PREFIX = 'KG_CD_CONFIRM_V1 '
|
||||
|
||||
|
||||
class CDError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def require(ok, message):
|
||||
if not ok:
|
||||
raise CDError(message)
|
||||
|
||||
|
||||
def stamp():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def read_json(path):
|
||||
return json.loads(path.read_bytes())
|
||||
|
||||
|
||||
def sync_dir(directory):
|
||||
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def atomic_write(path, data, mode=0o600):
|
||||
fd, temp = tempfile.mkstemp(dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as out:
|
||||
os.fchmod(out.fileno(), mode)
|
||||
out.write(data)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
os.replace(temp, path)
|
||||
sync_dir(path.parent)
|
||||
finally:
|
||||
Path(temp).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def record(path, value):
|
||||
atomic_write(path, (json.dumps(value, ensure_ascii=False, sort_keys=True) + '\n').encode())
|
||||
|
||||
|
||||
@contextmanager
|
||||
def deploy_lock(path):
|
||||
fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'r+') as handle:
|
||||
try:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError as exc:
|
||||
raise CDError('deployment lock busy') from exc
|
||||
yield
|
||||
|
||||
|
||||
def matches(pattern, text):
|
||||
return isinstance(text, str) and pattern.fullmatch(text) is not None
|
||||
|
||||
|
||||
def validate_request(request):
|
||||
actions = {'deploy': 'deploy-production', 'writeback': 'retry-writeback'}
|
||||
action = request.get('action')
|
||||
require(action in actions and request.get('confirm') == actions[action], 'explicit confirmation required')
|
||||
require(matches(SHA, request.get('sha')) and matches(UUID, request.get('task'))
|
||||
and matches(HASH, request.get('bundle')), 'require full SHA, bundle SHA256 and task UUID')
|
||||
require(matches(re.compile('[1-9][0-9]{0,14}'), request.get('run_id')), 'invalid Gitea run ID')
|
||||
event, digest = request.get('approval_event', ''), request.get('acceptance_digest', '')
|
||||
require((event == '' and digest == '') or
|
||||
(action == 'deploy' and matches(UUID, event) and matches(HASH, digest)),
|
||||
'invalid HiFox approval binding')
|
||||
|
||||
|
||||
def guard_proof(request, control_sha):
|
||||
require(matches(SHA, control_sha), 'invalid workflow source SHA')
|
||||
binding = {key: request[key] for key in ('run_id', 'action', 'confirm', 'sha', 'bundle', 'task')}
|
||||
if request.get('approval_event'):
|
||||
binding.update(approval_event=request['approval_event'], acceptance_digest=request['acceptance_digest'])
|
||||
binding.update(repository=REPO, target=TARGET, workflow_sha=control_sha)
|
||||
serialized = json.dumps(binding, sort_keys=True, separators=(',', ':')).encode()
|
||||
return GUARD_PREFIX + hashlib.sha256(serialized).hexdigest()
|
||||
|
||||
|
||||
def verify_guard_log(log, request, control_sha):
|
||||
expected = guard_proof(request, control_sha)
|
||||
pattern = re.compile(r'\d{4}-\d{2}-\d{2}T[0-9:.]+Z (' + GUARD_PREFIX + r'[0-9a-f]{64})')
|
||||
proofs = [match.group(1) for line in log.decode().splitlines() if (match := pattern.fullmatch(line))]
|
||||
require(proofs == [expected], 'Gitea guard dispatch proof missing or different')
|
||||
|
||||
|
||||
def hash_file(path):
|
||||
with path.open('rb') as src:
|
||||
return hashlib.file_digest(src, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def immutable_file(path):
|
||||
info = path.lstat()
|
||||
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.geteuid() and not info.st_mode & 0o022,
|
||||
'bundle requires regular files owned by the deployment account')
|
||||
return path
|
||||
|
||||
|
||||
def verify_bundle(directory, request, archives=True):
|
||||
raw = immutable_file(directory / 'release.json').read_bytes()
|
||||
require(hashlib.sha256(raw).hexdigest() == request['bundle'], 'release manifest digest mismatch')
|
||||
manifest = json.loads(raw)
|
||||
require(manifest.get('schema') == 1 and manifest.get('target') == TARGET
|
||||
and manifest.get('sha') == request['sha'] and manifest.get('task') == request['task'],
|
||||
'bundle commit, task or target mismatch')
|
||||
require(set(manifest.get('images', {})) == set(ROLES), 'bundle must include API, web and worker')
|
||||
for role, image in manifest['images'].items():
|
||||
require(matches(IMAGE, image.get('id')) and matches(HASH, image.get('sha256')), 'invalid image record')
|
||||
if archives:
|
||||
archive = immutable_file(directory / (role + '.tar'))
|
||||
require(hash_file(archive) == image['sha256'], f'{role} archive checksum mismatch')
|
||||
versions = manifest.get('migrations')
|
||||
require(isinstance(versions, list) and versions and all(type(n) is int and n > 0 for n in versions)
|
||||
and versions == sorted(set(versions)), 'invalid migration ledger in manifest')
|
||||
return manifest
|
||||
|
||||
|
||||
def verify_contexts(result, contexts):
|
||||
latest = {}
|
||||
for item in result.get('statuses') or []:
|
||||
latest.setdefault(item.get('context'), item.get('status'))
|
||||
require(bool(contexts) and all(latest.get(context) == 'success' for context in contexts),
|
||||
'required CI status is missing or unsuccessful')
|
||||
|
||||
|
||||
def metadata(task, key):
|
||||
value = (task.get('metadata') or {}).get(key)
|
||||
return json.loads(value) if isinstance(value, str) else None
|
||||
|
||||
|
||||
def check_task(task, request, receipt=None):
|
||||
require(task.get('id') == request['task'] and task.get('spaceId') == SPACE, 'HiFox task or space mismatch')
|
||||
status = (task.get('status') or {}).get('id')
|
||||
same_publication = receipt and metadata(task, 'cd_release') == receipt.get('hifox')
|
||||
require(status == READY or (status == PUBLISHED and same_publication), 'HiFox task is not ready for release')
|
||||
evidence = metadata(task, 'cd_acceptance') or {}
|
||||
url = urlsplit(evidence.get('evidence', ''))
|
||||
require(evidence.get('verdict') == 'passed' and evidence.get('sha') == request['sha']
|
||||
and evidence.get('bundle') == request['bundle'] and url.scheme == 'https' and url.hostname
|
||||
and not (url.username or url.password or url.query)
|
||||
and (not url.fragment or (url.netloc == 'app.hifox.com' and url.fragment.startswith('comment-')
|
||||
and matches(UUID, url.fragment.removeprefix('comment-')))),
|
||||
'missing or changed business acceptance for this commit and bundle')
|
||||
return evidence
|
||||
|
||||
|
||||
def acceptance_digest(acceptance):
|
||||
return hashlib.sha256(json.dumps(acceptance, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
|
||||
|
||||
def release_approval(task, timeline, request):
|
||||
evidence = check_task(task, request)
|
||||
changes = [row for row in timeline if row.get('event') == 'status_changed']
|
||||
require(bool(changes), 'missing HiFox status history')
|
||||
approval = changes[-1]
|
||||
approver = approval.get('actor') or {}
|
||||
event_at = approval.get('createdAt') or ''
|
||||
status_at = task.get('statusChangedAt') or ''
|
||||
try:
|
||||
difference = abs((datetime.fromisoformat(event_at.replace('Z', '+00:00'))
|
||||
- datetime.fromisoformat(status_at.replace('Z', '+00:00'))).total_seconds())
|
||||
except (ValueError, TypeError):
|
||||
difference = float('inf')
|
||||
# HiFox logs the status change after saving the task, sometimes across a second boundary.
|
||||
require((approval.get('metadata') or {}).get('to') == '待发布'
|
||||
and difference <= 2
|
||||
and approver.get('id') == RELEASE_OWNER and approver.get('type') == 'human'
|
||||
and matches(UUID, approval.get('id')), 'the latest transition must be an approval by the release owner')
|
||||
task_url = task.get('url', '')
|
||||
prefix = task_url + '#comment-'
|
||||
require(task_url.startswith('https://app.hifox.com/') and evidence['evidence'].startswith(prefix),
|
||||
'automated release requires the same-task acceptance report')
|
||||
comment_id = evidence['evidence'].removeprefix(prefix)
|
||||
require(matches(UUID, comment_id), 'invalid acceptance report ID')
|
||||
reports = [row for row in timeline if row.get('event') == 'commented' and row.get('id') == comment_id]
|
||||
require(len(reports) == 1, 'acceptance report missing from task history')
|
||||
report = reports[0]
|
||||
body = report.get('content') or ''
|
||||
require(report.get('createdAt') and (report.get('updatedAt') or report['createdAt']) < min(event_at, status_at)
|
||||
and request['sha'] in body and request['bundle'] in body,
|
||||
'the unchanged report must identify the candidate and predate approval')
|
||||
binding = {'approval_event': approval['id'], 'acceptance_digest': acceptance_digest(evidence)}
|
||||
require(all(request.get(key, value) == value for key, value in binding.items()),
|
||||
'HiFox approval or acceptance changed after dispatch')
|
||||
return binding, min(event_at, status_at)
|
||||
|
||||
|
||||
def accepted_task(host, request):
|
||||
task = host.task(request['task'])
|
||||
if request.get('approval_event'):
|
||||
release_approval(task, host.timeline(request['task']), request)
|
||||
return check_task(task, request)
|
||||
|
||||
|
||||
def release(host, request):
|
||||
validate_request(request)
|
||||
path = host.receipt_path
|
||||
existing = read_json(path) if path.exists() else None
|
||||
if request['action'] == 'writeback':
|
||||
require(existing and existing['state'] in ('deployed_hifox_pending', 'published'),
|
||||
'writeback requires a verified deployment receipt')
|
||||
require(all(existing[k] == request[k] for k in ('sha', 'task', 'bundle')), 'receipt binding mismatch')
|
||||
manifest = verify_bundle(host.bundle_path(request), request, archives=False)
|
||||
host.approve(request)
|
||||
host.verify(manifest)
|
||||
return writeback(host, request, existing)
|
||||
|
||||
require(existing is None, 'existing release receipt: use writeback or inspect interrupted/failed deployment')
|
||||
host.approve(request)
|
||||
manifest = verify_bundle(host.bundle_path(request), request)
|
||||
host.check_ci(request)
|
||||
accepted = accepted_task(host, request)
|
||||
before = host.baseline()
|
||||
host.pre_switch(before, manifest)
|
||||
receipt = {k: request[k] for k in ('sha', 'task', 'bundle', 'run_id')}
|
||||
receipt.update(state='preparing', target=TARGET, started_at=stamp(), previous=before)
|
||||
record(path, receipt)
|
||||
try:
|
||||
host.load(host.bundle_path(request), manifest)
|
||||
host.pre_switch(before, manifest)
|
||||
host.approve(request)
|
||||
require(accepted_task(host, request) == accepted, 'business acceptance changed before switch')
|
||||
except (CDError, OSError, ValueError, KeyError) as exc:
|
||||
receipt.update(state='failed_before_cutover')
|
||||
record(path, receipt)
|
||||
raise CDError(f'failed_before_cutover: {exc}' if isinstance(exc, CDError) else 'failed_before_cutover') from exc
|
||||
|
||||
receipt.update(state='cutover_started')
|
||||
record(path, receipt)
|
||||
try:
|
||||
host.switch(before, manifest)
|
||||
evidence = host.verify(manifest)
|
||||
except (CDError, OSError, ValueError, KeyError) as exc:
|
||||
status = 'rollback_failed'
|
||||
try:
|
||||
host.rollback(before)
|
||||
status = 'rolled_back'
|
||||
except (CDError, OSError, ValueError, KeyError):
|
||||
pass
|
||||
receipt.update(state=status, finished_at=stamp(), failure=str(exc) if isinstance(exc, CDError) else 'operation failed')
|
||||
record(path, receipt)
|
||||
raise CDError(f'{status}: deployment verification failed') from exc
|
||||
|
||||
receipt.update(state='deployed_hifox_pending', deployed_at=stamp(), evidence=evidence)
|
||||
receipt['hifox'] = {**evidence, 'target': TARGET, 'bundle': request['bundle'], 'deployed_at': receipt['deployed_at'],
|
||||
'login_url': LOGIN_URL,
|
||||
'run_url': f'{FORGE}/{REPO}/actions/runs/{request["run_id"]}'}
|
||||
record(path, receipt)
|
||||
return writeback(host, request, receipt)
|
||||
|
||||
|
||||
def writeback(host, request, receipt):
|
||||
try:
|
||||
task = host.task(request['task'])
|
||||
check_task(task, request, receipt)
|
||||
host.callback(request['task'], task, receipt.get('hifox'))
|
||||
receipt.update(state='published')
|
||||
record(host.receipt_path, receipt)
|
||||
except (CDError, OSError, ValueError, KeyError) as exc:
|
||||
raise CDError('DEPLOYED_HIFOX_PENDING: retry writeback for this receipt') from exc
|
||||
return receipt
|
||||
|
||||
|
||||
def with_images(config, images):
|
||||
result = copy.deepcopy(config)
|
||||
require(set(result['services']) == set(ROLES), 'unexpected Compose service set')
|
||||
for role in ROLES:
|
||||
result['services'][role]['image'] = images[role]
|
||||
return result
|
||||
|
||||
|
||||
def run(argv, purpose, *, cwd=None, input_data=None, timeout=30, allowed=(0,), env=None):
|
||||
try:
|
||||
result = subprocess.run(argv, cwd=cwd, input=input_data, capture_output=True, timeout=timeout, env=env)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise CDError(f'{purpose} unavailable or timed out') from exc
|
||||
require(result.returncode in allowed, f'{purpose} failed (exit {result.returncode})')
|
||||
return result.stdout
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, *_args, **_kwargs):
|
||||
raise CDError('unexpected HTTP redirect')
|
||||
|
||||
|
||||
def http(url, *, direct=False, limit=2**20):
|
||||
handlers = [NoRedirect()]
|
||||
if direct:
|
||||
handlers.append(ProxyHandler({}))
|
||||
try:
|
||||
with build_opener(*handlers).open(url, timeout=10) as response:
|
||||
data = response.read(limit + 1)
|
||||
require(len(data) <= limit, 'HTTP response exceeds limit')
|
||||
return data
|
||||
except (URLError, TimeoutError) as exc:
|
||||
raise CDError('HTTP read failed') from exc
|
||||
|
||||
|
||||
class Assets(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.paths = []
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
attrs = dict(attrs)
|
||||
path = attrs.get('src' if tag == 'script' else 'href', '')
|
||||
if path and re.fullmatch(r'/assets/[A-Za-z0-9_.-]+\.(?:js|css)', path):
|
||||
self.paths.append(path)
|
||||
|
||||
|
||||
def disk_assets(html):
|
||||
parser = Assets()
|
||||
parser.feed(html.decode())
|
||||
require(any(p.endswith('.js') for p in parser.paths), 'web index has no compiled entry point')
|
||||
return sorted(set(parser.paths))
|
||||
|
||||
|
||||
def image_inspect(image):
|
||||
return json.loads(run(['docker', 'image', 'inspect', image], 'read image identity'))[0]
|
||||
|
||||
|
||||
def inspect(name):
|
||||
obj = json.loads(run(['docker', 'container', 'inspect', name], 'read running container'))[0]
|
||||
require(obj['State']['Status'] == 'running' and matches(IMAGE, obj.get('Image')), 'expected container is not running')
|
||||
return obj
|
||||
|
||||
|
||||
def image_label(image):
|
||||
return image_inspect(image)['Config']['Labels'].get(REVISION, '')
|
||||
|
||||
|
||||
def api_identity(container):
|
||||
raw = run(['docker', 'exec', container, '/app/api', '--version-record-status'], 'read API build identity', allowed=(0, 1))
|
||||
obj = json.loads(raw)
|
||||
require(matches(SHA, obj.get('commit_sha')), 'API binary has no full build identity')
|
||||
return obj['commit_sha']
|
||||
|
||||
|
||||
def migration_files(git, sha):
|
||||
paths = git('ls-tree', '-r', '--name-only', sha, 'internal/platform/postgres/migrations').decode().splitlines()
|
||||
return sorted(int(Path(line).name.split('_', 1)[0]) for line in paths if line.endswith('.up.sql'))
|
||||
|
||||
|
||||
def ledger(container):
|
||||
probe = Path(__file__).with_name('cd_migration_probe.py').read_text()
|
||||
data = run(['docker', 'exec', container, 'python3', '-c', probe], 'read migration ledger')
|
||||
result = json.loads(data)
|
||||
require(isinstance(result, list) and result, 'unexpected migration ledger result')
|
||||
return result
|
||||
|
||||
|
||||
def verify_archive(archive, expected):
|
||||
# docker save by ID omits mutable RepoTags. Refuse archives that could retag another app.
|
||||
with tarfile.open(archive, 'r:') as t:
|
||||
entry = t.getmember('manifest.json')
|
||||
require(entry.isfile() and entry.size < 65536, 'unexpected Docker archive manifest')
|
||||
containers = json.load(t.extractfile(entry))
|
||||
require(len(containers) == 1 and not containers[0].get('RepoTags'), 'archive must contain one untagged image')
|
||||
config = t.getmember(containers[0]['Config'])
|
||||
require(config.isfile() and config.size < 2**20, 'unexpected Docker image config')
|
||||
require('sha256:' + hashlib.sha256(t.extractfile(config).read()).hexdigest() == expected,
|
||||
'archive config does not match approved image ID')
|
||||
for member in t:
|
||||
require((member.isdir() or member.isfile()) and not member.name.startswith('/')
|
||||
and '..' not in Path(member.name).parts, 'unexpected Docker archive path')
|
||||
if 'index.json' in t.getnames():
|
||||
index = t.getmember('index.json')
|
||||
require(index.isfile() and index.size < 65536, 'unexpected OCI archive index')
|
||||
oci = json.load(t.extractfile(index))
|
||||
require(len(oci.get('manifests', [])) == 1 and all(
|
||||
key not in descriptor.get('annotations', {}) for descriptor in oci['manifests']
|
||||
for key in ('org.opencontainers.image.ref.name', 'io.containerd.image.name')),
|
||||
'archive OCI index contains a mutable name')
|
||||
|
||||
|
||||
class LiveHost:
|
||||
def __init__(self, request):
|
||||
self.receipt_path = DATA / 'receipts' / (request['bundle'] + '.json')
|
||||
self.compose = APP / 'compose.json'
|
||||
self.git_path = DATA / 'source.git'
|
||||
self.containers = {role: 'kg-cloud-' + role for role in ROLES}
|
||||
self.health_url = 'http://127.0.0.1:8088'
|
||||
self.request = request
|
||||
|
||||
def bundle_path(self, request):
|
||||
return DATA / 'bundles' / request['bundle']
|
||||
|
||||
def git(self, *args):
|
||||
return run(['git', '-C', str(self.git_path), *args], 'release source check', timeout=90)
|
||||
|
||||
def approve(self, request):
|
||||
repo_url = f'{FORGE}/{REPO}'
|
||||
run_id = request['run_id']
|
||||
run_api = f'{FORGE}/api/v1/repos/{REPO}/actions/runs/{run_id}'
|
||||
dispatch = json.loads(http(run_api))
|
||||
control_sha = dispatch.get('head_sha')
|
||||
trigger_actor = dispatch.get('trigger_actor') or dispatch.get('actor') or {}
|
||||
require(str(dispatch.get('id')) == run_id and dispatch.get('event') == 'workflow_dispatch'
|
||||
and dispatch.get('path') == 'deploy-production.yml@refs/heads/main'
|
||||
and dispatch.get('head_branch') == 'main' and dispatch.get('status') in ('in_progress', 'running')
|
||||
and (dispatch.get('actor') or {}).get('id') == 1 and trigger_actor.get('id') == 1
|
||||
and matches(SHA, control_sha), 'Gitea run is not an active deployment dispatched by the release owner')
|
||||
# Repo secrets can be read by other workflows. Only a completed guard from
|
||||
# the installed workflow and controller may authorize the exact inputs.
|
||||
try:
|
||||
self.git('merge-base', '--is-ancestor', control_sha, 'refs/remotes/origin/main')
|
||||
except CDError:
|
||||
self.fetch_source()
|
||||
self.git('merge-base', '--is-ancestor', control_sha, 'refs/remotes/origin/main')
|
||||
trusted = {'scripts/production_cd.py': Path(__file__).resolve(),
|
||||
'.gitea/workflows/deploy-production.yml': DATA / 'deploy-production.yml'}
|
||||
for name, local in trusted.items():
|
||||
require(self.git('show', f'{control_sha}:{name}') == immutable_file(local).read_bytes(),
|
||||
'Gitea approval workflow differs from installed control files')
|
||||
jobs = json.loads(http(run_api + '/jobs')).get('jobs') or []
|
||||
guards = [job for job in jobs if job.get('name') == 'guard' and job.get('conclusion') == 'success'
|
||||
and str(job.get('run_id')) == run_id and job.get('head_sha') == control_sha
|
||||
and matches(re.compile('[1-9][0-9]{0,14}'), str(job.get('id')))]
|
||||
require(len(guards) == 1, 'Gitea approval guard has not succeeded')
|
||||
guard_id = guards[0]['id']
|
||||
verify_guard_log(http(f'{repo_url}/actions/runs/{run_id}/jobs/{guard_id}/logs'), request, control_sha)
|
||||
|
||||
def fetch_source(self):
|
||||
self.git('fetch', '--no-tags', '--prune', f'{FORGE}/{REPO}.git', '+refs/heads/*:refs/remotes/origin/*')
|
||||
|
||||
def check_ci(self, request):
|
||||
self.fetch_source()
|
||||
refs = self.git('for-each-ref', '--format=%(refname)', '--contains', request['sha'], 'refs/remotes/origin/')
|
||||
require(refs.strip(), 'candidate commit is not reachable from a repository branch')
|
||||
contexts = immutable_file(DATA / 'required-contexts.txt').read_text().splitlines()
|
||||
verify_contexts(json.loads(http(f'{FORGE}/api/v1/repos/{REPO}/commits/{request["sha"]}/status')),
|
||||
[line.strip() for line in contexts if line.strip() and not line.lstrip().startswith('#')])
|
||||
|
||||
def hifox(self, *args):
|
||||
cli = DATA / 'bin/hifox'
|
||||
env = {'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': str(DATA / 'hifox-home'), 'CI': '1'}
|
||||
raw = run([str(cli), '--organization-id', ORG, *args, '--output', 'json'], 'HiFox operation', env=env)
|
||||
result = json.JSONDecoder().raw_decode(raw.decode().strip())[0]
|
||||
require(isinstance(result, (dict, list)) and (not isinstance(result, dict)
|
||||
or (result.get('success') is not False and not result.get('error'))),
|
||||
'HiFox did not return a successful result')
|
||||
return result
|
||||
|
||||
def task(self, task):
|
||||
return self.hifox('task', 'view', task)
|
||||
|
||||
def timeline(self, task):
|
||||
return self.hifox('api', 'get', f'/rest/v1/tasks/{task}/timeline')
|
||||
|
||||
def comment_once(self, task, key, text):
|
||||
marker = f'KG-CD {key}'
|
||||
body = f'{text}\n\n`{marker}`'
|
||||
|
||||
def present():
|
||||
return any(row.get('event') == 'commented' and row.get('content') == body
|
||||
and (row.get('actor') or {}).get('id') == RELEASE_OWNER for row in self.timeline(task))
|
||||
|
||||
if not present():
|
||||
self.hifox('task', 'comment', task, '--body', body)
|
||||
require(present(), 'HiFox release comment readback mismatch')
|
||||
|
||||
def report_failure(self, request):
|
||||
if not self.receipt_path.exists():
|
||||
return
|
||||
receipt = read_json(self.receipt_path)
|
||||
if any(receipt.get(key) != request[key] for key in ('task', 'sha', 'bundle', 'run_id')):
|
||||
return
|
||||
messages = {
|
||||
'failed_before_cutover': '发布检查失败,未切换主站。',
|
||||
'rolled_back': '发布核验失败,已恢复原版本并复验。',
|
||||
'rollback_failed': '发布核验失败,回滚未通过复验,请检查主站。',
|
||||
'deployed_hifox_pending': '主站已部署并核验,HiFox 回写待完成。请重试回写。',
|
||||
}
|
||||
state = receipt['state']
|
||||
if state in messages:
|
||||
run_url = f'{FORGE}/{REPO}/actions/runs/{request["run_id"]}'
|
||||
self.comment_once(request['task'], f'{state} #{request["run_id"]}',
|
||||
f'{messages[state]}\n\n候选 `{request["sha"]}`\n\n[发布运行]({run_url})')
|
||||
|
||||
def callback(self, task_id, task, expected):
|
||||
if metadata(task, 'cd_release') != expected:
|
||||
self.hifox('task', 'metadata', 'set', task_id, 'cd_release', json.dumps(json.dumps(expected)))
|
||||
fresh = self.task(task_id)
|
||||
check_task(fresh, self.request, {'hifox': expected})
|
||||
require(metadata(fresh, 'cd_release') == expected, 'HiFox release receipt readback mismatch')
|
||||
images = '\n'.join(f'- {role} `{expected["images"][role]}`' for role in ROLES)
|
||||
self.comment_once(task_id, f'published {expected["bundle"]}',
|
||||
f'云治理主站发布完成,健康检查通过。\n\n'
|
||||
f'运行版本 `{expected.get("version") or expected["sha"]}`\n\n'
|
||||
f'提交 `{expected["sha"]}`\n\n{images}\n\n'
|
||||
f'[登录主站]({LOGIN_URL}) · [发布运行]({expected["run_url"]})')
|
||||
fresh = self.task(task_id)
|
||||
check_task(fresh, self.request, {'hifox': expected})
|
||||
require(metadata(fresh, 'cd_release') == expected, 'HiFox release changed during comment writeback')
|
||||
if fresh['status']['id'] != PUBLISHED:
|
||||
self.hifox('task', 'edit', task_id, '--status', PUBLISHED)
|
||||
final = self.task(task_id)
|
||||
final_status = (final.get('status') or {}).get('id')
|
||||
require(final_status == PUBLISHED and metadata(final, 'cd_release') == expected, 'HiFox published readback mismatch')
|
||||
|
||||
def compose_cmd(self, *args):
|
||||
return ['docker', 'compose', '-p', PROJECT, '-f', str(self.compose), *args]
|
||||
|
||||
def rendered_config(self):
|
||||
raw = run(self.compose_cmd('config', '--format', 'json'), 'render Compose configuration', cwd=APP)
|
||||
return json.loads(raw)['services']
|
||||
|
||||
def runtime(self):
|
||||
rendered = self.rendered_config()
|
||||
require(set(rendered) == set(ROLES), 'unexpected Compose service set')
|
||||
result = {}
|
||||
for role, name in self.containers.items():
|
||||
c = inspect(name)
|
||||
labels = c['Config']['Labels']
|
||||
require(labels.get('com.docker.compose.project') == PROJECT
|
||||
and labels.get('com.docker.compose.service') == role
|
||||
and labels.get('com.docker.compose.project.working_dir') == str(APP)
|
||||
and labels.get('com.docker.compose.project.config_files') == str(self.compose),
|
||||
f'{role} does not belong to the approved Compose chain')
|
||||
config = rendered[role]
|
||||
image = image_inspect(c['Image'])
|
||||
require(image_inspect(config['image'])['Id'] == c['Image'], f'{role} Compose image has drifted')
|
||||
env = lambda entries: dict(item.split('=', 1) for item in entries or [])
|
||||
expected_env = env(image['Config'].get('Env'))
|
||||
expected_env.update({key: str(value) for key, value in (config.get('environment') or {}).items()
|
||||
if value is not None})
|
||||
require(env(c['Config'].get('Env')) == expected_env, f'{role} running environment has drifted')
|
||||
expected_mounts = config.get('volumes') or []
|
||||
require(all(mount['type'] == 'bind' for mount in expected_mounts), 'unexpected non-bind Compose volume')
|
||||
mounts = {(v['Source'], v['Destination'], not v['RW']) for v in c.get('Mounts', []) if v['Type'] == 'bind'}
|
||||
require(mounts == {(v['source'], v['target'], v.get('read_only', False)) for v in expected_mounts}
|
||||
and len(mounts) == len(c.get('Mounts', [])), f'{role} running mounts have drifted')
|
||||
require(not config.get('network_mode') or config['network_mode'] == c['HostConfig']['NetworkMode'],
|
||||
f'{role} running network has drifted')
|
||||
result[role] = c['Image']
|
||||
return result
|
||||
|
||||
def baseline(self):
|
||||
images = self.runtime()
|
||||
self.probe_web()
|
||||
return {'compose_sha256': hash_file(self.compose), 'images': images,
|
||||
'revisions': {role: image_label(image) for role, image in images.items()}}
|
||||
|
||||
def pre_switch(self, previous, manifest):
|
||||
require(hash_file(self.compose) == previous['compose_sha256'] and self.runtime() == previous['images'],
|
||||
'target baseline changed during deployment')
|
||||
for revision in set(previous['revisions'].values()):
|
||||
require(matches(SHA, revision), 'running image has no source revision')
|
||||
self.git('merge-base', '--is-ancestor', revision, manifest['sha'])
|
||||
require(migration_files(self.git, manifest['sha']) == manifest['migrations'], 'source migration set differs from bundle')
|
||||
for role in ('api', 'worker'):
|
||||
require(ledger(self.containers[role]) == manifest['migrations'],
|
||||
f'{role} migration ledger mismatch; verify schema changes outside CD')
|
||||
|
||||
def load(self, directory, manifest):
|
||||
archives = {role: directory / (role + '.tar') for role in ROLES}
|
||||
for role, archive in archives.items():
|
||||
verify_archive(archive, manifest['images'][role]['id'])
|
||||
for role, archive in archives.items():
|
||||
image = manifest['images'][role]['id']
|
||||
run(['docker', 'image', 'load', '-i', str(archive)], f'load {role} image', timeout=600)
|
||||
require(image_inspect(image)['Id'] == image and image_label(image) == manifest['sha'],
|
||||
f'{role} loaded image differs from approved build')
|
||||
|
||||
@property
|
||||
def backup(self):
|
||||
return self.receipt_path.with_suffix('.compose.backup')
|
||||
|
||||
def switch(self, previous, manifest):
|
||||
current = self.compose.read_bytes()
|
||||
require(hashlib.sha256(current).hexdigest() == previous['compose_sha256'], 'Compose changed before switch')
|
||||
images = {role: manifest['images'][role]['id'] for role in ROLES}
|
||||
changed = with_images(json.loads(current), images)
|
||||
for role, image in previous['images'].items():
|
||||
run(['docker', 'image', 'tag', image, f'knowledge-governance-cd-rollback:{self.request["bundle"]}-{role}'],
|
||||
'retain rollback image')
|
||||
atomic_write(self.backup, current)
|
||||
atomic_write(self.compose, (json.dumps(changed, indent=2) + '\n').encode(), self.compose.stat().st_mode & 0o777)
|
||||
self.recreate()
|
||||
|
||||
def recreate(self):
|
||||
script = Path(__file__).with_name('deploy-api-web.sh')
|
||||
run(['bash', str(script), '--verified-compose', str(APP), PROJECT, str(self.compose), 'api', 'web', 'worker'],
|
||||
'switch governance Compose services', timeout=120)
|
||||
|
||||
def probe_web(self):
|
||||
origin = self.health_url
|
||||
require(json.loads(http(origin + '/health', direct=True)).get('status') == 'ok', 'web proxy health probe failed')
|
||||
require(json.loads(http('http://127.0.0.1:18098/readyz', direct=True)).get('status') in ('ok', 'ready'),
|
||||
'API readiness probe failed')
|
||||
index = http(origin + '/', direct=True)
|
||||
return index, {path: hashlib.sha256(http(origin + path, direct=True, limit=32 * 2**20)).hexdigest()
|
||||
for path in disk_assets(index)}
|
||||
|
||||
def verify_web_image(self):
|
||||
origin_index, assets = self.probe_web()
|
||||
name = self.containers['web']
|
||||
def read_asset(path):
|
||||
return run(['docker', 'exec', name, 'cat', '/usr/share/nginx/html' + path], 'read running web asset')
|
||||
|
||||
require(origin_index == read_asset('/index.html'), 'served index differs from running web image')
|
||||
for path, served_digest in assets.items():
|
||||
require(hashlib.sha256(read_asset(path)).hexdigest() == served_digest, 'served asset differs from running web image')
|
||||
return assets
|
||||
|
||||
def verify(self, manifest):
|
||||
images = {role: manifest['images'][role]['id'] for role in ROLES}
|
||||
def check():
|
||||
require(self.runtime() == images, 'running image IDs differ from approved bundle')
|
||||
require(api_identity(self.containers['api']) == manifest['sha'], 'running API SHA mismatches approval')
|
||||
assets = self.verify_web_image()
|
||||
version = image_inspect(images['api'])['Config']['Labels'].get('org.opencontainers.image.version')
|
||||
if not isinstance(version, str) or not re.fullmatch(r'[0-9A-Za-z.+_-]{1,128}', version):
|
||||
version = manifest['sha']
|
||||
return {'sha': manifest['sha'], 'version': version, 'images': images, 'health': 'ok', 'asset_sha256': assets}
|
||||
|
||||
return wait_ready(check)
|
||||
|
||||
def rollback(self, previous):
|
||||
if not self.backup.exists():
|
||||
require(hash_file(self.compose) == previous['compose_sha256'] and self.runtime() == previous['images'],
|
||||
'rollback baseline cannot be established')
|
||||
self.verify_web_image()
|
||||
return
|
||||
original = self.backup.read_bytes()
|
||||
require(hashlib.sha256(original).hexdigest() == previous['compose_sha256'], 'rollback backup checksum mismatch')
|
||||
source = json.loads(original)
|
||||
for role, image in previous['images'].items():
|
||||
reference = source['services'][role]['image']
|
||||
require(image_inspect(reference)['Id'] == image, 'rollback source tag has drifted')
|
||||
atomic_write(self.compose, original, self.compose.stat().st_mode & 0o777)
|
||||
self.recreate()
|
||||
|
||||
def check():
|
||||
require(self.runtime() == previous['images'], 'rollback running images mismatch')
|
||||
require(api_identity(self.containers['api']) == previous['revisions']['api'], 'rollback API SHA mismatch')
|
||||
self.verify_web_image()
|
||||
|
||||
wait_ready(check)
|
||||
|
||||
|
||||
def wait_ready(check, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
return check()
|
||||
except (CDError, OSError, KeyError, ValueError):
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def event_request(event, env):
|
||||
require(env.get('GITHUB_EVENT_NAME') == 'workflow_dispatch' and env.get('GITHUB_REF') == 'refs/heads/main'
|
||||
and env.get('GITHUB_REPOSITORY') == REPO, 'manual dispatch from main required')
|
||||
inputs = event.get('inputs') or {}
|
||||
request = {name: inputs.get(name) or '' for name in
|
||||
('action', 'sha', 'task', 'bundle', 'confirm', 'approval_event', 'acceptance_digest')}
|
||||
request['run_id'] = env.get('GITHUB_RUN_ID', '')
|
||||
validate_request(request)
|
||||
return request
|
||||
|
||||
|
||||
def pack(args):
|
||||
require(matches(SHA, args.sha) and matches(UUID, args.task), 'require full SHA and task UUID')
|
||||
require(not args.output.exists(), 'bundle output already exists')
|
||||
source = lambda *argv: run(['git', *argv], 'read candidate source')
|
||||
require(source('rev-parse', args.sha + '^{commit}').decode().strip() == args.sha, 'source commit not found')
|
||||
images = {}
|
||||
versions = migration_files(source, args.sha)
|
||||
manifest = dict(schema=1, target=TARGET, sha=args.sha, task=args.task, images=images, migrations=versions)
|
||||
with tempfile.TemporaryDirectory(dir=args.output.parent) as directory:
|
||||
build = Path(directory) / "sealed"
|
||||
build.mkdir(mode=0o700)
|
||||
for role in ROLES:
|
||||
image = image_inspect(getattr(args, role).removeprefix('sha256:'))
|
||||
image_id = image['Id']
|
||||
require(matches(IMAGE, image_id) and image_label(image_id) == args.sha, f'{role} source label mismatch')
|
||||
archive = build / (role + '.tar')
|
||||
run(['docker', 'image', 'save', '-o', str(archive), image_id], f'archive {role} image', timeout=900)
|
||||
verify_archive(archive, image_id)
|
||||
archive.chmod(0o600)
|
||||
images[role] = {'id': image_id, 'sha256': hash_file(archive)}
|
||||
record(build / 'release.json', manifest)
|
||||
for item in build.iterdir():
|
||||
with item.open("rb") as artifact:
|
||||
os.fsync(artifact.fileno())
|
||||
sync_dir(build)
|
||||
build.rename(args.output)
|
||||
sync_dir(args.output.parent)
|
||||
print(hash_file(args.output / 'release.json'))
|
||||
|
||||
|
||||
def attest(args):
|
||||
request = {'sha': args.sha, 'task': args.task, 'bundle': hash_file(args.directory / 'release.json')}
|
||||
require(matches(SHA, args.sha) and matches(UUID, args.task), 'require full SHA and task UUID')
|
||||
manifest = verify_bundle(args.directory, request)
|
||||
before = {role: inspect(getattr(args, role)) for role in ROLES}
|
||||
for role, obj in before.items():
|
||||
require(obj['Image'] == manifest['images'][role]['id'] and obj['Name'] != '/kg-cloud-' + role,
|
||||
'isolated test runtime image differs from bundle')
|
||||
require(api_identity(args.api) == args.sha and ledger(args.api) == manifest['migrations']
|
||||
and ledger(args.worker) == manifest['migrations'], 'test runtime SHA or schema differs')
|
||||
base = urlsplit(args.test_url)
|
||||
require(base.scheme in ('http', 'https') and base.hostname and not (base.username or base.password or base.query or base.fragment)
|
||||
and base.path in ('', '/') and base.port != 8088, 'provide isolated test endpoint')
|
||||
origin = args.test_url.rstrip('/')
|
||||
require(json.loads(http(origin + '/health', direct=True)).get('status') == 'ok', 'isolated test health probe failed')
|
||||
index = http(origin + '/', direct=True)
|
||||
require(index == run(['docker', 'exec', args.web, 'cat', '/usr/share/nginx/html/index.html'], 'read test web index'),
|
||||
'test endpoint is serving another web image')
|
||||
for role, obj in before.items():
|
||||
require(inspect(getattr(args, role))['Id'] == obj['Id'], 'test instance changed during readback')
|
||||
print(json.dumps({'sha': args.sha, 'bundle': request['bundle'], 'test_url': args.test_url,
|
||||
'images': {role: obj['Image'] for role, obj in before.items()}}, sort_keys=True))
|
||||
|
||||
|
||||
def cli():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
for command in ('guard', 'send', 'serve', 'pack', 'attest'):
|
||||
sub = commands.add_parser(command)
|
||||
if command in ('guard', 'send'):
|
||||
sub.add_argument('--event', type=Path, required=True)
|
||||
if command in ('pack', 'attest'):
|
||||
sub.add_argument('--sha', required=True)
|
||||
sub.add_argument('--task', required=True)
|
||||
if command in ('pack', 'attest'):
|
||||
for role in ROLES:
|
||||
sub.add_argument('--' + role, required=True)
|
||||
if command == 'pack':
|
||||
sub.add_argument('--output', type=Path, required=True)
|
||||
if command == 'attest':
|
||||
sub.add_argument('--directory', type=Path, required=True)
|
||||
sub.add_argument('--test-url', required=True)
|
||||
args = parser.parse_args()
|
||||
if args.command in ('guard', 'send'):
|
||||
request = event_request(read_json(args.event), os.environ)
|
||||
if args.command == 'guard':
|
||||
print(guard_proof(request, os.environ.get('GITHUB_SHA')))
|
||||
else:
|
||||
send(request)
|
||||
elif args.command == 'pack':
|
||||
pack(args)
|
||||
elif args.command == 'attest':
|
||||
attest(args)
|
||||
else:
|
||||
raw = sys.stdin.buffer.read(8193)
|
||||
require(len(raw) <= 8192, 'request exceeds size limit')
|
||||
request = json.loads(raw)
|
||||
validate_request(request)
|
||||
with deploy_lock(DATA / 'release.lock'):
|
||||
host = LiveHost(request)
|
||||
for item in (DATA / 'receipts').glob('*.json'):
|
||||
if read_json(item)['state'] in ('cutover_started', 'rollback_failed'):
|
||||
raise CDError('previous deployment outcome requires operator reconciliation')
|
||||
try:
|
||||
result = release(host, request)
|
||||
except (CDError, OSError, ValueError, KeyError):
|
||||
try:
|
||||
host.report_failure(request)
|
||||
except (CDError, OSError, ValueError, KeyError):
|
||||
print('CD: HiFox failure comment pending', file=sys.stderr)
|
||||
raise
|
||||
print(json.dumps({k: result[k] for k in ('state', 'sha', 'task', 'bundle', 'hifox')}, ensure_ascii=False))
|
||||
|
||||
|
||||
def send(request):
|
||||
key = os.environ.get('KG_CD_SSH_KEY', '')
|
||||
known_hosts = os.environ.get('KG_CD_KNOWN_HOSTS', '')
|
||||
host = os.environ.get('KG_CD_SSH_HOST', '')
|
||||
port = os.environ.get('KG_CD_SSH_PORT', '22') or '22'
|
||||
require(key.strip() and known_hosts.strip(), 'missing KG_CD_SSH_KEY or KG_CD_KNOWN_HOSTS')
|
||||
require(host in ('100.85.111.121', '::1') and port.isdecimal() and 1 <= int(port) <= 65535,
|
||||
'configure the direct or approved tunnel address for the target release endpoint')
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
temp = Path(directory)
|
||||
for filename, value in (('key', key), ('known_hosts', known_hosts)):
|
||||
atomic_write(temp / filename, (value.strip() + '\n').encode())
|
||||
argv = ['ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'IdentitiesOnly=yes',
|
||||
'-o', 'ClearAllForwardings=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'HostKeyAlias=kg-governance-cd',
|
||||
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', f'UserKnownHostsFile={temp / "known_hosts"}',
|
||||
'-i', str(temp / 'key'), '-p', port, '-T', 'root@' + host, 'kg-cd-v1']
|
||||
try:
|
||||
result = subprocess.run(argv, input=json.dumps(request).encode(), capture_output=True, timeout=2100)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise CDError('target outcome unknown; inspect durable receipt before retry') from exc
|
||||
if result.returncode:
|
||||
error = result.stderr.decode(errors='replace')
|
||||
for marker in ('DEPLOYED_HIFOX_PENDING', 'rollback_failed:', 'rolled_back:', 'failed_before_cutover:',
|
||||
'target preflight rejected', 'deployment lock busy', 'writeback requires a verified deployment receipt',
|
||||
'Gitea approval guard has not succeeded', 'Gitea guard dispatch proof missing or different'):
|
||||
if marker in error:
|
||||
raise CDError(error.strip().splitlines()[-1])
|
||||
raise CDError('target rejected request or outcome unknown; inspect durable receipt')
|
||||
response = json.loads(result.stdout)
|
||||
require(response.get('state') == 'published' and all(response.get(k) == request[k] for k in ('sha', 'task', 'bundle')),
|
||||
'invalid or unverified deployment receipt')
|
||||
print(json.dumps(response, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
cli()
|
||||
except CDError as error:
|
||||
print(f'CD: {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except (OSError, KeyError, ValueError, TypeError, tarfile.TarError) as error:
|
||||
print(f'CD: operation could not be verified ({type(error).__name__})', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -1,374 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare and exercise an isolated Knowledge Governance QA run."""
|
||||
|
||||
import argparse
|
||||
from contextlib import ExitStack
|
||||
import fcntl
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CONFIG = Path.home() / '.config/knowledge-governance/qa.json'
|
||||
API_PORT = 8088
|
||||
WEB_PORT = 5173
|
||||
RUNTIME_RESPONSE = 'KG_QA_RUNTIME_OK'
|
||||
|
||||
|
||||
class QAError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def report(stage, detail):
|
||||
print(f'[qa:{stage}] {detail}', flush=True)
|
||||
|
||||
|
||||
def capture(argv, stage, timeout=10, env=None):
|
||||
try:
|
||||
return subprocess.run(argv, cwd=ROOT, env=env, text=True, capture_output=True,
|
||||
timeout=timeout, stdin=subprocess.DEVNULL)
|
||||
except FileNotFoundError as exc:
|
||||
raise QAError(f'{stage} 缺少命令 {argv[0]}') from exc
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise QAError(f'{stage} 超过 {timeout} 秒') from exc
|
||||
|
||||
|
||||
def private_file(path):
|
||||
try:
|
||||
info = path.lstat()
|
||||
except FileNotFoundError as exc:
|
||||
raise QAError(f'缺少测试配置文件 {path}') from exc
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o600:
|
||||
raise QAError(f'{path} 必须是当前用户所有的 0600 普通文件')
|
||||
|
||||
|
||||
def database_config(path):
|
||||
private_file(path)
|
||||
try:
|
||||
config = json.loads(path.read_text())
|
||||
except (UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise QAError(f'{path} 不是有效 JSON') from exc
|
||||
if not isinstance(config, dict) or config.keys() != {'host', 'port', 'database', 'user'}:
|
||||
raise QAError('qa.json 只接受 host、port、database、user 四个字段')
|
||||
for field in ('database', 'user'):
|
||||
if not re.fullmatch(r'kg_qa_[a-z0-9_]{1,56}', str(config[field])):
|
||||
raise QAError(f'RDS {field} 必须以 kg_qa_ 开头并使用小写字母、数字或下划线')
|
||||
host = config['host']
|
||||
if not isinstance(host, str) or not re.fullmatch(r'[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+', host):
|
||||
raise QAError('RDS host 必须填写证书对应的 DNS 主机名')
|
||||
if type(config['port']) is not int or not 1 <= config['port'] <= 65535:
|
||||
raise QAError('RDS port 必须是 1–65535 的整数')
|
||||
return config
|
||||
|
||||
|
||||
def tool_env():
|
||||
allowed = ('HOME', 'PATH', 'LANG', 'TMPDIR', 'GOPROXY', 'GOSUMDB', 'GOPRIVATE', 'GONOSUMDB',
|
||||
'GOMODCACHE', 'GOCACHE', 'npm_config_cache', 'npm_config_registry',
|
||||
'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
|
||||
'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy')
|
||||
env = {key: os.environ[key] for key in allowed if key in os.environ}
|
||||
env['GOFLAGS'] = '-mod=readonly'
|
||||
return env
|
||||
|
||||
|
||||
def database_env(config, directory):
|
||||
# Keep inherited PG variables and integration switches out of application children.
|
||||
env = tool_env()
|
||||
env.update(PGHOST=config['host'], PGPORT=str(config['port']), PGDATABASE=config['database'],
|
||||
PGUSER=config['user'], PGSSLMODE='verify-full', PGCONNECT_TIMEOUT='5',
|
||||
PGPASSFILE=str(directory / 'qa.pgpass'), PGSSLROOTCERT=str(directory / 'rds-ca.pem'),
|
||||
PGOPTIONS='-c search_path=public', LC_ALL='C',
|
||||
TEST_WEKNORA_ENABLED='false', PP_SCAN_ENABLED='false',
|
||||
RELEASE_WORKER_ENABLED='false', PRODUCTION_RELEASE_REQUESTS_ENABLED='false',
|
||||
DOBOTAI_OPS_READ_ENABLED='false', DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED='false')
|
||||
env['APP_ADDR'] = f'127.0.0.1:{API_PORT}'
|
||||
env['DATA' + 'BASE_URL'] = (
|
||||
f"postgresql://{config['user']}@{config['host']}:{config['port']}/{config['database']}"
|
||||
'?sslmode=verify-full&connect_timeout=5&search_path=public'
|
||||
)
|
||||
return env
|
||||
|
||||
|
||||
def psql(env, sql):
|
||||
result = capture(['psql', '-XAtw', '-v', 'ON_ERROR_STOP=1', '-c', sql], 'RDS 探针', env=env)
|
||||
if result.returncode == 0:
|
||||
return result.stdout.strip()
|
||||
detail = result.stderr.lower()
|
||||
hints = (
|
||||
('password', '口令认证失败,检查 qa.pgpass 和登录角色'),
|
||||
('certificate', 'TLS 校验失败,检查 RDS 主机名和 CA'),
|
||||
('does not exist', '数据库或角色不存在,联系管理员确认专用 QA 库'),
|
||||
('permission denied', 'RDS 权限不足,检查专用 QA 角色的 CONNECT、schema USAGE/CREATE 权限'),
|
||||
('could not translate host name', 'RDS 主机名无法解析,检查私网 DNS'),
|
||||
('timeout', '连接 RDS 超时,检查 QA 虚拟机到 RDS 的私网和安全组'),
|
||||
('connection refused', 'RDS 拒绝 TCP 连接,检查主机名、端口和私网接入'),
|
||||
)
|
||||
hint = next((message for marker, message in hints if marker in detail), '连接或 SQL 探针失败,检查 RDS 接入和权限')
|
||||
raise QAError(f'RDS {hint}(psql 退出 {result.returncode})')
|
||||
|
||||
|
||||
def database_state(env):
|
||||
identity = psql(env, """
|
||||
SELECT concat_ws('|', current_database(), current_user,
|
||||
COALESCE((SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()), false),
|
||||
(SELECT NOT (rolsuper OR rolcreaterole OR rolcreatedb OR rolreplication OR rolbypassrls)
|
||||
FROM pg_roles WHERE rolname = current_user),
|
||||
(has_schema_privilege(current_user, 'public', 'USAGE') AND
|
||||
has_schema_privilege(current_user, 'public', 'CREATE')),
|
||||
to_regclass('public.schema_migrations') IS NOT NULL,
|
||||
EXISTS (SELECT FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
|
||||
WHERE n.nspname = 'public' AND c.relname <> 'schema_migrations')
|
||||
OR EXISTS (SELECT FROM pg_namespace
|
||||
WHERE nspname NOT IN ('public', 'information_schema') AND nspname !~ '^pg_')
|
||||
OR EXISTS (SELECT FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
|
||||
WHERE n.nspname = 'public'));
|
||||
""")
|
||||
fields = identity.split('|')
|
||||
if len(fields) != 7 or fields[:4] != [env['PGDATABASE'], env['PGUSER'], 't', 't']:
|
||||
raise QAError('RDS 实际库名、角色、TLS 或角色权限与 QA 配置不符')
|
||||
if fields[4] != 't':
|
||||
raise QAError('RDS 角色需要 public schema 的 USAGE 和 CREATE 权限')
|
||||
rows = psql(env, 'SELECT version FROM public.schema_migrations ORDER BY version;') if fields[5] == 't' else ''
|
||||
if any(not re.fullmatch(r'[0-9]+', row) for row in rows.splitlines()):
|
||||
raise QAError('RDS 迁移记录包含无效版本')
|
||||
return [int(row) for row in rows.splitlines()], fields[6] == 't'
|
||||
|
||||
|
||||
def expected_migrations():
|
||||
paths = (ROOT / 'internal/platform/postgres/migrations').glob('*.up.sql')
|
||||
try:
|
||||
versions = sorted(int(path.name.split('_', 1)[0]) for path in paths)
|
||||
except ValueError as exc:
|
||||
raise QAError('仓库存在无效的迁移文件名') from exc
|
||||
if not versions or len(versions) != len(set(versions)):
|
||||
raise QAError('仓库迁移文件缺失或版本重复')
|
||||
return versions
|
||||
|
||||
|
||||
def check_migrations(expected, applied, nonempty, *, complete):
|
||||
if not applied and nonempty:
|
||||
raise QAError('RDS 非空且缺少有效迁移记录,停止初始化')
|
||||
if expected[:len(applied)] != applied:
|
||||
raise QAError('RDS 迁移序列与当前提交不兼容,使用专用空库或匹配的测试库')
|
||||
if complete and applied != expected:
|
||||
raise QAError(f'RDS 迁移未完成,缺少版本 {expected[len(applied)]} 至 {expected[-1]}')
|
||||
|
||||
|
||||
def check_hifox(output):
|
||||
try:
|
||||
state = json.loads(output)
|
||||
online = state['connected'] is True and state['remoteLiveness']['status'] == 'online'
|
||||
except (ValueError, KeyError, TypeError) as exc:
|
||||
raise QAError('HiFox 未返回有效的在线状态,检查本机注册和接收服务') from exc
|
||||
if not online:
|
||||
raise QAError('HiFox 未确认测试机在线,检查本机接收服务和网络')
|
||||
|
||||
|
||||
def check_checkout(expected):
|
||||
if not re.fullmatch(r'[0-9a-f]{40}', expected):
|
||||
raise QAError('设置 KG_QA_SHA 为提测的完整 40 位 Git SHA')
|
||||
actual = capture(['git', 'rev-parse', 'HEAD'], 'Git 检出')
|
||||
if actual.returncode or actual.stdout.strip() != expected:
|
||||
raise QAError('Git 检出与提测提交不一致')
|
||||
state = capture(['git', 'status', '--porcelain'], 'Git 状态')
|
||||
if state.returncode or state.stdout.strip():
|
||||
raise QAError('QA 需要干净的独立检出,请检查 Git 状态')
|
||||
|
||||
|
||||
def preflight(env):
|
||||
for cmd in ('git', 'make', 'go', 'node', 'npm', 'psql', 'hifox', 'omp'):
|
||||
if not shutil.which(cmd, path=env.get('PATH')):
|
||||
raise QAError(f'工具链缺少 {cmd},检查 QA 机器的 PATH')
|
||||
go = capture(['go', 'env', 'GOROOT', 'GOVERSION'], 'Go 工具链', env=env)
|
||||
fields = go.stdout.splitlines()
|
||||
if go.returncode or len(fields) != 2 or not fields[1].startswith('go1.26.'):
|
||||
raise QAError('QA 需要 Go 1.26 工具链')
|
||||
root = Path(fields[0]) / 'bin'
|
||||
if not os.access(root / 'gofmt', os.X_OK):
|
||||
raise QAError('Go 工具链缺少 gofmt,请安装完整的 Go 1.26')
|
||||
env['PATH'] = f"{root}:{env['PATH']}"
|
||||
node = capture(['node', '--version'], 'Node.js 工具链', env=env)
|
||||
if node.returncode or not node.stdout.startswith('v22.'):
|
||||
raise QAError('QA 需要 Node.js 22 工具链')
|
||||
report('toolchain', f'{fields[1]} / Node.js {node.stdout.strip()}')
|
||||
|
||||
hifox = capture(['hifox', 'computer', 'status', '--output', 'json'], 'HiFox 在线检查', timeout=15)
|
||||
if hifox.returncode:
|
||||
raise QAError(f'HiFox 状态命令失败(退出 {hifox.returncode})')
|
||||
check_hifox(hifox.stdout)
|
||||
report('machine', f'{socket.gethostname()} / HiFox online')
|
||||
prompt = f'Reply with exactly {RUNTIME_RESPONSE}. Do not use tools.'
|
||||
omp = capture(['omp', '--no-session', '-p', prompt], 'OMP Runtime 探针', timeout=35)
|
||||
if omp.returncode or RUNTIME_RESPONSE not in {line.strip() for line in omp.stdout.splitlines()}:
|
||||
raise QAError('OMP Runtime 没有返回探针结果,检查 OMP 模型配置和 Magpie 网关')
|
||||
report('runtime', 'OMP 模型请求通过')
|
||||
|
||||
|
||||
def check_ports():
|
||||
for port in (API_PORT, WEB_PORT):
|
||||
with socket.socket() as listener:
|
||||
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
try:
|
||||
listener.bind(('127.0.0.1', port))
|
||||
except OSError as exc:
|
||||
raise QAError(f'QA 端口 {port} 无法绑定,检查已有监听进程') from exc
|
||||
|
||||
|
||||
def run_step(argv, stage, env, timeout):
|
||||
report(stage, ' '.join(argv[:2]))
|
||||
process = subprocess.Popen(argv, cwd=ROOT, env=env, stdin=subprocess.DEVNULL, start_new_session=True)
|
||||
try:
|
||||
code = process.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise QAError(f'{stage} 超过 {timeout} 秒') from exc
|
||||
finally:
|
||||
stop_process(process)
|
||||
if code:
|
||||
raise QAError(f'{stage} 失败(退出 {code}),查看上方命令输出')
|
||||
|
||||
|
||||
def stop_process(process):
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
def start_service(stack, argv, env, log):
|
||||
output = stack.enter_context(log.open('w', encoding='utf-8'))
|
||||
process = subprocess.Popen(argv, cwd=ROOT, env=env, stdin=subprocess.DEVNULL,
|
||||
stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
stack.callback(stop_process, process)
|
||||
return process
|
||||
|
||||
|
||||
def request(port, path):
|
||||
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=2)
|
||||
try:
|
||||
connection.request('GET', path)
|
||||
response = connection.getresponse()
|
||||
return response.status, response.getheader('Content-Type', ''), response.read(32768)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def probe(port, path, expected):
|
||||
try:
|
||||
code, content_type, body = request(port, path)
|
||||
if code != 200:
|
||||
return False
|
||||
if expected == 'html':
|
||||
return 'text/html' in content_type and b'id="root"' in body
|
||||
return 'application/json' in content_type and json.loads(body)['status'] == expected
|
||||
except (OSError, http.client.HTTPException, ValueError, KeyError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def wait_service(process, port, path, expected, log):
|
||||
deadline = time.monotonic() + 45
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise QAError(f'服务端口 {port} 启动进程提前退出(退出 {process.returncode}),日志 {log}')
|
||||
if probe(port, path, expected):
|
||||
return
|
||||
time.sleep(0.25)
|
||||
raise QAError(f'服务探针超时 127.0.0.1:{port}{path},日志 {log}')
|
||||
|
||||
|
||||
def qa_run(commit, env, db_env, versions, state):
|
||||
with tempfile.TemporaryDirectory(prefix='run-', dir=state) as directory, ExitStack() as services:
|
||||
binary = Path(directory) / 'api'
|
||||
run_step(['make', 'deps-install'], 'deps', env, 300)
|
||||
ldflags = f'-X knowledge-governance/internal/version.CommitSHA={commit}'
|
||||
run_step(['go', 'build', '-ldflags', ldflags, '-o', str(binary), './cmd/api'], 'build-api', env, 300)
|
||||
check_ports()
|
||||
log_dir = Path(tempfile.mkdtemp(prefix=f'{commit[:12]}-', dir=state))
|
||||
report('logs', str(log_dir))
|
||||
app_env = db_env | {'PATH': env['PATH'], 'GOVERNANCE_SPOOL_ROOT': str(Path(directory) / 'spool')}
|
||||
api_log = log_dir / 'api.log'
|
||||
api = start_service(services, [str(binary)], app_env, api_log)
|
||||
wait_service(api, API_PORT, '/readyz', 'ready', api_log)
|
||||
check_migrations(versions, *database_state(db_env), complete=True)
|
||||
report('migration', f'已核对全部 {len(versions)} 条迁移,最新版本 {versions[-1]}')
|
||||
|
||||
web_log = log_dir / 'web.log'
|
||||
web = start_service(services, ['npm', '--prefix', 'web', 'run', 'dev', '--', '--host', '127.0.0.1',
|
||||
'--port', str(WEB_PORT), '--strictPort'], env, web_log)
|
||||
wait_service(web, WEB_PORT, '/', 'html', web_log)
|
||||
wait_service(web, WEB_PORT, '/health', 'ok', web_log)
|
||||
report('services', 'API /readyz、Web 首页与 Vite /health 代理通过')
|
||||
run_step(['make', 'tests-go', 'tests-web'], 'tests', env, 300)
|
||||
check_checkout(commit)
|
||||
if api.poll() is not None or web.poll() is not None or not probe(WEB_PORT, '/health', 'ok'):
|
||||
raise QAError(f'服务在测试期间失去健康状态,日志目录 {log_dir}')
|
||||
report('result', f'PASS {commit},已停止本次 API 和 Web 进程')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('doctor', 'run'))
|
||||
args = parser.parse_args()
|
||||
env = tool_env()
|
||||
try:
|
||||
commit = os.environ.get('KG_QA_SHA', '')
|
||||
if args.action == 'run':
|
||||
check_checkout(commit)
|
||||
check_ports()
|
||||
preflight(env)
|
||||
config_path = Path(os.environ.get('KG_QA_CONFIG', CONFIG)).expanduser().absolute()
|
||||
config = database_config(config_path)
|
||||
private_file(config_path.parent / 'qa.pgpass')
|
||||
if not (config_path.parent / 'rds-ca.pem').is_file():
|
||||
raise QAError(f'缺少 RDS CA 文件 {config_path.parent / "rds-ca.pem"}')
|
||||
db_env = database_env(config, config_path.parent)
|
||||
versions = expected_migrations()
|
||||
if args.action == 'doctor':
|
||||
applied, nonempty = database_state(db_env)
|
||||
check_migrations(versions, applied, nonempty, complete=False)
|
||||
report('database', f'连接与身份正常,已应用 {len(applied)}/{len(versions)} 条迁移')
|
||||
return 0
|
||||
|
||||
state = Path.home() / '.local/state/knowledge-governance/qa'
|
||||
state.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with (state / 'run.lock').open('a') as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError as exc:
|
||||
raise QAError('本机已有 QA 任务,等待当前任务退出') from exc
|
||||
check_ports()
|
||||
check_migrations(versions, *database_state(db_env), complete=False)
|
||||
qa_run(commit, env, db_env, versions, state)
|
||||
return 0
|
||||
except (QAError, OSError, ValueError) as exc:
|
||||
print(f'[qa:FAIL] {exc}', file=sys.stderr)
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
print('[qa:FAIL] QA 任务中断', file=sys.stderr)
|
||||
return 130
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
def interrupt(_signal, _frame):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
signal.signal(signal.SIGTERM, interrupt)
|
||||
sys.exit(main())
|
||||
@@ -1,59 +0,0 @@
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
|
||||
import candidate_release as candidate
|
||||
import production_cd as cd
|
||||
|
||||
BASE, A, B, OTHER = [c * 40 for c in 'abcd']
|
||||
TASK, QA1, QA2, OWNER = [f'{n:08d}-1111-2222-3333-444444444444' for n in range(1, 5)]
|
||||
RUN = {'sha': B, 'bundle': 'e' * 64, 'ready_at': '2026-11-01T10:00:00Z', 'url': 'http://127.0.0.1:39191'}
|
||||
|
||||
|
||||
class CandidateReleaseTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.plan = {'task': TASK, 'sha': B, 'base': BASE,
|
||||
'items': [{'task': QA1, 'pr': 20}, {'task': QA2, 'pr': 21}],
|
||||
'extra': []}
|
||||
self.prs = {n: {'merged': True, 'base': {'ref': 'main'}, 'merge_commit_sha': sha}
|
||||
for n, sha in ((20, A), (21, B))}
|
||||
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
|
||||
|
||||
def test_scope_accounts_for_entire_main_range(self):
|
||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
|
||||
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
|
||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, OTHER, B])
|
||||
|
||||
def test_pr_must_be_merged_on_main_and_match_range(self):
|
||||
self.prs[20]['base']['ref'] = 'test'
|
||||
with self.assertRaisesRegex(cd.CDError, 'merged into main'):
|
||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
|
||||
|
||||
def test_require_all_qa_reports_and_shared_regression(self):
|
||||
sources = {QA1: (self.report, self.result()), QA2: (self.report, self.result())}
|
||||
with self.assertRaisesRegex(cd.CDError, 'every requirement and the release task'):
|
||||
candidate.check_qa(self.plan, RUN, sources, {OWNER})
|
||||
sources[TASK] = (self.report, self.result())
|
||||
candidate.check_qa(self.plan, RUN, sources, {OWNER})
|
||||
|
||||
def test_same_candidate_and_author_required(self):
|
||||
for result, author, reason in ((self.result(sha=OTHER), OWNER, 'different candidate'),
|
||||
(self.result(bundle='0' * 64), OWNER, 'different candidate'),
|
||||
(self.result(), QA1, 'authorized QA'),
|
||||
(self.result(failed=1), OWNER, 'not passed')):
|
||||
sources = {QA1: (dict(self.report, actor={'id': author}), result),
|
||||
QA2: (self.report, self.result()), TASK: (self.report, self.result())}
|
||||
with self.subTest(reason=reason), self.assertRaisesRegex(cd.CDError, reason):
|
||||
candidate.check_qa(self.plan, RUN, sources, {OWNER})
|
||||
|
||||
def test_preparation_rejected_from_review_branch(self):
|
||||
import json
|
||||
event = {'inputs': {'mode': 'prepare', 'plan': json.dumps(self.plan)}}
|
||||
env = {'GITHUB_EVENT_NAME': 'workflow_dispatch', 'GITHUB_REPOSITORY': cd.REPO,
|
||||
'GITHUB_REF': 'refs/heads/feat/candidate-release-batch'}
|
||||
with self.assertRaisesRegex(cd.CDError, 'workflow from main'):
|
||||
candidate.event_plan(event, env)
|
||||
event['inputs']['mode'] = 'verify'
|
||||
self.assertEqual(candidate.event_plan(event, env), (self.plan, 'verify'))
|
||||
|
||||
def result(self, **extra):
|
||||
return {**RUN, 'verdict': 'passed', 'required': 2, 'passed': 2, 'failed': 0, 'blocked': 0, **extra}
|
||||
@@ -1,71 +0,0 @@
|
||||
import json
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
import pathlib
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import pp_client
|
||||
|
||||
class PPClientTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.calls=[];self.login_code=0;self.list_status=200;self.items=[];self.total=None
|
||||
owner=self
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self,*args):pass
|
||||
def do_POST(self):
|
||||
owner.calls.append((self.command,self.path));self.rfile.read(int(self.headers.get('Content-Length','0')))
|
||||
self.send_response(200);self.end_headers();self.wfile.write(json.dumps({'code':owner.login_code,'data':{'access_token':'example-token'} if owner.login_code==0 else {}}).encode())
|
||||
def do_GET(self):
|
||||
owner.calls.append((self.command,self.path))
|
||||
if self.path=='/file.pdf':
|
||||
content=b'%PDF-1.4\nExample PP download\n';self.send_response(200);self.send_header('Content-Length',str(len(content)));self.end_headers();self.wfile.write(content);return
|
||||
self.send_response(owner.list_status);self.end_headers();self.wfile.write(json.dumps({'code':0,'data':{'list':owner.items,'total':len(owner.items) if owner.total is None else owner.total,'hasNextPage':False}}).encode())
|
||||
self.server=HTTPServer(('127.0.0.1',0),Handler);self.thread=threading.Thread(target=self.server.serve_forever,daemon=True);self.thread.start()
|
||||
self.client=pp_client.Client({'base_url':'http://127.0.0.1:'+str(self.server.server_port),'username':'example','password':'example-password'},allow_http=True)
|
||||
def tearDown(self):self.server.shutdown();self.server.server_close();self.thread.join()
|
||||
def test_check_really_logs_in_and_reads_empty_directory(self):
|
||||
result=self.client.check();self.assertEqual(result['state'],'valid');self.assertEqual([x[0] for x in self.calls],['POST','GET']);self.assertTrue(self.calls[0][1].endswith('/admin/login/token'));self.assertTrue(self.calls[1][1].startswith('/potal/file/back/page?'))
|
||||
def test_real_vendor_decimal_string_total_is_readable(self):
|
||||
for count,items in [('0',[]),('1',[{'id':'example'}])]:
|
||||
with self.subTest(count=count):
|
||||
self.total=count;self.items=items
|
||||
self.assertEqual(self.client.check()['state'],'valid')
|
||||
inventory=self.client.inventory(self.client.login())
|
||||
self.assertEqual(inventory['reported_total'],int(count));self.assertEqual(inventory['items'],items)
|
||||
def test_malformed_vendor_counts_are_not_normalized(self):
|
||||
for value in ['01',' 1','+1','1.0','-1','١','9'*20,True,1.5,-1]:
|
||||
with self.subTest(value=value):
|
||||
self.total=value;self.assertEqual(self.client.check()['state'],'invalid_response')
|
||||
def test_explicit_rejection_never_reads_catalog(self):
|
||||
self.login_code=401;result=self.client.check();self.assertEqual(result['state'],'auth_failed');self.assertEqual(len(self.calls),1)
|
||||
def test_permission_failure_and_transient_remain_distinct(self):
|
||||
self.list_status=403;self.assertEqual(self.client.check()['state'],'permission_denied');self.list_status=429;self.assertEqual(self.client.check()['state'],'unavailable')
|
||||
def test_latest_saved_active_config_owns_each_new_task(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
p=pathlib.Path(root)/'settings.json';p.write_text(json.dumps({'active':{'id':'one','base_url':'https://one.example.invalid','username':'example','password':'example-password'}}));p.chmod(0o600)
|
||||
self.assertEqual(pp_client.load_config(str(p))['id'],'one');p.write_text(json.dumps({'active':{'id':'two','base_url':'https://two.example.invalid','username':'example','password':'example-password'}}));self.assertEqual(pp_client.load_config(str(p))['base_url'],'https://two.example.invalid')
|
||||
def test_refresh_consumer_uses_the_shared_client(self):
|
||||
import live_catalog_refresh
|
||||
with patch('live_catalog_refresh.active_client',return_value=self.client),patch('live_catalog_refresh.build_pp_live_source',side_effect=lambda inventory,manifest:inventory),contextlib.redirect_stdout(io.StringIO()):
|
||||
result=live_catalog_refresh.refresh_pp()
|
||||
self.assertEqual(result['items'],[]);self.assertEqual([x[0] for x in self.calls],['POST','GET'])
|
||||
def test_download_consumer_uses_current_portal_and_real_file_bytes(self):
|
||||
import artifact_fetch
|
||||
url=self.client.base+'/file.pdf'
|
||||
self.items=[{'online':1,'potalGroup':{'groupName':'公开'},'fileUrl':url}]
|
||||
with patch('pp_client.active_client',return_value=self.client),patch('artifact_fetch.pp_find_entry',return_value=None):
|
||||
path,size,digest,local=artifact_fetch.pp_download({'locator_hash':hashlib.sha256(url.encode()).hexdigest(),'name':'example.pdf'},1024)
|
||||
try:
|
||||
self.assertFalse(local);self.assertGreater(size,0);self.assertEqual(hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest(),digest)
|
||||
self.assertEqual([x[0] for x in self.calls],['POST','GET','GET'])
|
||||
finally:os.unlink(path)
|
||||
def test_missing_state_never_implicitly_reuses_legacy_credentials(self):
|
||||
fake=json.dumps({'username':'example','password':'synthetic-'+'fixture'})
|
||||
with patch.dict(os.environ,{'PP_LEGACY_CREDENTIALS_FILE':''}),patch('pathlib.Path.exists',return_value=False),patch('pathlib.Path.read_text',return_value=fake):
|
||||
with self.assertRaises(pp_client.PPError):pp_client.load_config('/example-missing/settings.json')
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -1,227 +0,0 @@
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import production_cd as cd
|
||||
import hifox_release_trigger as trigger
|
||||
|
||||
|
||||
SHA = 'a' * 40
|
||||
TASK = 'd5abdf29-d0b5-4992-8073-0cb8fffd84ed'
|
||||
IMAGES = {role: 'sha256:' + str(i) * 64 for i, role in enumerate(('api', 'web', 'worker'), 1)}
|
||||
CTX = 'build / build (push)'
|
||||
|
||||
|
||||
class ProductionCD(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.request = dict(sha=SHA, task=TASK, bundle='b' * 64, confirm='deploy-production',
|
||||
action='deploy', run_id='42')
|
||||
self.manifest = dict(schema=1, target=cd.TARGET, sha=SHA, task=TASK, migrations=[1, 2], images={})
|
||||
for role, image in IMAGES.items():
|
||||
archive = self.root / (role + '.tar')
|
||||
archive.write_text(role)
|
||||
self.manifest['images'][role] = dict(id=image, sha256=hashlib.sha256(role.encode()).hexdigest())
|
||||
data = json.dumps(self.manifest).encode()
|
||||
(self.root / 'release.json').write_bytes(data)
|
||||
for path in self.root.iterdir():
|
||||
path.chmod(0o600)
|
||||
self.request['bundle'] = hashlib.sha256(data).hexdigest()
|
||||
self.acceptance = {'verdict': 'passed', 'sha': SHA, 'bundle': self.request['bundle'],
|
||||
'evidence': 'https://example.test/result/42'}
|
||||
self.host = Mock()
|
||||
self.host.task.return_value = {'id': TASK, 'spaceId': cd.SPACE, 'status': {'id': cd.READY},
|
||||
'metadata': {'cd_acceptance': json.dumps(self.acceptance)}}
|
||||
self.host.baseline.return_value = {'before': 'baseline'}
|
||||
self.host.pre_switch.return_value = None
|
||||
self.host.verify.return_value = {'sha': SHA, 'images': IMAGES, 'health': 'ok'}
|
||||
self.host.receipt_path = self.root / 'receipt.json'
|
||||
self.host.bundle_path.return_value = self.root
|
||||
|
||||
def execute(self):
|
||||
return cd.release(self.host, self.request)
|
||||
|
||||
def assert_no_deploy(self):
|
||||
self.host.load.assert_not_called()
|
||||
self.host.switch.assert_not_called()
|
||||
self.host.callback.assert_not_called()
|
||||
|
||||
def test_no_confirmation_has_zero_side_effects(self):
|
||||
self.request['confirm'] = ''
|
||||
with self.assertRaisesRegex(cd.CDError, 'confirmation'):
|
||||
self.execute()
|
||||
self.host.assert_not_called()
|
||||
self.assert_no_deploy()
|
||||
|
||||
def test_preconditions_prevent_loading_and_switching(self):
|
||||
for mode in ('approval', 'ci', 'test', 'changed_bundle', 'tampered_archive', 'migration'):
|
||||
with self.subTest(mode=mode):
|
||||
self.setUp()
|
||||
if mode in ('approval', 'ci', 'migration'):
|
||||
step = {'approval': self.host.approve, 'ci': self.host.check_ci,
|
||||
'migration': self.host.pre_switch}[mode]
|
||||
step.side_effect = cd.CDError(mode)
|
||||
elif mode == 'test':
|
||||
self.host.task.return_value['metadata'].clear()
|
||||
elif mode == 'changed_bundle':
|
||||
self.request['bundle'] = 'f' * 64
|
||||
else:
|
||||
(self.root / 'web.tar').write_bytes(b'other image')
|
||||
with self.assertRaises(cd.CDError):
|
||||
self.execute()
|
||||
self.assert_no_deploy()
|
||||
|
||||
def test_bare_ci_success_cannot_replace_required_context(self):
|
||||
for statuses in ([], [{'context': 'different', 'status': 'success'}],
|
||||
[{'context': CTX, 'status': 'failure'}, {'context': CTX, 'status': 'success'}]):
|
||||
with self.assertRaises(cd.CDError):
|
||||
cd.verify_contexts({'state': 'success', 'statuses': statuses}, [CTX])
|
||||
cd.verify_contexts({'state': 'success', 'statuses': [{'context': CTX, 'status': 'success'}]}, [CTX])
|
||||
|
||||
def test_approval_and_acceptance_rechecked_before_switch(self):
|
||||
self.host.approve.side_effect = [None, cd.CDError('revoked')]
|
||||
with self.assertRaisesRegex(cd.CDError, 'revoked'):
|
||||
self.execute()
|
||||
self.host.switch.assert_not_called()
|
||||
self.host.callback.assert_not_called()
|
||||
|
||||
def test_success_and_writeback_retry_do_not_switch_twice(self):
|
||||
self.host.callback.side_effect = [cd.CDError('HiFox timeout'), None]
|
||||
with self.assertRaisesRegex(cd.CDError, 'DEPLOYED_HIFOX_PENDING'):
|
||||
self.execute()
|
||||
self.assertEqual(cd.read_json(self.host.receipt_path)['state'], 'deployed_hifox_pending')
|
||||
self.request.update(action='writeback', confirm='retry-writeback')
|
||||
self.assertEqual(self.execute()['state'], 'published')
|
||||
self.host.switch.assert_called_once()
|
||||
self.host.load.assert_called_once()
|
||||
self.assertEqual(self.host.verify.call_count, 2)
|
||||
|
||||
def test_writeback_without_receipt_refuses(self):
|
||||
self.request.update(action='writeback', confirm='retry-writeback')
|
||||
with self.assertRaisesRegex(cd.CDError, 'receipt'):
|
||||
self.execute()
|
||||
self.assert_no_deploy()
|
||||
|
||||
def test_failed_cutover_rolls_back_and_never_marks_published(self):
|
||||
for result in ('rolled_back', 'rollback_failed'):
|
||||
with self.subTest(result=result):
|
||||
self.setUp()
|
||||
self.host.verify.side_effect = cd.CDError('new unhealthy')
|
||||
if result == 'rollback_failed':
|
||||
self.host.rollback.side_effect = cd.CDError('old unhealthy')
|
||||
with self.assertRaisesRegex(cd.CDError, result):
|
||||
self.execute()
|
||||
self.assertEqual(cd.read_json(self.host.receipt_path)['state'], result)
|
||||
self.host.rollback.assert_called_once()
|
||||
self.host.callback.assert_not_called()
|
||||
with self.assertRaisesRegex(cd.CDError, 'receipt'):
|
||||
self.execute()
|
||||
self.host.switch.assert_called_once()
|
||||
|
||||
def test_gitea_guard_log_binds_the_exact_dispatch(self):
|
||||
trusted = 'f' * 40
|
||||
proof = cd.guard_proof(self.request, trusted)
|
||||
log = f'2026-11-22T17:31:54.013Z {proof}\n'.encode()
|
||||
cd.verify_guard_log(log, self.request, trusted)
|
||||
for name, altered in (('sha', 'b' * 40), ('bundle', 'c' * 64), ('run_id', '43'),
|
||||
('task', 'd5abdf29-d0b5-4992-8073-0cb8fffd84ee2'), ('confirm', 'retry-writeback')):
|
||||
with self.subTest(name=name), self.assertRaisesRegex(cd.CDError, 'dispatch proof'):
|
||||
cd.verify_guard_log(log, {**self.request, name: altered}, trusted)
|
||||
with self.assertRaisesRegex(cd.CDError, 'dispatch proof'):
|
||||
cd.verify_guard_log(log + log, self.request, trusted)
|
||||
|
||||
def hifox_fixture(self):
|
||||
task = self.host.task.return_value
|
||||
report = 'ba3ced78-e648-47de-9c17-bccb8f31f36f'
|
||||
event = 'a3aa1dbe-4082-4972-8e29-ed3e39e26b30'
|
||||
task.update(url='https://app.hifox.com/example/task/TEST-42', statusChangedAt='2026-11-22T18:00:00Z')
|
||||
self.acceptance['evidence'] = task['url'] + '#comment-' + report
|
||||
task['metadata']['cd_acceptance'] = json.dumps(self.acceptance)
|
||||
timeline = [dict(id=report, event='commented', createdAt='2026-11-22T17:59:00Z',
|
||||
content=f'验收通过 {SHA} {self.request["bundle"]}'),
|
||||
dict(id=event, event='status_changed', createdAt=task['statusChangedAt'],
|
||||
actor={'type': 'human', 'id': cd.RELEASE_OWNER}, metadata={'to': '待发布'})]
|
||||
return task, timeline
|
||||
|
||||
def test_hifox_dispatch_claims_one_transition(self):
|
||||
task, timeline = self.hifox_fixture()
|
||||
timeline[-1]['createdAt'] = '2026-11-22T18:00:01Z'
|
||||
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
|
||||
with patch.object(trigger, 'hifox', side_effect=[task, timeline, task, timeline]), \
|
||||
patch.object(trigger, 'forge', return_value={'workflow_run_id': 42}) as dispatch:
|
||||
first = trigger.queue(TASK, 'unused', self.root)
|
||||
replay = trigger.queue(TASK, 'unused', self.root)
|
||||
self.assertEqual(first, replay)
|
||||
self.assertEqual(first['run_id'], '42')
|
||||
dispatch.assert_called_once_with('POST', trigger.DISPATCH, {'ref': 'main', 'inputs': first['inputs']})
|
||||
self.assertEqual(first['inputs']['approval_event'], timeline[-1]['id'])
|
||||
|
||||
def test_unknown_dispatch_outcome_is_held(self):
|
||||
task, timeline = self.hifox_fixture()
|
||||
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
|
||||
with patch.object(trigger, 'hifox', side_effect=[task, timeline, task, timeline]), \
|
||||
patch.object(trigger, 'forge', side_effect=TimeoutError()) as dispatch:
|
||||
with self.assertRaises(TimeoutError):
|
||||
trigger.queue(TASK, 'unused', self.root)
|
||||
with self.assertRaisesRegex(cd.CDError, 'outcome unknown'):
|
||||
trigger.queue(TASK, 'unused', self.root)
|
||||
dispatch.assert_called_once()
|
||||
|
||||
def test_hifox_gate_requires_owner_and_existing_candidate_report(self):
|
||||
for failure in ('agent', 'other human', 'mismatched report', 'updated report', 'stale transition', 'no evidence'):
|
||||
with self.subTest(failure=failure):
|
||||
task, timeline = self.hifox_fixture()
|
||||
if failure == 'agent':
|
||||
timeline[-1]['actor']['type'] = 'agent'
|
||||
if failure == 'other human':
|
||||
timeline[-1]['actor']['id'] = TASK
|
||||
if failure == 'mismatched report':
|
||||
timeline[0]['content'] = SHA
|
||||
if failure == 'updated report':
|
||||
timeline[0]['updatedAt'] = '2026-11-22T19:00:00Z'
|
||||
if failure == 'stale transition':
|
||||
task['statusChangedAt'] = '2026-11-22T19:00:00Z'
|
||||
if failure == 'no evidence':
|
||||
task['metadata'] = {}
|
||||
with patch.object(trigger, 'hifox', side_effect=[task, timeline]), patch.object(trigger, 'forge') as forge:
|
||||
with self.assertRaises(cd.CDError):
|
||||
trigger.queue(TASK, 'unused', self.root)
|
||||
forge.assert_not_called()
|
||||
|
||||
def test_auto_approval_is_checked_again_before_switch(self):
|
||||
task, timeline = self.hifox_fixture()
|
||||
approval, _ = cd.release_approval(task, timeline, self.request)
|
||||
self.request.update(approval)
|
||||
self.host.timeline.side_effect = [timeline, timeline[:-1]]
|
||||
proof = cd.guard_proof(self.request, 'f' * 40)
|
||||
self.assertNotEqual(proof, cd.guard_proof({**self.request, 'acceptance_digest': 'e' * 64}, 'f' * 40))
|
||||
with self.assertRaisesRegex(cd.CDError, 'status history'):
|
||||
self.execute()
|
||||
self.host.switch.assert_not_called()
|
||||
|
||||
def test_target_lock_is_exclusive(self):
|
||||
path = self.root / 'lock'
|
||||
with cd.deploy_lock(path):
|
||||
with self.assertRaisesRegex(cd.CDError, 'deployment lock'):
|
||||
with cd.deploy_lock(path):
|
||||
self.fail('lock was acquired twice')
|
||||
|
||||
def test_persisted_compose_changes_only_images(self):
|
||||
original = {'services': {role: {'image': role + ':old', 'env_file': [{'path': '/kept', 'format': 'raw'}],
|
||||
'volumes': ['/kept:/run/key:ro'], 'environment': {'GATE': 'true'}}
|
||||
for role in IMAGES}, 'name': 'governance'}
|
||||
changed = cd.with_images(original, IMAGES)
|
||||
for role, new in changed['services'].items():
|
||||
self.assertEqual(new.pop('image'), IMAGES[role])
|
||||
old = original['services'][role].copy()
|
||||
old.pop('image')
|
||||
self.assertEqual(new, old)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,99 +0,0 @@
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from threading import Thread
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import qa_env
|
||||
|
||||
|
||||
class QAEnvironmentTests(unittest.TestCase):
|
||||
def test_missing_approval_config_names_file(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
config = Path(directory) / 'qa.json'
|
||||
with self.assertRaisesRegex(qa_env.QAError, 'qa.json'):
|
||||
qa_env.database_config(config)
|
||||
|
||||
def test_rejects_non_qa_database_before_connection(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
config = Path(directory) / 'qa.json'
|
||||
config.write_text(json.dumps(dict(host='rds.example.test', port=5432,
|
||||
database='governance', user='kg_qa_app')))
|
||||
config.chmod(0o600)
|
||||
with self.assertRaisesRegex(qa_env.QAError, 'kg_qa_'):
|
||||
qa_env.database_config(config)
|
||||
|
||||
def test_database_environment_uses_only_approved_identity(self):
|
||||
settings = dict(host='rds.example.test', port=5432, database='kg_qa_app', user='kg_qa_app')
|
||||
with patch.dict(os.environ, {'PGHOSTADDR': '127.0.0.1', 'PGPASSWORD': 'fixture',
|
||||
'PGSERVICE': 'other', 'PRODUCTION_RELEASE_REQUESTS_ENABLED': 'true'}):
|
||||
env = qa_env.database_env(settings, Path('/approved'))
|
||||
self.assertEqual(env['PGHOST'], 'rds.example.test')
|
||||
self.assertEqual(env['PGSSLMODE'], 'verify-full')
|
||||
self.assertEqual(env['PRODUCTION_RELEASE_REQUESTS_ENABLED'], 'false')
|
||||
self.assertFalse({'PGHOSTADDR', 'PGPASSWORD', 'PGSERVICE'} & env.keys())
|
||||
|
||||
def test_empty_database_or_known_migration_prefix_can_bootstrap(self):
|
||||
for applied in ([], [1], [1, 2]):
|
||||
with self.subTest(applied=applied):
|
||||
qa_env.check_migrations([1, 2], applied, False, complete=False)
|
||||
|
||||
def test_pending_migrations_block_testing(self):
|
||||
with self.assertRaisesRegex(qa_env.QAError, '迁移未完成'):
|
||||
qa_env.check_migrations([1, 2], [1], False, complete=True)
|
||||
|
||||
def test_schema_without_ledger_is_rejected(self):
|
||||
with self.assertRaisesRegex(qa_env.QAError, '非空'):
|
||||
qa_env.check_migrations([1, 2], [], True, complete=False)
|
||||
|
||||
def test_unknown_or_missing_middle_migrations_are_rejected(self):
|
||||
for applied in ([1, 3], [1, 2, 3], [2]):
|
||||
with self.subTest(applied=applied), self.assertRaisesRegex(qa_env.QAError, '迁移序列'):
|
||||
qa_env.check_migrations([1, 2], applied, False, complete=False)
|
||||
|
||||
def test_hifox_exit_zero_does_not_override_offline_state(self):
|
||||
with self.assertRaisesRegex(qa_env.QAError, '在线'):
|
||||
qa_env.check_hifox('{"connected":true,"remoteLiveness":{"status":"offline"}}')
|
||||
qa_env.check_hifox('{"connected":true,"remoteLiveness":{"status":"online"}}')
|
||||
|
||||
def test_health_probe_rejects_spa_fallback(self):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'text/html')
|
||||
self.end_headers()
|
||||
self.wfile.write(b'<html><div id="root"></div></html>')
|
||||
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
with ThreadingHTTPServer(('127.0.0.1', 0), Handler) as server:
|
||||
thread = Thread(target=server.serve_forever)
|
||||
thread.start()
|
||||
try:
|
||||
self.assertTrue(qa_env.probe(server.server_port, '/', 'html'))
|
||||
self.assertFalse(qa_env.probe(server.server_port, '/health', 'ok'))
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
def test_database_identity_mismatch_stops_before_reading_migrations(self):
|
||||
env = {'PGDATABASE': 'kg_qa_app', 'PGUSER': 'kg_qa_app'}
|
||||
with patch.object(qa_env, 'psql', return_value='other|kg_qa_app|t|t|t|t|t') as probe:
|
||||
with self.assertRaisesRegex(qa_env.QAError, '实际库名'):
|
||||
qa_env.database_state(env)
|
||||
self.assertEqual(probe.call_count, 1)
|
||||
|
||||
def test_full_sha_mismatch_rejects_current_checkout(self):
|
||||
full_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=qa_env.ROOT, text=True).strip()
|
||||
wrong = ('0' if full_sha[0] != '0' else '1') + full_sha[1:]
|
||||
with self.assertRaisesRegex(qa_env.QAError, '提交不一致'):
|
||||
qa_env.check_checkout(wrong)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -14,61 +14,5 @@
|
||||
" expires_on : YYYY-MM-DD,过期当天即失效 —— 过期不是\"继续有效\",是\"重新走一遍审批\"",
|
||||
"纪律:例外是记账,不是免检。到期没人处理 ⇒ 门禁红 ⇒ 必须有人做决定。"
|
||||
],
|
||||
"exceptions": [
|
||||
{
|
||||
"tool": "npm-audit",
|
||||
"id": "GHSA-fc5q-39xc-vjpf",
|
||||
"package": "picomatch",
|
||||
"severity": "high",
|
||||
"scope": "dev",
|
||||
"reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。",
|
||||
"owner": "姚章浩",
|
||||
"approved_by": "姚章浩",
|
||||
"expires_on": "2027-02-15"
|
||||
},
|
||||
{
|
||||
"tool": "npm-audit",
|
||||
"id": "GHSA-fc5q-39xc-vjpf",
|
||||
"package": "fdir",
|
||||
"severity": "high",
|
||||
"scope": "dev",
|
||||
"reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。",
|
||||
"owner": "姚章浩",
|
||||
"approved_by": "姚章浩",
|
||||
"expires_on": "2027-02-15"
|
||||
},
|
||||
{
|
||||
"tool": "npm-audit",
|
||||
"id": "GHSA-fc5q-39xc-vjpf",
|
||||
"package": "tinyglobby",
|
||||
"severity": "high",
|
||||
"scope": "dev",
|
||||
"reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。",
|
||||
"owner": "姚章浩",
|
||||
"approved_by": "姚章浩",
|
||||
"expires_on": "2027-02-15"
|
||||
},
|
||||
{
|
||||
"tool": "npm-audit",
|
||||
"id": "GHSA-fc5q-39xc-vjpf",
|
||||
"package": "vite",
|
||||
"severity": "high",
|
||||
"scope": "dev",
|
||||
"reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。",
|
||||
"owner": "姚章浩",
|
||||
"approved_by": "姚章浩",
|
||||
"expires_on": "2027-02-15"
|
||||
},
|
||||
{
|
||||
"tool": "npm-audit",
|
||||
"id": "GHSA-fc5q-39xc-vjpf",
|
||||
"package": "vitest",
|
||||
"severity": "high",
|
||||
"scope": "dev",
|
||||
"reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。",
|
||||
"owner": "姚章浩",
|
||||
"approved_by": "姚章浩",
|
||||
"expires_on": "2027-02-15"
|
||||
}
|
||||
]
|
||||
}
|
||||
"exceptions": []
|
||||
}
|
||||
@@ -125,7 +125,7 @@ describe('ModulePage', () => {
|
||||
expect(html).toContain('P2 · 知识治理总览')
|
||||
expect(html).toContain('PP历史来源清单已接管')
|
||||
expect(html).toContain('生产写入:关闭')
|
||||
expect(html).toContain('以「系统设置 → 知识库映射」的实时探测为准')
|
||||
expect(html).toContain('以「系统设置 → 服务配置」的实时探测为准')
|
||||
expect(html).not.toContain('本地测试WeKnora已连接')
|
||||
expect(html).not.toContain('生产WeKnora仍未连接')
|
||||
expect(html).not.toContain('尚未连接测试或生产WeKnora')
|
||||
|
||||
+1
-48
@@ -410,53 +410,6 @@ export function ModulePage({
|
||||
return (
|
||||
<div className="release-module">
|
||||
<ReleaseTargets />
|
||||
<details className="release-legacy">
|
||||
<summary>文档级发布(旧流程,折叠保留):单篇文档发布成功不等于整库发布成功</summary>
|
||||
<ReleaseManagement
|
||||
reviewPage={reviewPage}
|
||||
reviewLoading={reviewLoading}
|
||||
reviewError={reviewError}
|
||||
reviewingId={reviewingId}
|
||||
batchPage={batchPage}
|
||||
batchDetail={batchDetail}
|
||||
batchLoading={batchLoading}
|
||||
batchError={batchError}
|
||||
mutatingBatchId={mutatingBatchId}
|
||||
onReview={onReview}
|
||||
onBatchReview={onBatchReview}
|
||||
reviewBatchMessage={reviewBatchMessage}
|
||||
onReviewRefresh={onReviewRefresh}
|
||||
onCreateBatch={onCreateBatch}
|
||||
onSealBatch={onSealBatch}
|
||||
onSelectBatch={onSelectBatch}
|
||||
onBatchRefresh={onBatchRefresh}
|
||||
releaseCapabilities={releaseCapabilities}
|
||||
releasePlan={releasePlan}
|
||||
releaseChangeSet={releaseChangeSet}
|
||||
changeSetBusy={changeSetBusy}
|
||||
changeSetError={changeSetError}
|
||||
onGenerateChangeSet={onGenerateChangeSet}
|
||||
onConfirmChangeSet={onConfirmChangeSet}
|
||||
selectedDeleteIDs={selectedDeleteIDs}
|
||||
onToggleDelete={onToggleDelete}
|
||||
executionPage={executionPage}
|
||||
executionDetail={executionDetail}
|
||||
executionChain={executionChain}
|
||||
executionLoading={executionLoading}
|
||||
executionError={executionError}
|
||||
onSelectExecution={onSelectExecution}
|
||||
onExecutionRefresh={onExecutionRefresh}
|
||||
pendingReleaseAction={pendingReleaseAction}
|
||||
releaseActionPhrase={releaseActionPhrase}
|
||||
releaseActionBusy={releaseActionBusy}
|
||||
releaseActionError={releaseActionError}
|
||||
releaseActionMessage={releaseActionMessage}
|
||||
onStartReleaseAction={onStartReleaseAction}
|
||||
onReleaseActionPhrase={onReleaseActionPhrase}
|
||||
onSubmitReleaseAction={onSubmitReleaseAction}
|
||||
onCancelReleaseAction={onCancelReleaseAction}
|
||||
/>
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -505,7 +458,7 @@ export function ModulePage({
|
||||
? '已开启'
|
||||
: '已开启(快照恢复未验证,仍被阻断)'
|
||||
: '关闭'}
|
||||
;测试 / 生产 WeKnora 连接状态以「系统设置 → 知识库映射」的实时探测为准。
|
||||
;测试 / 生产 WeKnora 连接状态以「系统设置 → 服务配置」的实时探测为准。
|
||||
</span>
|
||||
</div>
|
||||
<span className="safe-badge">Release Worker 默认关闭</span>
|
||||
|
||||
@@ -81,7 +81,7 @@ describe('BackupScheduleView', () => {
|
||||
const html = view()
|
||||
for (const text of [
|
||||
'存储与备份',
|
||||
'备份执行主机',
|
||||
'目标库所在主机',
|
||||
'定时时间',
|
||||
'储存天数',
|
||||
'每月归档保留',
|
||||
|
||||
@@ -104,7 +104,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<div>
|
||||
<h2>存储与备份</h2>
|
||||
<p>
|
||||
整库逻辑备份(pg_dump 目录格式)在<strong>备份执行主机</strong>(同 VPC 直连 RDS)
|
||||
整库逻辑备份(pg_dump 目录格式)在<strong>目标库所在主机</strong>
|
||||
上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。
|
||||
</p>
|
||||
</div>
|
||||
@@ -136,11 +136,9 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<dd>
|
||||
{schedule.host_next_run
|
||||
? schedule.host_next_run
|
||||
: !schedule.host_configured
|
||||
? '未接通备份执行主机:当前计划不会执行'
|
||||
: schedule.host_schedule_enabled
|
||||
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
|
||||
: '未启用定时或未从主机读到计划'}
|
||||
: schedule.host_schedule_enabled
|
||||
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
|
||||
: '未启用定时或未从主机读到计划'}
|
||||
</dd>
|
||||
<dt>最近一次运行</dt>
|
||||
<dd>
|
||||
@@ -165,13 +163,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<dt>覆盖的库</dt>
|
||||
<dd>{schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}</dd>
|
||||
<dt>失败的库</dt>
|
||||
<dd>
|
||||
{schedule.last_run_failed_databases.length
|
||||
? schedule.last_run_failed_databases.join('、')
|
||||
: schedule.last_run_stamp
|
||||
? '无'
|
||||
: '未知(还没有读到运行记录,不能据此判断没有失败)'}
|
||||
</dd>
|
||||
<dd>{schedule.last_run_failed_databases.length ? schedule.last_run_failed_databases.join('、') : '无'}</dd>
|
||||
<dt>主机上生效的计划</dt>
|
||||
<dd>
|
||||
{schedule.host_schedule_enabled
|
||||
@@ -276,7 +268,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
)
|
||||
}
|
||||
|
||||
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是备份执行主机(同 VPC 直连 RDS)。
|
||||
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是目标库所在主机(同 VPC 直连 RDS)。
|
||||
export function BackupScheduleSection() {
|
||||
const auth = useOptionalAuth()
|
||||
const isAdmin = auth?.identity?.role === 'admin'
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { DWSAccount } from './DWSAccount'
|
||||
const id = 'a'.repeat(32)
|
||||
const session = {
|
||||
id,
|
||||
state: 'waiting',
|
||||
verification_url: 'https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE',
|
||||
user_code: 'TEST-CODE',
|
||||
expires_at: '2099-01-01T01:00:00Z',
|
||||
}
|
||||
const json = (data: unknown, status = 200) => new Response(JSON.stringify({ data }), { status })
|
||||
let root: Root
|
||||
let container: HTMLDivElement
|
||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||
const flush = async () => {
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
const click = async (label: string) => {
|
||||
const button = Array.from(container.querySelectorAll('button')).find((x) => x.textContent === label)
|
||||
expect(button, label).toBeTruthy()
|
||||
await act(async () => button!.click())
|
||||
}
|
||||
beforeEach(() => {
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
||||
vi.useFakeTimers()
|
||||
container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
root = createRoot(container)
|
||||
fetcher = vi.fn((path: string, init?: RequestInit) => {
|
||||
if (path.endsWith('credential-status'))
|
||||
return Promise.resolve(json({ authenticated: false, refresh_token_valid: false }))
|
||||
if (path === '/api/v1/dws-login') return Promise.resolve(json(session, 202))
|
||||
if (path.startsWith('/api/v1/dws-login/'))
|
||||
return Promise.resolve(json({ ...session, state: init?.method === 'DELETE' ? 'cancelled' : 'waiting' }))
|
||||
if (path.endsWith('/available'))
|
||||
return Promise.resolve(json({ knowledge_bases: [], drive_spaces: [], fetched_at: '2026-11-17T09:00:00Z' }))
|
||||
throw new Error(`unexpected ${path}`)
|
||||
})
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
})
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount())
|
||||
container.remove()
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
const mount = async () => {
|
||||
await act(async () => root.render(<DWSAccount />))
|
||||
await flush()
|
||||
}
|
||||
|
||||
describe('DWS device authorization', () => {
|
||||
it('opens the official challenge and cancellation removes it', async () => {
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
expect(container.querySelector('[role="dialog"]')).not.toBeNull()
|
||||
expect(container.querySelector('a')?.href).toBe(session.verification_url)
|
||||
expect(container.textContent).toContain('TEST-CODE')
|
||||
await click('取消授权')
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull()
|
||||
expect(fetcher.mock.calls.some(([path, init]) => path.endsWith(id) && init?.method === 'DELETE')).toBe(true)
|
||||
})
|
||||
it('refreshes identity after login and independently reports failed directory access', async () => {
|
||||
let authorized = false
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) => {
|
||||
if (path.endsWith('credential-status'))
|
||||
return Promise.resolve(
|
||||
json({
|
||||
authenticated: authorized,
|
||||
refresh_token_valid: authorized,
|
||||
corp_name: '测试组织',
|
||||
user_name: '测试账号',
|
||||
})
|
||||
)
|
||||
if (path === '/api/v1/dws-login') return Promise.resolve(json(session, 202))
|
||||
if (path.endsWith('/available'))
|
||||
return Promise.resolve(new Response(JSON.stringify({ error: '目录权限不足' }), { status: 503 }))
|
||||
if (init?.method === 'DELETE') return Promise.resolve(json({ ...session, state: 'cancelled' }))
|
||||
authorized = true
|
||||
return Promise.resolve(json({ ...session, state: 'succeeded', verification_url: '', user_code: '' }))
|
||||
})
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
await act(async () => vi.advanceTimersByTimeAsync(1500))
|
||||
await flush()
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull()
|
||||
expect(container.textContent).toContain('DWS 登录成功')
|
||||
expect(container.textContent).toContain('测试账号 · 测试组织')
|
||||
expect(container.textContent).toContain('目录连接检查未通过:目录权限不足')
|
||||
expect(container.textContent).not.toContain('目录连接正常')
|
||||
})
|
||||
it('reports partial directory access without claiming full connection success', async () => {
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) =>
|
||||
path.endsWith('/available')
|
||||
? Promise.resolve(
|
||||
json({
|
||||
knowledge_bases: [{}],
|
||||
drive_spaces: [],
|
||||
knowledge_notice: '个人知识库权限不足',
|
||||
fetched_at: '2026-11-17T09:00:00Z',
|
||||
})
|
||||
)
|
||||
: fallback(path, init)
|
||||
)
|
||||
await mount()
|
||||
await click('检查连接')
|
||||
expect(container.textContent).toContain('目录部分可用')
|
||||
expect(container.textContent).toContain('个人知识库权限不足')
|
||||
expect(container.textContent).not.toContain('目录连接正常')
|
||||
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
|
||||
})
|
||||
it('shows backend startup errors and provides retry', async () => {
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) =>
|
||||
path === '/api/v1/dws-login'
|
||||
? Promise.resolve(new Response(JSON.stringify({ error: '另一位管理员正在授权' }), { status: 409 }))
|
||||
: fallback(path, init)
|
||||
)
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
expect(container.textContent).toContain('另一位管理员正在授权')
|
||||
expect(Array.from(container.querySelectorAll('button')).some((x) => x.textContent === '重试')).toBe(true)
|
||||
})
|
||||
it('cancels a session returned after its dialog was closed during startup', async () => {
|
||||
let resolve!: (response: Response) => void
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) =>
|
||||
path === '/api/v1/dws-login'
|
||||
? new Promise<Response>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
: fallback(path, init)
|
||||
)
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
await click('取消授权')
|
||||
await act(async () => resolve(json(session, 202)))
|
||||
await flush()
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull()
|
||||
expect(fetcher.mock.calls.some(([path, init]) => path.endsWith(id) && init?.method === 'DELETE')).toBe(true)
|
||||
})
|
||||
it('does not reopen a cancelled dialog when a late poll succeeds', async () => {
|
||||
let resolve!: (response: Response) => void
|
||||
const fallback = fetcher.getMockImplementation()!
|
||||
fetcher.mockImplementation((path: string, init?: RequestInit) =>
|
||||
path.endsWith(id) && init?.method === 'GET'
|
||||
? new Promise<Response>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
: fallback(path, init)
|
||||
)
|
||||
await mount()
|
||||
await click('登录授权')
|
||||
await act(async () => vi.advanceTimersByTimeAsync(1500))
|
||||
await click('取消授权')
|
||||
await act(async () => resolve(json({ ...session, state: 'succeeded' })))
|
||||
await flush()
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull()
|
||||
expect(container.textContent).not.toContain('DWS 登录成功')
|
||||
})
|
||||
})
|
||||
@@ -1,12 +0,0 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DingtalkAccountStatus } from './SourceManagement'
|
||||
|
||||
describe('DWS account entry', () => {
|
||||
it('offers device login and a separate connection check beside account status', () => {
|
||||
const html = renderToStaticMarkup(<DingtalkAccountStatus />)
|
||||
expect(html).toContain('登录授权')
|
||||
expect(html).toContain('检查连接')
|
||||
expect(html).not.toContain('扫码刷新会话')
|
||||
})
|
||||
})
|
||||
@@ -1,313 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
cancelDWSLogin,
|
||||
checkDWSConnection,
|
||||
dwsLoginActive,
|
||||
fetchDWSCredentials,
|
||||
fetchDWSLogin,
|
||||
startDWSLogin,
|
||||
} from './dwsLogin'
|
||||
import type { DWSCredentials, DWSLogin } from './dwsLogin'
|
||||
|
||||
const messageOf = (cause: unknown) => (cause instanceof Error ? cause.message : '请求失败,请重试')
|
||||
const moment = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
|
||||
export function DWSAccount({
|
||||
autoStart = false,
|
||||
onAuthorized,
|
||||
onCredentials,
|
||||
onCancel,
|
||||
}: {
|
||||
autoStart?: boolean
|
||||
onAuthorized?: (credentials: DWSCredentials) => void
|
||||
onCredentials?: (credentials: DWSCredentials) => void
|
||||
onCancel?: () => void
|
||||
} = {}) {
|
||||
const callbacks = useRef({ onAuthorized, onCredentials, onCancel })
|
||||
callbacks.current = { onAuthorized, onCredentials, onCancel }
|
||||
const startedAutomatically = useRef(false)
|
||||
const [credentials, setCredentials] = useState<DWSCredentials | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [notice, setNotice] = useState('')
|
||||
const [connection, setConnection] = useState<Awaited<ReturnType<typeof checkDWSConnection>> | null>(null)
|
||||
const [checking, setChecking] = useState(false)
|
||||
const [session, setSession] = useState<DWSLogin | null>(null)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [starting, setStarting] = useState(false)
|
||||
const [loginError, setLoginError] = useState('')
|
||||
const id = useRef('')
|
||||
const generation = useRef(0)
|
||||
const mounted = useRef(false)
|
||||
const handled = useRef('')
|
||||
const action = useRef<AbortController | null>(null)
|
||||
const checkAction = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true
|
||||
const controller = new AbortController()
|
||||
void fetchDWSCredentials(controller.signal)
|
||||
.then((fresh) => {
|
||||
setCredentials(fresh)
|
||||
callbacks.current.onCredentials?.(fresh)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted) setError(messageOf(cause))
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
mounted.current = false
|
||||
controller.abort()
|
||||
action.current?.abort()
|
||||
checkAction.current?.abort()
|
||||
generation.current++
|
||||
if (id.current) void cancelDWSLogin(id.current).catch(() => undefined)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const check = useCallback(async () => {
|
||||
checkAction.current?.abort()
|
||||
const controller = new AbortController()
|
||||
checkAction.current = controller
|
||||
setChecking(true)
|
||||
setConnection(null)
|
||||
setError('')
|
||||
try {
|
||||
const result = await checkDWSConnection(controller.signal)
|
||||
const fresh = await fetchDWSCredentials(controller.signal)
|
||||
if (!controller.signal.aborted && mounted.current) {
|
||||
setConnection(result)
|
||||
setCredentials(fresh)
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted && mounted.current) setError(`目录连接检查未通过:${messageOf(cause)}`)
|
||||
} finally {
|
||||
if (!controller.signal.aborted && mounted.current) setChecking(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const start = async () => {
|
||||
const current = ++generation.current
|
||||
action.current?.abort()
|
||||
checkAction.current?.abort()
|
||||
setChecking(false)
|
||||
const controller = new AbortController()
|
||||
action.current = controller
|
||||
setOpen(true)
|
||||
setStarting(true)
|
||||
setSession(null)
|
||||
setLoginError('')
|
||||
setNotice('')
|
||||
setConnection(null)
|
||||
setError('')
|
||||
try {
|
||||
const next = await startDWSLogin(controller.signal)
|
||||
if (!mounted.current || current !== generation.current) {
|
||||
void cancelDWSLogin(next.id).catch(() => undefined)
|
||||
return
|
||||
}
|
||||
id.current = next.id
|
||||
setSession(next)
|
||||
} catch (cause) {
|
||||
if (mounted.current && current === generation.current) setLoginError(messageOf(cause))
|
||||
} finally {
|
||||
if (mounted.current && current === generation.current) setStarting(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (autoStart && !startedAutomatically.current) {
|
||||
startedAutomatically.current = true
|
||||
void start()
|
||||
}
|
||||
}, [autoStart])
|
||||
|
||||
const close = async () => {
|
||||
const current = generation.current
|
||||
const sessionID = id.current
|
||||
setLoginError('')
|
||||
if (!sessionID && starting) {
|
||||
// Keep the POST alive so its returned session can be cancelled by ID.
|
||||
++generation.current
|
||||
setOpen(false)
|
||||
setStarting(false)
|
||||
callbacks.current.onCancel?.()
|
||||
return
|
||||
}
|
||||
if (sessionID && session && dwsLoginActive(session.state)) {
|
||||
try {
|
||||
await cancelDWSLogin(sessionID)
|
||||
} catch (cause) {
|
||||
if (mounted.current && generation.current === current) setLoginError(`取消未完成:${messageOf(cause)}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
if (mounted.current && generation.current === current) {
|
||||
++generation.current
|
||||
id.current = ''
|
||||
setOpen(false)
|
||||
setSession(null)
|
||||
callbacks.current.onCancel?.()
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!session || !dwsLoginActive(session.state) || loginError) return
|
||||
const controller = new AbortController()
|
||||
const current = generation.current
|
||||
const timer = window.setTimeout(() => {
|
||||
void fetchDWSLogin(session.id, controller.signal)
|
||||
.then((next) => {
|
||||
if (!controller.signal.aborted && current === generation.current) setSession(next)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted && current === generation.current) setLoginError(messageOf(cause))
|
||||
})
|
||||
}, 1500)
|
||||
return () => {
|
||||
window.clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [session, loginError])
|
||||
|
||||
useEffect(() => {
|
||||
if (session?.state !== 'succeeded' || handled.current === session.id) return
|
||||
handled.current = session.id
|
||||
const current = generation.current
|
||||
id.current = ''
|
||||
setOpen(false)
|
||||
setNotice('DWS 登录成功,正在检查目录连接…')
|
||||
void fetchDWSCredentials()
|
||||
.then((fresh) => {
|
||||
if (!mounted.current || current !== generation.current) return
|
||||
setCredentials(fresh)
|
||||
setNotice('DWS 登录成功')
|
||||
callbacks.current.onCredentials?.(fresh)
|
||||
void check()
|
||||
callbacks.current.onAuthorized?.(fresh)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (mounted.current && current === generation.current) setError(`授权成功,状态刷新失败:${messageOf(cause)}`)
|
||||
})
|
||||
}, [session, check])
|
||||
|
||||
const status = loading
|
||||
? '读取中…'
|
||||
: error && !credentials
|
||||
? '状态读取失败'
|
||||
: !credentials?.status_known
|
||||
? '登录状态待核验'
|
||||
: !credentials.authenticated
|
||||
? '未登录'
|
||||
: credentials.refresh_token_valid
|
||||
? '已登录'
|
||||
: '凭证需更新'
|
||||
const busy = starting || Boolean(session && dwsLoginActive(session.state))
|
||||
const labels: Record<DWSLogin['state'], string> = {
|
||||
starting: '正在生成授权入口…',
|
||||
waiting: '请打开钉钉授权页,确认本次登录。完成后此页会自动更新。',
|
||||
verifying: '已收到授权,正在验证并保存登录状态…',
|
||||
succeeded: '登录成功',
|
||||
expired: '授权已过期,请重新发起。',
|
||||
failed: '授权未完成,请重试。',
|
||||
cancelled: '授权已取消。',
|
||||
}
|
||||
return (
|
||||
<section className="source-account" aria-label="钉钉账号(DWS)">
|
||||
<div className="dws-account-heading">
|
||||
<div>
|
||||
<strong>钉钉账号(DWS) · {status}</strong>
|
||||
{credentials?.authenticated ? (
|
||||
<div>
|
||||
{[credentials.user_name, credentials.corp_name].filter(Boolean).join(' · ') || '账号信息暂未返回'}
|
||||
</div>
|
||||
) : null}
|
||||
{credentials?.authenticated && credentials.refresh_expires_at ? (
|
||||
<small>授权有效期至 {moment(credentials.refresh_expires_at)}</small>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-actions">
|
||||
<button onClick={() => void start()} disabled={busy}>
|
||||
{busy ? '授权进行中…' : credentials?.authenticated ? '重新授权' : '登录授权'}
|
||||
</button>
|
||||
<button className="secondary" onClick={() => void check()} disabled={checking || busy}>
|
||||
{checking ? '检查中…' : '检查连接'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<small>所有钉钉来源共用此账号。登录后检查知识库与钉盘的实际访问权限。</small>
|
||||
{notice ? (
|
||||
<p role="status" className="success-message">
|
||||
{notice}
|
||||
</p>
|
||||
) : null}
|
||||
{error ? (
|
||||
<p role="alert" className="error-message">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{connection ? (
|
||||
<div role="status">
|
||||
<p className={connection.notices.length ? 'hint' : 'success-message'}>
|
||||
{connection.notices.length ? '目录部分可用' : '目录连接正常'}:{connection.message} · 检查于{' '}
|
||||
{moment(connection.checkedAt)}
|
||||
</p>
|
||||
{connection.notices.map((value) => (
|
||||
<p className="hint" key={value}>
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{open ? (
|
||||
<div className="modal-backdrop" role="dialog" aria-modal="true" aria-label="DWS 登录授权">
|
||||
<div className="modal-card dws-login-card">
|
||||
<h3>DWS 登录授权</h3>
|
||||
<p role="status">{starting ? '正在生成授权入口…' : session ? labels[session.state] : '授权入口生成失败'}</p>
|
||||
{session?.state === 'waiting' && session.verification_url ? (
|
||||
<>
|
||||
<a
|
||||
className="primary-action dws-authorize-link"
|
||||
href={session.verification_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
referrerPolicy="no-referrer"
|
||||
>
|
||||
打开钉钉授权页
|
||||
</a>
|
||||
<p>
|
||||
若授权页要求输入授权码:<code className="dws-user-code">{session.user_code}</code>
|
||||
</p>
|
||||
<small>本次授权有效期至 {moment(session.expires_at)}</small>
|
||||
</>
|
||||
) : null}
|
||||
{session?.error ? (
|
||||
<p role="alert" className="error-message">
|
||||
{session.error}
|
||||
</p>
|
||||
) : null}
|
||||
{loginError ? (
|
||||
<p role="alert" className="error-message">
|
||||
{loginError}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="row-actions">
|
||||
{session && !dwsLoginActive(session.state) ? (
|
||||
<button onClick={() => void start()}>重新发起授权</button>
|
||||
) : null}
|
||||
{loginError && session && dwsLoginActive(session.state) ? (
|
||||
<button onClick={() => setLoginError('')}>重试读取状态</button>
|
||||
) : null}
|
||||
{!starting && !session ? <button onClick={() => void start()}>重试</button> : null}
|
||||
<button className="secondary" onClick={() => void close()}>
|
||||
{busy ? '取消授权' : '关闭'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -8,18 +8,11 @@ describe('DingtalkSourceDiscovery', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<DingtalkSourceDiscovery registeredNames={['ATOM知识库']} onRegistered={vi.fn()} />
|
||||
)
|
||||
for (const text of ['添加数据源向导', '类型', '授权', '范围', '校验', '保存', '钉钉知识库', '钉盘']) {
|
||||
for (const text of ['dws 导入(钉钉)', '刷新列表', '加入为来源(选中 0)', '已是来源']) {
|
||||
expect(html).toContain(text)
|
||||
}
|
||||
// 需求(2026-10-10):数据源配置这里不再做文件格式筛选——格式归目录级标注决定。
|
||||
for (const removed of [
|
||||
'文件格式筛选',
|
||||
'未勾选的一律不取件',
|
||||
'保存保留格式',
|
||||
'恢复继承上级规则',
|
||||
'扫码会话',
|
||||
'弹二维码',
|
||||
]) {
|
||||
for (const removed of ['文件格式筛选', '未勾选的一律不取件', '保存保留格式', '恢复继承上级规则']) {
|
||||
expect(html).not.toContain(removed)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
import { SourceWizard } from './SourceWizard'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { DingtalkRequestError, registerDingtalkSpace } from './dingtalkSession'
|
||||
import { DingtalkSessionControl } from './DingtalkSessionControl'
|
||||
import {
|
||||
discoveryCandidates,
|
||||
fetchAvailableDingtalkSources,
|
||||
type AvailableDingtalkSources,
|
||||
type DiscoveryCandidate,
|
||||
} from './dingtalkSources'
|
||||
|
||||
// 「系统设置 → 数据源配置」里的数据源发现面板(管理员):
|
||||
// ① 列出当前钉钉账号(dws)能看到的钉钉知识库;
|
||||
// ② 列出钉盘空间(我的文件 / 组织空间);
|
||||
// ③ 勾选后加入为来源(登记走既有路径,首次目录扫描自动排队);
|
||||
// ④ 登记需要有效的钉钉扫码会话:会话失效时直接弹二维码,扫完自动重试本次登记。
|
||||
// 这里不显示文件格式筛选:格式由目录级标注决定,不在这张卡上做。
|
||||
|
||||
// Keep historical callers on the same DWS authorization and recovery path.
|
||||
export function DingtalkSourceDiscovery({
|
||||
registeredNames,
|
||||
onRegistered,
|
||||
@@ -8,5 +23,171 @@ export function DingtalkSourceDiscovery({
|
||||
registeredNames: string[]
|
||||
onRegistered: () => void
|
||||
}) {
|
||||
return <SourceWizard registeredNames={registeredNames} ppConnected={false} onRegistered={onRegistered} initialOpen />
|
||||
const [list, setList] = useState<AvailableDingtalkSources | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
const [checked, setChecked] = useState<string[]>([])
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
const [loginRequired, setLoginRequired] = useState(false)
|
||||
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
setLoading(true)
|
||||
setLoadError(null)
|
||||
try {
|
||||
const next = await fetchAvailableDingtalkSources(signal)
|
||||
setList(next)
|
||||
// 已登记的默认不再勾选:避免重复登记。
|
||||
setChecked([])
|
||||
} catch (cause) {
|
||||
if (cause instanceof DOMException && cause.name === 'AbortError') return
|
||||
setLoadError(cause instanceof Error ? cause.message : '列举数据源失败')
|
||||
setList(null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void load(controller.signal)
|
||||
return () => controller.abort()
|
||||
}, [load])
|
||||
|
||||
const candidates = discoveryCandidates(list, registeredNames)
|
||||
const knowledgeBases = candidates.filter((item) => item.kind === 'knowledge_base')
|
||||
const driveSpaces = candidates.filter((item) => item.kind === 'drive_space')
|
||||
const selected = candidates.filter((item) => checked.includes(item.key))
|
||||
const toggle = (key: string) =>
|
||||
setChecked((current) => (current.includes(key) ? current.filter((item) => item !== key) : [...current, key]))
|
||||
|
||||
const submit = async (retryAfterLogin = false) => {
|
||||
setBusy(true)
|
||||
setFailure(null)
|
||||
setMessage(null)
|
||||
const added: string[] = []
|
||||
const failed: string[] = []
|
||||
let needLogin = false
|
||||
for (const candidate of selected) {
|
||||
try {
|
||||
const result = await registerDingtalkSpace(candidate.url)
|
||||
added.push(result.name || candidate.name)
|
||||
} catch (cause) {
|
||||
// 扫码会话失效:登记本身没问题,直接弹二维码,扫完自动重试剩下的。
|
||||
if (cause instanceof DingtalkRequestError && cause.code === 'login_required' && !retryAfterLogin) {
|
||||
needLogin = true
|
||||
break
|
||||
}
|
||||
failed.push(`${candidate.name}:${cause instanceof Error ? cause.message : '登记失败'}`)
|
||||
}
|
||||
}
|
||||
setBusy(false)
|
||||
if (needLogin) {
|
||||
setLoginRequired(true)
|
||||
setFailure('钉钉扫码会话已失效:请扫码登录,登录成功后会自动继续这次登记。')
|
||||
return
|
||||
}
|
||||
if (added.length) {
|
||||
setMessage(`已加入 ${added.length} 个来源:${added.join('、')}。首次目录扫描已在后台排队。`)
|
||||
onRegistered()
|
||||
void load()
|
||||
}
|
||||
if (failed.length) setFailure(failed.join(';'))
|
||||
}
|
||||
|
||||
const resumeAfterLogin = () => {
|
||||
setLoginRequired(false)
|
||||
setFailure(null)
|
||||
void submit(true)
|
||||
}
|
||||
|
||||
const renderRow = (candidate: DiscoveryCandidate) => {
|
||||
const already = candidate.alreadyRegistered
|
||||
return (
|
||||
<li key={candidate.key} className={already ? 'discovery-row registered' : 'discovery-row'}>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`选择${candidate.name}`}
|
||||
checked={checked.includes(candidate.key)}
|
||||
disabled={already || busy}
|
||||
onChange={() => toggle(candidate.key)}
|
||||
/>
|
||||
<span>
|
||||
<strong>{candidate.name}</strong>
|
||||
<small>{candidate.detail}</small>
|
||||
</span>
|
||||
</label>
|
||||
{already ? <span className="safe-badge">已是来源</span> : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="dingtalk-discovery" aria-label="可加入的数据源">
|
||||
<div className="dingtalk-discovery-heading">
|
||||
<div>
|
||||
<strong>dws 导入(钉钉)</strong>
|
||||
<small>按当前钉钉账号列出能访问的知识库与钉盘空间;勾选后加入为来源,首次目录扫描自动排队。</small>
|
||||
</div>
|
||||
<button type="button" className="secondary" onClick={() => void load()} disabled={loading}>
|
||||
{loading ? '正在列举…' : '刷新列表'}
|
||||
</button>
|
||||
</div>
|
||||
{loadError ? (
|
||||
<p className="error-message" role="alert">
|
||||
{loadError}
|
||||
</p>
|
||||
) : null}
|
||||
{list ? (
|
||||
<div className="dingtalk-discovery-groups">
|
||||
<div className="discovery-group">
|
||||
<h4>知识库({knowledgeBases.length})</h4>
|
||||
{list.knowledge_notice ? (
|
||||
<small className="empty-inline">知识库列表可能不全:{list.knowledge_notice}</small>
|
||||
) : null}
|
||||
{knowledgeBases.length ? (
|
||||
<ul>{knowledgeBases.map(renderRow)}</ul>
|
||||
) : (
|
||||
<small className="empty-inline">当前账号下没有可访问的知识库。</small>
|
||||
)}
|
||||
</div>
|
||||
<div className="discovery-group">
|
||||
<h4>钉盘({driveSpaces.length})</h4>
|
||||
{list.drive_notice ? <small className="empty-inline">钉盘这次列不出来:{list.drive_notice}</small> : null}
|
||||
{!list.drive_notice && !driveSpaces.length ? (
|
||||
<small className="empty-inline">当前账号下没有可见的钉盘空间。</small>
|
||||
) : null}
|
||||
{driveSpaces.length ? <ul>{driveSpaces.map(renderRow)}</ul> : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="dingtalk-discovery-actions">
|
||||
<button type="button" disabled={!selected.length || busy} onClick={() => void submit()}>
|
||||
{busy ? '正在加入…' : `加入为来源(选中 ${selected.length})`}
|
||||
</button>
|
||||
<small>勾选的知识库会登记为来源连接;已登记的条目标为「已是来源」,不会重复登记。</small>
|
||||
</div>
|
||||
{message ? (
|
||||
<p className="success-message" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
{failure ? (
|
||||
<p className="error-message" role="alert">
|
||||
{failure}
|
||||
</p>
|
||||
) : null}
|
||||
{loginRequired ? (
|
||||
<DingtalkSessionControl
|
||||
autoStart
|
||||
hideTrigger
|
||||
space={selected[0]?.url}
|
||||
onSuccess={resumeAfterLogin}
|
||||
onClose={() => setLoginRequired(false)}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -89,82 +89,78 @@ export function LibraryStorageSection() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<details className="settings-details" open={!policyConfigured}>
|
||||
<summary>保留策略与清理预览(未设置时按“全部保留”处理)</summary>
|
||||
<div className="library-storage-panel">
|
||||
<h4>保留与依赖保护</h4>
|
||||
<p>
|
||||
{policyConfigured
|
||||
? `策略:${[
|
||||
plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '',
|
||||
plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' + ')}`
|
||||
: '策略:未设置(不生成清理候选)'}
|
||||
</p>
|
||||
<p>
|
||||
受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、运行中作业引用,
|
||||
不论多久都不会进入候选。
|
||||
</p>
|
||||
{data.versions.filter((item) => item.protected).length > 0 ? (
|
||||
<ul className="library-storage-versions">
|
||||
{data.versions
|
||||
.filter((item) => item.protected)
|
||||
.map((item) => (
|
||||
<div className="library-storage-panel">
|
||||
<h4>保留与依赖保护</h4>
|
||||
<p>
|
||||
{policyConfigured
|
||||
? `策略:${[
|
||||
plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '',
|
||||
plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' + ')}`
|
||||
: '策略:未设置(不生成清理候选)'}
|
||||
</p>
|
||||
<p>
|
||||
受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、在飞作业引用,
|
||||
不论多久都不会进入候选。
|
||||
</p>
|
||||
{data.versions.filter((item) => item.protected).length > 0 ? (
|
||||
<ul className="library-storage-versions">
|
||||
{data.versions
|
||||
.filter((item) => item.protected)
|
||||
.map((item) => (
|
||||
<li key={item.id}>
|
||||
<code>{item.id.slice(0, 12)}</code> {item.kind} · {(item.protected_by ?? []).join('、')}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="library-storage-panel">
|
||||
<h4>清理预览</h4>
|
||||
{policyConfigured ? (
|
||||
plan && plan.candidates.length > 0 ? (
|
||||
<>
|
||||
<p>
|
||||
按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '}
|
||||
{formatBytes(plan.reclaim_preview_bytes)}(共享 blob 不会因此释放,这不是可回收空间)。
|
||||
</p>
|
||||
<ul className="library-storage-versions">
|
||||
{plan.candidates.map((item) => (
|
||||
<li key={item.id}>
|
||||
<code>{item.id.slice(0, 12)}</code> {item.kind} · {(item.protected_by ?? []).join('、')}
|
||||
<code>{item.id.slice(0, 12)}</code> {item.kind} · {item.reason.join(';')} ·{' '}
|
||||
{formatBytes(item.exclusive_bytes)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="library-storage-panel">
|
||||
<h4>清理预览</h4>
|
||||
{policyConfigured ? (
|
||||
plan && plan.candidates.length > 0 ? (
|
||||
<>
|
||||
<p>
|
||||
按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '}
|
||||
{formatBytes(plan.reclaim_preview_bytes)}(共享归档文件不会因此释放,这不是可回收空间)。
|
||||
</p>
|
||||
<ul className="library-storage-versions">
|
||||
{plan.candidates.map((item) => (
|
||||
<li key={item.id}>
|
||||
<code>{item.id.slice(0, 12)}</code> {item.kind} · {item.reason.join(';')} ·{' '}
|
||||
{formatBytes(item.exclusive_bytes)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<p>按当前策略没有可清理的候选版本。</p>
|
||||
)
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<p className="library-storage-warn">
|
||||
保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。
|
||||
</p>
|
||||
)}
|
||||
{plan?.blocked.length ? (
|
||||
<ul className="library-storage-blocked-list">
|
||||
{plan.blocked.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
<p>按当前策略没有可清理的候选版本。</p>
|
||||
)
|
||||
) : (
|
||||
<p className="library-storage-warn">
|
||||
保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。
|
||||
</p>
|
||||
)}
|
||||
{plan?.blocked.length ? (
|
||||
<ul className="library-storage-blocked-list">
|
||||
{plan.blocked.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ul className="library-storage-limits">
|
||||
<li>自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)</li>
|
||||
<li>实际删除需要单独授权,本页只给预览</li>
|
||||
<li>以上数字都不是「可回收空间」,不能用来估算清理收益</li>
|
||||
{data.notes.map((note) => (
|
||||
// 服务端注记里的 blob 指归档文件:页面统一术语,不把实现细节甩给操作者。
|
||||
<li key={note}>{note.replace(/blob/gi, '归档文件')}</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
<ul className="library-storage-limits">
|
||||
<li>自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)</li>
|
||||
<li>实际删除需要单独授权,本页只给预览</li>
|
||||
<li>以上数字都不是「可回收空间」,不能用来估算清理收益</li>
|
||||
{data.notes.map((note) => (
|
||||
<li key={note}>{note}</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
@@ -23,9 +23,6 @@ export function MembersSection() {
|
||||
const [busy, setBusy] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
// 重置密码用受控对话框(遮罩输入),不再借浏览器 prompt 显示明文。
|
||||
const [resetTarget, setResetTarget] = useState<{ id: string; username: string } | null>(null)
|
||||
const [resetValue, setResetValue] = useState('')
|
||||
const [form, setForm] = useState({
|
||||
username: '',
|
||||
display_name: '',
|
||||
@@ -157,8 +154,15 @@ export function MembersSection() {
|
||||
className="secondary-action"
|
||||
disabled={busy === user.id}
|
||||
onClick={() => {
|
||||
setResetTarget({ id: user.id, username: user.username })
|
||||
setResetValue('')
|
||||
const temporary = window.prompt(
|
||||
`为 ${user.username} 生成一个临时密码(至少 8 位,对方首次登录必须更换)`
|
||||
)
|
||||
if (temporary)
|
||||
void run(
|
||||
user.id,
|
||||
() => resetManagedUserPassword(user.id, temporary),
|
||||
`${user.username} 的临时密码已生效`
|
||||
)
|
||||
}}
|
||||
>
|
||||
重置密码
|
||||
@@ -234,47 +238,6 @@ export function MembersSection() {
|
||||
</button>
|
||||
</div>
|
||||
<small>停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。</small>
|
||||
{resetTarget ? (
|
||||
<div className="member-reset-dialog" role="dialog" aria-modal="true" aria-label="重置临时密码">
|
||||
<h3>重置 {resetTarget.username} 的临时密码</h3>
|
||||
<p>至少 8 位;对方首次登录必须更换,旧会话会立即失效。</p>
|
||||
<PasswordInput
|
||||
value={resetValue}
|
||||
autoFocus
|
||||
autoComplete="new-password"
|
||||
onChange={(event) => setResetValue(event.target.value)}
|
||||
/>
|
||||
<div className="row-actions">
|
||||
<button
|
||||
type="button"
|
||||
disabled={resetValue.length < 8 || busy === resetTarget.id}
|
||||
onClick={() => {
|
||||
const target = resetTarget
|
||||
const value = resetValue
|
||||
setResetTarget(null)
|
||||
setResetValue('')
|
||||
void run(
|
||||
target.id,
|
||||
() => resetManagedUserPassword(target.id, value),
|
||||
`${target.username} 的临时密码已生效`
|
||||
)
|
||||
}}
|
||||
>
|
||||
确认重置
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-action"
|
||||
onClick={() => {
|
||||
setResetTarget(null)
|
||||
setResetValue('')
|
||||
}}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
.pp-connection {
|
||||
border: 1px solid var(--border, #dce3eb);
|
||||
border-radius: 10px;
|
||||
padding: 16px;
|
||||
margin: 12px 0;
|
||||
background: var(--surface, #fff);
|
||||
}
|
||||
.pp-heading,
|
||||
.pp-actions,
|
||||
.pp-password {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.pp-heading {
|
||||
justify-content: space-between;
|
||||
}
|
||||
.pp-heading h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
.pp-state {
|
||||
color: var(--text-muted, #66758a);
|
||||
font-size: 13px;
|
||||
}
|
||||
.pp-connection dl {
|
||||
margin: 12px 0;
|
||||
}
|
||||
.pp-connection dl > div {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin: 6px 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.pp-connection dt {
|
||||
flex: 0 0 76px;
|
||||
color: var(--text-muted, #66758a);
|
||||
}
|
||||
.pp-connection dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.pp-connection form {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.pp-connection label {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.pp-connection input {
|
||||
width: 100%;
|
||||
max-width: 540px;
|
||||
box-sizing: border-box;
|
||||
padding: 9px 11px;
|
||||
border: 1px solid var(--border, #cdd7e4);
|
||||
border-radius: 6px;
|
||||
background: var(--surface, #fff);
|
||||
color: inherit;
|
||||
}
|
||||
.pp-connection button {
|
||||
padding: 7px 12px;
|
||||
border: 1px solid var(--border, #cdd7e4);
|
||||
border-radius: 6px;
|
||||
background: var(--surface, #fff);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pp-connection button.primary {
|
||||
background: #2563eb;
|
||||
color: #fff;
|
||||
border-color: #2563eb;
|
||||
}
|
||||
.pp-connection button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.pp-connection [role='alert'] {
|
||||
color: #a93835;
|
||||
}
|
||||
.pp-connection [role='status'] {
|
||||
font-size: 13px;
|
||||
}
|
||||
.pp-connection.compact {
|
||||
margin-top: 0;
|
||||
}
|
||||
.pp-test-result {
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--border, #dce3eb);
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { PPConnection } from './PPConnection'
|
||||
let root: Root, host: HTMLDivElement
|
||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||
const active = {
|
||||
id: 'active-one',
|
||||
base_url: 'https://api.example.invalid',
|
||||
username: 'example',
|
||||
password_configured: true,
|
||||
}
|
||||
const view = {
|
||||
revision: 1,
|
||||
active,
|
||||
pending: null,
|
||||
observation: { state: 'valid', message: '认证有效 · 目录可读', checked_at: '2026-11-17T10:00:00Z' },
|
||||
pending_observation: null,
|
||||
}
|
||||
const json = (data: unknown) => new Response(JSON.stringify({ data }))
|
||||
const click = async (label: string) => {
|
||||
const b = [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === label)
|
||||
expect(b, label).toBeTruthy()
|
||||
await act(async () => b!.click())
|
||||
}
|
||||
const type = async (label: string, value: string) => {
|
||||
const input = [...host.querySelectorAll('label')]
|
||||
.find((x) => x.textContent?.startsWith(label))
|
||||
?.querySelector('input')
|
||||
expect(input, label).toBeTruthy()
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
|
||||
input!.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
beforeEach(() => {
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
||||
host = document.createElement('div')
|
||||
document.body.append(host)
|
||||
root = createRoot(host)
|
||||
fetcher = vi.fn(async (_p: string, init?: RequestInit) =>
|
||||
json(init?.method === 'PUT' ? { ...view, revision: 2 } : view)
|
||||
)
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
})
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount())
|
||||
host.remove()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
describe('PP configuration editor', () => {
|
||||
it('keeps the stored password without sending a masked replacement or launching scans', async () => {
|
||||
await act(async () => root.render(<PPConnection />))
|
||||
await click('配置')
|
||||
expect(host.querySelector('input[type=password]')).toBeNull()
|
||||
await click('保存并校验')
|
||||
const writes = fetcher.mock.calls.filter(([, i]) => i?.method === 'PUT')
|
||||
expect(writes).toHaveLength(1)
|
||||
const data = JSON.parse(String(writes[0][1]?.body))
|
||||
expect(data).toEqual({ base_url: active.base_url, username: 'example', revision: 1 })
|
||||
expect(host.textContent).toContain('已保存并生效')
|
||||
expect(fetcher.mock.calls.every(([p]) => p.startsWith('/api/v1/pp-connection'))).toBe(true)
|
||||
})
|
||||
it('sends a newly entered password only on explicit replacement and clears it after save', async () => {
|
||||
await act(async () => root.render(<PPConnection />))
|
||||
await click('配置')
|
||||
await click('更新密码')
|
||||
await type('新密码', 'example-replacement')
|
||||
await click('保存并校验')
|
||||
const write = fetcher.mock.calls.find(([, i]) => i?.method === 'PUT')
|
||||
expect(JSON.parse(String(write?.[1]?.body)).password).toBe('example-replacement')
|
||||
expect(host.querySelector('input[type=password]')).toBeNull()
|
||||
expect(host.textContent).not.toContain('example-replacement')
|
||||
})
|
||||
})
|
||||
@@ -1,13 +0,0 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { PPConnection } from './PPConnection'
|
||||
describe('PP connection card', () => {
|
||||
it('starts with an observation gap and exposes configuration without inventing validity', () => {
|
||||
const html = renderToStaticMarkup(<PPConnection />)
|
||||
expect(html).toContain('PP 连接')
|
||||
expect(html).toContain('读取中')
|
||||
expect(html).toContain('配置')
|
||||
expect(html).not.toContain('认证有效')
|
||||
expect(html).not.toContain('公开只读可达')
|
||||
})
|
||||
})
|
||||
@@ -1,288 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
readPPConnection,
|
||||
savePPConnection,
|
||||
testPPConnection,
|
||||
type PPDraft,
|
||||
type PPObservation,
|
||||
type PPView,
|
||||
} from './ppConnection'
|
||||
import './PPConnection.css'
|
||||
const errorText = (e: unknown) => (e instanceof Error ? e.message : '请求失败,请重试')
|
||||
const when = (s: string) => new Date(s).toLocaleString('zh-CN', { hour12: false })
|
||||
export function PPConnection({ compact = false }: { compact?: boolean }) {
|
||||
const [view, setView] = useState<PPView | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [notice, setNotice] = useState('')
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [draft, setDraft] = useState<PPDraft>({ base_url: 'https://api.dobot.cn', username: '', revision: 0 })
|
||||
const [password, setPassword] = useState('')
|
||||
const [replacing, setReplacing] = useState(false)
|
||||
const [busy, setBusy] = useState('')
|
||||
const [tested, setTested] = useState<PPObservation | null>(null)
|
||||
const mounted = useRef(false)
|
||||
const sequence = useRef(0)
|
||||
const action = useRef<AbortController | null>(null)
|
||||
const formState = useRef({ editing: false, busy: '' })
|
||||
formState.current = { editing, busy }
|
||||
const load = useCallback(async () => {
|
||||
const current = ++sequence.current
|
||||
try {
|
||||
const next = await readPPConnection()
|
||||
if (mounted.current && sequence.current === current) {
|
||||
setView(next)
|
||||
setError('')
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted.current && sequence.current === current) setError(errorText(e))
|
||||
} finally {
|
||||
if (mounted.current && sequence.current === current) setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
mounted.current = true
|
||||
void load()
|
||||
const refresh = () => {
|
||||
if (!formState.current.editing && !formState.current.busy) void load()
|
||||
}
|
||||
window.addEventListener('pp-config-updated', refresh)
|
||||
return () => {
|
||||
mounted.current = false
|
||||
sequence.current++
|
||||
action.current?.abort()
|
||||
window.removeEventListener('pp-config-updated', refresh)
|
||||
}
|
||||
}, [load])
|
||||
const open = () => {
|
||||
if (!view) return
|
||||
const source = view.pending ?? view.active
|
||||
setDraft({
|
||||
base_url: source?.base_url ?? 'https://api.dobot.cn',
|
||||
username: source?.username ?? '',
|
||||
revision: view.revision,
|
||||
...(view.pending ? { pending_id: view.pending.id } : {}),
|
||||
})
|
||||
setPassword('')
|
||||
setReplacing(false)
|
||||
setTested(null)
|
||||
setNotice('')
|
||||
setError('')
|
||||
setEditing(true)
|
||||
}
|
||||
const resetTest = () => {
|
||||
setTested(null)
|
||||
setNotice('')
|
||||
}
|
||||
const run = async (save: boolean) => {
|
||||
if (!view) return
|
||||
setBusy(save ? 'saving' : 'testing')
|
||||
setError('')
|
||||
setNotice('')
|
||||
setTested(null)
|
||||
const controller = new AbortController()
|
||||
action.current = controller
|
||||
const current = ++sequence.current
|
||||
const payload: PPDraft = editing
|
||||
? { ...draft, ...(password ? { password } : {}) }
|
||||
: {
|
||||
base_url: view.active?.base_url ?? 'https://api.dobot.cn',
|
||||
username: view.active?.username ?? '',
|
||||
revision: view.revision,
|
||||
}
|
||||
try {
|
||||
if (save) {
|
||||
const next = await savePPConnection(payload, controller.signal)
|
||||
if (!mounted.current || sequence.current !== current) return
|
||||
setView(next)
|
||||
setPassword('')
|
||||
setReplacing(false)
|
||||
setEditing(false)
|
||||
setNotice(next.pending ? '修改已保存为待验证;原生效配置保留。' : 'PP 配置已保存并生效。')
|
||||
window.dispatchEvent(new Event('pp-config-updated'))
|
||||
} else {
|
||||
const result = await testPPConnection(payload, controller.signal)
|
||||
if (!mounted.current || sequence.current !== current) return
|
||||
setTested(result)
|
||||
const next = await readPPConnection(controller.signal)
|
||||
if (mounted.current && sequence.current === current) setView(next)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted && mounted.current && sequence.current === current) {
|
||||
setError(errorText(e))
|
||||
try {
|
||||
const next = await readPPConnection(controller.signal)
|
||||
if (mounted.current && sequence.current === current) setView(next)
|
||||
} catch {
|
||||
/* Keep the last observation with the visible error. */
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current && sequence.current === current) setBusy('')
|
||||
}
|
||||
}
|
||||
const observation = view?.observation
|
||||
const status = loading
|
||||
? '读取中…'
|
||||
: error && !view
|
||||
? '状态读取失败'
|
||||
: !view?.active
|
||||
? '未配置'
|
||||
: !observation
|
||||
? '未检查'
|
||||
: observation.state === 'valid'
|
||||
? '认证有效 · 目录可读'
|
||||
: observation.message
|
||||
return (
|
||||
<section className={`pp-connection${compact ? ' compact' : ''}`} aria-label="PP 连接">
|
||||
<div className="pp-heading">
|
||||
<h3>PP 连接</h3>
|
||||
<span className={observation?.state === 'valid' ? 'safe-badge' : 'pp-state'}>{status}</span>
|
||||
</div>
|
||||
{!editing && (
|
||||
<>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>API 地址</dt>
|
||||
<dd>{view?.active?.base_url || '未配置'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>账号</dt>
|
||||
<dd>{view?.active?.username || '未配置'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>密码</dt>
|
||||
<dd>{view?.active?.password_configured ? '已配置' : '未配置'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>最近检查</dt>
|
||||
<dd>{observation ? `${when(observation.checked_at)} · ${observation.message}` : '尚无检查记录'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{observation?.previous && (
|
||||
<p className="hint">
|
||||
上次结果(旧):{observation.previous.message} · {when(observation.previous.checked_at)}
|
||||
</p>
|
||||
)}
|
||||
{view?.pending && (
|
||||
<p className="hint">存在待验证修改;{view.active ? '当前仍使用原生效配置。' : '尚无生效配置。'}</p>
|
||||
)}
|
||||
<div className="pp-actions">
|
||||
<button type="button" disabled={!view || !!busy} onClick={open}>
|
||||
配置
|
||||
</button>
|
||||
<button type="button" disabled={!view || !!busy || !view.active} onClick={() => void run(false)}>
|
||||
{busy === 'testing' ? '正在检查…' : '测试连接'}
|
||||
</button>
|
||||
{error && (
|
||||
<button type="button" disabled={!!busy} onClick={() => void load()}>
|
||||
刷新状态
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{editing && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void run(true)
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
API 地址
|
||||
<input
|
||||
type="url"
|
||||
value={draft.base_url}
|
||||
disabled={!!busy}
|
||||
autoComplete="off"
|
||||
onChange={(e) => {
|
||||
setDraft({ ...draft, base_url: e.target.value })
|
||||
resetTest()
|
||||
}}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
账号
|
||||
<input
|
||||
value={draft.username}
|
||||
disabled={!!busy}
|
||||
autoComplete="off"
|
||||
onChange={(e) => {
|
||||
setDraft({ ...draft, username: e.target.value })
|
||||
resetTest()
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="pp-password">
|
||||
<span>密码:{(view?.pending ?? view?.active)?.password_configured ? '已配置' : '未配置'}</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!!busy}
|
||||
onClick={() => {
|
||||
setReplacing(!replacing)
|
||||
setPassword('')
|
||||
resetTest()
|
||||
}}
|
||||
>
|
||||
{replacing ? '保留已存密码' : '更新密码'}
|
||||
</button>
|
||||
</div>
|
||||
{replacing && (
|
||||
<label>
|
||||
新密码
|
||||
<input
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={password}
|
||||
disabled={!!busy}
|
||||
placeholder="留空保留已存密码"
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value)
|
||||
resetTest()
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<div className="pp-actions">
|
||||
<button
|
||||
type="button"
|
||||
disabled={!!busy}
|
||||
onClick={() => {
|
||||
setEditing(false)
|
||||
setPassword('')
|
||||
setTested(null)
|
||||
setError('')
|
||||
}}
|
||||
>
|
||||
取消修改
|
||||
</button>
|
||||
<button type="button" disabled={!!busy} onClick={() => void run(false)}>
|
||||
{busy === 'testing' ? '正在检查…' : '测试连接'}
|
||||
</button>
|
||||
<button type="submit" className="primary" disabled={!!busy}>
|
||||
{busy === 'saving' ? '正在校验…' : '保存并校验'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{tested && (
|
||||
<p role="status" className="pp-test-result">
|
||||
{editing ? '未保存配置测试:' : '当前配置检查:'}
|
||||
{tested.message}({when(tested.checked_at)})
|
||||
</p>
|
||||
)}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{error && (
|
||||
<p role="alert">
|
||||
{error}
|
||||
{view && ';上次读取的配置与检查结果仍保留。'}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
export function PPAuthorizationStep() {
|
||||
return <PPConnection compact />
|
||||
}
|
||||
@@ -65,7 +65,7 @@ describe('ProductionBindingsView', () => {
|
||||
it('旧文档级绑定标成旧路径,不再声称"发布写入此库"', () => {
|
||||
const html = view(bindings())
|
||||
expect(html).toContain('文档级发布(单篇文档写生产)· 旧路径')
|
||||
expect(html).toContain('整库封存/同步/恢复不读取这组配置')
|
||||
expect(html).toContain('仅文档级发布读取这组绑定;整库发布(封存/同步/恢复)不读它。')
|
||||
expect(html).toContain('对内文档级目标')
|
||||
expect(html).not.toContain('发布写入此库')
|
||||
})
|
||||
|
||||
@@ -103,9 +103,7 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
|
||||
</div>
|
||||
{error ? (
|
||||
<p className="error-message" role="alert">
|
||||
{/api key file/i.test(error)
|
||||
? '生产 API 读取凭据未配置:无法在此列出生产知识库。整库同步走独立执行器通道,不受这条读取凭据影响。'
|
||||
: error}
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{bindings ? (
|
||||
@@ -135,24 +133,19 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
|
||||
</div>
|
||||
) : null}
|
||||
{bindings ? (
|
||||
<details className="stack legacy-bindings">
|
||||
<summary>
|
||||
{bindings.legacy_scope || '文档级发布(单篇文档写生产)· 旧路径'}
|
||||
<span className="hint"> · 展开编辑;整库封存/同步/恢复不读取这组配置</span>
|
||||
</summary>
|
||||
<div className="stack">
|
||||
<h3>{bindings.legacy_scope || '文档级绑定(旧路径)'}</h3>
|
||||
<p className="hint">仅文档级发布读取这组绑定;整库发布(封存/同步/恢复)不读它。</p>
|
||||
<div className="kb-binding-grid">
|
||||
{renderSide('对内文档级目标', bindings.internal_kb_id, bindings.internal_kb_name)}
|
||||
{renderSide('对外文档级目标', bindings.external_kb_id, bindings.external_kb_name)}
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
) : null}
|
||||
{bindings && !bindings.production_connected ? (
|
||||
<p className="hint">
|
||||
生产端核对不可用:
|
||||
{/api key file/i.test(bindings.production_message)
|
||||
? '生产 API 读取凭据未配置(不影响整库执行器;整库同步走独立数据库/索引/存储通道)'
|
||||
: bindings.production_message}
|
||||
。{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''}
|
||||
生产端核对不可用:{bindings.production_message}。
|
||||
{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''}
|
||||
</p>
|
||||
) : null}
|
||||
{bindings && bindings.production_connected && bindings.production_base_url ? (
|
||||
@@ -163,8 +156,12 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
|
||||
) : null}
|
||||
{isAdmin && bindings ? (
|
||||
<div className="kb-binding-editor">
|
||||
<label>对内文档级目标 {editorFor(internalDraft, onInternalChange, '选择对内文档级目标库')}</label>
|
||||
<label>对外文档级目标 {editorFor(externalDraft, onExternalChange, '选择对外文档级目标库')}</label>
|
||||
<label>
|
||||
对内文档级目标 {editorFor(internalDraft, onInternalChange, '选择对内文档级目标库')}
|
||||
</label>
|
||||
<label>
|
||||
对外文档级目标 {editorFor(externalDraft, onExternalChange, '选择对外文档级目标库')}
|
||||
</label>
|
||||
<p className="hint">保存时只改文档级绑定;整库发布目标由部署配置决定,本页不改它。</p>
|
||||
<p className="hint">保存时会向生产端核对所选的库是否真实存在;对不上会拒收,生产端不可达则只提示。</p>
|
||||
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的生产知识库</p> : null}
|
||||
@@ -262,4 +259,4 @@ export function ProductionBindingsSection() {
|
||||
onReload={() => void load()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -288,7 +288,7 @@ export function QAAIWorkbench({
|
||||
{status ? (
|
||||
<small>
|
||||
{status.worker_ready ? '执行器在线' : '执行器未在线,任务会持久保留'}
|
||||
{!ready ? ';请先在系统设置 → AI 模型连接完成模型核验' : ''}
|
||||
{!ready ? ';请先在系统设置 → 服务配置完成模型核验' : ''}
|
||||
</small>
|
||||
) : (
|
||||
<small>读取后台状态…</small>
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ReleaseTargetsView } from './ReleaseTargets'
|
||||
import type { LibraryJobRecord, LibraryOverview, LibrarySnapshot } from './librarySnapshots'
|
||||
|
||||
// The existing mounted suite exercises transport races and owner-bound recovery.
|
||||
// This suite exercises the visible flow without authorizing any real operation.
|
||||
vi.mock('./RestoreVerificationSection', () => ({
|
||||
RestoreVerificationSection: () => <section aria-label="恢复验证">恢复验证入口</section>,
|
||||
}))
|
||||
|
||||
type Props = Parameters<typeof ReleaseTargetsView>[0]
|
||||
const snapshot: LibrarySnapshot = {
|
||||
snapshot_id: 'a'.repeat(64),
|
||||
scope: 'internal',
|
||||
knowledge_base_id: 'test-kb',
|
||||
tenant_id: 1,
|
||||
created_at: '2026-11-17T01:00:00Z',
|
||||
validation_policy: 'artifact-acceptance-v1',
|
||||
format: 'weknora-library-snapshot/v1',
|
||||
compatibility: {
|
||||
weknora_version: 'v0.9.0',
|
||||
schema_version: 134,
|
||||
retriever_engine: 'elasticsearch_v8',
|
||||
embedding_model: 'test-model',
|
||||
embedding_dimension: 1024,
|
||||
index_mapping_sha256: 'b'.repeat(64),
|
||||
},
|
||||
parts: [],
|
||||
logical_bytes: 0,
|
||||
unique_bytes: 0,
|
||||
shared_bytes: 0,
|
||||
totals: {},
|
||||
}
|
||||
const overview: LibraryOverview = {
|
||||
scope: 'internal',
|
||||
production: { state: 'unknown', empty_baseline: true },
|
||||
prebackup: { state: 'unknown' },
|
||||
diff: { state: 'computed', added: [], updated: [], removed: [] },
|
||||
gate: { sync_allowed: false, reasons: ['没有与目标快照匹配的有效发布授权'] },
|
||||
authorization: { state: 'none' },
|
||||
capture_available: true,
|
||||
jobs: [],
|
||||
now: '2026-11-17T01:00:00Z',
|
||||
}
|
||||
let props: Props
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
const draw = async (next: Partial<Props> = {}) => {
|
||||
props = { ...props, ...next }
|
||||
await act(async () => root.render(<ReleaseTargetsView {...props} />))
|
||||
}
|
||||
const primary = () => container.querySelector<HTMLButtonElement>('.rel-primary')!
|
||||
const details = (label: string) =>
|
||||
Array.from(container.querySelectorAll('details')).find((item) =>
|
||||
item.querySelector('summary')?.textContent?.startsWith(label)
|
||||
)!
|
||||
const click = async (element: HTMLElement) => {
|
||||
await act(async () => element.click())
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
props = {
|
||||
page: null,
|
||||
jobs: [],
|
||||
overview,
|
||||
loading: false,
|
||||
error: null,
|
||||
notice: null,
|
||||
scope: 'internal',
|
||||
onScope: vi.fn(),
|
||||
drawerOpen: false,
|
||||
onDrawer: vi.fn(),
|
||||
expandedSnapshot: null,
|
||||
onExpandSnapshot: vi.fn(),
|
||||
pendingCapture: false,
|
||||
canCapture: true,
|
||||
canWrite: true,
|
||||
canReconcileCapture: false,
|
||||
pendingReconcileCapture: '',
|
||||
onReconcileCapture: vi.fn(),
|
||||
sync: { canSign: true, pendingGrant: false, onGrant: vi.fn(), canStart: false, pending: false, onStart: vi.fn() },
|
||||
baseline: { canStart: false, pending: false, onStart: vi.fn() },
|
||||
verification: { onAccepted: vi.fn(), onComplete: vi.fn() },
|
||||
canRestore: false,
|
||||
restore: null,
|
||||
restoreNotice: null,
|
||||
pendingRestore: false,
|
||||
pendingGrant: false,
|
||||
onGrantRestore: vi.fn(),
|
||||
onRestore: vi.fn(),
|
||||
maintenance: null,
|
||||
now: 0,
|
||||
onRefresh: vi.fn(),
|
||||
onCapture: vi.fn(),
|
||||
onRecover: vi.fn(),
|
||||
}
|
||||
})
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount())
|
||||
container.remove()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('发布管理精简主流程', () => {
|
||||
it('同一挂载依次封存、授权、同步,每次点击只调用当前动作', async () => {
|
||||
await draw()
|
||||
expect(primary().textContent).toBe('封存测试版本')
|
||||
await click(primary())
|
||||
expect(props.onCapture).toHaveBeenCalledOnce()
|
||||
expect(props.sync.onGrant).not.toHaveBeenCalled()
|
||||
expect(props.sync.onStart).not.toHaveBeenCalled()
|
||||
await draw({ overview: { ...overview, test_sealed: snapshot } })
|
||||
expect(primary().textContent).toBe('签发同步授权(30 分钟)')
|
||||
await click(primary())
|
||||
expect(props.sync.onGrant).toHaveBeenCalledOnce()
|
||||
expect(props.sync.onStart).not.toHaveBeenCalled()
|
||||
await draw({
|
||||
overview: {
|
||||
...overview,
|
||||
test_sealed: snapshot,
|
||||
authorization: { state: 'active' },
|
||||
gate: { sync_allowed: true, reasons: [] },
|
||||
},
|
||||
sync: { ...props.sync, canStart: true },
|
||||
})
|
||||
expect(primary().textContent).toBe('▶ 启动同步')
|
||||
expect(primary().disabled).toBe(false)
|
||||
await click(primary())
|
||||
expect(props.sync.onStart).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('默认收起明细,展开和收起均不调用业务写入;历史只保留一个入口', async () => {
|
||||
await draw({ overview: { ...overview, test_sealed: snapshot } })
|
||||
expect(container.querySelectorAll('button').length).toBeGreaterThan(0)
|
||||
const history = Array.from(container.querySelectorAll('button')).filter((b) =>
|
||||
b.textContent?.includes('版本与快照')
|
||||
)
|
||||
expect(history).toHaveLength(1)
|
||||
for (const label of ['查看变更明细', '发布准备与恢复验证', '目标维护', '封存完整性']) {
|
||||
const panel = details(label)
|
||||
expect(panel.open).toBe(false)
|
||||
await click(panel.querySelector('summary')!)
|
||||
expect(panel.open).toBe(true)
|
||||
await click(panel.querySelector('summary')!)
|
||||
expect(panel.open).toBe(false)
|
||||
}
|
||||
await click(history[0])
|
||||
expect(props.onDrawer).toHaveBeenCalledWith(true)
|
||||
expect(props.onCapture).not.toHaveBeenCalled()
|
||||
expect(props.sync.onGrant).not.toHaveBeenCalled()
|
||||
expect(props.sync.onStart).not.toHaveBeenCalled()
|
||||
expect(props.onRestore).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('运行时只查看进度,不能再封存、授权或同步', async () => {
|
||||
const job: LibraryJobRecord = {
|
||||
id: 'job-1',
|
||||
scope: 'internal',
|
||||
kind: 'sync',
|
||||
state: 'running',
|
||||
stage: 'database',
|
||||
request_digest: '',
|
||||
queue_job_id: '',
|
||||
snapshot_id: '',
|
||||
target_snapshot_id: snapshot.snapshot_id,
|
||||
actor: 'test',
|
||||
error: '',
|
||||
recovery: '',
|
||||
created_at: overview.now,
|
||||
updated_at: overview.now,
|
||||
finished_at: null,
|
||||
stages: [],
|
||||
}
|
||||
await draw({
|
||||
overview: { ...overview, test_sealed: snapshot, job, jobs: [job] },
|
||||
sync: { ...props.sync, canStart: true },
|
||||
})
|
||||
expect(primary().textContent).toBe('查看当前任务')
|
||||
expect(container.textContent).not.toContain('重新封存')
|
||||
await click(primary())
|
||||
expect(props.onCapture).not.toHaveBeenCalled()
|
||||
expect(props.sync.onGrant).not.toHaveBeenCalled()
|
||||
expect(props.sync.onStart).not.toHaveBeenCalled()
|
||||
expect(details('查看执行明细').open).toBe(false)
|
||||
})
|
||||
|
||||
it('无作业不展示空进度,失败作业展开显示原始原因', async () => {
|
||||
await draw()
|
||||
expect(container.textContent).not.toContain('最近作业')
|
||||
const job: LibraryJobRecord = {
|
||||
id: 'job-failed',
|
||||
scope: 'internal',
|
||||
kind: 'sync',
|
||||
state: 'failed',
|
||||
stage: 'database',
|
||||
request_digest: '',
|
||||
queue_job_id: '',
|
||||
snapshot_id: '',
|
||||
target_snapshot_id: '',
|
||||
actor: 'test',
|
||||
error: '目标连接失败',
|
||||
recovery: '',
|
||||
created_at: overview.now,
|
||||
updated_at: overview.now,
|
||||
finished_at: overview.now,
|
||||
stages: [],
|
||||
}
|
||||
await draw({ overview: { ...overview, job, jobs: [job] } })
|
||||
expect(details('最近作业').open).toBe(true)
|
||||
expect(details('最近作业').textContent).toContain('目标连接失败')
|
||||
})
|
||||
|
||||
it('维护占用时自动展开,释放后恢复折叠;切库不沿用展开状态', async () => {
|
||||
await draw({ maintenance: { held: false } })
|
||||
expect(details('目标维护').open).toBe(false)
|
||||
await draw({ maintenance: { held: true } })
|
||||
expect(details('目标维护').open).toBe(true)
|
||||
await draw({ maintenance: { held: false } })
|
||||
expect(details('目标维护').open).toBe(false)
|
||||
await click(details('查看变更明细').querySelector('summary')!)
|
||||
expect(details('查看变更明细').open).toBe(true)
|
||||
const external = Array.from(container.querySelectorAll<HTMLButtonElement>('[role="tab"]'))[1]
|
||||
await click(external)
|
||||
expect(props.onScope).toHaveBeenCalledWith('external')
|
||||
await draw({ scope: 'external', overview: { ...overview, scope: 'external' } })
|
||||
expect(details('查看变更明细').open).toBe(false)
|
||||
expect(container.querySelector('[aria-selected="true"]')?.textContent).toContain('对外知识库')
|
||||
})
|
||||
|
||||
it('只读权限与刷新失败均不提供可执行主动作', async () => {
|
||||
await draw({ canWrite: false, canCapture: false })
|
||||
expect(primary().disabled).toBe(true)
|
||||
await click(primary())
|
||||
expect(props.onCapture).not.toHaveBeenCalled()
|
||||
await draw({ overview: { ...overview, test_sealed: snapshot }, sync: { ...props.sync, canSign: false } })
|
||||
expect(primary().textContent).toBe('等待管理员授权')
|
||||
expect(primary().disabled).toBe(true)
|
||||
await draw({ error: '网络中断', sync: { ...props.sync, canSign: true } })
|
||||
expect(primary().disabled).toBe(true)
|
||||
expect(container.textContent).toContain('网络中断')
|
||||
await click(primary())
|
||||
expect(props.sync.onGrant).not.toHaveBeenCalled()
|
||||
await draw({ canWrite: true, canCapture: true })
|
||||
const recapture = Array.from(container.querySelectorAll('button')).find(
|
||||
(button) => button.textContent === '重新封存'
|
||||
)!
|
||||
expect(recapture.disabled).toBe(true)
|
||||
await click(recapture)
|
||||
expect(props.onCapture).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -228,12 +228,10 @@ describe('ReleaseTargetsView(确认稿布局)', () => {
|
||||
|
||||
it('没有当前作业时不把历史封存当成阶段完成', () => {
|
||||
const html = render()
|
||||
// 阶段条第一段必须是 idle(○),"✓" 只允许出现在准备清单,不出现在阶段条
|
||||
const stageBar = html.slice(html.indexOf('aria-label="作业阶段"'), html.indexOf('rel-steps-note'))
|
||||
expect(stageBar).not.toContain('✓')
|
||||
expect(stageBar).toContain('本次作业尚未开始')
|
||||
expect(html).toContain('已有测试封存')
|
||||
expect(html).toContain('没有当前作业证据时不会把历史封存当作阶段完成')
|
||||
// 没有作业就不展示空进度,更不能将历史封存伪装成当前作业完成。
|
||||
expect(html).not.toContain('aria-label="作业阶段"')
|
||||
expect(html).not.toContain('启动后的作业进度')
|
||||
expect(html).toContain('尚未启动,不修改生产')
|
||||
})
|
||||
|
||||
it('差异已计算时按文档身份列增改撤销,并标注比对的两个版本', () => {
|
||||
@@ -895,7 +893,7 @@ describe('ReleaseTargetsView(确认稿布局)', () => {
|
||||
it('闸口全满足时“启动同步”真的可点,并给出执行说明', () => {
|
||||
const html = render({
|
||||
sync: { canSign: false, pendingGrant: false, onGrant: vi.fn(), canStart: true, pending: false, onStart: vi.fn() },
|
||||
overview: { ...overview, gate: { sync_allowed: true, reasons: [] } },
|
||||
overview: { ...overview, authorization: { state: 'active' }, gate: { sync_allowed: true, reasons: [] } },
|
||||
})
|
||||
expect(html).toMatch(/<button[^>]*class="rel-primary"[^>]*>▶ 启动同步/)
|
||||
expect(html).not.toMatch(/class="rel-primary"[^>]*disabled/)
|
||||
@@ -1060,7 +1058,7 @@ describe('生产目标四类状态:known / 空 / 非空 / 不可读', () => {
|
||||
expect(html).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/)
|
||||
})
|
||||
|
||||
it('空目标但没有测试封存:启动同步保持禁用并说明缺候选', () => {
|
||||
it('空目标但没有测试封存:主动作是封存,不提供启动同步', () => {
|
||||
const html = render({
|
||||
baseline,
|
||||
overview: {
|
||||
@@ -1070,7 +1068,8 @@ describe('生产目标四类状态:known / 空 / 非空 / 不可读', () => {
|
||||
test_sealed_reason: '还没有该目标的测试封存',
|
||||
},
|
||||
})
|
||||
expect(html).toMatch(/<button[^>]*class="rel-primary"[^>]*disabled/)
|
||||
expect(html).toMatch(/<button[^>]*class="rel-primary"[^>]*>封存测试版本/)
|
||||
expect(html).not.toContain('▶ 启动同步')
|
||||
expect(html).toContain('尚无测试封存')
|
||||
})
|
||||
})
|
||||
|
||||
+420
-426
File diff suppressed because it is too large
Load Diff
@@ -124,46 +124,22 @@ export function RoutingBindingsSection() {
|
||||
</p>
|
||||
) : null}
|
||||
{bindings ? (
|
||||
<>
|
||||
<div className="source-consistency" role="status" aria-label="入库目标与封存源对照">
|
||||
{(['internal', 'external'] as const).map((scope) => {
|
||||
const binding = scope === 'internal' ? bindings.internal_kb_id : bindings.external_kb_id
|
||||
const source =
|
||||
scope === 'internal' ? bindings.library_source_internal_kb : bindings.library_source_external_kb
|
||||
const state = scope === 'internal' ? bindings.internal_source_state : bindings.external_source_state
|
||||
return (
|
||||
<div key={scope} className={`source-consistency-row ${state}`}>
|
||||
<b>{scope === 'internal' ? '对内' : '对外'}</b>
|
||||
<span>入库目标 {binding ? `${binding.slice(0, 8)}…` : '未绑定'}</span>
|
||||
<span>封存源 {source ? `${source.slice(0, 8)}…` : '未配置(LIBRARY_SOURCE_KB_*)'}</span>
|
||||
<em>
|
||||
{state === 'consistent'
|
||||
? '一致'
|
||||
: state === 'mismatch'
|
||||
? '不一致:改绑定不会改封存源,封存仍导出旧库'
|
||||
: '未配置:整库封存无法定位来源'}
|
||||
</em>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="kb-binding-grid">
|
||||
{renderSide(
|
||||
'对内知识库',
|
||||
bindings.internal_kb_id,
|
||||
bindings.internal_kb_name,
|
||||
bindings.internal_env_fallback,
|
||||
bindings.internal_bound_by_ui
|
||||
)}
|
||||
{renderSide(
|
||||
'对外知识库',
|
||||
bindings.external_kb_id,
|
||||
bindings.external_kb_name,
|
||||
bindings.external_env_fallback,
|
||||
bindings.external_bound_by_ui
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
<div className="kb-binding-grid">
|
||||
{renderSide(
|
||||
'对内知识库',
|
||||
bindings.internal_kb_id,
|
||||
bindings.internal_kb_name,
|
||||
bindings.internal_env_fallback,
|
||||
bindings.internal_bound_by_ui
|
||||
)}
|
||||
{renderSide(
|
||||
'对外知识库',
|
||||
bindings.external_kb_id,
|
||||
bindings.external_kb_name,
|
||||
bindings.external_env_fallback,
|
||||
bindings.external_bound_by_ui
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
{bindings && !bindings.weknora_connected ? (
|
||||
<p className="hint">当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。</p>
|
||||
|
||||
@@ -20,39 +20,12 @@
|
||||
border-bottom: 0;
|
||||
}
|
||||
.source-account {
|
||||
border: 1px solid var(--border, #dce3eb);
|
||||
border-radius: 10px;
|
||||
padding: 16px;
|
||||
margin: 12px 0;
|
||||
background: var(--surface, #fff);
|
||||
margin: 0 0 14px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.dws-account-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.dws-account-heading strong {
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.dws-login-card {
|
||||
width: min(480px, calc(100vw - 40px));
|
||||
}
|
||||
.dws-authorize-link {
|
||||
display: inline-block;
|
||||
margin: 8px 0;
|
||||
}
|
||||
.dws-user-code {
|
||||
font-size: 18px;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
.dws-login-card .row-actions {
|
||||
margin-top: 20px;
|
||||
.source-account > button {
|
||||
padding: 5px 0;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.source-account-detail {
|
||||
padding: 12px 16px;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user