Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

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

linus-liu-webbcbd65a459e9
diff --git a/internal/datasource/connector/dingtalk/client.go b/internal/datasource/connector/dingtalk/client.go
index f2f34e88f..57bc998b1 100644
--- a/internal/datasource/connector/dingtalk/client.go
+++ b/internal/datasource/connector/dingtalk/client.go
@@ -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},
- }
- 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)
+ nodes, next, err := c.listNodesPage(ctx, parentNodeID, nextToken)
+ if err != nil {
+ return nil, 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
diff --git a/internal/datasource/connector/dingtalk/connector.go b/internal/datasource/connector/dingtalk/connector.go
index bd0fed8ec..976a952f1 100644
--- a/internal/datasource/connector/dingtalk/connector.go
+++ b/internal/datasource/connector/dingtalk/connector.go
@@ -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)
- }
- for _, child := range children {
- if !child.isDocument() {
- continue
+ 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)
}
- if _, err := api.documentBlocks(ctx, child.ID); err != nil {
- return fmt.Errorf("validate DingTalk data source: %w", err)
+ workspaceFail++
+ continue
+ }
+ 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
+ }
+
+ // 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 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.
diff --git a/internal/datasource/connector/dingtalk/connector_test.go b/internal/datasource/connector/dingtalk/connector_test.go
index cfd3e182d..f70734a89 100644
--- a/internal/datasource/connector/dingtalk/connector_test.go
+++ b/internal/datasource/connector/dingtalk/connector_test.go
@@ -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)
diff --git a/internal/datasource/connector/dingtalk/validate_test.go b/internal/datasource/connector/dingtalk/validate_test.go
new file mode 100644
index 000000000..86ac79c63
--- /dev/null
+++ b/internal/datasource/connector/dingtalk/validate_test.go
@@ -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)
+ }
+}