fix(datasource/dingtalk): Validate 不再因为某个工作区读不到就整库判失败 (#3782)

* fix(datasource/dingtalk): 多工作区租户里一个工作区读不到就整库判失败

Validate 原来在第一个读不到的工作区或文档上直接 return err。租户的
listWorkspaces 会返回组织内的全部工作区,而 operator 通常只被授权其中
一部分,于是"知识库里混了多个工作区、其中一个没权限"会被判成"凭据
错误",整库都建不起来,哪怕另一个工作区完全可读。

改为在循环里累计 lastErr / workspaceFail / sawDocument:某个工作区列不出
节点、或某个文档读不到,都只记录原因并 continue,不再中断;循环结束后
只有"一个能读的都没有"才报错。一个文档都没暴露的租户仍然放行——没有
可读之物就无法证伪凭据,只有"存在却读不到"才算问题。

文档探测抽成 verifyDocument,后续接入上传文件、表格时在这里加分支。

验证:
- 容器内 go build ./internal/...(仅第三方 sqlite-vec cgo 因环境缺
  sqlite3.h 失败)+ go test ./internal/datasource/... 全部通过
- 反向验证:把 Validate 还原成"第一个失败即返回"后,
  TestValidateSkipsWorkspacesTheOperatorCannotRead 与
  TestValidateSurvivesWorkspaceListingFailure 立即失败

* test(datasource/dingtalk): 钉住 Validate 收紧路径并修正 verifyDocument 注释

Validate 改成继续遍历所有工作区后,多出一条比改动前更严的失败路径:
"工作区 1 只有文件夹(可读)+ 工作区 2 有一个本 operator 读不到的文档"
这种配置,改动前在第一个工作区末尾就 return nil,现在会报错。这条路径是
有意的——存在却读不到的文档意味着数据源同步不出任何东西,不是无关工作区
的权限噪音——但之前没有任何测试。

新增 TestValidateRejectsTenantWhoseOnlyDocumentIsUnreadable 固定该行为与
意图;并给既有的"全部文档都读不到"用例补上"错误必须带工作区名/文档名"的
断言(原先只 Contains("no permission"))。

顺带把 verifyDocument 的注释从"上传文件与表格目前不可摄取、永远到不了
这个函数"改成描述不变量:只有 isDocument 接受的原生类型才会进入该函数,
一个类型获得摄取路径时同时成为 document、获得同步读路径并在该函数获得
探测,上传文件与表格随各自的摄取路径一起接入。原措辞在表格/上传 PR 合并
后即失效。

验证:
- go test ./internal/datasource/connector/dingtalk/... -count=1 通过
- 反向验证:把 Validate 换回改动前的实现(首个工作区无文档即 return nil)
  后,新用例失败并报 "Validate must fail";恢复后通过

* fix(datasource/dingtalk): Validate 每个工作区只探 1 个文档,并给探测总数加上限

应用缺少文档读权限时每次探测都会失败,原先会把每个工作区根目录下的每个文档
都串行探一遍,大租户里一次校验就是几百次调用。改为探测失败后直接跳到下一个
工作区,并且最多探测 maxValidateProbes(5) 个文档后返回最后一个错误。

* fix(datasource/dingtalk): Validate 进入文件夹找文档,根目录只有文件夹的工作区不再被误判

根目录只有文件夹、文件夹里有可读文档的工作区,原先会被另一个读不到的工作区拖累,
整体判失败(main 上这种情况是通过的)。Validate 现在按 scanWorkspace 的走法对
每个工作区做广度优先查找,取第一个文档探测;子文件夹列举共用 20 次额度,额度用尽
仍有文件夹没看完时视为无法证伪,直接通过。

* fix(datasource/dingtalk): Validate 子文件夹列举失败不再当空目录,并按页限额、防环

- 非根文件夹列举失败时把本次校验记为无法确定(放行),不再当成空目录导致
  另一个工作区的不可读文档把整库判死;取消/超时错误直接返回,不再被当成
  凭据有效,也不会被之前记下的 inconclusive 吞掉。
- BFS 加 visited 集合,子节点 ID 等于祖先或工作区根时不再无限列举。
- 新增 listNodesPage 单页列举,Validate 的列举额度按实际 HTTP 分页计数:
  节点列举请求最多 len(workspaces) + maxValidateListings 次(另加客户端重试)。

* fix(datasource/dingtalk): Validate 先翻完同层分页再进子文件夹,重复 nextToken 时停下

子文件夹排在父目录下一页之前时,根目录第一页全是文件夹、文档在第二页的
工作区会把列举额度花在子文件夹上,第二页的文档永远探不到。现在每个文件夹
先翻完自己的分页再下钻,和 listNodes 给 scanWorkspace 的顺序一致;同一
文件夹重复返回 nextToken 时停下并按无法确定处理。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: 🏠 <linus@192.168.10.6>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
linus-liu-web 2026-10-08 15:20:27 +08:00 committed by GitHub
parent ae90546262
commit bcbd65a459
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 829 additions and 28 deletions

View File

@ -121,6 +121,7 @@ func (n node) modifiedAt() time.Time {
type dingTalkAPI interface {
listWorkspaces(context.Context) ([]workspace, error)
listNodes(context.Context, string) ([]node, error)
listNodesPage(ctx context.Context, parentNodeID, pageToken string) ([]node, string, error)
documentBlocks(context.Context, string) ([]json.RawMessage, error)
}
@ -333,25 +334,12 @@ func (c *client) listNodes(ctx context.Context, parentNodeID string) ([]node, er
seenTokens := make(map[string]struct{})
for page := 0; page < maxPages; page++ {
query := url.Values{
"maxResults": {"50"},
"operatorId": {c.operator},
"parentNodeId": {parentNodeID},
nodes, next, err := c.listNodesPage(ctx, parentNodeID, nextToken)
if err != nil {
return nil, err
}
if nextToken != "" {
query.Set("nextToken", nextToken)
}
var response struct {
Nodes []node `json:"nodes"`
NextToken string `json:"nextToken"`
}
if err := c.doJSON(
ctx, http.MethodGet, "/v2.0/wiki/nodes?"+query.Encode(), nil, true, &response,
); err != nil {
return nil, fmt.Errorf("list DingTalk nodes: %w", err)
}
all = append(all, response.Nodes...)
nextToken = strings.TrimSpace(response.NextToken)
all = append(all, nodes...)
nextToken = next
if nextToken == "" {
return all, nil
}
@ -363,6 +351,30 @@ func (c *client) listNodes(ctx context.Context, parentNodeID string) ([]node, er
return nil, fmt.Errorf("DingTalk node pagination exceeded %d pages", maxPages)
}
// listNodesPage requests a single page of children, so one call is one HTTP
// request plus the client's own retries. An empty next token marks the last
// page.
func (c *client) listNodesPage(ctx context.Context, parentNodeID, pageToken string) ([]node, string, error) {
query := url.Values{
"maxResults": {"50"},
"operatorId": {c.operator},
"parentNodeId": {parentNodeID},
}
if pageToken != "" {
query.Set("nextToken", pageToken)
}
var response struct {
Nodes []node `json:"nodes"`
NextToken string `json:"nextToken"`
}
if err := c.doJSON(
ctx, http.MethodGet, "/v2.0/wiki/nodes?"+query.Encode(), nil, true, &response,
); err != nil {
return nil, "", fmt.Errorf("list DingTalk nodes: %w", err)
}
return response.Nodes, strings.TrimSpace(response.NextToken), nil
}
func (c *client) documentBlocks(ctx context.Context, documentID string) ([]json.RawMessage, error) {
const pageSize = 100
var all []json.RawMessage

View File

@ -99,8 +99,19 @@ func (c *Connector) Type() string {
return types.ConnectorTypeDingTalk
}
// maxValidateProbes caps how many documents Validate reads before giving up.
// An app missing the document read permission fails every probe, so without a
// cap a large tenant would turn one Validate into hundreds of serial calls.
const maxValidateProbes = 5
// Validate checks the application credentials and operator access, including
// node listing and a sample document read when one is visible at the workspace root.
// node listing and a sample document read when one is visible in a workspace.
//
// The operator is not expected to reach every workspace in the tenant: app
// credentials are valid as long as one reachable workspace yields one readable
// document. Reading the first document of the first workspace and failing on it
// rejects a working configuration whenever an unrelated workspace — one the
// operator was never granted — happens to be listed first.
func (c *Connector) Validate(ctx context.Context, dataSourceConfig *types.DataSourceConfig) error {
cfg, err := parseConfig(dataSourceConfig)
if err != nil {
@ -111,27 +122,157 @@ func (c *Connector) Validate(ctx context.Context, dataSourceConfig *types.DataSo
if err != nil {
return fmt.Errorf("validate DingTalk data source: %w", err)
}
var (
lastErr error
sawDocument bool
inconclusive bool
workspaceFail int
probes int
listings int
)
for _, item := range workspaces {
rootNodeID := strings.TrimSpace(item.RootNodeID)
if rootNodeID == "" {
continue
}
children, err := api.listNodes(ctx, rootNodeID)
document, found, unexplored, err := firstValidateDocument(ctx, api, rootNodeID, &listings)
if err != nil {
return fmt.Errorf("validate DingTalk data source: %w", err)
lastErr = fmt.Errorf("workspace %q: %w", item.Name, err)
// A cancelled or timed-out request proves nothing about the
// credentials, so it must never fall through to acceptance.
if ctx.Err() != nil || isContextError(err) {
return fmt.Errorf("validate DingTalk data source: %w", lastErr)
}
workspaceFail++
continue
}
for _, child := range children {
if !child.isDocument() {
continue
}
if _, err := api.documentBlocks(ctx, child.ID); err != nil {
return fmt.Errorf("validate DingTalk data source: %w", err)
if unexplored {
inconclusive = true
}
if !found {
continue
}
sawDocument = true
probes++
if err := verifyDocument(ctx, api, document); err != nil {
lastErr = fmt.Errorf("workspace %q document %q: %w", item.Name, document.Name, err)
if ctx.Err() != nil || isContextError(err) {
return fmt.Errorf("validate DingTalk data source: %w", lastErr)
}
} else {
return nil
}
if probes >= maxValidateProbes {
break
}
}
// Folders were left unexplored, because the listing budget ran out or a
// folder could not be listed, so an unreadable document elsewhere does not
// prove the data source is unusable.
if inconclusive {
return nil
}
return nil
// Nothing readable anywhere. Only a tenant that exposed no document at all
// is accepted: there was nothing to read, so credentials could not be
// disproved. A document that exists but cannot be read means the data
// source would sync nothing, which is worth reporting.
if !sawDocument && workspaceFail == 0 {
return nil
}
if lastErr == nil {
return nil
}
return fmt.Errorf("validate DingTalk data source: %w", lastErr)
}
// maxValidateListings caps the node listing pages Validate requests while
// looking for a document, shared by all workspaces. Each page is one HTTP
// request of up to 50 nodes, and only the first page of each workspace root is
// outside the budget, so the walk issues at most
// len(workspaces) + maxValidateListings node listing requests (plus the
// client's retries of each).
const maxValidateListings = 20
// firstValidateDocument walks a workspace breadth-first, the way scanWorkspace
// does, and returns the first document it finds. It requests one page at a
// time instead of listing whole folders, so the budget bounds real requests.
// unexplored reports that some nodes were never seen, because the budget ran
// out or a folder could not be listed, so the walk cannot prove the workspace
// holds no readable document.
func firstValidateDocument(
ctx context.Context, api dingTalkAPI, rootNodeID string, listings *int,
) (document node, found, unexplored bool, err error) {
queue := []string{rootNodeID}
visited := map[string]struct{}{rootNodeID: {}}
for len(queue) > 0 {
parent := queue[0]
queue = queue[1:]
// Finish every page of a folder before descending, like listNodes
// does for scanWorkspace: a document on a later page of this folder
// must be found before the budget is spent on its subfolders.
var subfolders []string
pageToken := ""
seenTokens := map[string]struct{}{}
for {
rootPage := parent == rootNodeID && pageToken == ""
if !rootPage {
if *listings >= maxValidateListings {
return node{}, false, true, nil
}
*listings++
}
children, next, listErr := api.listNodesPage(ctx, parent, pageToken)
if listErr != nil {
if rootPage || ctx.Err() != nil || isContextError(listErr) {
return node{}, false, false, listErr
}
// The documents this operator can read may live in exactly
// this folder, so its failure leaves the walk inconclusive
// rather than treating the folder as empty.
unexplored = true
break
}
for _, child := range children {
if child.isDocument() {
return child, true, unexplored, nil
}
if child.isFolder() || child.HasChildren {
if _, seen := visited[child.ID]; seen {
continue
}
visited[child.ID] = struct{}{}
subfolders = append(subfolders, child.ID)
}
}
if next == "" {
break
}
if _, repeated := seenTokens[next]; repeated {
// listNodes rejects a repeated nextToken; here the rest of the
// folder is simply unknown.
unexplored = true
break
}
seenTokens[next] = struct{}{}
pageToken = next
}
queue = append(queue, subfolders...)
}
return node{}, false, unexplored, nil
}
// verifyDocument proves one visible document is readable by calling the read
// API that backs its ingest path — the blocks API for adoc today. The caller
// only reaches this function for nodes isDocument accepts, and a native type
// becomes a document, gains a sync read path and gains its probe here in the
// same change. Types that are not ingestible yet are therefore not documents
// yet: uploaded files and native spreadsheets join all three together when
// their ingest paths land, instead of being probed here in advance.
func verifyDocument(ctx context.Context, api dingTalkAPI, document node) error {
_, err := api.documentBlocks(ctx, document.ID)
return err
}
// ListResources lazily lists selectable workspaces, folders and documents.

View File

@ -33,6 +33,12 @@ func (f *fakeAPI) listNodes(_ context.Context, parentID string) ([]node, error)
return f.nodes[parentID], nil
}
// listNodesPage serves every child of parentID as a single page.
func (f *fakeAPI) listNodesPage(ctx context.Context, parentID, _ string) ([]node, string, error) {
nodes, err := f.listNodes(ctx, parentID)
return nodes, "", err
}
func (f *fakeAPI) documentBlocks(_ context.Context, documentID string) ([]json.RawMessage, error) {
if f.blockCalls == nil {
f.blockCalls = make(map[string]int)

View File

@ -0,0 +1,642 @@
package dingtalk
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
)
// A tenant lists every workspace in the organisation, but the operator is only
// granted access to some of them. Validate must not fail because an unrelated,
// unreadable workspace happens to be returned first: app credentials are proven
// by one workspace that yields a readable document.
func TestValidateSkipsWorkspacesTheOperatorCannotRead(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{
{ID: "locked", RootNodeID: "root-locked", Name: "Locked"},
{ID: "open", RootNodeID: "root-open", Name: "Open"},
},
nodes: map[string][]node{
"root-locked": {
{ID: "doc-locked", Name: "Secret", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
"root-open": {
{ID: "doc-open", Name: "Public", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blocks: map[string][]json.RawMessage{
"doc-open": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
blockErrors: map[string]error{
"doc-locked": errors.New("forbidden.accessDenied: the operator has no permission"),
},
}
c := testConnector(api)
if err := c.Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must pass when a later workspace is readable, got: %v", err)
}
}
// The first workspace exposes no document at all, so nothing is proven there.
// A later workspace that does expose a readable document must still be tried.
func TestValidateKeepsLookingPastWorkspacesWithoutDocuments(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{
{ID: "empty", RootNodeID: "root-empty", Name: "Empty"},
{ID: "docs", RootNodeID: "root-docs", Name: "Docs"},
},
nodes: map[string][]node{
"root-empty": {
{ID: "folder", Name: "Folder", Type: "FOLDER"},
},
"root-docs": {
{ID: "doc", Name: "Handbook", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blocks: map[string][]json.RawMessage{
"doc": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
}
c := testConnector(api)
if err := c.Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must pass once a later workspace yields a document, got: %v", err)
}
}
// A workspace that only holds folders proves nothing: there was no document to
// read there. Validate must keep looking, and when the next workspace does hold
// a document the operator cannot read, the data source would sync nothing at
// all, so Validate must reject it.
//
// This is deliberately stricter than stopping at the first listed workspace: an
// unreadable document means an unusable data source, not an unrelated
// permission problem, so the failure must name that workspace and document.
func TestValidateRejectsTenantWhoseOnlyDocumentIsUnreadable(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{
{ID: "folders", RootNodeID: "root-folders", Name: "Folders"},
{ID: "locked", RootNodeID: "root-locked", Name: "Locked"},
},
nodes: map[string][]node{
"root-folders": {
{ID: "folder", Name: "Folder", Type: "FOLDER"},
},
"root-locked": {
{ID: "doc-locked", Name: "Secret", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blockErrors: map[string]error{
"doc-locked": errors.New("forbidden.accessDenied: the operator has no permission"),
},
}
c := testConnector(api)
err := c.Validate(context.Background(), testConfig())
if err == nil {
t.Fatal("Validate must fail: the only document in the tenant is unreadable, " +
"so the data source would sync nothing")
}
for _, want := range []string{`workspace "Locked"`, `document "Secret"`, "no permission"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("Validate error should carry %s, got: %v", want, err)
}
}
}
// Every visible document is unreadable, so the data source could never sync
// anything. That is worth reporting instead of accepting the credentials.
func TestValidateReportsWhenNoVisibleDocumentIsReadable(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{
{ID: "a", RootNodeID: "root-a", Name: "Alpha"},
{ID: "b", RootNodeID: "root-b", Name: "Beta"},
},
nodes: map[string][]node{
"root-a": {
{ID: "doc-a", Name: "Doc A", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
"root-b": {
{ID: "doc-b", Name: "Doc B", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blockErrors: map[string]error{
"doc-a": errors.New("forbidden.accessDenied: the operator has no permission"),
"doc-b": errors.New("forbidden.accessDenied: the operator has no permission"),
},
}
c := testConnector(api)
err := c.Validate(context.Background(), testConfig())
if err == nil {
t.Fatal("Validate must fail when no visible document can be read")
}
// The operator has to find the offending object in DingTalk, so the error
// names the workspace and the document of the last failed probe, not just
// the provider cause.
for _, want := range []string{`workspace "Beta"`, `document "Doc B"`, "no permission"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("Validate error should carry %s, got: %v", want, err)
}
}
}
// A tenant with no documents anywhere leaves nothing to read, so the
// credentials cannot be disproved and Validate accepts them.
func TestValidateAcceptsTenantWithoutDocuments(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "a", RootNodeID: "root-a", Name: "Alpha"}},
nodes: map[string][]node{
"root-a": {
{ID: "folder", Name: "Folder", Type: "FOLDER"},
},
},
}
c := testConnector(api)
if err := c.Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must accept a tenant that exposes no document, got: %v", err)
}
}
// A workspace whose node listing fails must not abort the whole validation
// while another workspace can still prove the credentials.
func TestValidateSurvivesWorkspaceListingFailure(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{
{ID: "broken", RootNodeID: "root-broken", Name: "Broken"},
{ID: "ok", RootNodeID: "root-ok", Name: "Ok"},
},
nodeErrors: map[string]error{
"root-broken": errors.New("DingTalk API status=500"),
},
nodes: map[string][]node{
"root-ok": {
{ID: "doc", Name: "Handbook", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blocks: map[string][]json.RawMessage{
"doc": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
}
c := testConnector(api)
if err := c.Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must survive one unlistable workspace, got: %v", err)
}
}
// An app without the document read permission fails every probe. Validate must
// probe at most one document per workspace and stop after maxValidateProbes,
// instead of firing one call per document across the whole tenant.
func TestValidateCapsProbesWhenEveryDocumentIsUnreadable(t *testing.T) {
api := &fakeAPI{
nodes: map[string][]node{},
blockErrors: map[string]error{},
}
denied := errors.New("forbidden.accessDenied: the operator has no permission")
workspaces := 3 * maxValidateProbes
for w := 0; w < workspaces; w++ {
root := fmt.Sprintf("root-%d", w)
api.workspaces = append(api.workspaces, workspace{ID: root, RootNodeID: root, Name: root})
for d := 0; d < 4; d++ {
id := fmt.Sprintf("doc-%d-%d", w, d)
api.nodes[root] = append(api.nodes[root],
node{ID: id, Name: id, Type: "FILE", Category: "ALIDOC", Extension: "adoc"})
api.blockErrors[id] = denied
}
}
c := testConnector(api)
if err := c.Validate(context.Background(), testConfig()); err == nil {
t.Fatal("Validate must fail when no visible document can be read")
}
total := 0
for _, n := range api.blockCalls {
total += n
}
if total > maxValidateProbes {
t.Fatalf("Validate made %d document probes, want at most %d", total, maxValidateProbes)
}
for w := 0; w < workspaces; w++ {
if api.blockCalls[fmt.Sprintf("doc-%d-1", w)] != 0 {
t.Fatalf("workspace root-%d was probed past its first document", w)
}
}
}
// listCountingAPI counts node listing calls so tests can bound the folder walk.
// Past limit, when set, every listing fails, so a walk that never terminates
// shows up as a failed assertion instead of a hung test.
type listCountingAPI struct {
*fakeAPI
listCalls int
limit int
}
func (a *listCountingAPI) count() error {
a.listCalls++
if a.limit > 0 && a.listCalls > a.limit {
return errors.New("listing limit exceeded")
}
return nil
}
func (a *listCountingAPI) listNodes(ctx context.Context, parentID string) ([]node, error) {
if err := a.count(); err != nil {
return nil, err
}
return a.fakeAPI.listNodes(ctx, parentID)
}
func (a *listCountingAPI) listNodesPage(ctx context.Context, parentID, pageToken string) ([]node, string, error) {
if err := a.count(); err != nil {
return nil, "", err
}
return a.fakeAPI.listNodesPage(ctx, parentID, pageToken)
}
// A workspace whose root holds only folders can still hold readable documents
// below them, and sync walks into folders to reach them. Validate must look
// there too instead of letting an unrelated unreadable workspace fail the data
// source, whichever order the workspaces are listed in.
func TestValidateFindsReadableDocumentBelowRootFolders(t *testing.T) {
team := workspace{ID: "team", RootNodeID: "root-team", Name: "Team"}
other := workspace{ID: "other", RootNodeID: "root-other", Name: "Other"}
denied := errors.New("forbidden.accessDenied: the operator has no permission")
cases := []struct {
name string
workspaces []workspace
nodeErrors map[string]error
}{
{name: "folder-only workspace first", workspaces: []workspace{team, other}},
{name: "folder-only workspace second", workspaces: []workspace{other, team}},
{
name: "other workspace unlistable",
workspaces: []workspace{team, other},
nodeErrors: map[string]error{"root-other": errors.New("DingTalk API status=500")},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
api := &fakeAPI{
workspaces: tc.workspaces,
nodes: map[string][]node{
"root-team": {
{ID: "folder", Name: "Folder", Type: "FOLDER"},
},
"folder": {
{ID: "doc-team", Name: "Handbook", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
"root-other": {
{ID: "doc-other", Name: "Secret", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
nodeErrors: tc.nodeErrors,
blocks: map[string][]json.RawMessage{
"doc-team": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
blockErrors: map[string]error{"doc-other": denied},
}
c := testConnector(api)
if err := c.Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must find the readable document below the root folder, got: %v", err)
}
if api.blockCalls["doc-team"] != 1 {
t.Fatalf("Validate should probe the document inside the folder, calls=%v", api.blockCalls)
}
})
}
}
// A workspace with a deep folder tree must not turn Validate into an unbounded
// walk. When the listing budget runs out with folders still unexplored, an
// unreadable document elsewhere proves nothing, so Validate accepts.
func TestValidateCapsFolderListingsAndAcceptsWhenInconclusive(t *testing.T) {
inner := &fakeAPI{
workspaces: []workspace{
{ID: "deep", RootNodeID: "root-deep", Name: "Deep"},
{ID: "locked", RootNodeID: "root-locked", Name: "Locked"},
},
nodes: map[string][]node{
"root-locked": {
{ID: "doc-locked", Name: "Secret", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blockErrors: map[string]error{
"doc-locked": errors.New("forbidden.accessDenied: the operator has no permission"),
},
}
parent := "root-deep"
for i := 0; i < 3*maxValidateListings; i++ {
id := fmt.Sprintf("folder-%d", i)
inner.nodes[parent] = []node{{ID: id, Name: id, Type: "FOLDER"}}
parent = id
}
api := &listCountingAPI{fakeAPI: inner}
c := testConnector(api)
if err := c.Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must accept when folders were left unexplored, got: %v", err)
}
// Each workspace root is listed once on top of the shared folder budget.
if limit := maxValidateListings + len(inner.workspaces); api.listCalls > limit {
t.Fatalf("Validate made %d listings, want at most %d", api.listCalls, limit)
}
}
// A folder that cannot be listed may be exactly where the operator's readable
// documents live, so it must not be treated as empty: an unreadable document
// in another workspace then proves nothing, whichever order they are listed in.
func TestValidateTreatsUnlistableFolderAsInconclusive(t *testing.T) {
team := workspace{ID: "team", RootNodeID: "root-team", Name: "Team"}
other := workspace{ID: "other", RootNodeID: "root-other", Name: "Other"}
for _, order := range [][]workspace{{team, other}, {other, team}} {
api := &fakeAPI{
workspaces: order,
nodes: map[string][]node{
"root-team": {
{ID: "folder", Name: "Folder", Type: "FOLDER"},
},
"root-other": {
{ID: "doc-other", Name: "Secret", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
nodeErrors: map[string]error{"folder": errors.New("DingTalk API status=500")},
blockErrors: map[string]error{
"doc-other": errors.New("forbidden.accessDenied: the operator has no permission"),
},
}
c := testConnector(api)
if err := c.Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate with workspace %s first must accept when a folder could not be listed, got: %v",
order[0].Name, err)
}
}
}
// A cancelled or timed-out listing proves nothing about the credentials, so
// Validate must report it instead of accepting the data source, including when
// an earlier workspace already left the walk inconclusive.
func TestValidateReturnsContextErrorsFromTheFolderWalk(t *testing.T) {
t.Run("subfolder listing times out", func(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "team", RootNodeID: "root-team", Name: "Team"}},
nodes: map[string][]node{
"root-team": {{ID: "folder", Name: "Folder", Type: "FOLDER"}},
},
nodeErrors: map[string]error{"folder": context.DeadlineExceeded},
}
err := testConnector(api).Validate(context.Background(), testConfig())
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Validate must return the timeout, got: %v", err)
}
})
t.Run("root listing cancelled after an inconclusive workspace", func(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{
{ID: "team", RootNodeID: "root-team", Name: "Team"},
{ID: "late", RootNodeID: "root-late", Name: "Late"},
},
nodes: map[string][]node{
"root-team": {{ID: "folder", Name: "Folder", Type: "FOLDER"}},
},
nodeErrors: map[string]error{
"folder": errors.New("DingTalk API status=500"),
"root-late": context.Canceled,
},
}
err := testConnector(api).Validate(context.Background(), testConfig())
if !errors.Is(err, context.Canceled) {
t.Fatalf("Validate must return the cancellation, got: %v", err)
}
})
t.Run("document probe times out after an inconclusive workspace", func(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{
{ID: "team", RootNodeID: "root-team", Name: "Team"},
{ID: "other", RootNodeID: "root-other", Name: "Other"},
},
nodes: map[string][]node{
"root-team": {{ID: "folder", Name: "Folder", Type: "FOLDER"}},
"root-other": {
{ID: "doc-other", Name: "Doc", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
nodeErrors: map[string]error{"folder": errors.New("DingTalk API status=500")},
blockErrors: map[string]error{"doc-other": context.DeadlineExceeded},
}
err := testConnector(api).Validate(context.Background(), testConfig())
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Validate must return the timeout, got: %v", err)
}
})
}
// DingTalk can list a folder, or the workspace root itself, among a node's
// children. The walk must list each folder once instead of repeating the same
// listings until the request is cancelled.
func TestValidateFolderWalkSurvivesCycles(t *testing.T) {
inner := &fakeAPI{
workspaces: []workspace{
{ID: "loop", RootNodeID: "root-loop", Name: "Loop"},
{ID: "locked", RootNodeID: "root-locked", Name: "Locked"},
},
nodes: map[string][]node{
"root-loop": {
{ID: "root-loop", Name: "Self", Type: "FOLDER"},
{ID: "folder", Name: "Folder", Type: "FOLDER"},
},
"folder": {
{ID: "root-loop", Name: "Parent", Type: "FOLDER"},
{ID: "folder", Name: "Self", Type: "FOLDER"},
},
"root-locked": {
{ID: "doc-locked", Name: "Secret", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blockErrors: map[string]error{
"doc-locked": errors.New("forbidden.accessDenied: the operator has no permission"),
},
}
api := &listCountingAPI{fakeAPI: inner, limit: 100}
err := testConnector(api).Validate(context.Background(), testConfig())
// root-loop, folder and root-locked are each listed exactly once.
if api.listCalls != 3 {
t.Fatalf("Validate made %d listings, want 3", api.listCalls)
}
// Every folder was explored, so the unreadable document is conclusive.
if err == nil || !strings.Contains(err.Error(), `document "Secret"`) {
t.Fatalf("Validate must report the unreadable document, got: %v", err)
}
}
// The listing budget must bound real HTTP requests: a folder can hold
// thousands of nodes served 50 per page, and listing it whole would turn one
// budget unit into hundreds of serial requests.
func TestValidateBudgetCountsNodeListingPages(t *testing.T) {
const folderPages = 200
cases := []struct {
name string
documentPage int // folder page holding a readable document; 0 for none
wantRequests int
}{
{name: "no document", wantRequests: 1 + maxValidateListings},
{name: "document on third page", documentPage: 3, wantRequests: 1 + 3},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var mu sync.Mutex
nodeRequests, blockRequests := 0, 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == "/v1.0/oauth2/accessToken":
_, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`))
case r.URL.Path == "/v2.0/wiki/workspaces":
_, _ = w.Write([]byte(`{"workspaces":[{"workspaceId":"a","rootNodeId":"root-a","name":"A"}]}`))
case r.URL.Path == "/v2.0/wiki/nodes":
mu.Lock()
nodeRequests++
mu.Unlock()
if r.URL.Query().Get("parentNodeId") == "root-a" {
_, _ = w.Write([]byte(`{"nodes":[{"nodeId":"folder","type":"FOLDER"}]}`))
return
}
page, _ := strconv.Atoi(r.URL.Query().Get("nextToken"))
page++
item := fmt.Sprintf(`{"nodeId":"pdf-%d","type":"FILE","category":"FILE","extension":"pdf"}`, page)
if page == tc.documentPage {
item = `{"nodeId":"doc","name":"Doc","type":"FILE","category":"ALIDOC","extension":"adoc"}`
}
next := ""
if page < folderPages {
next = strconv.Itoa(page)
}
_, _ = fmt.Fprintf(w, `{"nodes":[%s],"nextToken":%q}`, item, next)
case strings.HasPrefix(r.URL.Path, "/v1.0/doc/suites/documents/"):
mu.Lock()
blockRequests++
mu.Unlock()
_, _ = w.Write([]byte(`{"success":true,"result":{"data":[{"blockType":"paragraph"}]}}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
c := testConnector(testClient(server))
if err := c.Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must accept, got: %v", err)
}
mu.Lock()
defer mu.Unlock()
if nodeRequests != tc.wantRequests {
t.Fatalf("Validate made %d node listing requests, want %d", nodeRequests, tc.wantRequests)
}
if wantBlocks := min(tc.documentPage, 1); blockRequests != wantBlocks {
t.Fatalf("Validate made %d document probes, want %d", blockRequests, wantBlocks)
}
})
}
}
// A folder's later pages must be read before its subfolders: otherwise a root
// whose first page is all folders spends the budget below them and never sees
// the document on the root's second page.
func TestValidateReadsFolderPagesBeforeDescending(t *testing.T) {
var mu sync.Mutex
probed := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == "/v1.0/oauth2/accessToken":
_, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`))
case r.URL.Path == "/v2.0/wiki/workspaces":
_, _ = w.Write([]byte(`{"workspaces":[{"workspaceId":"a","rootNodeId":"root-a","name":"A"}]}`))
case r.URL.Path == "/v2.0/wiki/nodes":
parent := r.URL.Query().Get("parentNodeId")
switch {
case parent == "root-a" && r.URL.Query().Get("nextToken") == "":
folders := make([]string, 0, maxValidateListings)
for i := 0; i < maxValidateListings; i++ {
folders = append(folders, fmt.Sprintf(`{"nodeId":"folder-%d","type":"FOLDER"}`, i))
}
_, _ = fmt.Fprintf(w, `{"nodes":[%s],"nextToken":"p2"}`, strings.Join(folders, ","))
case parent == "root-a":
_, _ = w.Write([]byte(
`{"nodes":[{"nodeId":"doc","name":"Doc","type":"FILE","category":"ALIDOC","extension":"adoc"}]}`))
default:
_, _ = w.Write([]byte(`{"nodes":[{"nodeId":"pdf","type":"FILE","category":"FILE","extension":"pdf"}]}`))
}
case strings.HasPrefix(r.URL.Path, "/v1.0/doc/suites/documents/"):
mu.Lock()
probed = true
mu.Unlock()
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"code":"forbidden.accessDenied","message":"no permission"}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
err := testConnector(testClient(server)).Validate(context.Background(), testConfig())
mu.Lock()
defer mu.Unlock()
if !probed {
t.Fatalf("the document on the root's second page was never probed (err=%v)", err)
}
if err == nil {
t.Fatal("Validate must report the unreadable document instead of accepting")
}
}
// A folder that keeps returning the same nextToken must not be paged again
// until the budget runs out; the rest of it is unknown, so Validate accepts.
func TestValidateStopsOnRepeatedPageToken(t *testing.T) {
var mu sync.Mutex
folderRequests := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/v1.0/oauth2/accessToken":
_, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`))
case "/v2.0/wiki/workspaces":
_, _ = w.Write([]byte(`{"workspaces":[{"workspaceId":"a","rootNodeId":"root-a","name":"A"}]}`))
case "/v2.0/wiki/nodes":
if r.URL.Query().Get("parentNodeId") == "root-a" {
_, _ = w.Write([]byte(`{"nodes":[{"nodeId":"folder","type":"FOLDER"}]}`))
return
}
mu.Lock()
folderRequests++
mu.Unlock()
_, _ = w.Write([]byte(
`{"nodes":[{"nodeId":"pdf","type":"FILE","category":"FILE","extension":"pdf"}],"nextToken":"same"}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
if err := testConnector(testClient(server)).Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must accept an inconclusive walk, got: %v", err)
}
mu.Lock()
defer mu.Unlock()
if folderRequests != 2 {
t.Fatalf("folder was listed %d times, want 2 (first page + the repeated token once)", folderRequests)
}
}