feat(settings): 数据源配置改成「列出来、勾选、变成来源」,并去掉文件格式筛选
用户对 系统设置 → 数据源配置 的四条要求: ① 这里不要做文件格式筛选(格式归目录级标注决定); ② 列出我账号下能看到的知识库;③ 列出钉盘能看到哪些;④ 勾选那些作为来源。 ① 来源卡片不再渲染 FilenameFilterEditor(目录级筛选仍在「来源与目录」里,按目录就近覆盖)。 ②③ 新端点 GET /api/v1/dingtalk-spaces/available(管理员,只读):用 dws 列举 - 知识库:wiki +space-list --type orgWikiSpace/myWikiSpace(实测 17 + 1 个) - 钉盘:wiki space list --type mySpace/orgSpace(实测 我的文件 + 6 个组织空间) 实测约束写进命令形态:--limit 上限是 50;翻页必须 --page-all(--max-items 兜底), 否则超过一页的知识库会被静默截断(被截断时页面显示"可能不全"而不是假装列全)。 列不出来 ≠ 空列表:dws 未登录/权限不足 → 503 + 原因;某一类失败只丢那一类。 ④ 面板勾选后走既有登记路径(/api/v1/dingtalk-spaces),首次目录扫描自动排队; 已登记的按空间名标「已是来源」并禁用勾选;扫码会话失效时直接弹二维码,扫完自动重试。 基础设施:api 与 worker 共享同一份 dws 状态(bind mount 同一份,refresh token 是轮换制, 不能各留一份)。子进程 HOME 必须指向 DWS_HOME —— 这条是实测踩出来的:漏了会报"未登录", 已有回归测试钉住。dws 子进程沿用白名单环境,库口令等变量不进子进程。 测试:新包 internal/dingtalkdiscovery(fixture 用真实 dws 输出形状):paging 约束、 截断提示、一类失败不连带、全部失败→ErrUnavailable、子进程环境;httpapi 侧 401/501/503/500 与不泄漏内部错误;OpenAPI 契约(400/503 组件)通过。前端 189 条 + tsc 干净。 面板实测:知识库(18)/钉盘(7)都列出来,已有三条钉钉来源自动标「已是来源」; 勾选「视觉文档」→ 加入为来源 → 新来源 sc-8a4be5b8293d1c9a048c3c7e9b194155(dingtalk,enabled) + source.catalog.refresh 已完成。
This commit is contained in:
@@ -0,0 +1,233 @@
|
||||
// Package dingtalkdiscovery 用 dws CLI 枚举「我账号下能看到的数据源」:
|
||||
// 钉钉知识库(组织知识库 + 我的知识库)与钉盘空间(我的文件 / 组织空间)。
|
||||
//
|
||||
// 只读:本包只运行 dws 的列举命令并解析 JSON,不写任何远端对象,也不碰凭据值。
|
||||
//
|
||||
// 两条实测约束决定了命令形态:--limit 只能是 1-50;翻页必须靠 --page-all(带 --max-items
|
||||
// 兜底),否则超过一页的知识库会被静默截断。
|
||||
//
|
||||
// dws 的令牌是轮换制,因此运行它的进程必须与 worker 共享同一份状态目录(见 compose.yaml),
|
||||
// 且子进程的 HOME 必须指向 DWS_HOME(文件型 keychain 在 $HOME/.local/share/dws-cli)。
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// KnowledgeBase 是一个钉钉知识库(wiki 空间)。URL 是 alidocs 空间链接,直接可用于登记来源。
|
||||
type KnowledgeBase struct {
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
SpaceType string `json:"space_type"`
|
||||
URL string `json:"url"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
// DriveSpace 是一个钉盘空间(我的文件 = mySpace;组织空间 = orgSpace)。
|
||||
type DriveSpace struct {
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
RootFolderID string `json:"root_folder_id,omitempty"`
|
||||
SpaceType string `json:"space_type"`
|
||||
}
|
||||
|
||||
// Result 是一次发现的结果。
|
||||
type Result struct {
|
||||
KnowledgeBases []KnowledgeBase `json:"knowledge_bases"`
|
||||
DriveSpaces []DriveSpace `json:"drive_spaces"`
|
||||
// KnowledgeNotice / DriveNotice 说明「这一类为什么不全」:权限不足、未登录、或被上限截断。
|
||||
// 列不出某一类是常见状态(租户权限差异),页面照常显示能列出来的那部分,只在这里给原因。
|
||||
KnowledgeNotice string `json:"knowledge_notice,omitempty"`
|
||||
DriveNotice string `json:"drive_notice,omitempty"`
|
||||
FetchedAt time.Time `json:"fetched_at"`
|
||||
}
|
||||
|
||||
// Runner 执行一条 dws 命令并返回 stdout。实现要求:非零退出码也要把 stdout 交回
|
||||
// (dws 把错误 JSON 写在那里),并且超时即失败,绝不返回半截 JSON。
|
||||
type Runner interface {
|
||||
RunDWS(ctx context.Context, args ...string) ([]byte, error)
|
||||
}
|
||||
|
||||
// ErrUnavailable 表示 dws 不可用(二进制缺失、未登录、权限不足、输出不可解析):
|
||||
// 调用方应把它映射成「探测不可用」而不是 500 —— 这是环境问题,不是平台缺陷。
|
||||
var ErrUnavailable = errors.New("dws unavailable")
|
||||
|
||||
// knowledgeSpaceTypes 是知识库的两个范围:组织知识库与我的知识库。
|
||||
var knowledgeSpaceTypes = []string{"orgWikiSpace", "myWikiSpace"}
|
||||
|
||||
// SpaceListArgs 是知识库列举的固定命令形态:一次取完,最多 200 条(4 页 × 50)。
|
||||
func SpaceListArgs(spaceType string) []string {
|
||||
return []string{"wiki", "+space-list", "--type", spaceType, "--page-all", "--max-items", "200", "--page-limit", "4", "--limit", "50"}
|
||||
}
|
||||
|
||||
// Discover 枚举知识库与钉盘空间。
|
||||
//
|
||||
// 知识库整体列不出来 → 返回 ErrUnavailable(页面必须提示「列不出来」,不能装成空列表)。
|
||||
// 单独一类失败、钉盘失败、或结果被上限截断 → 只丢那一部分,把原因写进对应的 Notice。
|
||||
func Discover(ctx context.Context, runner Runner) (Result, 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, err))
|
||||
continue
|
||||
}
|
||||
bases, notice, err := parseKnowledgeBases(raw, spaceType)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
continue
|
||||
}
|
||||
if notice != "" {
|
||||
result.KnowledgeNotice = notice
|
||||
}
|
||||
for _, base := range bases {
|
||||
if seenKnowledge[base.SpaceID] {
|
||||
continue
|
||||
}
|
||||
seenKnowledge[base.SpaceID] = true
|
||||
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...), ";")
|
||||
}
|
||||
|
||||
seenDrive := map[string]bool{}
|
||||
for _, spaceType := range []string{"mySpace", "orgSpace"} {
|
||||
raw, err := runner.RunDWS(ctx, "wiki", "space", "list", "--type", spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = err.Error()
|
||||
continue
|
||||
}
|
||||
spaces, err := parseDriveSpaces(raw, spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = err.Error()
|
||||
continue
|
||||
}
|
||||
for _, space := range spaces {
|
||||
if seenDrive[space.SpaceType+":"+space.SpaceID] {
|
||||
continue
|
||||
}
|
||||
seenDrive[space.SpaceType+":"+space.SpaceID] = true
|
||||
result.DriveSpaces = append(result.DriveSpaces, space)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func describe(scope string, err error) string {
|
||||
return scope + ":" + err.Error()
|
||||
}
|
||||
|
||||
// parseKnowledgeBases 解析 `dws wiki +space-list`:
|
||||
// {"ok":true,"data":{"count":17,"hasMore":false,"autoPageComplete":true,"spaces":[{name,url,workspaceId}]}}
|
||||
// 第二个返回值是「结果不完整」的说明(被 --max-items 截断)。
|
||||
func parseKnowledgeBases(raw []byte, spaceType string) ([]KnowledgeBase, string, error) {
|
||||
var payload struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Count int `json:"count"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
AutoPageComplete bool `json:"autoPageComplete"`
|
||||
Spaces []struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
WorkspaceID string `json:"workspaceId"`
|
||||
Description string `json:"description"`
|
||||
} `json:"spaces"`
|
||||
} `json:"data"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return nil, "", fmt.Errorf("parse knowledge base list: %w", err)
|
||||
}
|
||||
if !payload.OK {
|
||||
message := "dws reported failure"
|
||||
if payload.Error != nil && payload.Error.Message != "" {
|
||||
message = payload.Error.Message
|
||||
}
|
||||
return nil, "", errors.New(message)
|
||||
}
|
||||
out := make([]KnowledgeBase, 0, len(payload.Data.Spaces))
|
||||
for _, space := range payload.Data.Spaces {
|
||||
name := strings.TrimSpace(space.Name)
|
||||
id := strings.TrimSpace(space.WorkspaceID)
|
||||
if name == "" || id == "" {
|
||||
continue
|
||||
}
|
||||
url := strings.TrimSpace(space.URL)
|
||||
if url == "" {
|
||||
url = SpaceURL(id)
|
||||
}
|
||||
out = append(out, KnowledgeBase{Name: name, SpaceID: id, SpaceType: spaceType, URL: url, Description: strings.TrimSpace(space.Description)})
|
||||
}
|
||||
notice := ""
|
||||
if payload.Data.HasMore && !payload.Data.AutoPageComplete {
|
||||
notice = fmt.Sprintf("%s 结果超过上限,只列出前 %d 个知识库。", spaceType, len(out))
|
||||
}
|
||||
return out, notice, nil
|
||||
}
|
||||
|
||||
// parseDriveSpaces 解析 `dws wiki space list --type …`:
|
||||
// {"success":true,"result":{"items":[{spaceId,spaceName,spaceType,rootFolderId}]}}
|
||||
func parseDriveSpaces(raw []byte, spaceType string) ([]DriveSpace, error) {
|
||||
var payload struct {
|
||||
Success bool `json:"success"`
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
ErrorCode string `json:"errorCode"`
|
||||
Result struct {
|
||||
Items []struct {
|
||||
SpaceID json.Number `json:"spaceId"`
|
||||
SpaceName string `json:"spaceName"`
|
||||
SpaceType string `json:"spaceType"`
|
||||
RootFolderID string `json:"rootFolderId"`
|
||||
} `json:"items"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return nil, fmt.Errorf("parse drive space list: %w", err)
|
||||
}
|
||||
if !payload.Success {
|
||||
message := strings.TrimSpace(payload.ErrorMsg)
|
||||
if message == "" {
|
||||
message = strings.TrimSpace(payload.ErrorCode)
|
||||
}
|
||||
if message == "" {
|
||||
message = "dws reported failure"
|
||||
}
|
||||
return nil, errors.New(message)
|
||||
}
|
||||
out := make([]DriveSpace, 0, len(payload.Result.Items))
|
||||
for _, item := range payload.Result.Items {
|
||||
name := strings.TrimSpace(item.SpaceName)
|
||||
id := strings.TrimSpace(item.SpaceID.String())
|
||||
if name == "" || id == "" {
|
||||
continue
|
||||
}
|
||||
kind := strings.TrimSpace(item.SpaceType)
|
||||
if kind == "" {
|
||||
kind = spaceType
|
||||
}
|
||||
out = append(out, DriveSpace{Name: name, SpaceID: id, SpaceType: kind, RootFolderID: strings.TrimSpace(item.RootFolderID)})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SpaceURL 由空间 id 拼出 alidocs 链接:登记来源走的就是这个形态。
|
||||
func SpaceURL(spaceID string) string {
|
||||
return "https://alidocs.dingtalk.com/i/spaces/" + spaceID + "/overview"
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeRunner 按命令行返回预设 stdout —— fixture 用的是 dws 真实输出形状(已实跑核对)。
|
||||
type fakeRunner struct {
|
||||
responses map[string]string
|
||||
failures map[string]error
|
||||
seen []string
|
||||
}
|
||||
|
||||
func (f *fakeRunner) RunDWS(_ context.Context, args ...string) ([]byte, error) {
|
||||
key := strings.Join(args, " ")
|
||||
f.seen = append(f.seen, key)
|
||||
if err, ok := f.failures[key]; ok {
|
||||
return nil, err
|
||||
}
|
||||
if body, ok := f.responses[key]; ok {
|
||||
return []byte(body), nil
|
||||
}
|
||||
return []byte(`{"ok":true,"data":{"spaces":[]}}`), nil
|
||||
}
|
||||
|
||||
func kbKey(spaceType string) string { return strings.Join(SpaceListArgs(spaceType), " ") }
|
||||
|
||||
const orgKnowledgeFixture = `{
|
||||
"ok": true,
|
||||
"outcome": "success",
|
||||
"data": {
|
||||
"autoPageComplete": true,
|
||||
"count": 3,
|
||||
"hasMore": false,
|
||||
"pagesFetched": 1,
|
||||
"requestedType": "orgWikiSpace",
|
||||
"spaces": [
|
||||
{"createTime": 1753837670187, "description": "", "name": "ATOM知识库",
|
||||
"url": "https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview", "workspaceId": "9JOGOQneRgkneX4Q"},
|
||||
{"createTime": 1770260286344, "description": "公司级知识库,是公司统一口径、可被 AI 使用、可持续维护的权威知识中心。",
|
||||
"name": "公司级技术支持知识库", "url": "https://alidocs.dingtalk.com/i/spaces/9JOGO6332vlBnm4Q/overview", "workspaceId": "9JOGO6332vlBnm4Q"},
|
||||
{"createTime": 1, "description": "", "name": "没有链接的空间", "url": "", "workspaceId": "9JOGO0000000000Q"}
|
||||
]
|
||||
}
|
||||
}`
|
||||
|
||||
const myKnowledgeFixture = `{"ok": true, "data": {"autoPageComplete": true, "count": 1, "hasMore": false, "requestedType": "myWikiSpace",
|
||||
"spaces": [{"description": "", "name": "我的文档", "url": "https://alidocs.dingtalk.com/i/spaces/9JOGOxeo90ybnz4Q/overview", "workspaceId": "9JOGOxeo90ybnz4Q"}]}}`
|
||||
|
||||
const mySpaceFixture = `{"success": true, "result": {"items": [
|
||||
{"createTime": 1768373459000, "modifyTime": 1768374168000, "rootFolderId": "65Y1OQX0akWmxN7DYGwUw8GlDd3mERZq",
|
||||
"spaceId": "28122692916", "spaceName": "我的文件", "spaceType": "mySpace"}
|
||||
]}}`
|
||||
|
||||
const orgSpaceFixture = `{"success": true, "result": {"items": [
|
||||
{"createTime": 1453221947000, "modifyTime": 1782304977000, "rootFolderId": "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a",
|
||||
"spaceId": "102571304", "spaceName": "全员文件夹", "spaceType": "orgSpace"},
|
||||
{"createTime": 1773248364000, "modifyTime": 1791620354000, "rootFolderId": "DElyQod3RxJKGnaQ61nIAJkb4Mw9r5vq",
|
||||
"spaceId": "28459418500", "spaceName": "公司级营销资料管理", "spaceType": "orgSpace"}
|
||||
]}}`
|
||||
|
||||
func fullRunner() *fakeRunner {
|
||||
return &fakeRunner{responses: map[string]string{
|
||||
kbKey("orgWikiSpace"): orgKnowledgeFixture,
|
||||
kbKey("myWikiSpace"): myKnowledgeFixture,
|
||||
"wiki space list --type mySpace": mySpaceFixture,
|
||||
"wiki space list --type orgSpace": orgSpaceFixture,
|
||||
}}
|
||||
}
|
||||
|
||||
func TestDiscoverParsesKnowledgeBasesAndDriveSpaces(t *testing.T) {
|
||||
runner := fullRunner()
|
||||
result, err := Discover(context.Background(), runner)
|
||||
if err != nil {
|
||||
t.Fatalf("discover: %v", err)
|
||||
}
|
||||
if len(result.KnowledgeBases) != 4 {
|
||||
t.Fatalf("knowledge bases = %d, want 4(组织 3 + 我的 1)", len(result.KnowledgeBases))
|
||||
}
|
||||
// 缺 url 的空间由空间 id 拼链接,保证勾选后仍能登记。
|
||||
missingURL := result.KnowledgeBases[2]
|
||||
if missingURL.URL != "https://alidocs.dingtalk.com/i/spaces/9JOGO0000000000Q/overview" {
|
||||
t.Fatalf("synthesised url = %q", missingURL.URL)
|
||||
}
|
||||
if result.KnowledgeBases[0].SpaceType != "orgWikiSpace" || result.KnowledgeBases[3].SpaceType != "myWikiSpace" {
|
||||
t.Fatalf("space types = %q / %q", result.KnowledgeBases[0].SpaceType, result.KnowledgeBases[3].SpaceType)
|
||||
}
|
||||
if len(result.DriveSpaces) != 3 {
|
||||
t.Fatalf("drive spaces = %d, want 3 (%+v)", len(result.DriveSpaces), result.DriveSpaces)
|
||||
}
|
||||
if result.DriveSpaces[1].SpaceType != "orgSpace" || result.DriveSpaces[1].RootFolderID == "" {
|
||||
t.Fatalf("org space = %+v", result.DriveSpaces[1])
|
||||
}
|
||||
if result.DriveNotice != "" || result.KnowledgeNotice != "" {
|
||||
t.Fatalf("unexpected notices: %q / %q", result.KnowledgeNotice, result.DriveNotice)
|
||||
}
|
||||
// 两条实测约束:--limit 上限是 50,且必须 --page-all,否则知识库会被静默截断。
|
||||
for _, call := range runner.seen {
|
||||
if strings.HasPrefix(call, "wiki +space-list") {
|
||||
if !strings.Contains(call, "--page-all") || !strings.Contains(call, "--limit 50") {
|
||||
t.Fatalf("knowledge list call misses paging constraints: %q", call)
|
||||
}
|
||||
if strings.Contains(call, "--limit 200") {
|
||||
t.Fatalf("--limit above the CLI cap is rejected at runtime: %q", call)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 钉盘列举被拒(租户权限)时,知识库必须照常返回,只带一条原因 —— 否则页面上什么都看不到。
|
||||
func TestDiscoverKeepsKnowledgeBasesWhenDriveIsDenied(t *testing.T) {
|
||||
runner := fullRunner()
|
||||
runner.failures = map[string]error{
|
||||
"wiki space list --type mySpace": errors.New("permission denied (operation: drive/list_spaces)"),
|
||||
"wiki space list --type orgSpace": errors.New("permission denied (operation: drive/list_spaces)"),
|
||||
}
|
||||
result, err := Discover(context.Background(), runner)
|
||||
if err != nil {
|
||||
t.Fatalf("discover should tolerate drive failure, got %v", err)
|
||||
}
|
||||
if len(result.KnowledgeBases) != 4 {
|
||||
t.Fatalf("knowledge bases = %d, want 4", len(result.KnowledgeBases))
|
||||
}
|
||||
if len(result.DriveSpaces) != 0 {
|
||||
t.Fatalf("drive spaces = %d, want 0", len(result.DriveSpaces))
|
||||
}
|
||||
if !strings.Contains(result.DriveNotice, "permission denied") {
|
||||
t.Fatalf("drive notice = %q", result.DriveNotice)
|
||||
}
|
||||
}
|
||||
|
||||
// 一类知识库失败(例如个人知识库无权限)不该连带组织知识库一起消失。
|
||||
func TestDiscoverKeepsOneKnowledgeScopeWhenTheOtherFails(t *testing.T) {
|
||||
runner := fullRunner()
|
||||
runner.failures = map[string]error{kbKey("myWikiSpace"): errors.New("[AUTH_PERMISSION_DENIED] Permission denied")}
|
||||
result, err := Discover(context.Background(), runner)
|
||||
if err != nil {
|
||||
t.Fatalf("discover: %v", err)
|
||||
}
|
||||
if len(result.KnowledgeBases) != 3 {
|
||||
t.Fatalf("knowledge bases = %d, want the org scope only", len(result.KnowledgeBases))
|
||||
}
|
||||
if !strings.Contains(result.KnowledgeNotice, "myWikiSpace") {
|
||||
t.Fatalf("notice should name the failed scope: %q", result.KnowledgeNotice)
|
||||
}
|
||||
}
|
||||
|
||||
// 被 --max-items 截断时必须留下提示,不能假装列出了全部。
|
||||
func TestDiscoverReportsTruncatedKnowledgeList(t *testing.T) {
|
||||
runner := fullRunner()
|
||||
runner.responses[kbKey("orgWikiSpace")] = `{"ok":true,"data":{"autoPageComplete":false,"count":50,"hasMore":true,
|
||||
"spaces":[{"name":"只列出一部分","url":"","workspaceId":"9JOGO1111111111Q"}]}}`
|
||||
result, err := Discover(context.Background(), runner)
|
||||
if err != nil {
|
||||
t.Fatalf("discover: %v", err)
|
||||
}
|
||||
if !strings.Contains(result.KnowledgeNotice, "上限") {
|
||||
t.Fatalf("expected a truncation notice, got %q", result.KnowledgeNotice)
|
||||
}
|
||||
}
|
||||
|
||||
// 知识库是主列表:两个范围都列不出来时按「环境不可用」上报,页面显示提示而不是空列表。
|
||||
func TestDiscoverReportsUnavailableWhenEveryKnowledgeScopeFails(t *testing.T) {
|
||||
for name, body := range map[string]string{
|
||||
"not logged in": `{"ok":false,"outcome":"failure","error":{"type":"auth","message":"dws: 未登录,请先执行 dws auth login"}}`,
|
||||
"permission": `{"ok":false,"outcome":"failure","error":{"type":"permission","message":"[AUTH_PERMISSION_DENIED] Permission denied"}}`,
|
||||
"garbage output": `not json at all`,
|
||||
"bad flag": `{"ok":false,"outcome":"failure","error":{"type":"internal","message":"--limit 必须是 1-50 之间的整数"}}`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{kbKey("orgWikiSpace"): body, kbKey("myWikiSpace"): body}}
|
||||
_, err := Discover(context.Background(), runner)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("err = %v, want ErrUnavailable", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverReportsUnavailableWhenDWSMissing(t *testing.T) {
|
||||
runner := &fakeRunner{failures: map[string]error{
|
||||
kbKey("orgWikiSpace"): errors.New("dws binary not found"),
|
||||
kbKey("myWikiSpace"): errors.New("dws binary not found"),
|
||||
}}
|
||||
_, err := Discover(context.Background(), runner)
|
||||
if !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("err = %v, want ErrUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpaceURL(t *testing.T) {
|
||||
if got := SpaceURL("ABC123"); got != "https://alidocs.dingtalk.com/i/spaces/ABC123/overview" {
|
||||
t.Fatalf("space url = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ExecRunner 是真的 dws 运行器。它只传 dws 需要的白名单环境(与取件器一致):
|
||||
// 漏掉 DWS_CONFIG_DIR / DWS_HOME 时 dws 会找不到配置目录与文件型 keychain,报"未登录"。
|
||||
type ExecRunner struct {
|
||||
// Binary 是 dws 可执行文件;空值取 DWS_BIN,再取 PATH 里的 dws。
|
||||
Binary string
|
||||
// Timeout 单条命令超时;为零取 25 秒。
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
if binary == "" {
|
||||
found, err := exec.LookPath("dws")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dws binary not found: %w", err)
|
||||
}
|
||||
binary = found
|
||||
}
|
||||
timeout := r.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 25 * time.Second
|
||||
}
|
||||
runCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
command := exec.CommandContext(runCtx, binary, args...)
|
||||
command.Env = dwsEnv()
|
||||
var stdout, stderr bytes.Buffer
|
||||
command.Stdout = &stdout
|
||||
command.Stderr = &stderr
|
||||
if err := command.Run(); err != nil {
|
||||
// 退出码非零时 dws 仍会把错误 JSON 写在 stdout 上,保留它便于上层判定。
|
||||
if stdout.Len() > 0 {
|
||||
return stdout.Bytes(), fmt.Errorf("dws %s: %w", strings.Join(args, " "), err)
|
||||
}
|
||||
message := strings.TrimSpace(stderr.String())
|
||||
if message == "" {
|
||||
message = err.Error()
|
||||
}
|
||||
return nil, fmt.Errorf("dws %s: %s", strings.Join(args, " "), message)
|
||||
}
|
||||
return stdout.Bytes(), nil
|
||||
}
|
||||
|
||||
// dwsEnv 是给 dws 子进程的环境白名单:不把平台的库口令等变量带进子进程。
|
||||
func dwsEnv() []string {
|
||||
env := make([]string, 0, 8)
|
||||
for _, name := range []string{"PATH", "SSL_CERT_FILE", "LANG"} {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
env = append(env, name+"="+value)
|
||||
}
|
||||
}
|
||||
// dws 的文件型 keychain 固定在 $HOME/.local/share/dws-cli,而 keychain 是挂在 DWS_HOME
|
||||
// 下面的(容器自身的 HOME 指向别处)。因此只给 dws 子进程换 HOME,不动整个进程。
|
||||
home := os.Getenv("DWS_HOME")
|
||||
if home == "" {
|
||||
home = os.Getenv("HOME")
|
||||
}
|
||||
if home != "" {
|
||||
env = append(env, "HOME="+home)
|
||||
}
|
||||
for _, name := range []string{"DWS_BIN", "DWS_CONFIG_DIR", "DWS_HOME", "DWS_DISABLE_KEYCHAIN"} {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
env = append(env, name+"="+value)
|
||||
}
|
||||
}
|
||||
return env
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// dws 的文件型 keychain 固定在 $HOME/.local/share/dws-cli,而 keychain 挂在 DWS_HOME 下面;
|
||||
// 子进程若沿用容器自身的 HOME 就会报"未登录"。这条断言把该行为钉住(实测踩过)。
|
||||
func TestDWSEnvPutsTheKeychainHomeOnTheDWSHome(t *testing.T) {
|
||||
t.Setenv("DWS_HOME", "/data/home")
|
||||
t.Setenv("HOME", "/home/app")
|
||||
t.Setenv("DWS_CONFIG_DIR", "/data/dws")
|
||||
t.Setenv("DWS_DISABLE_KEYCHAIN", "1")
|
||||
t.Setenv("DWS_BIN", "/usr/local/bin/dws")
|
||||
t.Setenv("DATABASE_URL", "postgres://governance:secret@postgres/governance")
|
||||
t.Setenv("TEST_WEKNORA_API_KEY", "sk-should-not-leak")
|
||||
|
||||
env := dwsEnv()
|
||||
joined := strings.Join(env, "\n")
|
||||
if !strings.Contains(joined, "HOME=/data/home") {
|
||||
t.Fatalf("dws child HOME should follow DWS_HOME, env=%v", env)
|
||||
}
|
||||
if strings.Contains(joined, "HOME=/home/app") {
|
||||
t.Fatalf("container HOME leaked into dws child: %v", env)
|
||||
}
|
||||
for _, leaked := range []string{"DATABASE_URL", "TEST_WEKNORA_API_KEY"} {
|
||||
if strings.Contains(joined, leaked) {
|
||||
t.Fatalf("%s leaked into the dws child: %v", leaked, env)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 没有 DWS_HOME 时退回进程自己的 HOME。
|
||||
func TestDWSEnvFallsBackToProcessHome(t *testing.T) {
|
||||
t.Setenv("DWS_HOME", "")
|
||||
t.Setenv("HOME", "/home/app")
|
||||
if joined := strings.Join(dwsEnv(), "\n"); !strings.Contains(joined, "HOME=/home/app") {
|
||||
t.Fatalf("expected fallback HOME, got %v", dwsEnv())
|
||||
}
|
||||
}
|
||||
|
||||
// 真跑一个假的 dws:确认参数被原样传给二进制,且非零退出码时仍把 stdout 交回上层
|
||||
// (dws 把错误 JSON 写在 stdout 上,丢了它就没法分辨"未登录"与"权限不足")。
|
||||
func TestExecRunnerRunsTheBinaryAndKeepsStdoutOnFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
binary := filepath.Join(dir, "dws")
|
||||
script := "#!/bin/sh\necho \"args:$@\"\necho '{\"ok\":false,\"error\":{\"message\":\"dws: 未登录\"}}'\nexit 4\n"
|
||||
if err := os.WriteFile(binary, []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := ExecRunner{Binary: binary, Timeout: 5 * time.Second}
|
||||
out, err := runner.RunDWS(context.Background(), "wiki", "+space-list", "--limit", "200")
|
||||
if err == nil {
|
||||
t.Fatal("expected a non-zero exit to be reported")
|
||||
}
|
||||
if !strings.Contains(string(out), "未登录") {
|
||||
t.Fatalf("stdout should be preserved on failure, got %q", string(out))
|
||||
}
|
||||
if !strings.Contains(string(out), "args:wiki +space-list --limit 200") {
|
||||
t.Fatalf("args not passed through: %q", string(out))
|
||||
}
|
||||
if !strings.Contains(err.Error(), "wiki +space-list") {
|
||||
t.Fatalf("error should name the command: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
// dingtalkSourcesLister 是本路由需要的最小能力面:枚举「我账号下能看到」的钉钉知识库与
|
||||
// 钉盘空间。真实实现由 cmd/api 注入(用 worker 同一份 dws 状态跑只读列举);
|
||||
// 未接线时返回 501,而不是把"没接线"当成空列表。
|
||||
type dingtalkSourcesLister interface {
|
||||
ListAvailableDingtalkSources(context.Context) (dingtalkdiscovery.Result, error)
|
||||
}
|
||||
|
||||
// listDingtalkSources 处理 GET /api/v1/dingtalk-spaces/available:
|
||||
// 「系统设置 → 数据源配置」用它列出可勾选为来源的钉钉知识库与钉盘空间。
|
||||
//
|
||||
// 走 /api/v1/dingtalk-spaces 前缀是刻意的:该前缀在角色判定里是管理员专用(与扫码会话、
|
||||
// 空间登记同级),因为这里用的是平台持有的钉钉凭据读租户目录。
|
||||
func listDingtalkSources(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
lister := config.DingtalkSources
|
||||
if lister == nil {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
|
||||
// 环境问题(dws 未登录 / 权限不足 / 二进制缺失):页面显示"暂时列不出来",
|
||||
// 不是平台故障,也不该把内部错误细节当 500 抛出去。
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"error": "dingtalk_discovery_unavailable",
|
||||
"hint": "dws 未登录或缺少租户目录读权限;请先刷新钉钉会话,或让管理员检查 dws 凭据。",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list dingtalk sources"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": result})
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
type fakeDingtalkSources struct {
|
||||
result dingtalkdiscovery.Result
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeDingtalkSources) ListAvailableDingtalkSources(context.Context) (dingtalkdiscovery.Result, error) {
|
||||
return f.result, f.err
|
||||
}
|
||||
|
||||
func dingtalkSourcesRequest(role string) *http.Request {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/dingtalk-spaces/available", nil)
|
||||
if role == "" {
|
||||
return request
|
||||
}
|
||||
return request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role}))
|
||||
}
|
||||
|
||||
func TestListDingtalkSourcesRequiresAdminAndWiring(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
listDingtalkSources(rec, dingtalkSourcesRequest(""), Config{})
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthenticated = %d, want 401", rec.Code)
|
||||
}
|
||||
|
||||
// 未接线:501("没接线"不能被当成空列表)。
|
||||
rec = httptest.NewRecorder()
|
||||
listDingtalkSources(rec, dingtalkSourcesRequest(roleAdmin), Config{})
|
||||
if rec.Code != http.StatusNotImplemented {
|
||||
t.Fatalf("unwired = %d, want 501 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDingtalkSourcesReportsEnvironmentProblemsAsUnavailable(t *testing.T) {
|
||||
// 用包装错误模拟真实映射:errors.Is 必须认出来,页面才会显示"暂时列不出来"。
|
||||
config := Config{DingtalkSources: fakeDingtalkSources{err: wrapUnavailable()}}
|
||||
rec := httptest.NewRecorder()
|
||||
listDingtalkSources(rec, dingtalkSourcesRequest(roleAdmin), config)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("unavailable = %d, want 503 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), "dingtalk_discovery_unavailable") {
|
||||
t.Fatalf("body = %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func wrapUnavailable() error {
|
||||
return &wrappedUnavailable{err: dingtalkdiscovery.ErrUnavailable}
|
||||
}
|
||||
|
||||
type wrappedUnavailable struct{ err error }
|
||||
|
||||
func (w *wrappedUnavailable) Error() string { return "list knowledge bases: " + w.err.Error() }
|
||||
func (w *wrappedUnavailable) Unwrap() error { return w.err }
|
||||
|
||||
func TestListDingtalkSourcesReturnsKnowledgeBasesAndDriveSpaces(t *testing.T) {
|
||||
config := Config{DingtalkSources: fakeDingtalkSources{result: dingtalkdiscovery.Result{
|
||||
KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "ATOM知识库", SpaceID: "9JOGOQneRgkneX4Q", URL: "https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview"}},
|
||||
DriveSpaces: []dingtalkdiscovery.DriveSpace{{Name: "全员文件夹", SpaceID: "102571304", SpaceType: "orgSpace"}},
|
||||
DriveNotice: "list orgSpace: permission denied",
|
||||
FetchedAt: time.Date(2026, 10, 10, 8, 0, 0, 0, time.UTC),
|
||||
}}}
|
||||
rec := httptest.NewRecorder()
|
||||
listDingtalkSources(rec, dingtalkSourcesRequest(roleAdmin), config)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
Data struct {
|
||||
KnowledgeBases []struct {
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
URL string `json:"url"`
|
||||
} `json:"knowledge_bases"`
|
||||
DriveSpaces []struct {
|
||||
Name string `json:"name"`
|
||||
SpaceType string `json:"space_type"`
|
||||
} `json:"drive_spaces"`
|
||||
DriveNotice string `json:"drive_notice"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(payload.Data.KnowledgeBases) != 1 || payload.Data.KnowledgeBases[0].Name != "ATOM知识库" {
|
||||
t.Fatalf("knowledge bases = %+v", payload.Data.KnowledgeBases)
|
||||
}
|
||||
if len(payload.Data.DriveSpaces) != 1 || payload.Data.DriveSpaces[0].SpaceType != "orgSpace" {
|
||||
t.Fatalf("drive spaces = %+v", payload.Data.DriveSpaces)
|
||||
}
|
||||
if payload.Data.DriveNotice == "" {
|
||||
t.Fatal("drive notice should be relayed so the page can explain why 钉盘 is missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDingtalkSourcesHidesInternalErrors(t *testing.T) {
|
||||
config := Config{DingtalkSources: fakeDingtalkSources{err: errors.New("internal detail: connection string leaked")}}
|
||||
rec := httptest.NewRecorder()
|
||||
listDingtalkSources(rec, dingtalkSourcesRequest(roleAdmin), config)
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "connection string") {
|
||||
t.Fatalf("internal error leaked: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,9 @@ type Config struct {
|
||||
ProductionBackupRestoreVerified bool
|
||||
ProductionReleaseAuthorizerRef string
|
||||
ProductionReleaseAuthorizationToken string
|
||||
// DingtalkSources 枚举「我账号下能看到」的钉钉知识库与钉盘空间(只读,dws)。
|
||||
// 未接线时对应路由返回 501,页面显示"列不出来"而不是空列表。
|
||||
DingtalkSources dingtalkSourcesLister
|
||||
NewID func() (string, error)
|
||||
Auth *AuthConfig
|
||||
}
|
||||
@@ -348,6 +351,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /api/v1/dingtalk-spaces", func(w http.ResponseWriter, r *http.Request) {
|
||||
registerDingtalkSpace(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/dingtalk-spaces/available", func(w http.ResponseWriter, r *http.Request) {
|
||||
listDingtalkSources(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/dingtalk-session/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
getDingtalkSession(w, r)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user