chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,812 @@
// Package dingtalk implements the DingTalk document data source connector.
package dingtalk
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"academy/internal/datasource"
"academy/internal/types"
)
const (
apiBaseURL = "https://api.dingtalk.com"
apiTimeout = 30 * time.Second
maxResponseBytes = 16 << 20
maxPages = 1000
maxAttempts = 3
// downloadTimeout is deliberately longer than apiTimeout: the JSON calls
// are small, while an uploaded document can be several megabytes.
downloadTimeout = 5 * time.Minute
// maxDocumentBytes bounds a single uploaded file transfer. DingTalk lists a
// "size" per node that does not match the stored object, so the cap is
// enforced on the transfer itself instead of on listing metadata.
maxDocumentBytes = 64 << 20
)
type config struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
OperatorID string `json:"operator_id"`
}
func parseConfig(dataSourceConfig *types.DataSourceConfig) (*config, error) {
if dataSourceConfig == nil {
return nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig)
}
raw, err := json.Marshal(dataSourceConfig.Credentials)
if err != nil {
return nil, fmt.Errorf("%w: marshal DingTalk credentials: %v",
datasource.ErrInvalidCredentials, err)
}
var cfg config
if err := json.Unmarshal(raw, &cfg); err != nil {
return nil, fmt.Errorf("%w: decode DingTalk credentials: %v",
datasource.ErrInvalidCredentials, err)
}
cfg.ClientID = strings.TrimSpace(cfg.ClientID)
cfg.ClientSecret = strings.TrimSpace(cfg.ClientSecret)
cfg.OperatorID = strings.TrimSpace(cfg.OperatorID)
switch {
case cfg.ClientID == "":
return nil, fmt.Errorf("%w: client_id is required", datasource.ErrInvalidCredentials)
case cfg.ClientSecret == "":
return nil, fmt.Errorf("%w: client_secret is required", datasource.ErrInvalidCredentials)
case cfg.OperatorID == "":
return nil, fmt.Errorf("%w: operator_id is required", datasource.ErrInvalidCredentials)
}
return &cfg, nil
}
type workspace struct {
ID string `json:"workspaceId"`
RootNodeID string `json:"rootNodeId"`
Name string `json:"name"`
Description string `json:"description"`
URL string `json:"url"`
ModifiedTime string `json:"modifiedTime"`
}
type node struct {
ID string `json:"nodeId"`
WorkspaceID string `json:"workspaceId"`
Name string `json:"name"`
Type string `json:"type"`
Category string `json:"category"`
Extension string `json:"extension"`
URL string `json:"url"`
ModifiedTime string `json:"modifiedTime"`
ModifiedTimestamp int64 `json:"modifiedTimestamp"`
HasChildren bool `json:"hasChildren"`
}
// binaryDocumentTypes maps the extension of an uploaded DingTalk file to the
// MIME type Academy stores it under. Only formats Academy can parse are listed;
// native ALIDOC files have their own online read APIs and are absent on
// purpose, as are media files that would be pointless to index as text.
var binaryDocumentTypes = map[string]string{
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"pdf": "application/pdf",
}
func (n node) isFolder() bool {
return strings.EqualFold(n.Type, "FOLDER")
}
// isOnlineDocument reports whether the node is a native DingTalk document whose
// blocks can be read through the doc suites API.
func (n node) isOnlineDocument() bool {
return strings.EqualFold(n.Type, "FILE") &&
strings.EqualFold(n.Category, "ALIDOC") &&
strings.EqualFold(n.Extension, "adoc")
}
// binaryContentType returns the MIME type of an uploaded file node. Uploaded
// files are listed as DOCUMENT; ALIDOC covers DingTalk's own document family,
// which is never downloaded as a file.
func (n node) binaryContentType() (string, bool) {
if !strings.EqualFold(n.Type, "FILE") || !strings.EqualFold(n.Category, "DOCUMENT") {
return "", false
}
contentType, ok := binaryDocumentTypes[strings.ToLower(strings.TrimSpace(n.Extension))]
return contentType, ok
}
// isBinaryDocument reports whether the node is an uploaded file this connector
// can download and hand to Academy's own parsers.
func (n node) isBinaryDocument() bool {
_, ok := n.binaryContentType()
return ok
}
// isDocument reports whether the connector has a read path for the node at all:
// a native adoc document through the blocks API, or an uploaded file through
// the storage download API. Whether a given data source takes it is
// isIngestible's answer, because an upload is guarded by its own switch.
func (n node) isDocument() bool {
return n.isOnlineDocument() || n.isBinaryDocument()
}
// isIngestible reports whether this data source ingests the node: a read path
// must exist and the switch guarding it must be on. Validate, the resource
// picker and both sync modes select nodes through this one predicate, so a
// switch that is off is off in every one of them.
func (n node) isIngestible(settings documentSettings) bool {
if n.isOnlineDocument() {
return true
}
return settings.IncludeUploadedFiles && n.isBinaryDocument()
}
func (n node) title() string {
if title := strings.TrimSpace(n.Name); title != "" {
return title
}
return n.ID
}
func (n node) revision() string {
// Prefer the millisecond timestamp when present. Official node listings
// also return modifiedTime at minute precision (e.g. 2023-05-15T11:29Z),
// which would skip same-minute edits during incremental sync.
if n.ModifiedTimestamp > 0 {
return strconv.FormatInt(n.ModifiedTimestamp, 10)
}
return strings.TrimSpace(n.ModifiedTime)
}
func (n node) modifiedAt() time.Time {
if n.ModifiedTimestamp > 0 {
return time.UnixMilli(n.ModifiedTimestamp)
}
return parseDingTalkTime(n.ModifiedTime)
}
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)
// verifyDocumentDownload proves an uploaded file is downloadable without
// transferring its body, so validation stays cheap for multi-megabyte files.
verifyDocumentDownload(context.Context, string) error
downloadDocument(context.Context, string) ([]byte, error)
}
type client struct {
baseURL string
operator string
appKey string
appSecret string
http *http.Client
sleep func(context.Context, time.Duration) error
// fileHTTP transfers document bytes. It is separate from http so a large
// download is not bound by the short control-plane timeout.
fileHTTP *http.Client
// downloadLimit overrides maxDocumentBytes; zero means the default.
downloadLimit int64
token string
tokenExpiry time.Time
}
func newClient(cfg *config) *client {
return &client{
baseURL: apiBaseURL,
operator: cfg.OperatorID,
appKey: cfg.ClientID,
appSecret: cfg.ClientSecret,
http: datasource.NewConnectorHTTPClient(apiTimeout),
fileHTTP: datasource.NewConnectorHTTPClient(downloadTimeout),
sleep: sleepContext,
}
}
// transferHTTP returns the client used for byte transfers.
func (c *client) transferHTTP() *http.Client {
if c.fileHTTP != nil {
return c.fileHTTP
}
return c.http
}
// maxDownloadBytes returns the effective per-document size cap.
func (c *client) maxDownloadBytes() int64 {
if c.downloadLimit > 0 {
return c.downloadLimit
}
return maxDocumentBytes
}
type accessTokenResponse struct {
AccessToken string `json:"accessToken"`
ExpireIn int64 `json:"expireIn"`
}
func (c *client) accessToken(ctx context.Context) (string, error) {
if c.token != "" && time.Now().Before(c.tokenExpiry) {
return c.token, nil
}
var response accessTokenResponse
err := c.doJSON(ctx, http.MethodPost, "/v1.0/oauth2/accessToken", map[string]string{
"appKey": c.appKey,
"appSecret": c.appSecret,
}, false, &response)
if err != nil {
return "", fmt.Errorf("get DingTalk access token: %w", err)
}
response.AccessToken = strings.TrimSpace(response.AccessToken)
if response.AccessToken == "" {
return "", fmt.Errorf("%w: DingTalk returned an empty access token", datasource.ErrInvalidCredentials)
}
ttl := time.Duration(response.ExpireIn) * time.Second
if ttl <= 0 {
ttl = 90 * time.Minute
}
if ttl > 5*time.Minute {
ttl -= 5 * time.Minute
}
c.token = response.AccessToken
c.tokenExpiry = time.Now().Add(ttl)
return c.token, nil
}
func (c *client) doJSON(
ctx context.Context,
method, path string,
requestBody any,
authenticated bool,
result any,
) error {
var payload []byte
var err error
if requestBody != nil {
payload, err = json.Marshal(requestBody)
if err != nil {
return fmt.Errorf("encode DingTalk request: %w", err)
}
}
refreshed := false
retryAttempt := 0
for {
var body io.Reader
if payload != nil {
body = bytes.NewReader(payload)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
if err != nil {
return fmt.Errorf("create DingTalk request: %w", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
var token string
if authenticated {
token, err = c.accessToken(ctx)
if err != nil {
return err
}
req.Header.Set("x-acs-dingtalk-access-token", token)
}
resp, err := c.http.Do(req)
if err != nil {
requestErr := redactRequestError(err)
if retryAttempt+1 < maxAttempts && !isContextError(requestErr) {
delay := retryDelay(retryAttempt)
retryAttempt++
if err := c.wait(ctx, delay); err != nil {
return err
}
continue
}
return fmt.Errorf("execute DingTalk request: %w", requestErr)
}
responseBody, readErr := readBody(resp.Body)
_ = resp.Body.Close()
if readErr != nil {
return fmt.Errorf("read DingTalk response: %w", readErr)
}
if authenticated && resp.StatusCode == http.StatusUnauthorized && !refreshed {
if c.token == token {
c.token = ""
c.tokenExpiry = time.Time{}
}
refreshed = true
continue
}
if isTransient(resp.StatusCode) {
apiErr := c.redactAPIError(decodeAPIError(resp.StatusCode, responseBody))
if retryAttempt+1 < maxAttempts {
delay := retryDelay(retryAttempt)
if resp.StatusCode == http.StatusTooManyRequests {
delay = parseRetryAfter(resp.Header.Get("Retry-After"), delay)
}
retryAttempt++
if err := c.wait(ctx, delay); err != nil {
return err
}
continue
}
return apiErr
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
apiErr := c.redactAPIError(decodeAPIError(resp.StatusCode, responseBody))
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
return fmt.Errorf("%w: %w", datasource.ErrInvalidCredentials, apiErr)
}
return apiErr
}
if result != nil && len(responseBody) > 0 {
if err := json.Unmarshal(responseBody, result); err != nil {
return fmt.Errorf("decode DingTalk response: %w", err)
}
}
return nil
}
}
func (c *client) redactAPIError(err error) error {
message := err.Error()
for _, sensitive := range []string{c.appKey, c.appSecret, c.operator, c.token} {
if sensitive != "" {
message = strings.ReplaceAll(message, sensitive, "[REDACTED]")
}
}
return errors.New(message)
}
func (c *client) listWorkspaces(ctx context.Context) ([]workspace, error) {
var all []workspace
nextToken := ""
seenTokens := make(map[string]struct{})
for page := 0; page < maxPages; page++ {
query := url.Values{
"maxResults": {"30"},
"operatorId": {c.operator},
}
if nextToken != "" {
query.Set("nextToken", nextToken)
}
var response struct {
Workspaces []workspace `json:"workspaces"`
NextToken string `json:"nextToken"`
}
if err := c.doJSON(
ctx, http.MethodGet, "/v2.0/wiki/workspaces?"+query.Encode(), nil, true, &response,
); err != nil {
return nil, fmt.Errorf("list DingTalk workspaces: %w", err)
}
all = append(all, response.Workspaces...)
nextToken = strings.TrimSpace(response.NextToken)
if nextToken == "" {
return all, nil
}
if _, exists := seenTokens[nextToken]; exists {
return nil, errors.New("DingTalk workspace pagination repeated nextToken")
}
seenTokens[nextToken] = struct{}{}
}
return nil, fmt.Errorf("DingTalk workspace pagination exceeded %d pages", maxPages)
}
func (c *client) listNodes(ctx context.Context, parentNodeID string) ([]node, error) {
var all []node
nextToken := ""
seenTokens := make(map[string]struct{})
for page := 0; page < maxPages; page++ {
nodes, next, err := c.listNodesPage(ctx, parentNodeID, nextToken)
if err != nil {
return nil, err
}
all = append(all, nodes...)
nextToken = next
if nextToken == "" {
return all, nil
}
if _, exists := seenTokens[nextToken]; exists {
return nil, errors.New("DingTalk node pagination repeated nextToken")
}
seenTokens[nextToken] = struct{}{}
}
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
for page := 0; page < maxPages; page++ {
start := page * pageSize
query := url.Values{
"endIndex": {strconv.Itoa(start + pageSize - 1)},
"operatorId": {c.operator},
"startIndex": {strconv.Itoa(start)},
}
var response struct {
Success *bool `json:"success"`
Result *struct {
Data []json.RawMessage `json:"data"`
} `json:"result"`
}
path := "/v1.0/doc/suites/documents/" + url.PathEscape(documentID) +
"/blocks?" + query.Encode()
if err := c.doJSON(ctx, http.MethodGet, path, nil, true, &response); err != nil {
return nil, fmt.Errorf("query DingTalk document blocks: %w", err)
}
if response.Success == nil || !*response.Success || response.Result == nil {
return nil, errors.New("DingTalk document blocks request was unsuccessful")
}
all = append(all, response.Result.Data...)
if len(response.Result.Data) < pageSize {
return all, nil
}
}
return nil, fmt.Errorf("DingTalk document block pagination exceeded %d pages", maxPages)
}
// dentryRef identifies one file inside 钉盘. Wiki node IDs are UUIDs, but the
// storage APIs accept only the numeric spaceId/dentryId pair, so every upload
// is translated first. Response shape:
//
// {"dentryId":"<numeric>","spaceId":"<numeric>","dentryUuid":"<uuid>"}
type dentryRef struct {
DentryID string `json:"dentryId"`
SpaceID string `json:"spaceId"`
DentryUUID string `json:"dentryUuid"`
}
// resolveDentry maps a wiki node UUID to its 钉盘 storage identifiers.
func (c *client) resolveDentry(ctx context.Context, documentID string) (dentryRef, error) {
query := url.Values{"operatorId": {c.operator}}
path := "/v2.0/doc/dentries/" + url.PathEscape(documentID) +
"/queryDentryId?" + query.Encode()
var ref dentryRef
if err := c.doJSON(ctx, http.MethodGet, path, nil, true, &ref); err != nil {
return dentryRef{}, fmt.Errorf("resolve DingTalk document location: %w", err)
}
ref.DentryID = strings.TrimSpace(ref.DentryID)
ref.SpaceID = strings.TrimSpace(ref.SpaceID)
if ref.DentryID == "" || ref.SpaceID == "" {
return dentryRef{}, errors.New("DingTalk returned no storage location for the document")
}
return ref, nil
}
// downloadTarget is a short-lived pre-signed URL for one document version.
type downloadTarget struct {
URL string
Headers map[string]string
}
type downloadInfoResponse struct {
Protocol string `json:"protocol"`
HeaderSignatureInfo *struct {
Headers map[string]string `json:"headers"`
ResourceURLs []string `json:"resourceUrls"`
ExpirationSeconds int64 `json:"expirationSeconds"`
} `json:"headerSignatureInfo"`
}
// requestDownloadURL asks the storage API for a pre-signed download URL.
// preferIntranet stays false so the URL is reachable from outside DingTalk's
// own network.
func (c *client) requestDownloadURL(ctx context.Context, ref dentryRef) (downloadTarget, error) {
query := url.Values{"unionId": {c.operator}}
path := "/v1.0/storage/spaces/" + url.PathEscape(ref.SpaceID) +
"/dentries/" + url.PathEscape(ref.DentryID) + "/downloadInfos/query?" + query.Encode()
body := map[string]interface{}{
"option": map[string]interface{}{"version": 1, "preferIntranet": false},
}
var response downloadInfoResponse
if err := c.doJSON(ctx, http.MethodPost, path, body, true, &response); err != nil {
return downloadTarget{}, fmt.Errorf("query DingTalk download URL: %w", err)
}
info := response.HeaderSignatureInfo
if info == nil || len(info.ResourceURLs) == 0 {
return downloadTarget{}, fmt.Errorf(
"DingTalk returned no download URL for the document (protocol %q)",
strings.TrimSpace(response.Protocol))
}
target := downloadTarget{
URL: strings.TrimSpace(info.ResourceURLs[0]),
Headers: info.Headers,
}
if target.URL == "" {
return downloadTarget{}, errors.New("DingTalk returned an empty download URL")
}
return target, nil
}
// verifyDocumentDownload proves an uploaded file is reachable end to end
// without transferring its body: the node must resolve to a storage location
// and yield a pre-signed URL. Validate uses this so credentials can be checked
// without downloading several megabytes per attempt.
func (c *client) verifyDocumentDownload(ctx context.Context, documentID string) error {
ref, err := c.resolveDentry(ctx, documentID)
if err != nil {
return err
}
_, err = c.requestDownloadURL(ctx, ref)
return err
}
// downloadDocument fetches the raw bytes of an uploaded document. The pre-signed
// URL is versioned and short lived, so it is re-requested whenever a transfer
// attempt fails in a way a fresh signature could fix.
func (c *client) downloadDocument(ctx context.Context, documentID string) ([]byte, error) {
ref, err := c.resolveDentry(ctx, documentID)
if err != nil {
return nil, err
}
var lastErr error
for attempt := 0; attempt < maxAttempts; attempt++ {
if attempt > 0 {
if err := c.wait(ctx, retryDelay(attempt-1)); err != nil {
return nil, err
}
}
target, err := c.requestDownloadURL(ctx, ref)
if err != nil {
return nil, err
}
data, retryable, err := c.fetchSigned(ctx, target)
if err == nil {
return data, nil
}
lastErr = err
if !retryable || isContextError(err) {
return nil, err
}
}
return nil, lastErr
}
// fetchSigned transfers a document body from a pre-signed URL. It reports
// whether the failure is worth retrying with a freshly signed URL.
func (c *client) fetchSigned(ctx context.Context, target downloadTarget) ([]byte, bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.URL, nil)
if err != nil {
return nil, false, fmt.Errorf("create DingTalk download request: %w", err)
}
for name, value := range target.Headers {
req.Header.Set(name, value)
}
// The signature covers the object as stored. Asking for an identity
// encoding keeps a proxy from re-encoding the bytes into an unparseable
// document.
req.Header.Set("Accept-Encoding", "identity")
resp, err := c.transferHTTP().Do(req)
if err != nil {
return nil, true, fmt.Errorf("download DingTalk document: %w", redactRequestError(err))
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
// Object-store failures are small XML bodies. Only a bounded prefix is
// read, and decodeAPIError never echoes the body verbatim.
detail, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
retryable := isTransient(resp.StatusCode) ||
resp.StatusCode == http.StatusUnauthorized ||
resp.StatusCode == http.StatusForbidden ||
resp.StatusCode == http.StatusNotFound
return nil, retryable, fmt.Errorf(
"download DingTalk document: %w", decodeAPIError(resp.StatusCode, detail))
}
limit := c.maxDownloadBytes()
if resp.ContentLength > limit {
return nil, false, fmt.Errorf(
"%w: %d bytes announced, limit is %d bytes",
errDocumentTooLarge, resp.ContentLength, limit)
}
data, err := readLimited(resp.Body, limit)
if err != nil {
if errors.Is(err, errDocumentTooLarge) {
return nil, false, fmt.Errorf("download DingTalk document: %w", err)
}
return nil, true, fmt.Errorf("read DingTalk document: %w", err)
}
return data, false, nil
}
// errDocumentTooLarge marks a document whose transfer passed the configured
// size cap. The size is a property of the stored object rather than a transient
// failure — a freshly signed URL returns the very same bytes — so a caller must
// not retry it.
var errDocumentTooLarge = errors.New("document exceeds the download limit")
// readLimited reads at most limit bytes and fails when the body is longer, so
// an over-sized document is reported instead of silently truncated. The failure
// wraps errDocumentTooLarge so the streaming guard and the announced-length
// guard report the same, recognisable error.
func readLimited(body io.Reader, limit int64) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(body, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, fmt.Errorf("%w of %d bytes", errDocumentTooLarge, limit)
}
return data, nil
}
type apiError struct {
status int
code string
message string
}
func (e *apiError) Error() string {
switch {
case e.code != "" && e.message != "":
return fmt.Sprintf("DingTalk API status=%d code=%s message=%s", e.status, e.code, e.message)
case e.code != "":
return fmt.Sprintf("DingTalk API status=%d code=%s", e.status, e.code)
default:
return fmt.Sprintf("DingTalk API status=%d", e.status)
}
}
func decodeAPIError(status int, body []byte) error {
var response struct {
Code json.RawMessage `json:"code"`
ErrCode json.RawMessage `json:"errcode"`
Message string `json:"message"`
ErrMsg string `json:"errmsg"`
}
_ = json.Unmarshal(body, &response)
code := rawValue(response.Code)
if code == "" {
code = rawValue(response.ErrCode)
}
message := strings.TrimSpace(response.Message)
if message == "" {
message = strings.TrimSpace(response.ErrMsg)
}
return &apiError{status: status, code: code, message: message}
}
func rawValue(value json.RawMessage) string {
if len(value) == 0 || string(value) == "null" {
return ""
}
var text string
if err := json.Unmarshal(value, &text); err == nil {
return strings.TrimSpace(text)
}
return strings.TrimSpace(string(value))
}
func readBody(body io.Reader) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(body, maxResponseBytes+1))
if err != nil {
return nil, err
}
if len(data) > maxResponseBytes {
return nil, fmt.Errorf("response exceeds %d bytes", maxResponseBytes)
}
return data, nil
}
func isTransient(status int) bool {
return status == http.StatusTooManyRequests || status >= http.StatusInternalServerError
}
func retryDelay(attempt int) time.Duration {
if attempt < 0 {
attempt = 0
}
if attempt > 4 {
attempt = 4
}
return time.Duration(1<<attempt) * 250 * time.Millisecond
}
func parseRetryAfter(value string, fallback time.Duration) time.Duration {
const maximum = 30 * time.Second
delay := fallback
if seconds, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && value != "" {
if seconds <= 0 {
delay = 100 * time.Millisecond
} else {
delay = time.Duration(seconds) * time.Second
}
} else if parsed, err := http.ParseTime(value); err == nil {
delay = time.Until(parsed)
if delay <= 0 {
delay = 100 * time.Millisecond
}
}
if delay > maximum {
return maximum
}
return delay
}
func (c *client) wait(ctx context.Context, delay time.Duration) error {
if c.sleep == nil {
return sleepContext(ctx, delay)
}
return c.sleep(ctx, delay)
}
func sleepContext(ctx context.Context, delay time.Duration) error {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func isContextError(err error) bool {
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}
func redactRequestError(err error) error {
for {
var requestErr *url.Error
if !errors.As(err, &requestErr) || requestErr.Err == nil {
return err
}
// url.Error includes the full request URL. DingTalk puts operatorId in
// the query string, so retain the cause without persisting that ID.
err = requestErr.Err
}
}
@@ -0,0 +1,638 @@
package dingtalk
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return f(request)
}
func testClient(server *httptest.Server) *client {
return &client{
baseURL: server.URL,
operator: "union/user",
appKey: "app",
appSecret: "secret",
http: server.Client(),
sleep: func(context.Context, time.Duration) error { return nil },
}
}
func TestClientUsesOfficialEndpointsAndPaginates(t *testing.T) {
var mu sync.Mutex
requests := make([]string, 0, 5)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
requests = append(requests, r.Method+" "+r.URL.RequestURI())
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/v1.0/oauth2/accessToken":
body, _ := io.ReadAll(r.Body)
if !strings.Contains(string(body), `"appKey":"app"`) ||
!strings.Contains(string(body), `"appSecret":"secret"`) {
t.Errorf("token request body = %s", body)
}
_, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`))
case "/v2.0/wiki/workspaces":
if r.Header.Get("x-acs-dingtalk-access-token") != "token" ||
r.URL.Query().Get("operatorId") != "union/user" ||
r.URL.Query().Get("maxResults") != "30" {
t.Errorf("workspace request = %#v, headers = %#v", r.URL.Query(), r.Header)
}
if r.URL.Query().Get("nextToken") == "" {
_, _ = w.Write([]byte(`{
"workspaces":[{"workspaceId":"a","rootNodeId":"root-a","name":"A"}],
"nextToken":"page 2"
}`))
} else {
_, _ = w.Write([]byte(`{
"workspaces":[{"workspaceId":"b","rootNodeId":"root-b","name":"B"}]
}`))
}
case "/v2.0/wiki/nodes":
if r.URL.Query().Get("parentNodeId") != "root/a" ||
r.URL.Query().Get("maxResults") != "50" {
t.Errorf("node request query = %#v", r.URL.Query())
}
_, _ = w.Write([]byte(`{"nodes":[{"nodeId":"doc","type":"FILE","category":"ALIDOC","extension":"adoc"}]}`))
case "/v1.0/doc/suites/documents/doc/key/blocks":
if !strings.Contains(r.URL.EscapedPath(), "doc%2Fkey") {
t.Errorf("document key was not path-escaped: %s", r.URL.EscapedPath())
}
if r.URL.Query().Get("startIndex") != "0" ||
r.URL.Query().Get("endIndex") != "99" {
t.Errorf("block request query = %#v", r.URL.Query())
}
_, _ = w.Write([]byte(`{"success":true,"result":{"data":[{"blockType":"paragraph"}]}}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := testClient(server)
workspaces, err := client.listWorkspaces(context.Background())
if err != nil || len(workspaces) != 2 {
t.Fatalf("listWorkspaces() = %#v, %v", workspaces, err)
}
nodes, err := client.listNodes(context.Background(), "root/a")
if err != nil || len(nodes) != 1 {
t.Fatalf("listNodes() = %#v, %v", nodes, err)
}
blocks, err := client.documentBlocks(context.Background(), "doc/key")
if err != nil || len(blocks) != 1 {
t.Fatalf("documentBlocks() = %#v, %v", blocks, err)
}
tokenRequests := 0
for _, request := range requests {
if request == "POST /v1.0/oauth2/accessToken" {
tokenRequests++
}
}
if tokenRequests != 1 {
t.Fatalf("access token requested %d times, requests = %#v", tokenRequests, requests)
}
}
func TestClientRefreshesUnauthorizedTokenAndRetriesRateLimit(t *testing.T) {
tokenRequests, workspaceRequests, nodeRequests, waits := 0, 0, 0, 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":
tokenRequests++
_, _ = w.Write([]byte(`{"accessToken":"token-` + string(rune('0'+tokenRequests)) + `","expireIn":7200}`))
case "/v2.0/wiki/workspaces":
workspaceRequests++
if workspaceRequests == 1 {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"code":"InvalidToken","message":"expired"}`))
return
}
if r.Header.Get("x-acs-dingtalk-access-token") != "token-2" {
t.Errorf("refreshed token header = %q", r.Header.Get("x-acs-dingtalk-access-token"))
}
_, _ = w.Write([]byte(`{"workspaces":[]}`))
case "/v2.0/wiki/nodes":
nodeRequests++
if nodeRequests == 1 {
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{"code":"TooManyRequests"}`))
return
}
_, _ = w.Write([]byte(`{"nodes":[]}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := testClient(server)
client.sleep = func(context.Context, time.Duration) error {
waits++
return nil
}
if _, err := client.listWorkspaces(context.Background()); err != nil {
t.Fatalf("listWorkspaces() error = %v", err)
}
if _, err := client.listNodes(context.Background(), "root"); err != nil {
t.Fatalf("listNodes() error = %v", err)
}
if tokenRequests != 2 || workspaceRequests != 2 || nodeRequests != 2 || waits != 1 {
t.Fatalf(
"requests token=%d workspace=%d nodes=%d waits=%d",
tokenRequests, workspaceRequests, nodeRequests, waits,
)
}
}
func TestDecodeAPIErrorDoesNotExposeUnstructuredBody(t *testing.T) {
body, _ := json.Marshal(map[string]string{"unexpected": "credential=secret"})
err := decodeAPIError(http.StatusBadRequest, body)
if strings.Contains(err.Error(), "secret") {
t.Fatalf("decodeAPIError() leaked response body: %v", err)
}
}
func TestClientDoesNotExposeQueryValuesInTransportErrors(t *testing.T) {
client := &client{
baseURL: "https://api.dingtalk.com",
http: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return nil, errors.New("dial failed")
})},
sleep: func(context.Context, time.Duration) error { return nil },
}
err := client.doJSON(
context.Background(),
http.MethodGet,
"/v2.0/wiki/nodes?operatorId=sensitive-union-id",
nil,
false,
nil,
)
if err == nil || strings.Contains(err.Error(), "sensitive-union-id") {
t.Fatalf("doJSON() error = %v", err)
}
}
func TestClientRejectsRepeatedPaginationTokens(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/v2.0/wiki/workspaces":
_, _ = w.Write([]byte(`{"workspaces":[],"nextToken":"same"}`))
case "/v2.0/wiki/nodes":
_, _ = w.Write([]byte(`{"nodes":[],"nextToken":"same"}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := testClient(server)
client.token = "cached"
client.tokenExpiry = time.Now().Add(time.Hour)
if _, err := client.listWorkspaces(context.Background()); err == nil ||
!strings.Contains(err.Error(), "repeated nextToken") {
t.Fatalf("listWorkspaces() error = %v", err)
}
if _, err := client.listNodes(context.Background(), "root"); err == nil ||
!strings.Contains(err.Error(), "repeated nextToken") {
t.Fatalf("listNodes() error = %v", err)
}
}
func TestClientRedactsCredentialsFromStructuredAPIErrors(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{
"code":"Forbidden",
"message":"app-key app-secret operator-union cached-token"
}`))
}))
defer server.Close()
client := testClient(server)
client.appKey = "app-key"
client.appSecret = "app-secret"
client.operator = "operator-union"
client.token = "cached-token"
client.tokenExpiry = time.Now().Add(time.Hour)
err := client.doJSON(context.Background(), http.MethodGet, "/forbidden", nil, true, nil)
if err == nil {
t.Fatal("doJSON() error = nil")
}
for _, sensitive := range []string{
client.appKey, client.appSecret, client.operator, client.token,
} {
if strings.Contains(err.Error(), sensitive) {
t.Fatalf("doJSON() leaked %q: %v", sensitive, err)
}
}
}
func TestReadBodyRejectsOversizedResponses(t *testing.T) {
body := strings.NewReader(strings.Repeat("x", maxResponseBytes+1))
if _, err := readBody(body); err == nil ||
!strings.Contains(err.Error(), "response exceeds") {
t.Fatalf("readBody() error = %v", err)
}
}
// The whole uploaded-file chain, in the order the provider is called:
// node UUID → numeric 钉盘 ids → pre-signed URL → raw bytes.
func TestClientDownloadsUploadedDocumentThroughStorageAPI(t *testing.T) {
const payload = "PK\x03\x04word-bytes"
var dentryQueries, downloadQueries, objectFetches int
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 strings.HasSuffix(r.URL.Path, "/queryDentryId"):
dentryQueries++
if r.Method != http.MethodGet ||
r.URL.EscapedPath() != "/v2.0/doc/dentries/node%2Fid/queryDentryId" {
t.Errorf("dentry request = %s %s", r.Method, r.URL.EscapedPath())
}
if r.URL.Query().Get("operatorId") != "union/user" ||
r.Header.Get("x-acs-dingtalk-access-token") != "token" {
t.Errorf("dentry request query = %#v, headers = %#v", r.URL.Query(), r.Header)
}
_, _ = w.Write([]byte(
`{"dentryId":"100000000001","spaceId":"200000000002","dentryUuid":"node/id"}`,
))
case strings.HasSuffix(r.URL.Path, "/downloadInfos/query"):
downloadQueries++
if r.Method != http.MethodPost ||
r.URL.Path != "/v1.0/storage/spaces/200000000002/dentries/100000000001/downloadInfos/query" {
t.Errorf("download request = %s %s", r.Method, r.URL.Path)
}
if r.URL.Query().Get("unionId") != "union/user" {
t.Errorf("download request query = %#v", r.URL.Query())
}
body, _ := io.ReadAll(r.Body)
if !strings.Contains(string(body), `"preferIntranet":false`) ||
!strings.Contains(string(body), `"version":1`) {
t.Errorf("download request body = %s", body)
}
_, _ = w.Write([]byte(`{
"protocol":"HEADER_SIGNATURE",
"headerSignatureInfo":{
"headers":{"Authorization":"OSS key:signature","x-oss-date":"Sun, 27 Sep 2026 03:34:30 GMT"},
"resourceUrls":["http://` + r.Host + `/oss/object"],
"expirationSeconds":900
}
}`))
case r.URL.Path == "/oss/object":
objectFetches++
if r.Header.Get("Authorization") != "OSS key:signature" ||
r.Header.Get("x-oss-date") != "Sun, 27 Sep 2026 03:34:30 GMT" {
t.Errorf("signed request headers = %#v", r.Header)
}
if r.Header.Get("Accept-Encoding") != "identity" {
t.Errorf("signed request encoding = %q", r.Header.Get("Accept-Encoding"))
}
_, _ = w.Write([]byte(payload))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := testClient(server)
data, err := client.downloadDocument(context.Background(), "node/id")
if err != nil {
t.Fatalf("downloadDocument() error = %v", err)
}
if string(data) != payload {
t.Fatalf("downloadDocument() = %q, want %q", data, payload)
}
if dentryQueries != 1 || downloadQueries != 1 || objectFetches != 1 {
t.Fatalf("requests dentry=%d download=%d object=%d",
dentryQueries, downloadQueries, objectFetches)
}
// Validation resolves the same location without transferring the payload.
if err := client.verifyDocumentDownload(context.Background(), "node/id"); err != nil {
t.Fatalf("verifyDocumentDownload() error = %v", err)
}
if downloadQueries != 2 || objectFetches != 1 {
t.Fatalf("verify transferred bytes: download=%d object=%d", downloadQueries, objectFetches)
}
}
func TestClientRejectsIncompleteDentryResponse(t *testing.T) {
for _, body := range []string{
`{"dentryId":"1"}`,
`{"spaceId":"2"}`,
`{"dentryId":" ","spaceId":"2"}`,
`{}`,
} {
t.Run(body, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := testClient(server)
c.token = "cached"
c.tokenExpiry = time.Now().Add(time.Hour)
if _, err := c.resolveDentry(context.Background(), "doc"); err == nil {
t.Fatalf("resolveDentry() accepted %s", body)
}
})
}
}
func TestClientRejectsDownloadWithoutResourceURL(t *testing.T) {
for _, body := range []string{
`{}`,
`{"protocol":"HEADER_SIGNATURE","headerSignatureInfo":null}`,
`{"protocol":"HEADER_SIGNATURE","headerSignatureInfo":{"resourceUrls":[]}}`,
`{"protocol":"SIGNATURE","headerSignatureInfo":{"resourceUrls":[" "]}}`,
} {
t.Run(body, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := testClient(server)
c.token = "cached"
c.tokenExpiry = time.Now().Add(time.Hour)
_, err := c.requestDownloadURL(context.Background(), dentryRef{DentryID: "1", SpaceID: "2"})
if err == nil {
t.Fatalf("requestDownloadURL() accepted %s", body)
}
})
}
}
// An expired pre-signed URL must be re-signed rather than failing the document.
func TestClientResignsDownloadURLAfterObjectStoreRefusal(t *testing.T) {
var downloadQueries, objectFetches int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/queryDentryId"):
_, _ = w.Write([]byte(`{"dentryId":"1","spaceId":"2"}`))
case strings.HasSuffix(r.URL.Path, "/downloadInfos/query"):
downloadQueries++
_, _ = w.Write([]byte(`{"protocol":"HEADER_SIGNATURE","headerSignatureInfo":{
"headers":{"Authorization":"OSS key:sig` + string(rune('0'+downloadQueries)) + `"},
"resourceUrls":["http://` + r.Host + `/oss/object"]}}`))
case r.URL.Path == "/oss/object":
objectFetches++
if objectFetches == 1 {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`<Error><Code>SignatureDoesNotMatch</Code></Error>`))
return
}
if r.Header.Get("Authorization") != "OSS key:sig2" {
t.Errorf("retry reused the stale signature: %#v", r.Header)
}
_, _ = w.Write([]byte("bytes"))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
c := testClient(server)
c.token = "cached"
c.tokenExpiry = time.Now().Add(time.Hour)
data, err := c.downloadDocument(context.Background(), "doc")
if err != nil {
t.Fatalf("downloadDocument() error = %v", err)
}
if string(data) != "bytes" || downloadQueries != 2 || objectFetches != 2 {
t.Fatalf("data = %q, download=%d object=%d", data, downloadQueries, objectFetches)
}
}
func TestClientBoundsDocumentDownloads(t *testing.T) {
t.Run("declared length", func(t *testing.T) {
var downloadQueries, objectFetches int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/queryDentryId"):
_, _ = w.Write([]byte(`{"dentryId":"1","spaceId":"2"}`))
case strings.HasSuffix(r.URL.Path, "/downloadInfos/query"):
downloadQueries++
_, _ = w.Write([]byte(`{"protocol":"HEADER_SIGNATURE","headerSignatureInfo":{
"resourceUrls":["http://` + r.Host + `/oss/object"]}}`))
default:
objectFetches++
w.Header().Set("Content-Length", strconv.Itoa(4096))
w.WriteHeader(http.StatusOK)
}
}))
defer server.Close()
c := testClient(server)
c.token = "cached"
c.tokenExpiry = time.Now().Add(time.Hour)
c.downloadLimit = 1024
data, err := c.downloadDocument(context.Background(), "doc")
if err == nil || !errors.Is(err, errDocumentTooLarge) ||
!strings.Contains(err.Error(), "1024 bytes") {
t.Fatalf("downloadDocument() = %q, %v; want a size refusal", data, err)
}
if downloadQueries != 1 || objectFetches != 1 {
t.Fatalf("over-sized download retried: signature queries = %d, object fetches = %d",
downloadQueries, objectFetches)
}
})
t.Run("streamed length", func(t *testing.T) {
var downloadQueries, objectFetches int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/queryDentryId"):
_, _ = w.Write([]byte(`{"dentryId":"1","spaceId":"2"}`))
case strings.HasSuffix(r.URL.Path, "/downloadInfos/query"):
downloadQueries++
_, _ = w.Write([]byte(`{"protocol":"HEADER_SIGNATURE","headerSignatureInfo":{
"resourceUrls":["http://` + r.Host + `/oss/object"]}}`))
default:
objectFetches++
// Flushing first drops Content-Length, so only the streaming
// guard can stop an over-sized body.
w.WriteHeader(http.StatusOK)
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
}
_, _ = w.Write([]byte(strings.Repeat("x", 4096)))
}
}))
defer server.Close()
c := testClient(server)
c.token = "cached"
c.tokenExpiry = time.Now().Add(time.Hour)
c.downloadLimit = 1024
if _, err := c.downloadDocument(context.Background(), "doc"); err == nil ||
!errors.Is(err, errDocumentTooLarge) ||
!strings.Contains(err.Error(), "1024 bytes") {
t.Fatalf("downloadDocument() error = %v, want a size refusal", err)
}
// A body with no Content-Length is only measurable while it is read, so
// before the sentinel existed every attempt paid for a fresh signature
// and another over-sized read before failing. The size is a property of
// the document, not a transient fault: one attempt, one signature, one
// transfer.
if downloadQueries != 1 || objectFetches != 1 {
t.Fatalf("over-sized download retried: signature queries = %d, object fetches = %d",
downloadQueries, objectFetches)
}
})
}
// A read failure that is not a size refusal stays retryable: the transfer is
// re-signed and re-attempted, and the document is still returned.
func TestClientRetriesTransientReadFailuresWithAFreshSignature(t *testing.T) {
var downloadQueries, objectFetches int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/queryDentryId"):
_, _ = w.Write([]byte(`{"dentryId":"1","spaceId":"2"}`))
case strings.HasSuffix(r.URL.Path, "/downloadInfos/query"):
downloadQueries++
_, _ = w.Write([]byte(`{"protocol":"HEADER_SIGNATURE","headerSignatureInfo":{
"headers":{"Authorization":"OSS key:sig` + strconv.Itoa(downloadQueries) + `"},
"resourceUrls":["http://` + r.Host + `/oss/object"]}}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
c := testClient(server)
c.token = "cached"
c.tokenExpiry = time.Now().Add(time.Hour)
// The object store is served by a transport that truncates the first body
// mid-stream, which surfaces as a plain read error rather than a size
// refusal, and succeeds on the second attempt.
c.fileHTTP = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
objectFetches++
body := io.NopCloser(strings.NewReader("bytes"))
if objectFetches == 1 {
body = io.NopCloser(&failingReader{data: "byt"})
}
return &http.Response{
StatusCode: http.StatusOK,
Body: body,
Header: make(http.Header),
Request: req,
}, nil
})}
data, err := c.downloadDocument(context.Background(), "doc")
if err != nil {
t.Fatalf("downloadDocument() error = %v", err)
}
if string(data) != "bytes" || downloadQueries != 2 || objectFetches != 2 {
t.Fatalf("data = %q, download=%d object=%d; want a re-signed retry",
data, downloadQueries, objectFetches)
}
}
// failingReader yields its data and then fails, standing in for a connection
// dropped in the middle of a transfer.
type failingReader struct {
data string
read bool
}
func (r *failingReader) Read(p []byte) (int, error) {
if r.read {
return 0, errors.New("connection reset by peer")
}
r.read = true
return copy(p, r.data), nil
}
func TestReadLimitedRejectsOverlongBody(t *testing.T) {
if data, err := readLimited(strings.NewReader("1234"), 4); err != nil || string(data) != "1234" {
t.Fatalf("readLimited() = %q, %v", data, err)
}
if _, err := readLimited(strings.NewReader("12345"), 4); err == nil ||
!errors.Is(err, errDocumentTooLarge) ||
!strings.Contains(err.Error(), "download limit") {
t.Fatalf("readLimited() error = %v, want errDocumentTooLarge", err)
}
}
func TestDocumentBlocksRejectsIncompleteResponse(t *testing.T) {
for _, body := range []string{`{}`, `{"success":false}`, `{"success":true}`, `{"success":true,"result":null}`} {
t.Run(body, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := testClient(server)
c.token = "cached"
c.tokenExpiry = time.Now().Add(time.Hour)
blocks, err := c.documentBlocks(context.Background(), "doc")
if err == nil || len(blocks) != 0 {
t.Fatalf("invalid response accepted: %#v, %v", blocks, err)
}
})
}
}
func TestDocumentBlocksReadsMultiplePagesAndAcceptsEmptyDocument(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
var blocks []json.RawMessage
if r.URL.Query().Get("startIndex") == "0" && strings.Contains(r.URL.Path, "/long/") {
for i := 0; i < 100; i++ {
blocks = append(blocks, json.RawMessage(`{"blockType":"paragraph","paragraph":{"text":"first page"}}`))
}
} else if strings.Contains(r.URL.Path, "/long/") {
if r.URL.Query().Get("startIndex") != "100" {
t.Errorf("unexpected page: %s", r.URL.RawQuery)
}
blocks = []json.RawMessage{json.RawMessage(`{"blockType":"paragraph","paragraph":{"text":"last page"}}`)}
}
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "result": map[string]any{"data": blocks}})
}))
defer server.Close()
c := testClient(server)
c.token = "cached"
c.tokenExpiry = time.Now().Add(time.Hour)
blocks, err := c.documentBlocks(context.Background(), "long")
if err != nil || len(blocks) != 101 || calls != 2 {
t.Fatalf("long document: %d blocks, %d calls, %v", len(blocks), calls, err)
}
blocks, err = c.documentBlocks(context.Background(), "empty")
if err != nil || len(blocks) != 0 {
t.Fatalf("empty document: %#v, %v", blocks, err)
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,142 @@
package dingtalk
import (
"bytes"
"context"
"encoding/json"
"os"
"reflect"
"strings"
"testing"
"academy/internal/logger"
)
// The unknown-type collection is a value on its own so the reporting path is
// testable without asserting on free-form log text: whatever this returns is
// exactly what the warning and the pipeline event carry.
func TestCollectUnknownBlockTypesReportsDocumentIdentity(t *testing.T) {
document := node{
ID: "node-1",
Name: "季度规划",
URL: "https://example.com/i/nodes/node-1",
}
rendered := renderResult{Markdown: "# 季度规划\n", UnknownTypes: []string{"attachment", "code"}}
unknown, ok := collectUnknownBlockTypes(document, rendered)
if !ok {
t.Fatal("collectUnknownBlockTypes() reported a complete document")
}
if unknown.NodeID != "node-1" || unknown.Title != "季度规划" ||
unknown.URL != "https://example.com/i/nodes/node-1" ||
!reflect.DeepEqual(unknown.BlockTypes, []string{"attachment", "code"}) {
t.Fatalf("unknownBlockTypes = %#v", unknown)
}
fields := unknown.fields()
if fields["node_id"] != "node-1" || fields["title"] != "季度规划" ||
fields["block_types"] != "attachment,code" || fields["count"] != 2 {
t.Fatalf("fields() = %#v", fields)
}
}
func TestCollectUnknownBlockTypesIsSilentWhenComplete(t *testing.T) {
if _, ok := collectUnknownBlockTypes(node{ID: "node-1"}, renderResult{Markdown: "# ok\n"}); ok {
t.Fatal("collectUnknownBlockTypes() reported loss for a fully rendered document")
}
}
func TestUnknownBlockTypesTitleFallsBackToNodeID(t *testing.T) {
unknown, ok := collectUnknownBlockTypes(
node{ID: "node-2"},
renderResult{UnknownTypes: []string{"code"}},
)
if !ok || unknown.Title != "node-2" {
t.Fatalf("unknownBlockTypes = %#v, ok = %v", unknown, ok)
}
}
// An unmodelled block type must stay visible on the fetch path: it keeps the
// metadata entry and additionally reaches the structured pipeline event that
// monitoring keys on. A block the API could not map carries only the real type
// name, and that name is what the metadata and the event must show. Only the
// stage/action pair and the document identity are asserted here, never the
// free-form message.
func TestFetchAllReportsUnknownBlockTypes(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "space", RootNodeID: "root", Name: "Space"}},
nodes: map[string][]node{
"root": {{
ID: "doc-unmapped", Type: "FILE", Category: "ALIDOC", Extension: "adoc",
Name: "Release notes",
}},
},
blocks: map[string][]json.RawMessage{
"doc-unmapped": {rawJSON(`{"blockType":"unknown","unknown":{"rawType":"card"}}`)},
},
nodeErrors: make(map[string]error),
blockErrors: make(map[string]error),
}
var buf bytes.Buffer
logger.SetOutput(&buf)
defer logger.SetOutput(os.Stdout)
items, err := testConnector(api).FetchAll(context.Background(), testConfig("space"), []string{"space"})
if err != nil {
t.Fatalf("FetchAll() error = %v", err)
}
if len(items) != 1 {
t.Fatalf("FetchAll() returned %d items, want 1", len(items))
}
if got := items[0].Metadata["unknown_block_types"]; got != "unknown:card" {
t.Fatalf("metadata unknown_block_types = %q, want %q", got, "unknown:card")
}
for _, want := range []string{
"stage=DingTalkConnector",
"action=unknown_block_types",
`node_id="doc-unmapped"`,
`block_types="unknown:card"`,
} {
if !strings.Contains(buf.String(), want) {
t.Fatalf("pipeline event missing %q:\n%s", want, buf.String())
}
}
t.Logf("emitted warnings:\n%s", strings.TrimSpace(buf.String()))
}
// A document whose blocks are all modelled must not emit the warning.
func TestFetchAllStaysQuietForModelledBlocks(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "space", RootNodeID: "root", Name: "Space"}},
nodes: map[string][]node{
"root": {{
ID: "doc-plain", Type: "FILE", Category: "ALIDOC", Extension: "adoc",
Name: "Release notes",
}},
},
blocks: map[string][]json.RawMessage{
"doc-plain": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"all good"}}`)},
},
nodeErrors: make(map[string]error),
blockErrors: make(map[string]error),
}
var buf bytes.Buffer
logger.SetOutput(&buf)
defer logger.SetOutput(os.Stdout)
items, err := testConnector(api).FetchAll(context.Background(), testConfig("space"), []string{"space"})
if err != nil {
t.Fatalf("FetchAll() error = %v", err)
}
if len(items) != 1 {
t.Fatalf("FetchAll() returned %d items, want 1", len(items))
}
if _, exists := items[0].Metadata["unknown_block_types"]; exists {
t.Fatalf("metadata = %#v, want no unknown_block_types", items[0].Metadata)
}
if strings.Contains(buf.String(), "action=unknown_block_types") {
t.Fatalf("unexpected warning for a fully rendered document:\n%s", buf.String())
}
}
@@ -0,0 +1,198 @@
package dingtalk
import (
"context"
"encoding/json"
"strings"
"testing"
"academy/internal/types"
)
// --- settings ---
// The folder switch is read through the same helper as the uploaded-files
// switch, and an absent, malformed or unexpected value has to leave the data
// source on the historical flat layout.
func TestParseDocumentSettingsReadsTheFolderSwitch(t *testing.T) {
for _, testCase := range []struct {
label string
settings map[string]interface{}
want bool
}{
{"absent key", map[string]interface{}{}, false},
{"null settings entry", map[string]interface{}{"preserve_folder_structure": nil}, false},
{"bool true", map[string]interface{}{"preserve_folder_structure": true}, true},
{"bool false", map[string]interface{}{"preserve_folder_structure": false}, false},
{"numeric string", map[string]interface{}{"preserve_folder_structure": "1"}, true},
{"padded on", map[string]interface{}{"preserve_folder_structure": " on "}, true},
{"padded OFF", map[string]interface{}{"preserve_folder_structure": " OFF "}, false},
{"unknown spelling", map[string]interface{}{"preserve_folder_structure": "maybe"}, false},
{"unexpected type", map[string]interface{}{"preserve_folder_structure": 1}, false},
{
"independent of the uploaded-files switch",
map[string]interface{}{"include_uploaded_files": true},
false,
},
} {
t.Run(testCase.label, func(t *testing.T) {
dataSourceConfig := testConfig("ws")
dataSourceConfig.Settings = testCase.settings
got := parseDocumentSettings(dataSourceConfig)
if got.PreserveFolderStructure != testCase.want {
t.Fatalf("PreserveFolderStructure = %t, want %t", got.PreserveFolderStructure, testCase.want)
}
if got.IncludeUploadedFiles != settingBool(testCase.settings["include_uploaded_files"], false) {
t.Fatalf("IncludeUploadedFiles = %t, the two switches are not independent",
got.IncludeUploadedFiles)
}
})
}
if got := parseDocumentSettings(nil); got.PreserveFolderStructure {
t.Fatal("parseDocumentSettings(nil).PreserveFolderStructure = true, want false")
}
}
// documentFolders is the single place the switch is honoured, so the nil it
// returns when the switch is off is what keeps an existing data source
// byte-for-byte unchanged.
func TestDocumentFoldersIsNilUnlessTheSwitchIsOn(t *testing.T) {
scope := []string{"天诛渗透攻防"}
scan := []string{"2024 年度"}
off := documentFolders(documentSettings{}, "工作区", scope, scan)
if off != nil {
t.Fatalf("documentFolders() with the switch off = %#v, want nil", off)
}
on := documentFolders(
documentSettings{PreserveFolderStructure: true}, "工作区", scope, scan,
)
want := []string{"工作区", "天诛渗透攻防", "2024 年度"}
if strings.Join(on, "|") != strings.Join(want, "|") {
t.Fatalf("documentFolders() = %#v, want %#v", on, want)
}
// A workspace with no name of its own contributes no segment rather than an
// empty level.
unnamed := documentFolders(documentSettings{PreserveFolderStructure: true}, "", scope, nil)
if strings.Join(unnamed, "|") != "天诛渗透攻防" {
t.Fatalf("documentFolders() without a workspace name = %#v", unnamed)
}
}
// --- file name assembly ---
// The folder path a synced document ends up in is derived downstream from
// FileName alone, so the encoding is only correct if that split recovers the
// hierarchy.
func TestBuildFolderFileNameSurvivesTheDownstreamFolderSplit(t *testing.T) {
for _, testCase := range []struct {
label string
folders []string
fileName string
wantFolder string
wantName string
}{
{
"no folders keeps the historical shape",
nil, "FAQ.md", "", "FAQ.md",
},
{
"workspace only",
[]string{"工作区"},
"FAQ.md", "工作区", "FAQ.md",
},
{
"workspace and nested folders",
[]string{"天穹安全能力中心", "天诛渗透攻防", "2024 年度"},
"2024 年度复盘 FAQ.md",
"天穹安全能力中心/天诛渗透攻防/2024 年度",
"2024 年度复盘 FAQ.md",
},
{
"a separator inside a name cannot add a level",
[]string{"安全/中心", "A/B"},
"A_B 手册.md",
"安全_中心/A_B",
"A_B 手册.md",
},
{
"a level the normaliser rejects is dropped, not fatal",
[]string{"工作区", ".", "子目录"},
"FAQ.md",
"工作区/子目录",
"FAQ.md",
},
} {
t.Run(testCase.label, func(t *testing.T) {
raw := buildFolderFileName(testCase.folders, testCase.fileName)
folder, name := types.SplitKnowledgeRelativePath(raw)
if folder != testCase.wantFolder || name != testCase.wantName {
t.Fatalf("split(%q) = (%q, %q), want (%q, %q)",
raw, folder, name, testCase.wantFolder, testCase.wantName)
}
})
}
}
func TestBuildFolderFileNameWithoutFoldersIsTheIdentity(t *testing.T) {
for _, name := range []string{"FAQ.md", "手册.docx", "untitled"} {
if got := buildFolderFileName(nil, name); got != name {
t.Fatalf("buildFolderFileName(nil, %q) = %q, want it unchanged", name, got)
}
}
}
// Sibling folders are recorded while the walk visits them, so a name must not
// be written into a slice another sibling is still holding.
func TestAppendFolderNeverSharesABackingArray(t *testing.T) {
parent := make([]string, 1, 8)
parent[0] = "工作区"
first := appendFolder(parent, "天诛渗透攻防")
second := appendFolder(parent, "天禹漏洞情报")
if first[len(first)-1] != "天诛渗透攻防" {
t.Fatalf("first sibling = %#v, its name was overwritten", first)
}
if second[len(second)-1] != "天禹漏洞情报" {
t.Fatalf("second sibling = %#v, its name was overwritten", second)
}
if len(parent) != 1 || parent[0] != "工作区" {
t.Fatalf("appendFolder() mutated its input: %#v", parent)
}
}
// --- cursor safety ---
// The folder dimension is an ingest-path concern only. If it reached the sync
// cursor, turning the switch on would change what the next incremental sync
// considers unchanged — and, worse, which documents it considers deleted.
func TestFolderPathsNeverReachTheSyncCursor(t *testing.T) {
_, off, err := testConnector(tenantFolderPathFixture()).FetchIncremental(
context.Background(), tenantUploadedFilesConfig(tenantWorkspaceID), nil,
)
if err != nil {
t.Fatalf("FetchIncremental() with the switch off error = %v", err)
}
_, on, err := testConnector(tenantFolderPathFixture()).FetchIncremental(
context.Background(), tenantFolderPathTestConfig(tenantWorkspaceID), nil,
)
if err != nil {
t.Fatalf("FetchIncremental() with the switch on error = %v", err)
}
encode := func(t *testing.T, cursor *types.SyncCursor) string {
t.Helper()
if cursor == nil {
t.Fatal("FetchIncremental() returned no cursor")
}
raw, err := json.Marshal(cursor.ConnectorCursor["resources"])
if err != nil {
t.Fatal(err)
}
return string(raw)
}
offCursor, onCursor := encode(t, off), encode(t, on)
if offCursor != onCursor {
t.Fatalf("the cursor depends on the folder switch:\noff: %s\non: %s", offCursor, onCursor)
}
if strings.Contains(onCursor, tenantWorkspaceName) {
t.Fatalf("the cursor carries folder names: %s", onCursor)
}
}
@@ -0,0 +1,435 @@
package dingtalk
import (
"context"
"encoding/json"
"testing"
"academy/internal/types"
)
// The fixture below reproduces the shape of the tenant that reported the
// problem: one workspace whose root holds five folders, a document that sits
// directly at the root, both formats inside the folders (native adoc FAQ pages
// and uploaded docx/pptx manuals), an empty folder, and one extra nesting level
// so the depth is not uniform. It goes through the public fetch entry points
// only, so every assertion describes what an operator sees in the knowledge
// base rather than how the connector is wired internally.
//
// Node names carry no file extension: DingTalk reports the extension in its own
// field, exactly as the rest of this package's fixtures do.
const (
tenantWorkspaceID = "ws-tianqiong"
tenantWorkspaceName = "天穹安全能力中心-天系列使用FAQ"
tenantRootNodeID = "root-tianqiong"
// tenantModifiedAt is the millisecond revision DingTalk reports for the
// fixture's documents. It is what makes an incremental sync skip an
// untouched document, so the relocation case below is about the file name
// and not about a missing revision.
tenantModifiedAt = int64(1760000000000)
)
// tenantUploadedFilesConfig is the state of the reported tenant before this
// change: uploaded manuals are ingested, the folder-path switch does not exist
// yet, so the settings bag has no key for it.
func tenantUploadedFilesConfig(resources ...string) *types.DataSourceConfig {
cfg := testConfig(resources...)
cfg.Settings = map[string]interface{}{"include_uploaded_files": true}
return cfg
}
// tenantFolderPathTestConfig turns the folder-path switch on as well.
func tenantFolderPathTestConfig(resources ...string) *types.DataSourceConfig {
cfg := tenantUploadedFilesConfig(resources...)
cfg.Settings["preserve_folder_structure"] = true
return cfg
}
// tenantFolderPathFixture builds the reported tenant tree.
func tenantFolderPathFixture() *fakeAPI {
adoc := func(id, name string) node {
return node{
ID: id, WorkspaceID: tenantWorkspaceID, Type: "FILE", Category: "ALIDOC",
Extension: "adoc", Name: name, ModifiedTimestamp: tenantModifiedAt,
}
}
upload := func(id, name, extension string) node {
return node{
ID: id, WorkspaceID: tenantWorkspaceID, Type: "FILE", Category: "DOCUMENT",
Extension: extension, Name: name, ModifiedTimestamp: tenantModifiedAt,
}
}
folder := func(id, name string) node {
return node{
ID: id, WorkspaceID: tenantWorkspaceID, Type: "FOLDER", Name: name, HasChildren: true,
}
}
return &fakeAPI{
workspaces: []workspace{{
ID: tenantWorkspaceID, RootNodeID: tenantRootNodeID, Name: tenantWorkspaceName,
}},
nodes: map[string][]node{
tenantRootNodeID: {
folder("f-easm", "EASM-外部攻击面管理模块"),
adoc("d-cloud-faq", "天穹云端安全能力中枢常见问题 FAQ"),
folder("f-tianxi", "天析应急分析"),
folder("f-tianyu", "天禹漏洞情报"),
folder("f-tianfu", "天伏攻防知识库"),
folder("f-tianzhu", "天诛渗透攻防"),
},
"f-easm": {
adoc("d-easm-faq", "EASM 模块使用 FAQ"),
upload("d-easm-manual", "EASM 模块操作手册.docx", "docx"),
},
"f-tianxi": {
adoc("d-tianxi-faq", "天析应急分析 FAQ"),
upload("d-tianxi-deck", "天析应急分析介绍.pptx", "pptx"),
},
"f-tianyu": {
upload("d-tianyu-manual", "天禹漏洞情报使用手册.docx", "docx"),
upload("d-tianyu-deck", "天禹漏洞情报介绍.pptx", "pptx"),
},
// 天伏攻防知识库 is listed but holds nothing: an empty folder must
// stay invisible in the knowledge base instead of producing a level
// with no documents in it.
"f-tianfu": {},
"f-tianzhu": {
upload("d-tianzhu-manual", "天诛渗透攻防手册.docx", "docx"),
adoc("d-tianzhu-faq-1", "天诛渗透攻防 FAQ 一"),
adoc("d-tianzhu-faq-2", "天诛渗透攻防 FAQ 二"),
folder("f-tianzhu-2024", "2024 年度"),
},
"f-tianzhu-2024": {
adoc("d-tianzhu-2024-faq", "2024 年度复盘 FAQ"),
},
},
blocks: map[string][]json.RawMessage{
"d-cloud-faq": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"cloud"}}`)},
"d-easm-faq": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"easm"}}`)},
"d-tianxi-faq": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"tianxi"}}`)},
"d-tianzhu-faq-1": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"one"}}`)},
"d-tianzhu-faq-2": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"two"}}`)},
"d-tianzhu-2024-faq": {
rawJSON(`{"blockType":"paragraph","paragraph":{"text":"review"}}`),
},
},
downloads: map[string][]byte{
"d-easm-manual": []byte("easm"),
"d-tianxi-deck": []byte("tianxi"),
"d-tianyu-manual": []byte("tianyu-manual"),
"d-tianyu-deck": []byte("tianyu-deck"),
"d-tianzhu-manual": []byte("tianzhu"),
},
nodeErrors: make(map[string]error),
blockErrors: make(map[string]error),
}
}
// fileNamesByDocument indexes the fetched items by node ID so an assertion can
// name the document it is talking about instead of an index.
func fileNamesByDocument(t *testing.T, items []types.FetchedItem) map[string]string {
t.Helper()
names := make(map[string]string, len(items))
for _, item := range items {
if _, seen := names[item.ExternalID]; seen {
t.Fatalf("document %q was fetched more than once", item.ExternalID)
}
names[item.ExternalID] = item.FileName
}
return names
}
func assertFileNames(t *testing.T, got map[string]string, want map[string]string) {
t.Helper()
for id, wantName := range want {
if got[id] != wantName {
t.Errorf("document %s FileName = %q, want %q", id, got[id], wantName)
}
}
if len(got) != len(want) {
t.Fatalf("fetched %d documents, want %d: %#v", len(got), len(want), got)
}
}
// Regression guard: a data source that never turned the switch on keeps the
// historical flat file names, byte for byte. Every document of the reported
// tenant is listed, in the same format it was ingested with before.
func TestDingTalkFolderPathsDefaultOffKeepsHistoricalFileNames(t *testing.T) {
captureLogs(t)
connector := testConnector(tenantFolderPathFixture())
items, err := connector.FetchAll(
context.Background(), tenantUploadedFilesConfig(tenantWorkspaceID),
[]string{tenantWorkspaceID},
)
if err != nil {
t.Fatalf("FetchAll() error = %v", err)
}
assertFileNames(t, fileNamesByDocument(t, items), map[string]string{
"d-easm-faq": "EASM 模块使用 FAQ.md",
"d-easm-manual": "EASM 模块操作手册.docx",
"d-cloud-faq": "天穹云端安全能力中枢常见问题 FAQ.md",
"d-tianxi-faq": "天析应急分析 FAQ.md",
"d-tianxi-deck": "天析应急分析介绍.pptx",
"d-tianyu-manual": "天禹漏洞情报使用手册.docx",
"d-tianyu-deck": "天禹漏洞情报介绍.pptx",
"d-tianzhu-manual": "天诛渗透攻防手册.docx",
"d-tianzhu-faq-1": "天诛渗透攻防 FAQ 一.md",
"d-tianzhu-faq-2": "天诛渗透攻防 FAQ 二.md",
"d-tianzhu-2024-faq": "2024 年度复盘 FAQ.md",
})
}
// The reported problem, end to end: with the switch on, every document encodes
// its source folder hierarchy relative to the workspace root, so the five
// top-level folders stay distinguishable in the knowledge base. The workspace
// name is the first segment, and a document sitting at the root carries no
// folder segment beyond it.
func TestDingTalkFolderPathsPreserveTheTenantShapeWhenEnabled(t *testing.T) {
captureLogs(t)
connector := testConnector(tenantFolderPathFixture())
items, err := connector.FetchAll(
context.Background(),
tenantFolderPathTestConfig(tenantWorkspaceID),
[]string{tenantWorkspaceID},
)
if err != nil {
t.Fatalf("FetchAll() error = %v", err)
}
root := tenantWorkspaceName + "/"
assertFileNames(t, fileNamesByDocument(t, items), map[string]string{
"d-easm-faq": root + "EASM-外部攻击面管理模块/EASM 模块使用 FAQ.md",
"d-easm-manual": root + "EASM-外部攻击面管理模块/EASM 模块操作手册.docx",
"d-cloud-faq": root + "天穹云端安全能力中枢常见问题 FAQ.md",
"d-tianxi-faq": root + "天析应急分析/天析应急分析 FAQ.md",
"d-tianxi-deck": root + "天析应急分析/天析应急分析介绍.pptx",
"d-tianyu-manual": root + "天禹漏洞情报/天禹漏洞情报使用手册.docx",
"d-tianyu-deck": root + "天禹漏洞情报/天禹漏洞情报介绍.pptx",
"d-tianzhu-manual": root + "天诛渗透攻防/天诛渗透攻防手册.docx",
"d-tianzhu-faq-1": root + "天诛渗透攻防/天诛渗透攻防 FAQ 一.md",
"d-tianzhu-faq-2": root + "天诛渗透攻防/天诛渗透攻防 FAQ 二.md",
"d-tianzhu-2024-faq": root + "天诛渗透攻防/2024 年度/2024 年度复盘 FAQ.md",
})
}
// The switch has to read the same string spellings the connector's other switch
// reads, and anything unrecognised — including an absent key — has to leave the
// historical behaviour alone.
func TestDingTalkFolderPathsReadsTheSameSettingsSpellings(t *testing.T) {
captureLogs(t)
for _, testCase := range []struct {
label string
settings map[string]interface{}
want string
}{
{
"key absent",
map[string]interface{}{"include_uploaded_files": true},
"天诛渗透攻防 FAQ 一.md",
},
{
"bool true",
map[string]interface{}{"preserve_folder_structure": true},
tenantWorkspaceName + "/天诛渗透攻防/天诛渗透攻防 FAQ 一.md",
},
{
"string yes",
map[string]interface{}{"preserve_folder_structure": "yes"},
tenantWorkspaceName + "/天诛渗透攻防/天诛渗透攻防 FAQ 一.md",
},
{
"string ON with padding",
map[string]interface{}{"preserve_folder_structure": " ON "},
tenantWorkspaceName + "/天诛渗透攻防/天诛渗透攻防 FAQ 一.md",
},
{
"bool false",
map[string]interface{}{"preserve_folder_structure": false},
"天诛渗透攻防 FAQ 一.md",
},
{
"unknown spelling",
map[string]interface{}{"preserve_folder_structure": "sometimes"},
"天诛渗透攻防 FAQ 一.md",
},
{
"unexpected type",
map[string]interface{}{"preserve_folder_structure": 42},
"天诛渗透攻防 FAQ 一.md",
},
} {
t.Run(testCase.label, func(t *testing.T) {
cfg := tenantUploadedFilesConfig(tenantWorkspaceID)
cfg.Settings = testCase.settings
connector := testConnector(tenantFolderPathFixture())
items, err := connector.FetchAll(
context.Background(), cfg, []string{tenantWorkspaceID},
)
if err != nil {
t.Fatalf("FetchAll() error = %v", err)
}
names := fileNamesByDocument(t, items)
if names["d-tianzhu-faq-1"] != testCase.want {
t.Fatalf("FileName = %q, want %q", names["d-tianzhu-faq-1"], testCase.want)
}
})
}
}
// Selecting a folder is the common case, and the path a document lands on must
// not depend on how deep the operator drilled into the picker: the same
// document selected through the whole workspace, through its own folder and as
// a single document has to end up in one folder, not three.
func TestDingTalkFolderPathsDoNotDependOnTheSelectedScope(t *testing.T) {
captureLogs(t)
connector := testConnector(tenantFolderPathFixture())
wholeWorkspace, err := connector.FetchAll(
context.Background(),
tenantFolderPathTestConfig(tenantWorkspaceID),
[]string{tenantWorkspaceID},
)
if err != nil {
t.Fatalf("workspace scope error = %v", err)
}
folderID, err := encodeResourceReference(resourceReference{
WorkspaceID: tenantWorkspaceID, NodeID: "f-tianzhu-2024", Ancestors: []string{"f-tianzhu"},
})
if err != nil {
t.Fatal(err)
}
nestedFolder, err := connector.FetchAll(
context.Background(),
tenantFolderPathTestConfig(folderID),
[]string{folderID},
)
if err != nil {
t.Fatalf("folder scope error = %v", err)
}
documentID, err := encodeResourceReference(resourceReference{
WorkspaceID: tenantWorkspaceID, NodeID: "d-tianzhu-2024-faq",
Ancestors: []string{"f-tianzhu", "f-tianzhu-2024"},
})
if err != nil {
t.Fatal(err)
}
singleDocument, err := connector.FetchAll(
context.Background(),
tenantFolderPathTestConfig(documentID),
[]string{documentID},
)
if err != nil {
t.Fatalf("document scope error = %v", err)
}
want := tenantWorkspaceName + "/天诛渗透攻防/2024 年度/2024 年度复盘 FAQ.md"
for label, items := range map[string][]types.FetchedItem{
"workspace": wholeWorkspace,
"folder": nestedFolder,
"document": singleDocument,
} {
if got := fileNamesByDocument(t, items)["d-tianzhu-2024-faq"]; got != want {
t.Errorf("%s scope FileName = %q, want %q", label, got, want)
}
}
}
// Names are hostile but not tidy: a folder name may contain the path separator,
// punctuation DingTalk allows and file systems do not, and two sibling folders
// may share a name. Each level is sanitised on its own so a "/" inside one name
// cannot invent an extra level, and same-named siblings merge into one folder —
// the same trade-off the Yuque connector documents for same-named groups.
func TestDingTalkFolderPathsSanitizeEachLevelAndMergeSameNamedFolders(t *testing.T) {
captureLogs(t)
const workspaceName = "安全/中心"
adoc := func(id, name string) node {
return node{
ID: id, WorkspaceID: "ws-odd", Type: "FILE", Category: "ALIDOC",
Extension: "adoc", Name: name,
}
}
folder := func(id, name string) node {
return node{
ID: id, WorkspaceID: "ws-odd", Type: "FOLDER", Name: name, HasChildren: true,
}
}
api := &fakeAPI{
workspaces: []workspace{{ID: "ws-odd", RootNodeID: "root-odd", Name: workspaceName}},
nodes: map[string][]node{
"root-odd": {
folder("f-slash", "A/B"),
folder("f-punct", `<>:"|?*`),
// Two folders with the same title: DingTalk node IDs are
// unique, titles are not.
folder("f-dup-1", "重复"),
folder("f-dup-2", "重复"),
// A name of only whitespace falls back to the node ID, which
// is what the resource picker shows for it too.
folder("f-unnamed", " "),
},
"f-slash": {adoc("d-slash", "A/B 手册")},
"f-punct": {adoc("d-punct", "符号")},
"f-dup-1": {adoc("d-dup-1", "第一份")},
"f-dup-2": {adoc("d-dup-2", "第二份")},
"f-unnamed": {adoc("d-unnamed", "无名目录")},
},
blocks: map[string][]json.RawMessage{
"d-slash": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"a"}}`)},
"d-punct": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"b"}}`)},
"d-dup-1": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"c"}}`)},
"d-dup-2": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"d"}}`)},
"d-unnamed": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"e"}}`)},
},
nodeErrors: make(map[string]error),
blockErrors: make(map[string]error),
}
connector := testConnector(api)
items, err := connector.FetchAll(
context.Background(), tenantFolderPathTestConfig("ws-odd"), []string{"ws-odd"},
)
if err != nil {
t.Fatalf("FetchAll() error = %v", err)
}
// "安全/中心" cannot invent a level either, and neither can "A/B" or the
// document name: the file name keeps the sanitised form it already had.
assertFileNames(t, fileNamesByDocument(t, items), map[string]string{
"d-slash": "安全_中心/A_B/A_B 手册.md",
"d-punct": "安全_中心/_______/符号.md",
"d-dup-1": "安全_中心/重复/第一份.md",
"d-dup-2": "安全_中心/重复/第二份.md",
"d-unnamed": "安全_中心/f-unnamed/无名目录.md",
})
}
// Turning the switch on in an existing data source is an ingest-path change,
// not a migration: an incremental sync compares content revisions, so the
// documents already in the knowledge base are not re-read and therefore keep
// the flat file names they were ingested with — and, above all, the folder
// dimension must never make the connector report them as deleted.
func TestDingTalkEnablingFolderPathsDoesNotRelocateOrDeleteExistingDocuments(t *testing.T) {
captureLogs(t)
connector := testConnector(tenantFolderPathFixture())
items, cursor, err := connector.FetchIncremental(
context.Background(), tenantUploadedFilesConfig(tenantWorkspaceID), nil,
)
if err != nil {
t.Fatalf("first FetchIncremental() error = %v", err)
}
if names := fileNamesByDocument(t, items); names["d-tianzhu-faq-1"] != "天诛渗透攻防 FAQ 一.md" {
t.Fatalf("first sync FileName = %q, want the flat name", names["d-tianzhu-faq-1"])
}
items, _, err = connector.FetchIncremental(
context.Background(), tenantFolderPathTestConfig(tenantWorkspaceID), cursor,
)
if err != nil {
t.Fatalf("second FetchIncremental() error = %v", err)
}
for _, item := range items {
if item.IsDeleted {
t.Fatalf("enabling folder paths reported document %q as deleted", item.ExternalID)
}
}
if len(items) != 0 {
t.Fatalf("second sync returned %d items, want none: unchanged documents are not "+
"re-read, so they keep the file name they were ingested with", len(items))
}
}
@@ -0,0 +1,731 @@
package dingtalk
import (
"encoding/json"
"fmt"
"net/url"
"sort"
"strconv"
"strings"
)
const maxRenderDepth = 32
type block struct {
BlockType string `json:"blockType"`
Paragraph textBlock `json:"paragraph"`
Heading headingBlock `json:"heading"`
Blockquote textBlock `json:"blockquote"`
OrderedList listBlock `json:"orderedList"`
UnorderedList listBlock `json:"unorderedList"`
Table tableBlock `json:"table"`
Code codeBlock `json:"code"`
Attachment attachmentBlock `json:"attachment"`
Unknown unknownBlock `json:"unknown"`
Children []json.RawMessage `json:"children"`
}
type textBlock struct {
Text string `json:"text"`
}
type headingBlock struct {
Level flexibleInt `json:"level"`
Text string `json:"text"`
}
type listBlock struct {
Text string `json:"text"`
List struct {
Level flexibleInt `json:"level"`
} `json:"list"`
}
type tableBlock struct {
Cells json.RawMessage `json:"cells"`
}
// codeBlock is the payload the Blocks API returns for a code block:
// {"syntax":"bash","text":"...","title":"..."}. The language key is syntax
// (not "language", as some public references assume) and title is optional.
type codeBlock struct {
Text string `json:"text"`
Syntax string `json:"syntax"`
Title string `json:"title"`
}
// attachmentBlock identifies a file stored in the document. The payload has no
// download URL: resourceId is an opaque identifier, not a resolvable address.
type attachmentBlock struct {
Name string `json:"name"`
Size int64 `json:"size"`
Type string `json:"type"`
ViewType string `json:"viewType"`
ResourceID string `json:"resourceId"`
}
// unknownBlock is the payload of a block whose real type the API did not map:
// {"rawType":"..."}. It carries no body text, only the original type name.
type unknownBlock struct {
RawType string `json:"rawType"`
Text string `json:"text"`
}
type inline struct {
ElementType string `json:"elementType"`
Text string `json:"text"`
Bold bool `json:"bold"`
Italic bool `json:"italic"`
Strike bool `json:"strike"`
Stike bool `json:"stike"` // DingTalk payloads have used this misspelling.
Fonts string `json:"fonts"`
Properties inlineProperties `json:"properties"`
Children []json.RawMessage `json:"children"`
}
type inlineProperties struct {
Code string `json:"code"`
Src string `json:"src"`
Href string `json:"href"`
}
func renderDocument(title string, blocks []json.RawMessage) renderResult {
var builder strings.Builder
if title = strings.TrimSpace(title); title != "" {
title = strings.NewReplacer("\r", " ", "\n", " ").Replace(title)
builder.WriteString("# ")
builder.WriteString(escapeText(title))
builder.WriteString("\n\n")
}
unknown := make(map[string]struct{})
for _, raw := range blocks {
renderBlock(&builder, raw, 0, unknown)
}
markdown := strings.TrimSpace(builder.String())
if markdown != "" {
markdown += "\n"
}
unknownTypes := make([]string, 0, len(unknown))
for blockType := range unknown {
unknownTypes = append(unknownTypes, blockType)
}
sort.Strings(unknownTypes)
return renderResult{Markdown: markdown, UnknownTypes: unknownTypes}
}
func renderBlock(
builder *strings.Builder,
raw json.RawMessage,
depth int,
unknown map[string]struct{},
) {
if depth > maxRenderDepth {
unknown["max_depth"] = struct{}{}
return
}
var value block
if err := json.Unmarshal(raw, &value); err != nil {
unknown["invalid_json"] = struct{}{}
return
}
blockType := strings.ToLower(strings.TrimSpace(value.BlockType))
switch blockType {
case "paragraph":
text := renderInlines(value.Children, depth+1, unknown)
if text == "" {
text = escapeText(value.Paragraph.Text)
}
writeParagraph(builder, text)
case "heading":
text := renderInlines(value.Children, depth+1, unknown)
if text == "" {
text = escapeText(value.Heading.Text)
}
if text == "" {
return
}
level := int(value.Heading.Level)
if level < 1 {
level = 1
} else if level > 6 {
level = 6
}
fmt.Fprintf(builder, "%s %s\n\n", strings.Repeat("#", level), text)
case "blockquote":
text := renderInlines(value.Children, depth+1, unknown)
if text == "" {
text = escapeText(value.Blockquote.Text)
}
if text == "" {
return
}
for _, line := range strings.Split(text, "\n") {
fmt.Fprintf(builder, "> %s\n", line)
}
builder.WriteByte('\n')
case "orderedlist", "unorderedlist":
renderListBlock(builder, value, blockType, depth, 0, unknown)
case "callout", "columns":
if len(value.Children) == 0 {
// The Blocks API only returns first-level blocks. A container with
// no inlined children is indistinguishable from an empty callout,
// so surface it instead of silently dropping nested body text.
unknown["nested_blocks_unavailable"] = struct{}{}
return
}
renderChildBlocks(builder, value.Children, depth, unknown)
case "table":
renderTable(builder, parseTableCells(value.Table.Cells))
case "code":
renderCodeBlock(builder, value, depth, unknown)
case "attachment":
renderAttachmentBlock(builder, value, depth, unknown)
case "":
unknown["missing_block_type"] = struct{}{}
default:
marker := blockType
if rawType := strings.TrimSpace(value.Unknown.RawType); rawType != "" {
// The payload of this block carries no body text, only the real
// type name, so keep that name in the marker instead of the
// uninformative "unknown": it is what the metadata and the sync
// warning report.
marker = "unknown:" + rawType
}
unknown[marker] = struct{}{}
// Some unmodelled blocks still carry their body text: the live `sdt`
// block is a table of contents and holds the whole thing. The type stays
// unknown — the marker above still reports it — but the text must not be
// dropped just because the presentation semantics are not modelled.
if text := strings.TrimSpace(value.Unknown.Text); text != "" {
writeParagraph(builder, escapeText(text))
}
// Preserve useful content when DingTalk introduces a container block
// before the connector learns its presentation semantics.
renderChildBlocks(builder, value.Children, depth, unknown)
}
}
// renderListBlock renders one list block.
//
// Documented shape: children are inline elements and one block is one item —
// nesting comes from list.level (0-based) and the items of one list are linked
// by a shared listId across sibling blocks, not by structural nesting. The
// child walk below also accepts block children, which the contract does not
// produce: the previous implementation rendered inline children *or* block
// children (never both), so a payload outside the contract lost whichever kind
// it did not pick, sometimes without even an unknown-type marker.
//
// minLevel is the smallest indent level this list may use; pass 0 for a
// top-level list.
func renderListBlock(
builder *strings.Builder,
value block,
blockType string,
depth int,
minLevel int,
unknown map[string]struct{},
) {
if depth > maxRenderDepth {
unknown["max_depth"] = struct{}{}
return
}
level, marker := int(value.UnorderedList.List.Level), "- "
if blockType == "orderedlist" {
level, marker = int(value.OrderedList.List.Level), "1. "
}
if level < minLevel {
level = minLevel
}
if level < 0 {
level = 0
} else if level > maxRenderDepth {
level = maxRenderDepth
}
indent := strings.Repeat(" ", level)
// Inline children are the current item's own text and block children are
// further items, so walk the children in payload order: consecutive inline
// elements form one item, and every block child becomes its own item.
// The live Blocks API delivers one block per list item, with the item text
// in the block's own text field and no children at all: across every list
// block of nine production documents there is no children, no list.level
// and no listId. Every other text-bearing block type already falls back to
// its own text field; lists were the one that did not, so their content was
// dropped without even an unknown-type marker — the type is known, it just
// carried nothing the renderer read.
ownText := strings.TrimSpace(listOwnText(value, blockType))
if ownText != "" {
writeListItem(builder, indent, marker, escapeText(ownText))
}
var pending strings.Builder
flush := func() {
if text := pending.String(); text != "" {
writeListItem(builder, indent, marker, text)
}
pending.Reset()
}
for _, child := range value.Children {
childType := blockChildType(child)
if childType == "" {
if ownText != "" {
// A shape the API does not produce. The item text is already in
// the block's own field, so a second bullet would duplicate it;
// surface the shape instead of guessing which one is the item.
unknown["list_text_and_inline_children"] = struct{}{}
continue
}
pending.WriteString(renderInlines([]json.RawMessage{child}, depth+1, unknown))
continue
}
flush()
if childType == "orderedlist" || childType == "unorderedlist" {
var nested block
if err := json.Unmarshal(child, &nested); err != nil {
unknown["invalid_json"] = struct{}{}
continue
}
// Outside the documented contract: the Blocks API returns lists
// flat (one block per item, siblings linked by listId, nesting
// carried by list.level), so a list child that is itself a list
// should not appear. If one does, keep it below its parent rather
// than at the same indent, and never drop it.
renderListBlock(builder, nested, childType, depth+1, level+1, unknown)
continue
}
var item strings.Builder
renderBlock(&item, child, depth+1, unknown)
if text := strings.TrimSpace(item.String()); text != "" {
writeListItem(builder, indent, marker, text)
}
}
flush()
}
// listOwnText returns the item text a list block carries in its own payload.
// The live Blocks API puts one item per block and its text here.
func listOwnText(value block, blockType string) string {
if blockType == "orderedlist" {
return value.OrderedList.Text
}
return value.UnorderedList.Text
}
// blockChildType reports the block type of a list child, or "" when the child
// is an inline element (including an untyped text run) rather than a block.
func blockChildType(raw json.RawMessage) string {
var probe struct {
BlockType string `json:"blockType"`
ElementType string `json:"elementType"`
}
if err := json.Unmarshal(raw, &probe); err != nil {
return ""
}
if strings.TrimSpace(probe.ElementType) != "" {
return ""
}
return strings.ToLower(strings.TrimSpace(probe.BlockType))
}
// writeListItem writes one list item. Continuation lines of a multi-line item
// are aligned under the first line so the value cannot escape its bullet.
func writeListItem(builder *strings.Builder, indent string, marker string, text string) {
lines := strings.Split(text, "\n")
builder.WriteString(indent)
builder.WriteString(marker)
builder.WriteString(lines[0])
builder.WriteByte('\n')
if len(lines) == 1 {
return
}
continuation := strings.Repeat(" ", len(indent)+len(marker))
for _, line := range lines[1:] {
if line = strings.TrimRight(line, " \t"); line == "" {
continue
}
builder.WriteString(continuation)
builder.WriteString(line)
builder.WriteByte('\n')
}
}
func renderChildBlocks(
builder *strings.Builder,
children []json.RawMessage,
depth int,
unknown map[string]struct{},
) {
for _, child := range children {
renderBlock(builder, child, depth+1, unknown)
}
}
func renderInlines(
children []json.RawMessage,
depth int,
unknown map[string]struct{},
) string {
if depth > maxRenderDepth {
unknown["inline_max_depth"] = struct{}{}
return ""
}
var builder strings.Builder
for _, raw := range children {
var value inline
if err := json.Unmarshal(raw, &value); err != nil {
unknown["invalid_inline_json"] = struct{}{}
continue
}
elementType := strings.ToLower(strings.TrimSpace(value.ElementType))
switch elementType {
case "", "text":
builder.WriteString(styleText(value.Text, value))
case "sticker":
builder.WriteString(escapeText(value.Properties.Code))
case "image":
if src, ok := safeURL(value.Properties.Src); ok {
fmt.Fprintf(&builder, "![image](%s)", src)
}
case "link":
label := renderInlines(value.Children, depth+1, unknown)
href, ok := safeURL(value.Properties.Href)
if !ok {
builder.WriteString(label)
} else if label == "" {
fmt.Fprintf(&builder, "[%s](%s)", escapeLabel(href), href)
} else {
fmt.Fprintf(&builder, "[%s](%s)", label, href)
}
default:
unknown["inline_"+elementType] = struct{}{}
// Inline types this renderer does not model can carry their text in
// children instead of in a text field (slot is documented that way),
// so falling back to children keeps the run from vanishing.
if text := escapeText(value.Text); text != "" {
builder.WriteString(text)
} else {
builder.WriteString(renderInlines(value.Children, depth+1, unknown))
}
}
}
return builder.String()
}
func styleText(text string, value inline) string {
text = strings.ReplaceAll(text, "\x00", "")
if text == "" {
return ""
}
if strings.EqualFold(value.Fonts, "monospace") {
text = codeSpan(text)
} else {
text = escapeText(text)
}
if value.Bold {
text = "**" + text + "**"
}
if value.Italic {
text = "*" + text + "*"
}
if value.Strike || value.Stike {
text = "~~" + text + "~~"
}
return text
}
func safeURL(value string) (string, bool) {
value = strings.TrimSpace(value)
parsed, err := url.Parse(value)
if err != nil || parsed.Scheme == "" {
return "", false
}
switch strings.ToLower(parsed.Scheme) {
case "http", "https", "mailto":
return strings.NewReplacer(
"\\", "%5C",
" ", "%20",
"(", "%28",
")", "%29",
"<", "%3C",
">", "%3E",
).Replace(value), true
default:
return "", false
}
}
func writeParagraph(builder *strings.Builder, text string) {
if text != "" {
builder.WriteString(text)
builder.WriteString("\n\n")
}
}
// renderCodeBlock renders a code block as a fenced code block. The language
// comes from syntax, and a non-empty title becomes a bold line above the fence.
// A block without text stays unmodelled: an empty fence would only be noise, so
// the loss is still reported instead.
func renderCodeBlock(
builder *strings.Builder,
value block,
depth int,
unknown map[string]struct{},
) {
if strings.TrimSpace(value.Code.Text) == "" {
unknown["code"] = struct{}{}
// The documented shape carries no children, but a payload outside the
// contract must not lose them.
renderChildBlocks(builder, value.Children, depth, unknown)
return
}
if title := oneLine(value.Code.Title); title != "" {
fmt.Fprintf(builder, "**%s**\n\n", escapeText(title))
}
fence := strings.Repeat("`", codeFenceLength(value.Code.Text))
builder.WriteString(fence)
builder.WriteString(codeInfo(value.Code.Syntax))
builder.WriteByte('\n')
builder.WriteString(value.Code.Text)
if !strings.HasSuffix(value.Code.Text, "\n") {
builder.WriteByte('\n')
}
builder.WriteString(fence)
builder.WriteString("\n\n")
}
// codeFenceLength returns a fence longer than the longest backtick run inside
// text, so code that itself contains a fence cannot end the block early.
func codeFenceLength(text string) int {
longest := 0
for _, run := range strings.FieldsFunc(text, func(r rune) bool { return r != '`' }) {
if len(run) > longest {
longest = len(run)
}
}
if longest < 2 {
return 3
}
return longest + 1
}
// codeInfo returns the info string of the fence, or "" when the syntax value
// cannot be one: a backtick or a line break would break the fence line, and
// dropping it loses nothing because the code text is written verbatim.
func codeInfo(syntax string) string {
syntax = strings.TrimSpace(syntax)
if syntax == "" || strings.ContainsAny(syntax, "`\r\n") {
return ""
}
return syntax
}
// renderAttachmentBlock renders an attachment as one plain line: the payload
// holds no download URL, so the renderer names the file instead of fabricating
// a link that cannot be resolved. An attachment without a name stays
// unmodelled and is reported.
func renderAttachmentBlock(
builder *strings.Builder,
value block,
depth int,
unknown map[string]struct{},
) {
name := oneLine(value.Attachment.Name)
if name == "" {
unknown["attachment"] = struct{}{}
renderChildBlocks(builder, value.Children, depth, unknown)
return
}
line := "Attachment: " + escapeText(name)
if size := humanSize(value.Attachment.Size); size != "" {
line += " (" + size + ")"
}
writeParagraph(builder, line)
}
// humanSize formats a byte count with one decimal place. A size of zero or
// below means the API did not report one, so it is omitted rather than shown
// as "0.0 B".
func humanSize(size int64) string {
if size <= 0 {
return ""
}
const unit = 1024
switch {
case size < unit:
return fmt.Sprintf("%.1f B", float64(size))
case size < unit*unit:
return fmt.Sprintf("%.1f KB", float64(size)/unit)
case size < unit*unit*unit:
return fmt.Sprintf("%.1f MB", float64(size)/(unit*unit))
default:
return fmt.Sprintf("%.1f GB", float64(size)/(unit*unit*unit))
}
}
// oneLine collapses a value that is rendered inline so an embedded line break
// cannot split the surrounding Markdown construct.
func oneLine(value string) string {
return strings.TrimSpace(strings.NewReplacer("\r", " ", "\n", " ").Replace(value))
}
func renderTable(builder *strings.Builder, rows [][]string) {
columns := 0
for _, row := range rows {
if len(row) > columns {
columns = len(row)
}
}
if columns == 0 {
return
}
writeTableRow(builder, normalizeRow(rows[0], columns))
separator := make([]string, columns)
for index := range separator {
separator[index] = "---"
}
writeTableRow(builder, separator)
for _, row := range rows[1:] {
writeTableRow(builder, normalizeRow(row, columns))
}
builder.WriteByte('\n')
}
func normalizeRow(row []string, columns int) []string {
normalized := make([]string, columns)
for index := 0; index < len(row) && index < columns; index++ {
normalized[index] = escapeTableCell(row[index])
}
return normalized
}
func writeTableRow(builder *strings.Builder, row []string) {
fmt.Fprintf(builder, "| %s |\n", strings.Join(row, " | "))
}
func escapeText(value string) string {
value = strings.ReplaceAll(value, "\x00", "")
value = strings.ReplaceAll(value, "\\", "\\\\")
return strings.NewReplacer(
"`", "\\`",
"*", "\\*",
"_", "\\_",
"{", "\\{",
"}", "\\}",
"[", "\\[",
"]", "\\]",
"<", "\\<",
">", "\\>",
"#", "\\#",
"+", "\\+",
"-", "\\-",
"!", "\\!",
).Replace(value)
}
func escapeLabel(value string) string {
value = strings.ReplaceAll(value, "\\", "\\\\")
value = strings.ReplaceAll(value, "[", "\\[")
return strings.ReplaceAll(value, "]", "\\]")
}
func escapeTableCell(value string) string {
value = escapeText(value)
value = strings.ReplaceAll(value, "|", "\\|")
value = strings.ReplaceAll(value, "\r\n", "<br>")
return strings.ReplaceAll(value, "\n", "<br>")
}
func codeSpan(value string) string {
delimiter := "`"
for strings.Contains(value, delimiter) {
delimiter += "`"
}
if len(delimiter) == 1 {
return delimiter + value + delimiter
}
return delimiter + " " + value + " " + delimiter
}
type flexibleInt int
func (f *flexibleInt) UnmarshalJSON(data []byte) error {
*f = 0
if len(data) == 0 || string(data) == "null" {
return nil
}
var n int
if err := json.Unmarshal(data, &n); err == nil {
*f = flexibleInt(n)
return nil
}
var s string
if err := json.Unmarshal(data, &s); err != nil {
return nil
}
s = strings.ToLower(strings.TrimSpace(s))
s = strings.TrimPrefix(s, "heading-")
s = strings.TrimPrefix(s, "h")
n, err := strconv.Atoi(s)
if err != nil {
return nil
}
*f = flexibleInt(n)
return nil
}
func parseTableCells(raw json.RawMessage) [][]string {
if len(raw) == 0 || string(raw) == "null" {
return nil
}
var rows [][]string
if err := json.Unmarshal(raw, &rows); err == nil {
return rows
}
var generic [][]any
if err := json.Unmarshal(raw, &generic); err != nil {
return nil
}
out := make([][]string, len(generic))
for i, row := range generic {
out[i] = make([]string, len(row))
for j, cell := range row {
out[i][j] = tableCellText(cell)
}
}
return out
}
func tableCellText(cell any) string {
switch value := cell.(type) {
case nil:
return ""
case string:
return value
case float64:
return strconv.FormatFloat(value, 'f', -1, 64)
case bool:
return strconv.FormatBool(value)
case map[string]any:
if text, ok := value["text"].(string); ok && strings.TrimSpace(text) != "" {
return text
}
if children, ok := value["children"].([]any); ok {
var builder strings.Builder
for _, child := range children {
builder.WriteString(tableCellText(child))
}
return builder.String()
}
return ""
default:
return ""
}
}
@@ -0,0 +1,247 @@
package dingtalk
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
// The shapes pinned in this file come from read-only probes of real documents:
// a code block carries {"syntax","text","title"} with an optional title, an
// attachment carries file metadata but no download URL, and a block the API
// could not map carries only {"rawType"}. All fixtures below are synthetic.
func TestRenderCodeBlockUsesSyntaxAsLanguage(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"code","code":{"syntax":"bash","text":"echo hello"}}`),
})
want := "# 测试文档\n\n```bash\necho hello\n```\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
func TestRenderCodeBlockWithoutSyntaxOrTitle(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"code","code":{"text":"plain code"}}`),
})
want := "```\nplain code\n```\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
func TestRenderCodeBlockWritesTitleAboveTheFence(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"code","code":{"syntax":"bash","title":"Example *script*","text":"ls"}}`),
})
want := "**Example \\*script\\***\n\n```bash\nls\n```\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
// Code that itself contains a fence must not terminate the block early, so the
// fence grows past the longest backtick run in the text. The payload is written
// as an interpreted string because a raw one cannot hold the backticks.
func TestRenderCodeBlockLengthensFenceAroundEmbeddedFence(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON("{\"blockType\":\"code\",\"code\":{\"syntax\":\"markdown\"," +
"\"text\":\"before\\n```\\ninner\\n```\\nafter\"}}"),
})
want := "````markdown\nbefore\n```\ninner\n```\nafter\n````\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
func TestCodeFenceLengthOutgrowsEmbeddedBacktickRuns(t *testing.T) {
for _, test := range []struct {
name string
text string
want int
}{
{name: "no backtick", text: "plain", want: 3},
{name: "single backtick", text: "a `b` c", want: 3},
{name: "two backticks", text: "a ``b`` c", want: 3},
{name: "fence inside", text: "a ```b``` c", want: 4},
{name: "long run", text: "a `````b````` c", want: 6},
{name: "fence only", text: "```", want: 4},
} {
t.Run(test.name, func(t *testing.T) {
if got := codeFenceLength(test.text); got != test.want {
t.Fatalf("codeFenceLength(%q) = %d, want %d", test.text, got, test.want)
}
})
}
}
// A code block without text has nothing to fence. An empty fence would only be
// noise, so the block stays reported as an unmodelled payload; children outside
// the documented shape are rendered rather than dropped.
func TestRenderCodeBlockWithoutTextIsReportedNotRendered(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"code","code":{"syntax":"bash","title":"Example"},` +
`"children":[{"blockType":"paragraph","paragraph":{"text":"kept body"}}]}`),
})
if strings.Contains(result.Markdown, "```") || strings.Contains(result.Markdown, "**Example**") {
t.Fatalf("empty code block rendered a fragment:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "kept body") {
t.Fatalf("child content lost:\n%s", result.Markdown)
}
if want := []string{"code"}; !reflect.DeepEqual(result.UnknownTypes, want) {
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
}
}
// The attachment payload has no download URL, so the renderer only names the
// file. Sizes are byte counts with binary units and one decimal place; a size
// the API did not report is omitted instead of rendered as "0.0 B".
func TestRenderAttachmentFormatsNameAndSize(t *testing.T) {
for _, test := range []struct {
name string
payload string
want string
}{
{
name: "half a kilobyte stays in bytes",
payload: `{"name":"example.pdf","size":512}`,
want: "Attachment: example.pdf (512.0 B)\n",
},
{
name: "just below a kilobyte",
payload: `{"name":"example.pdf","size":1023}`,
want: "Attachment: example.pdf (1023.0 B)\n",
},
{
name: "kilobyte boundary",
payload: `{"name":"example.pdf","size":1024}`,
want: "Attachment: example.pdf (1.0 KB)\n",
},
{
name: "kilobytes",
payload: `{"name":"example.pdf","size":1229}`,
want: "Attachment: example.pdf (1.2 KB)\n",
},
{
name: "megabytes",
payload: `{"name":"example.pdf","size":1258291}`,
want: "Attachment: example.pdf (1.2 MB)\n",
},
{
name: "gigabytes",
payload: `{"name":"example.pdf","size":2147483648}`,
want: "Attachment: example.pdf (2.0 GB)\n",
},
{
name: "size omitted",
payload: `{"name":"example.pdf"}`,
want: "Attachment: example.pdf\n",
},
{
name: "zero size omitted",
payload: `{"name":"example.pdf","size":0}`,
want: "Attachment: example.pdf\n",
},
{
name: "negative size omitted",
payload: `{"name":"example.pdf","size":-1}`,
want: "Attachment: example.pdf\n",
},
{
name: "without resource id",
payload: `{"name":"example.pdf","size":1024,"type":"pdf","viewType":"preview"}`,
want: "Attachment: example.pdf (1.0 KB)\n",
},
} {
t.Run(test.name, func(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"attachment","attachment":` + test.payload + `}`),
})
if result.Markdown != test.want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, test.want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
})
}
}
// The name is document content, not a link target, and the opaque resourceId is
// never turned into a download URL because the payload has no resolvable one.
func TestRenderAttachmentEscapesNameAndBuildsNoLink(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"attachment","attachment":{"name":"example_[draft]*.pdf","size":1024,` +
`"resourceId":"res-synthetic-1"}}`),
})
want := "Attachment: example\\_\\[draft\\]\\*.pdf (1.0 KB)\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
for _, forbidden := range []string{"](", "http", "res-synthetic-1"} {
if strings.Contains(result.Markdown, forbidden) {
t.Fatalf("attachment rendered %q:\n%s", forbidden, result.Markdown)
}
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
func TestRenderAttachmentWithoutNameIsReportedNotRendered(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"attachment","attachment":{"size":1024,"resourceId":"res-synthetic-1"},` +
`"children":[{"blockType":"paragraph","paragraph":{"text":"kept body"}}]}`),
})
if strings.Contains(result.Markdown, "Attachment:") {
t.Fatalf("nameless attachment rendered a line:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "kept body") {
t.Fatalf("child content lost:\n%s", result.Markdown)
}
if want := []string{"attachment"}; !reflect.DeepEqual(result.UnknownTypes, want) {
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
}
}
// A block the API could not map carries no body text, only the real type name.
// Keeping that name in the marker is what makes the document metadata and the
// sync warning actionable, and children outside the documented shape are still
// rendered instead of dropped.
func TestRenderUnknownBlockKeepsRawTypeVisible(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"unknown","unknown":{"rawType":"card"},` +
`"children":[{"blockType":"paragraph","paragraph":{"text":"card body"}}]}`),
rawJSON(`{"blockType":"unknown","unknown":{}}`),
rawJSON(`{"blockType":"unknown","unknown":{"rawType":" "}}`),
})
if !strings.Contains(result.Markdown, "card body") {
t.Fatalf("child content lost:\n%s", result.Markdown)
}
if want := []string{"unknown", "unknown:card"}; !reflect.DeepEqual(result.UnknownTypes, want) {
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
}
}
@@ -0,0 +1,114 @@
package dingtalk
import (
"encoding/json"
"testing"
)
// A list block can carry inline children (the item text) and block children
// (one per item) at the same time. Both kinds must survive rendering: an inline
// item used to shadow every block item that followed it.
func TestRenderListKeepsInlineAndBlockItems(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"level":0}},"children":[` +
`{"elementType":"text","text":"第一项"},` +
`{"blockType":"paragraph","paragraph":{"text":"第二项整段内容"}}]}`),
})
want := "# 测试文档\n\n- 第一项\n- 第二项整段内容\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
// Items delivered as block children must keep one bullet line each instead of
// being flattened onto a single line.
func TestRenderListEmitsOneBulletPerBlockItem(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"level":0}},"children":[` +
`{"blockType":"paragraph","paragraph":{"text":"甲项"}},` +
`{"blockType":"paragraph","paragraph":{"text":"乙项"}},` +
`{"blockType":"paragraph","paragraph":{"text":"丙项"}}]}`),
})
want := "# 测试文档\n\n- 甲项\n- 乙项\n- 丙项\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
}
// Inline and block children keep their payload order, so an inline run that
// follows a block item is not hoisted above it or merged into another item.
func TestRenderListKeepsItemOrder(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"orderedList","orderedList":{"list":{"level":0}},"children":[` +
`{"blockType":"paragraph","paragraph":{"text":"块项"}},` +
`{"elementType":"text","text":"内联项一"},` +
`{"elementType":"text","text":"内联项二"}]}`),
})
want := "1. 块项\n1. 内联项一内联项二\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
}
// Nested lists are indented by their own level, and never sit at or above the
// parent list even when the payload repeats the parent level.
func TestRenderListIndentsNestedLists(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"level":0}},"children":[` +
`{"elementType":"text","text":"父项"},` +
`{"blockType":"unorderedList","unorderedList":{"list":{"level":1}},"children":[` +
`{"elementType":"text","text":"子项"}]},` +
`{"blockType":"unorderedList","unorderedList":{"list":{"level":0}},"children":[` +
`{"elementType":"text","text":"孙项同层级"}]}]}`),
})
want := "- 父项\n - 子项\n - 孙项同层级\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
}
// A multi-line item stays inside its bullet: continuation lines are aligned
// under the first line rather than escaping to the document root.
func TestRenderListIndentsContinuationLines(t *testing.T) {
// A document title keeps the leading indentation of the first list from
// being trimmed away, matching how these lists appear in real documents.
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"level":1}},"children":[` +
`{"blockType":"paragraph","paragraph":{"text":"第一行\n第二行"}}]}`),
})
want := "# 测试文档\n\n - 第一行\n 第二行\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
}
// The documented list shape is flat: one block per item, nesting carried by
// list.level, the items of one list linked by a shared listId across sibling
// blocks. This pins that main path — two sibling items at different levels —
// so the defensive block-child handling above cannot become the assumed model.
func TestRenderListFollowsTheFlatDocumentedShape(t *testing.T) {
result := renderDocument("", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"listId":"list-1","level":0}},` +
`"children":[{"text":"父项"}]}`),
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"listId":"list-1","level":1}},` +
`"children":[{"text":"子项"}]}`),
rawJSON(`{"blockType":"unorderedList","unorderedList":{"list":{"listId":"list-2","level":0}},` +
`"children":[{"text":"另一组的项"}]}`),
})
want := "- 父项\n - 子项\n- 另一组的项\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
@@ -0,0 +1,130 @@
package dingtalk
import (
"encoding/json"
"testing"
)
// Fixtures in this file are **live payloads**, copied from
// `GET /v1.0/doc/suites/documents/{id}/blocks` against a production tenant and
// only shortened where marked. They exist because the list renderer was once
// written against a shape the API never returns — `children` — while the real
// response carries one item per block with the text in the block's own field.
// Nine production documents, every list block: no `children`, no `list.level`,
// no `listId`. A fixture invented from the docs cannot catch that; these can.
// The live shape of an unordered list item: the whole item is `text`, nothing else.
func TestRenderListReadsTheLiveFlatShape(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","index":87,"id":"m050v0j3o1iic0pr7xg",` +
`"unorderedList":{"text":"确认是否自定义全端口,默认是常见端口"}}`),
rawJSON(`{"blockType":"orderedList","index":88,"id":"m050w04e41a0sfbcy1",` +
`"orderedList":{"text":"第一步:确认资产范围"}}`),
})
want := "# 测试文档\n\n- 确认是否自定义全端口,默认是常见端口\n1. 第一步:确认资产范围\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
// Consecutive live list blocks are consecutive items of one list, and every one
// of them must survive. This is the regression that shipped: 190 of 190 list
// items were dropped, silently, because the type was "known" and so never
// showed up in the unknown-type report either.
func TestRenderListKeepsEveryItemOfALiveDocument(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","index":1,"id":"a","unorderedList":{"text":"项目分享(团队版中)"}}`),
rawJSON(`{"blockType":"unorderedList","index":2,"id":"b","unorderedList":{"text":"项目报告导出"}}`),
rawJSON(`{"blockType":"unorderedList","index":3,"id":"c","unorderedList":{"text":"任务下发"}}`),
})
want := "# 测试文档\n\n- 项目分享(团队版中)\n- 项目报告导出\n- 任务下发\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
}
// Multi-line items keep their continuation lines aligned under the first line,
// so the value cannot escape its bullet.
func TestRenderListKeepsLiveMultiLineItem(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"orderedList","index":4,"id":"d",` +
`"orderedList":{"text":"连接到内网探测模块:\n执行所下载的探测Agent"}}`),
})
want := "# 测试文档\n\n1. 连接到内网探测模块:\n 执行所下载的探测Agent\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
}
// The live `sdt` block is a table of contents and carries the whole thing in
// `text`. The type is still unmodelled, so the marker must stay — but dropping
// the text because the presentation is unknown loses the document's contents
// page. Verified live: 1,212 characters in one block.
func TestRenderUnknownBlockRendersItsLiveText(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unknown","index":19,"id":"lqaap37i2lv2yn7i5w7",` +
`"unknown":{"rawType":"sdt","text":"目录目录1前言11. 产品介绍1"}}`),
})
want := "# 测试文档\n\n目录目录1前言11. 产品介绍1\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 1 || result.UnknownTypes[0] != "unknown:sdt" {
t.Fatalf("UnknownTypes = %#v, want [unknown:sdt]", result.UnknownTypes)
}
}
// Not every unmodelled block has text: the live `card` and `sectionBr` blocks
// carry only `rawType`, so they stay a marker and render nothing.
func TestRenderUnknownBlockWithoutTextStaysAMarker(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unknown","index":21,"id":"mulaiyzgurq2s6o7b2f",` +
`"unknown":{"rawType":"sectionBr"}}`),
})
want := "# 测试文档\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 1 || result.UnknownTypes[0] != "unknown:sectionBr" {
t.Fatalf("UnknownTypes = %#v, want [unknown:sectionBr]", result.UnknownTypes)
}
}
// A block carrying both its own text and inline children is a shape the API does
// not produce. Emitting both would duplicate the item, so the shape is reported
// instead of guessed at.
func TestRenderListFlagsOwnTextAndInlineChildrenTogether(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","unorderedList":{"text":"甲"},` +
`"children":[{"elementType":"text","text":"甲"}]}`),
})
want := "# 测试文档\n\n- 甲\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 1 || result.UnknownTypes[0] != "list_text_and_inline_children" {
t.Fatalf("UnknownTypes = %#v, want [list_text_and_inline_children]", result.UnknownTypes)
}
}
// Escaping still applies to the block's own text, so an item that starts with a
// marker character cannot turn into a nested list or a heading.
func TestRenderListEscapesLiveOwnText(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"unorderedList","unorderedList":{"text":"- 不是子列表"}}`),
})
want := "# 测试文档\n\n- \\- 不是子列表\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
}
@@ -0,0 +1,202 @@
package dingtalk
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
func TestRenderDocumentSupportsDocumentedBlocks(t *testing.T) {
blocks := []json.RawMessage{
rawJSON(`{"blockType":"heading","heading":{"level":2,"text":"Overview"}}`),
rawJSON(`{
"blockType":"paragraph",
"children":[
{"elementType":"text","text":"bold","bold":true},
{"elementType":"text","text":" and 2 * 3 "},
{"elementType":"link","properties":{"href":"https://example.com/a"},
"children":[{"elementType":"text","text":"link"}]},
{"elementType":"image","properties":{"src":"https://example.com/image.png"}}
]
}`),
rawJSON(`{"blockType":"blockquote","blockquote":{"text":"first\nsecond"}}`),
rawJSON(`{
"blockType":"orderedList",
"orderedList":{"list":{"level":1}},
"children":[{"elementType":"text","text":"nested"}]
}`),
rawJSON(`{"blockType":"table","table":{"cells":[["A","B"],["1","x|y"]]}}`),
rawJSON(`{
"blockType":"callout",
"children":[{"blockType":"paragraph","paragraph":{"text":"note"}}]
}`),
}
result := renderDocument("Team | Notes", blocks)
for _, expected := range []string{
"# Team | Notes",
"## Overview",
"**bold** and 2 \\* 3 [link](https://example.com/a)![image](https://example.com/image.png)",
"> first\n> second",
" 1. nested",
"| A | B |\n| --- | --- |\n| 1 | x\\|y |",
"note",
} {
if !strings.Contains(result.Markdown, expected) {
t.Errorf("Markdown missing %q:\n%s", expected, result.Markdown)
}
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v", result.UnknownTypes)
}
}
func TestRenderDocumentHandlesUnknownAndUnsafeContent(t *testing.T) {
result := renderDocument("Doc", []json.RawMessage{
rawJSON(`{
"blockType":"futureContainer",
"children":[{"blockType":"paragraph","paragraph":{"text":"preserved"}}]
}`),
rawJSON(`{
"blockType":"paragraph",
"children":[
{"elementType":"link","properties":{"href":"javascript:alert(1)"},
"children":[{"elementType":"text","text":"safe label"}]},
{"elementType":"image","properties":{"src":"data:text/html,unsafe"}},
{"elementType":"futureInline","text":"fallback"}
]
}`),
json.RawMessage(`{`),
})
if strings.Contains(result.Markdown, "javascript:") || strings.Contains(result.Markdown, "data:") {
t.Fatalf("unsafe URL rendered:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "preserved") ||
!strings.Contains(result.Markdown, "safe labelfallback") {
t.Fatalf("useful fallback content lost:\n%s", result.Markdown)
}
wantUnknown := []string{"futurecontainer", "inline_futureinline", "invalid_json"}
if !reflect.DeepEqual(result.UnknownTypes, wantUnknown) {
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, wantUnknown)
}
}
func TestSanitizeFilenameDoesNotSplitUTF8(t *testing.T) {
name := strings.Repeat("文", 100) + "/draft"
sanitized := sanitizeFilename(name)
if !strings.HasSuffix(sanitized, "文") || len(sanitized) > 200 {
t.Fatalf("sanitizeFilename() = %q (%d bytes)", sanitized, len(sanitized))
}
if sanitized = sanitizeFilename("line\nname"); sanitized != "line_name" {
t.Fatalf("sanitizeFilename() retained control character: %q", sanitized)
}
}
func TestRenderDocumentAcceptsOfficialBlockVariants(t *testing.T) {
result := renderDocument("Doc", []json.RawMessage{
rawJSON(`{"blockType":"heading","heading":{"level":"heading-3","text":"Section"}}`),
rawJSON(`{
"blockType":"paragraph",
"children":[
{"elementType":"text","text":"gone","strike":true},
{"elementType":"text","text":" also","stike":true}
]
}`),
rawJSON(`{"blockType":"table","table":{"cells":[[{"text":"A"},{"text":"B"}],[{"text":"1"},{"text":"2"}]]}}`),
rawJSON(`{
"blockType":"unorderedList",
"unorderedList":{"list":{"level":"0"}},
"children":[{"blockType":"paragraph","paragraph":{"text":"item body"}}]
}`),
rawJSON(`{"blockType":"callout"}`),
})
for _, expected := range []string{
"### Section",
"~~gone~~",
"~~ also~~",
"| A | B |",
"| 1 | 2 |",
"- item body",
} {
if !strings.Contains(result.Markdown, expected) {
t.Errorf("Markdown missing %q:\n%s", expected, result.Markdown)
}
}
if !reflect.DeepEqual(result.UnknownTypes, []string{"nested_blocks_unavailable"}) {
t.Fatalf("UnknownTypes = %#v", result.UnknownTypes)
}
}
// A block whose type is modelled but whose payload carries nothing renderable
// (a code block without text, an attachment without a name) must still be
// collected, so the loss stays visible instead of turning into an empty
// fragment of Markdown.
func TestRenderDocumentCollectsUnknownBlockTypes(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"code","code":{"syntax":"bash"}}`),
rawJSON(`{"blockType":"attachment","attachment":{"resourceId":"res-synthetic-1"}}`),
rawJSON(`{"blockType":"paragraph","paragraph":{"text":"正文仍然保留"}}`),
})
if !strings.Contains(result.Markdown, "正文仍然保留") {
t.Fatalf("known content lost:\n%s", result.Markdown)
}
if strings.Contains(result.Markdown, "```") || strings.Contains(result.Markdown, "Attachment:") {
t.Fatalf("empty payload rendered a fragment:\n%s", result.Markdown)
}
if want := []string{"attachment", "code"}; !reflect.DeepEqual(result.UnknownTypes, want) {
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
}
}
// The list fix must not change how ordinary documents render: paragraphs,
// headings, styles, blockquotes, tables and inline-only lists keep their exact
// Markdown output.
func TestRenderDocumentKeepsOrdinaryBlocksStable(t *testing.T) {
result := renderDocument("标题 Doc", []json.RawMessage{
rawJSON(`{"blockType":"heading","heading":{"level":2,"text":"Overview"}}`),
rawJSON(`{"blockType":"paragraph","children":[` +
`{"elementType":"text","text":"bold","bold":true},` +
`{"elementType":"text","text":" and plain"}]}`),
rawJSON(`{"blockType":"blockquote","blockquote":{"text":"first\nsecond"}}`),
rawJSON(`{"blockType":"table","table":{"cells":[["A","B"],["1","x|y"]]}}`),
rawJSON(`{"blockType":"orderedList","orderedList":{"list":{"level":1}},` +
`"children":[{"elementType":"text","text":"nested"}]}`),
rawJSON(`{"blockType":"paragraph","paragraph":{"text":"tail"}}`),
})
want := "# 标题 Doc\n\n" +
"## Overview\n\n" +
"**bold** and plain\n\n" +
"> first\n> second\n\n" +
"| A | B |\n| --- | --- |\n| 1 | x\\|y |\n\n" +
" 1. nested\n" +
"tail\n"
if result.Markdown != want {
t.Fatalf("Markdown = %q, want %q", result.Markdown, want)
}
if len(result.UnknownTypes) != 0 {
t.Fatalf("UnknownTypes = %#v, want none", result.UnknownTypes)
}
}
// Inline element types the renderer does not model may carry their text in
// children rather than in a text field (slot is documented that way), and those
// runs used to disappear: the default branch wrote an empty text and stopped.
func TestRenderDocumentKeepsTextOfUnmodelledInlineElements(t *testing.T) {
result := renderDocument("测试文档", []json.RawMessage{
rawJSON(`{"blockType":"paragraph","children":[` +
`{"elementType":"text","text":"由 "},` +
`{"elementType":"slot","children":[{"elementType":"text","text":"张三"}]},` +
`{"elementType":"text","text":" 负责"}]}`),
})
if !strings.Contains(result.Markdown, "由 张三 负责") {
t.Fatalf("inline run lost its unmodelled element:\n%s", result.Markdown)
}
if want := []string{"inline_slot"}; !reflect.DeepEqual(result.UnknownTypes, want) {
t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, want)
}
}
@@ -0,0 +1,154 @@
package dingtalk
import (
"fmt"
"net/url"
"strings"
"unicode"
)
const (
resourceIDPrefix = "dingtalk:v1?"
maxResourceIDBytes = 8 * 1024
maxResourceDepth = 64
)
// resourceReference is embedded in resource picker IDs for folders and
// documents. Workspace IDs remain unchanged for compatibility with data
// sources created by earlier builds of the connector.
type resourceReference struct {
WorkspaceID string
NodeID string
Ancestors []string
}
func (r resourceReference) child(nodeID string) resourceReference {
ancestors := append([]string(nil), r.Ancestors...)
if r.NodeID != "" {
ancestors = append(ancestors, r.NodeID)
}
return resourceReference{
WorkspaceID: r.WorkspaceID,
NodeID: strings.TrimSpace(nodeID),
Ancestors: ancestors,
}
}
func encodeResourceReference(ref resourceReference) (string, error) {
if err := validateResourceReference(ref); err != nil {
return "", err
}
if ref.NodeID == "" {
return ref.WorkspaceID, nil
}
values := url.Values{}
values.Set("workspace", ref.WorkspaceID)
values.Set("node", ref.NodeID)
for _, ancestor := range ref.Ancestors {
values.Add("ancestor", ancestor)
}
encoded := resourceIDPrefix + values.Encode()
if len(encoded) > maxResourceIDBytes {
return "", fmt.Errorf("DingTalk resource ID exceeds %d bytes", maxResourceIDBytes)
}
return encoded, nil
}
func decodeResourceReference(raw string) (resourceReference, error) {
if len(raw) == 0 || len(raw) > maxResourceIDBytes {
return resourceReference{}, fmt.Errorf("invalid DingTalk resource ID")
}
if !strings.HasPrefix(raw, resourceIDPrefix) {
ref := resourceReference{WorkspaceID: raw}
if err := validateResourceReference(ref); err != nil {
return resourceReference{}, err
}
return ref, nil
}
values, err := url.ParseQuery(strings.TrimPrefix(raw, resourceIDPrefix))
if err != nil {
return resourceReference{}, fmt.Errorf("parse DingTalk resource ID: %w", err)
}
for key := range values {
if key != "workspace" && key != "node" && key != "ancestor" {
return resourceReference{}, fmt.Errorf("DingTalk resource ID contains an unsupported field")
}
}
if len(values["workspace"]) != 1 || len(values["node"]) != 1 {
return resourceReference{}, fmt.Errorf("DingTalk resource ID has invalid workspace or node fields")
}
ref := resourceReference{
WorkspaceID: values.Get("workspace"),
NodeID: values.Get("node"),
Ancestors: append([]string(nil), values["ancestor"]...),
}
if err := validateResourceReference(ref); err != nil {
return resourceReference{}, err
}
return ref, nil
}
func validateResourceReference(ref resourceReference) error {
if err := validateExternalID("workspace", ref.WorkspaceID); err != nil {
return err
}
if ref.NodeID != "" {
if err := validateExternalID("node", ref.NodeID); err != nil {
return err
}
} else if len(ref.Ancestors) != 0 {
return fmt.Errorf("DingTalk workspace resource cannot have ancestors")
}
if len(ref.Ancestors) > maxResourceDepth {
return fmt.Errorf("DingTalk resource depth exceeds %d", maxResourceDepth)
}
seen := make(map[string]struct{}, len(ref.Ancestors)+1)
for _, ancestor := range ref.Ancestors {
if err := validateExternalID("ancestor", ancestor); err != nil {
return err
}
if _, exists := seen[ancestor]; exists {
return fmt.Errorf("DingTalk resource contains an ancestor cycle")
}
seen[ancestor] = struct{}{}
}
if _, exists := seen[ref.NodeID]; ref.NodeID != "" && exists {
return fmt.Errorf("DingTalk resource contains a node cycle")
}
return nil
}
func validateExternalID(kind, value string) error {
if value == "" || value != strings.TrimSpace(value) {
return fmt.Errorf("DingTalk resource has invalid %s ID", kind)
}
for _, r := range value {
if unicode.IsControl(r) {
return fmt.Errorf("DingTalk resource has invalid %s ID", kind)
}
}
return nil
}
func resourceAncestorIDs(ref resourceReference) ([]string, error) {
rootID, err := encodeResourceReference(resourceReference{WorkspaceID: ref.WorkspaceID})
if err != nil {
return nil, err
}
ancestors := []string{rootID}
for index, nodeID := range ref.Ancestors {
id, err := encodeResourceReference(resourceReference{
WorkspaceID: ref.WorkspaceID,
NodeID: nodeID,
Ancestors: append([]string(nil), ref.Ancestors[:index]...),
})
if err != nil {
return nil, err
}
ancestors = append(ancestors, id)
}
return ancestors, nil
}
@@ -0,0 +1,79 @@
package dingtalk
import (
"strings"
"testing"
)
func TestResourceReferenceRoundTripAndAncestors(t *testing.T) {
folder := resourceReference{WorkspaceID: "workspace", NodeID: "folder"}
document := folder.child("document")
documentID, err := encodeResourceReference(document)
if err != nil {
t.Fatal(err)
}
decoded, err := decodeResourceReference(documentID)
if err != nil {
t.Fatal(err)
}
if decoded.WorkspaceID != "workspace" || decoded.NodeID != "document" ||
len(decoded.Ancestors) != 1 || decoded.Ancestors[0] != "folder" {
t.Fatalf("decoded reference = %#v", decoded)
}
ancestorIDs, err := resourceAncestorIDs(decoded)
if err != nil {
t.Fatal(err)
}
folderID, err := encodeResourceReference(folder)
if err != nil {
t.Fatal(err)
}
if len(ancestorIDs) != 2 || ancestorIDs[0] != "workspace" || ancestorIDs[1] != folderID {
t.Fatalf("ancestor IDs = %#v", ancestorIDs)
}
}
func TestResourceReferenceRejectsMalformedOrCyclicIDs(t *testing.T) {
tooDeep := make([]string, maxResourceDepth+1)
for index := range tooDeep {
tooDeep[index] = strings.Repeat("a", index+1)
}
for _, ref := range []resourceReference{
{},
{WorkspaceID: " workspace"},
{WorkspaceID: "workspace", Ancestors: []string{"folder"}},
{WorkspaceID: "workspace", NodeID: "folder", Ancestors: []string{"folder"}},
{WorkspaceID: "workspace", NodeID: "document", Ancestors: []string{"folder", "folder"}},
{WorkspaceID: "workspace", NodeID: "document", Ancestors: tooDeep},
} {
if _, err := encodeResourceReference(ref); err == nil {
t.Fatalf("encodeResourceReference(%#v) error = nil", ref)
}
}
for _, raw := range []string{
resourceIDPrefix + "workspace=space",
resourceIDPrefix + "node=doc",
resourceIDPrefix + "workspace=space&workspace=other&node=doc",
resourceIDPrefix + "workspace=space&node=doc&unexpected=value",
} {
if _, err := decodeResourceReference(raw); err == nil {
t.Fatalf("decodeResourceReference(%q) error = nil", raw)
}
}
}
func TestResourceReferenceKeepsWorkspaceIDsBackwardCompatible(t *testing.T) {
decoded, err := decodeResourceReference("legacy-workspace")
if err != nil {
t.Fatal(err)
}
if decoded.WorkspaceID != "legacy-workspace" || decoded.NodeID != "" {
t.Fatalf("decoded legacy workspace = %#v", decoded)
}
encoded, err := encodeResourceReference(decoded)
if err != nil || encoded != "legacy-workspace" {
t.Fatalf("encoded workspace = %q, %v", encoded, err)
}
}
@@ -0,0 +1,62 @@
package dingtalk
import (
"strings"
"academy/internal/types"
)
// settingBool interprets a data source settings value as a boolean, returning
// def when the value is absent or of an unrecognised shape. Settings arrive
// from JSON, so a hand-edited config may carry either a real bool or its string
// form. The accepted spellings are the ones the Yuque connector's settingBool
// accepts, so every connector reads its switches the same way.
func settingBool(v interface{}, def bool) bool {
switch t := v.(type) {
case bool:
return t
case string:
switch strings.ToLower(strings.TrimSpace(t)) {
case "true", "1", "yes", "on":
return true
case "false", "0", "no", "off":
return false
}
}
return def
}
// documentSettings holds the optional ingestion switches carried in
// DataSourceConfig.Settings.
//
// Every switch defaults to false: a data source created before the switch
// existed keeps the behaviour it had then until an operator turns the switch on
// deliberately, so an upgrade never starts downloading or embedding content
// nobody asked for.
type documentSettings struct {
// IncludeUploadedFiles admits uploaded Office/PDF files (FILE/DOCUMENT
// nodes) that are downloaded from 钉盘 and parsed by Academy itself.
IncludeUploadedFiles bool
// PreserveFolderStructure encodes each document's DingTalk folder hierarchy
// into its FileName, so the document lands in the knowledge base folder
// that mirrors where it lives in the wiki instead of at the root.
//
// It is an ingest-path switch, not a migration. An already-ingested
// document is only re-read when its content changes, so turning the switch
// on does not relocate it; a full sync does.
PreserveFolderStructure bool
}
// parseDocumentSettings reads the settings bag of a data source. A missing or
// malformed value leaves the switch off, so a hand-edited config can only ever
// opt in to an ingest path, never alter one by accident.
func parseDocumentSettings(dataSourceConfig *types.DataSourceConfig) documentSettings {
var raw map[string]interface{}
if dataSourceConfig != nil {
raw = dataSourceConfig.Settings
}
return documentSettings{
IncludeUploadedFiles: settingBool(raw["include_uploaded_files"], false),
PreserveFolderStructure: settingBool(raw["preserve_folder_structure"], false),
}
}
@@ -0,0 +1,240 @@
package dingtalk
import (
"context"
"encoding/json"
"errors"
"testing"
"academy/internal/datasource"
"academy/internal/types"
)
func twoFolderFixture(t *testing.T) (*Connector, *fakeAPI, *types.DataSourceConfig, string, string) {
t.Helper()
a, err := encodeResourceReference(resourceReference{WorkspaceID: "space", NodeID: "a"})
if err != nil {
t.Fatal(err)
}
b, err := encodeResourceReference(resourceReference{WorkspaceID: "space", NodeID: "b"})
if err != nil {
t.Fatal(err)
}
api := &fakeAPI{
workspaces: []workspace{{ID: "space", RootNodeID: "root"}},
nodes: map[string][]node{"root": {{ID: "a", Type: "FOLDER"}, {ID: "b", Type: "FOLDER"}}},
blocks: map[string][]json.RawMessage{
"doc": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"content"}}`)},
},
nodeErrors: make(map[string]error), blockErrors: make(map[string]error),
}
return testConnector(api), api, testConfig(a, b), a, b
}
func syncDocument() node {
return node{
ID: "doc", WorkspaceID: "space", Name: "Doc", Type: "FILE",
Category: "ALIDOC", Extension: "adoc", ModifiedTime: "r1",
}
}
func assertNoDeletion(t *testing.T, items []types.FetchedItem) {
t.Helper()
for _, item := range items {
if item.IsDeleted {
t.Fatalf("unexpected deletion: %#v", item)
}
}
}
func TestIncrementalMoveBetweenSelectedFolders(t *testing.T) {
for _, from := range []string{"a", "b"} {
t.Run(from, func(t *testing.T) {
c, api, cfg, a, b := twoFolderFixture(t)
to, fromID, toID := "b", a, b
if from == "b" {
to, fromID, toID = "a", b, a
}
api.nodes[from] = []node{syncDocument()}
_, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
api.nodes[from] = nil
api.nodes[to] = []node{syncDocument()}
items, next, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatal(err)
}
assertNoDeletion(t, items)
if len(items) != 1 || len(items[0].Content) == 0 {
t.Fatalf("move result: %#v", items)
}
state, err := decodeCursor(next)
if err != nil {
t.Fatal(err)
}
if _, ok := state.Resources[fromID]["doc"]; ok {
t.Fatal("old scope retained moved document")
}
if state.Resources[toID]["doc"] != "r1" {
t.Fatalf("destination cursor: %#v", state)
}
items, _, err = c.FetchIncremental(context.Background(), cfg, next)
if err != nil || len(items) != 0 {
t.Fatalf("unchanged after move: %#v, %v", items, err)
}
})
}
}
func TestIncrementalMoveWithContentFailureRetries(t *testing.T) {
c, api, cfg, _, b := twoFolderFixture(t)
api.nodes["a"] = []node{syncDocument()}
_, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
api.nodes["a"] = nil
api.nodes["b"] = []node{syncDocument()}
api.blockErrors["doc"] = errors.New("permission denied")
items, next, err := c.FetchIncremental(context.Background(), cfg, cursor)
var partial *datasource.PartialFetchError
if !errors.As(err, &partial) {
t.Fatalf("want partial, got %v", err)
}
assertNoDeletion(t, items)
if len(items) != 1 || items[0].Metadata["error_reason_code"] != "dingtalk_document_failed" {
t.Fatalf("failure result: %#v", items)
}
state, _ := decodeCursor(next)
if _, ok := state.Resources[b]["doc"]; ok {
t.Fatal("failed destination advanced cursor")
}
delete(api.blockErrors, "doc")
items, _, err = c.FetchIncremental(context.Background(), cfg, next)
if err != nil || len(items) != 1 || len(items[0].Content) == 0 {
t.Fatalf("retry result: %#v, %v", items, err)
}
}
func TestIncrementalDefersDeletionUntilEveryScopeRecovers(t *testing.T) {
for _, resolveFailure := range []bool{false, true} {
t.Run(map[bool]string{false: "scan", true: "resolve"}[resolveFailure], func(t *testing.T) {
c, api, cfg, a, _ := twoFolderFixture(t)
api.nodes["a"] = []node{syncDocument()}
_, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
api.nodes["a"] = nil
if resolveFailure {
api.nodes["root"] = api.nodes["root"][:1]
} else {
api.nodeErrors["b"] = errors.New("temporary failure")
}
items, next, err := c.FetchIncremental(context.Background(), cfg, cursor)
var partial *datasource.PartialFetchError
if !errors.As(err, &partial) {
t.Fatalf("want partial, got %v", err)
}
assertNoDeletion(t, items)
state, _ := decodeCursor(next)
if state.Resources[a]["doc"] != "r1" {
t.Fatal("deferred deletion lost revision")
}
api.nodes["root"] = []node{{ID: "a", Type: "FOLDER"}, {ID: "b", Type: "FOLDER"}}
delete(api.nodeErrors, "b")
items, next, err = c.FetchIncremental(context.Background(), cfg, next)
if err != nil || len(items) != 1 || !items[0].IsDeleted {
t.Fatalf("recovered deletion: %#v, %v", items, err)
}
items, _, err = c.FetchIncremental(context.Background(), cfg, next)
if err != nil || len(items) != 0 {
t.Fatalf("duplicate deletion: %#v, %v", items, err)
}
})
}
}
func TestUnavailableSelectionPreservesCursorAndHealthyWork(t *testing.T) {
c, api, cfg, a, b := twoFolderFixture(t)
api.nodes["a"] = []node{syncDocument()}
_, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
// The saved folder no longer resolves, but the other selected folder works.
api.nodes["root"] = api.nodes["root"][1:]
healthy := syncDocument()
healthy.ID = "healthy"
api.nodes["b"] = []node{healthy}
api.blocks["healthy"] = api.blocks["doc"]
items, next, err := c.FetchIncremental(context.Background(), cfg, cursor)
var partial *datasource.PartialFetchError
if !errors.As(err, &partial) || len(items) != 2 {
t.Fatalf("result: %#v, %v", items, err)
}
if len(partial.Details) != 0 {
t.Fatal("raw diagnostics duplicated localized item errors")
}
assertNoDeletion(t, items)
if items[0].Metadata["error_reason_code"] != "dingtalk_resource_failed" ||
items[1].ExternalID != "healthy" || len(items[1].Content) == 0 {
t.Fatalf("items: %#v", items)
}
state, _ := decodeCursor(next)
if state.Resources[a]["doc"] != "r1" || state.Resources[b]["healthy"] != "r1" {
t.Fatalf("cursor: %#v", state)
}
// Recovery must retry the old scope instead of dropping its previous state.
api.nodes["root"] = []node{{ID: "a", Type: "FOLDER"}, {ID: "b", Type: "FOLDER"}}
changed := syncDocument()
changed.ModifiedTime = "r2"
api.nodes["a"] = []node{changed}
items, _, err = c.FetchIncremental(context.Background(), cfg, next)
if err != nil || len(items) != 1 || items[0].ExternalID != "doc" {
t.Fatalf("recovery: %#v, %v", items, err)
}
// Full sync isolates the same missing selection too.
api.nodes["root"] = api.nodes["root"][1:]
items, err = c.FetchAll(context.Background(), cfg, cfg.ResourceIDs)
if !errors.As(err, &partial) || len(items) != 2 || items[1].ExternalID != "healthy" {
t.Fatalf("full sync: %#v, %v", items, err)
}
}
func TestScopeResolutionCancellationDoesNotProduceCursor(t *testing.T) {
c, api, cfg, _, _ := twoFolderFixture(t)
api.nodeErrors["root"] = context.Canceled
items, next, err := c.FetchIncremental(context.Background(), cfg, nil)
if !errors.Is(err, context.Canceled) || next != nil || len(items) != 0 {
t.Fatalf("canceled: %#v, %#v, %v", items, next, err)
}
}
func TestFetchAllFromCursorReFetchesAndReconcilesDeletions(t *testing.T) {
c, api, cfg, _, _ := twoFolderFixture(t)
api.nodes["a"] = []node{syncDocument()}
_, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
items, next, err := c.FetchAllFromCursor(context.Background(), cfg, cfg.ResourceIDs, cursor)
if err != nil || next == nil || len(items) != 1 || len(items[0].Content) == 0 {
t.Fatalf("full re-fetch: %#v, %#v, %v", items, next, err)
}
api.nodes["a"] = nil
items, err = c.FetchAll(context.Background(), cfg, cfg.ResourceIDs)
if err != nil {
t.Fatal(err)
}
assertNoDeletion(t, items)
items, _, err = c.FetchAllFromCursor(context.Background(), cfg, cfg.ResourceIDs, next)
if err != nil || len(items) != 1 || !items[0].IsDeleted {
t.Fatalf("full sync deletion: %#v, %v", items, err)
}
}
@@ -0,0 +1,628 @@
package dingtalk
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"testing"
"academy/internal/datasource"
)
// A data source that names resources syncs those resources, so Validate has to
// check them instead of the whole tenant. Sampling the tenant answers a
// different question, and an unreadable workspace listed first can spend the
// probe budget before the selection is ever reached.
// recordingAPI records every node listing, so a test can prove which
// workspaces a validation walked. The fakeAPI counters only say which
// documents were probed.
type recordingAPI struct {
*fakeAPI
listed []string
}
func (a *recordingAPI) listNodes(ctx context.Context, parentID string) ([]node, error) {
a.listed = append(a.listed, parentID)
return a.fakeAPI.listNodes(ctx, parentID)
}
func (a *recordingAPI) listNodesPage(ctx context.Context, parentID, pageToken string) ([]node, string, error) {
a.listed = append(a.listed, parentID)
return a.fakeAPI.listNodesPage(ctx, parentID, pageToken)
}
// mustEncodeResource encodes a picker reference the way ListResources does, so
// the tests exercise the resource IDs a saved data source really carries.
func mustEncodeResource(t *testing.T, ref resourceReference) string {
t.Helper()
id, err := encodeResourceReference(ref)
if err != nil {
t.Fatalf("encode resource reference %+v: %v", ref, err)
}
return id
}
// realTenant mirrors the tenant shape this scoping was reported from: eight
// workspaces in the listing, the first ones full of documents the operator
// cannot read, and the reachable one — the fifth — behind them. The probe
// budget was spent on the first workspace, so the reachable documents were
// never probed and the data source could not be created, even though a sync of
// the same selection read every one of its documents.
func realTenant(t *testing.T, denied error) *fakeAPI {
t.Helper()
api := &fakeAPI{
workspaces: []workspace{
{ID: "security", RootNodeID: "root-security", Name: "Security"},
{ID: "ops", RootNodeID: "root-ops", Name: "Operations"},
{ID: "sales", RootNodeID: "root-sales", Name: "Sales"},
{ID: "hr", RootNodeID: "root-hr", Name: "People"},
{ID: "faq", RootNodeID: "root-faq", Name: "Product FAQ"},
{ID: "pm", RootNodeID: "root-pm", Name: "Projects"},
{ID: "design", RootNodeID: "root-design", Name: "Design"},
{ID: "archive", RootNodeID: "root-archive", Name: "Archive"},
},
nodes: map[string][]node{
"root-faq": {
{ID: "faq-folder", Name: "FAQ", Type: "FOLDER"},
},
"faq-folder": {
{ID: "faq-doc", Name: "Product FAQ", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
"root-design": {
{ID: "design-folder", Name: "Design", Type: "FOLDER"},
},
"root-archive": {
{ID: "archive-folder", Name: "Archive", Type: "FOLDER"},
},
},
blocks: map[string][]json.RawMessage{
"faq-doc": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
blockErrors: map[string]error{},
}
// Every other workspace exposes documents this operator cannot read,
// several of them enough to spend the whole probe budget.
for _, workspaceID := range []string{"security", "ops", "sales", "hr", "pm"} {
root := "root-" + workspaceID
for i := 0; i < 6; i++ {
id := fmt.Sprintf("%s-doc-%d", workspaceID, i)
api.nodes[root] = append(api.nodes[root], node{
ID: id, Name: id, Type: "FILE", Category: "ALIDOC", Extension: "adoc",
})
api.blockErrors[id] = denied
}
}
return api
}
// A selected workspace or folder must be validated on its own: the readable
// document inside it decides the outcome, whatever the rest of the tenant
// looks like. On the tenant this was reported from, Validate failed here and
// the data source could not be created at all.
func TestValidateSamplesOnlyTheSelectedResources(t *testing.T) {
denied := errors.New("forbidden.accessDenied: the operator has no permission")
cases := []struct {
name string
resourceID func(t *testing.T) string
}{
{
name: "the selected workspace",
resourceID: func(*testing.T) string { return "faq" },
},
{
name: "a folder inside the selected workspace",
resourceID: func(t *testing.T) string {
return mustEncodeResource(t, resourceReference{
WorkspaceID: "faq", NodeID: "faq-folder",
})
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
api := realTenant(t, denied)
recorder := &recordingAPI{fakeAPI: api}
err := testConnector(recorder).Validate(
context.Background(), testConfig(tc.resourceID(t)),
)
if err != nil {
t.Fatalf("Validate must accept a selection whose documents are readable, got: %v", err)
}
if api.blockCalls["faq-doc"] != 1 {
t.Fatalf("the selected document was probed %d times, want 1", api.blockCalls["faq-doc"])
}
// The unrelated workspaces must not be walked at all: sampling
// them is what spent the budget before the selection was reached.
if len(recorder.listed) == 0 {
t.Fatal("Validate never listed the selection")
}
for _, parent := range recorder.listed {
if parent != "root-faq" && parent != "faq-folder" {
t.Fatalf("Validate listed %q, which the selection does not name", parent)
}
}
})
}
}
// The mirror image: a readable document outside the selection must not vouch
// for a selection whose own documents are all unreadable. The data source
// would sync nothing, so Validate has to reject it.
func TestValidateRejectsASelectionWhoseDocumentsAreAllUnreadable(t *testing.T) {
denied := errors.New("forbidden.accessDenied: the operator has no permission")
api := &fakeAPI{
workspaces: []workspace{
{ID: "open", RootNodeID: "root-open", Name: "Open"},
{ID: "locked", RootNodeID: "root-locked", Name: "Locked"},
},
nodes: map[string][]node{
"root-open": {
{ID: "doc-open", Name: "Public", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
"root-locked": {
{ID: "locked-folder", Name: "Contracts", Type: "FOLDER"},
},
"locked-folder": {
{ID: "locked-a", Name: "Contract A", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
{ID: "locked-b", Name: "Contract B", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blocks: map[string][]json.RawMessage{
"doc-open": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
blockErrors: map[string]error{"locked-a": denied, "locked-b": denied},
}
selected := mustEncodeResource(t, resourceReference{
WorkspaceID: "locked", NodeID: "locked-folder",
})
err := testConnector(api).Validate(context.Background(), testConfig(selected))
if err == nil {
t.Fatal("Validate must fail: every document in the selection is unreadable, " +
"so the data source would sync nothing")
}
for _, want := range []string{`workspace "Locked"`, `document "Contract B"`, "no permission"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("Validate error should carry %s, got: %v", want, err)
}
}
if strings.Contains(err.Error(), "only the first") {
t.Fatalf("two probed documents must not be described as the probe cap, got: %v", err)
}
if api.blockCalls["doc-open"] != 0 {
t.Fatalf("a document outside the selection was probed %d times", api.blockCalls["doc-open"])
}
if api.blockCalls["locked-a"] != 1 || api.blockCalls["locked-b"] != 1 {
t.Fatalf("both selected documents should be probed, calls=%v", api.blockCalls)
}
}
// A selection that holds no document at all has nothing to read, so the
// credentials cannot be disproved and Validate accepts. Folders and types with
// no ingest path do not count as documents.
func TestValidateAcceptsASelectionWithoutDocuments(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "empty", RootNodeID: "root-empty", Name: "Empty"}},
nodes: map[string][]node{
"root-empty": {
{ID: "empty-folder", Name: "Empty", Type: "FOLDER"},
},
"empty-folder": {
{ID: "sub", Name: "Sub", Type: "FOLDER"},
{ID: "clip", Name: "Clip", Type: "FILE", Category: "VIDEO", Extension: "mp4"},
},
"sub": {},
},
}
selected := mustEncodeResource(t, resourceReference{
WorkspaceID: "empty", NodeID: "empty-folder",
})
if err := testConnector(api).Validate(context.Background(), testConfig(selected)); err != nil {
t.Fatalf("Validate must accept a selection that holds no document to read, got: %v", err)
}
if len(api.blockCalls) != 0 || len(api.verifyCalls) != 0 {
t.Fatalf("a selection without ingestible documents must not be probed, blocks=%v verifies=%v",
api.blockCalls, api.verifyCalls)
}
}
// A cancelled or timed-out request proves nothing about the credentials, so it
// must never fall through to acceptance, not even when another selected scope
// would have proven them.
func TestValidateFailsWhenTheSelectionWalkIsCancelled(t *testing.T) {
denied := errors.New("forbidden.accessDenied: the operator has no permission")
t.Run("cancelled before the first call", func(t *testing.T) {
api := realTenant(t, denied)
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := testConnector(api).Validate(ctx, testConfig("faq"))
if !errors.Is(err, context.Canceled) {
t.Fatalf("Validate must report the cancellation, got: %v", err)
}
if api.blockCalls["faq-doc"] != 0 {
t.Fatal("Validate must not probe anything under a cancelled context")
}
})
t.Run("document probe times out", func(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "faq", RootNodeID: "root-faq", Name: "FAQ"}},
nodes: map[string][]node{
"root-faq": {
{ID: "faq-doc", Name: "FAQ", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blockErrors: map[string]error{"faq-doc": context.DeadlineExceeded},
}
err := testConnector(api).Validate(context.Background(), testConfig("faq"))
if !errors.Is(err, context.DeadlineExceeded) ||
!strings.Contains(err.Error(), `document "FAQ"`) {
t.Fatalf("Validate must surface the timed-out probe with its document, got: %v", err)
}
})
t.Run("resolution listing is cancelled", func(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "faq", RootNodeID: "root-faq", Name: "FAQ"}},
nodes: map[string][]node{"root-faq": {{ID: "faq-folder", Type: "FOLDER"}}},
nodeErrors: map[string]error{"root-faq": context.Canceled},
}
selected := mustEncodeResource(t, resourceReference{
WorkspaceID: "faq", NodeID: "faq-folder",
})
err := testConnector(api).Validate(context.Background(), testConfig(selected))
if !errors.Is(err, context.Canceled) {
t.Fatalf("Validate must report the cancellation, got: %v", err)
}
})
t.Run("a cancelled scope is not rescued by a readable one", func(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: "cancelled-doc", Name: "Cancelled", Type: "FILE",
Category: "ALIDOC", Extension: "adoc",
},
},
"root-open": {
{ID: "open-folder", Name: "Handbook", Type: "FOLDER"},
},
"open-folder": {
{
ID: "open-doc", Name: "Handbook", Type: "FILE",
Category: "ALIDOC", Extension: "adoc",
},
},
},
blocks: map[string][]json.RawMessage{"open-doc": {rawJSON(`{"paragraph":{"text":"hi"}}`)}},
blockErrors: map[string]error{"cancelled-doc": context.Canceled},
}
selected := []string{
"locked",
mustEncodeResource(t, resourceReference{WorkspaceID: "open", NodeID: "open-folder"}),
}
err := testConnector(api).Validate(context.Background(), testConfig(selected...))
if !errors.Is(err, context.Canceled) {
t.Fatalf("Validate must report the cancellation, got: %v", err)
}
if api.blockCalls["open-doc"] != 0 {
t.Fatal("Validate must stop at the cancellation instead of accepting on the next scope")
}
})
}
// Without a selection there is nothing narrower to sample, so the whole tenant
// is walked exactly as before.
func TestValidateWithoutASelectionKeepsSamplingTheTenant(t *testing.T) {
denied := errors.New("forbidden.accessDenied: the operator has no permission")
t.Run("a readable later workspace still proves the credentials", func(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": denied},
}
recorder := &recordingAPI{fakeAPI: api}
if err := testConnector(recorder).Validate(context.Background(), testConfig()); err != nil {
t.Fatalf("Validate must sample the whole tenant without a selection, got: %v", err)
}
if api.blockCalls["doc-locked"] != 1 || api.blockCalls["doc-open"] != 1 {
t.Fatalf("every workspace should be sampled, calls=%v", api.blockCalls)
}
if !slices.Contains(recorder.listed, "root-locked") ||
!slices.Contains(recorder.listed, "root-open") {
t.Fatalf("the tenant walk must list every workspace, listed=%v", recorder.listed)
}
})
t.Run("the probe cap still stops the tenant walk", func(t *testing.T) {
// Deliberately unchanged: with no selection, the probe budget is still
// shared across the tenant, so a workspace that spends all of it
// still hides the readable workspace behind it. A selection is what
// makes Validate answer for the operator's own scope.
api := realTenant(t, denied)
err := testConnector(api).Validate(context.Background(), testConfig())
if err == nil {
t.Fatal("Validate must fail when the probe cap stops the tenant walk")
}
wantNote := fmt.Sprintf("only the first %d documents were probed", maxValidateProbes)
if !strings.Contains(err.Error(), wantNote) {
t.Fatalf("Validate error should say the probe cap stopped the walk, got: %v", err)
}
if api.blockCalls["faq-doc"] != 0 {
t.Fatal("the tenant walk must not have reached the later workspace")
}
})
}
// A reference this build cannot resolve must be reported, never quietly
// replaced by the tenant walk: the data source would fail on that resource,
// and a selection the picker can no longer resolve is what the operator has to
// see. The first case is the shape of a Base reference
// (dingtalk:v1?base=<id>) on a build whose resource IDs do not model Bases:
// the reference does not decode, so it cannot be validated and must not be
// silently dropped.
func TestValidateRejectsASelectionItCannotResolve(t *testing.T) {
readableTenant := func() *fakeAPI {
return &fakeAPI{
workspaces: []workspace{{ID: "open", RootNodeID: "root-open", Name: "Open"}},
nodes: map[string][]node{
"root-open": {
{ID: "doc-open", Name: "Public", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blocks: map[string][]json.RawMessage{
"doc-open": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
}
}
cases := []struct {
name string
resource string
want string
wantErr error
}{
{
name: "a reference field this build does not model",
resource: "dingtalk:v1?base=base-1",
want: "unsupported field",
},
{
name: "a workspace that is gone",
resource: "gone",
want: "is unavailable",
wantErr: datasource.ErrResourceNotFound,
},
{
name: "a node that is gone",
resource: mustEncodeResource(t, resourceReference{
WorkspaceID: "open", NodeID: "gone-node",
}),
want: "is unavailable",
wantErr: datasource.ErrResourceNotFound,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
api := readableTenant()
err := testConnector(api).Validate(context.Background(), testConfig(tc.resource))
if err == nil {
t.Fatal("Validate must not accept a selection it cannot resolve")
}
if !strings.Contains(err.Error(), "resource "+tc.resource) {
t.Fatalf("Validate error should name the resource, got: %v", err)
}
if !strings.Contains(err.Error(), tc.want) {
t.Fatalf("Validate error should carry %q, got: %v", tc.want, err)
}
if tc.wantErr != nil && !errors.Is(err, tc.wantErr) {
t.Fatalf("Validate error should wrap %v, got: %v", tc.wantErr, err)
}
if len(api.blockCalls) != 0 {
t.Fatalf("Validate must not fall back to the tenant walk, probed %v", api.blockCalls)
}
})
}
t.Run("a node with no ingest path", func(t *testing.T) {
// The upload switch is off for testConfig, so the uploaded file the
// reference names is not ingestible in this data source: the selection
// would sync nothing, and a sync would report the resource as failed.
api := readableTenant()
api.nodes["root-open"] = []node{{
ID: "doc-open", Name: "Upload", Type: "FILE", Category: "DOCUMENT", Extension: "pdf",
}}
selected := mustEncodeResource(t, resourceReference{WorkspaceID: "open", NodeID: "doc-open"})
err := testConnector(api).Validate(context.Background(), testConfig(selected))
if err == nil {
t.Fatal("Validate must not accept a selection it cannot resolve")
}
if !strings.Contains(err.Error(), "not a supported online document or folder") {
t.Fatalf("Validate error should name the unsupported node, got: %v", err)
}
if len(api.blockCalls) != 0 || len(api.verifyCalls) != 0 {
t.Fatalf("Validate must not fall back to the tenant walk, blocks=%v verifies=%v",
api.blockCalls, api.verifyCalls)
}
})
}
// A selected folder that cannot be listed cannot be scanned, so Validate
// reports it instead of accepting. The error names the folder, which is what
// the operator has to look at: the workspace alone would not say which one.
func TestValidateReportsASelectedFolderThatCannotBeListed(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "team", RootNodeID: "root-team", Name: "Team"}},
nodes: map[string][]node{
"root-team": {
{ID: "broken", Name: "Broken", Type: "FOLDER"},
},
},
nodeErrors: map[string]error{"broken": errors.New("DingTalk API status=500")},
}
selected := mustEncodeResource(t, resourceReference{WorkspaceID: "team", NodeID: "broken"})
err := testConnector(api).Validate(context.Background(), testConfig(selected))
if err == nil {
t.Fatal("Validate must not accept a selection it cannot scan")
}
for _, want := range []string{`workspace "Team"`, `node "broken"`, "status=500"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("Validate error should carry %s, got: %v", want, err)
}
}
}
// A selected document is a leaf: it is probed through its own read API instead
// of being walked, and a readable one is enough to accept the data source.
func TestValidateProbesASelectedDocumentDirectly(t *testing.T) {
denied := errors.New("forbidden.accessDenied: the operator has no permission")
t.Run("readable document", func(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "open", RootNodeID: "root-open", Name: "Open"}},
nodes: map[string][]node{
"root-open": {
{ID: "doc", Name: "Handbook", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blocks: map[string][]json.RawMessage{
"doc": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
}
recorder := &recordingAPI{fakeAPI: api}
selected := mustEncodeResource(t, resourceReference{WorkspaceID: "open", NodeID: "doc"})
if err := testConnector(recorder).Validate(context.Background(), testConfig(selected)); err != nil {
t.Fatalf("Validate must accept a readable selected document, got: %v", err)
}
if api.blockCalls["doc"] != 1 {
t.Fatalf("the selected document was probed %d times, want 1", api.blockCalls["doc"])
}
if len(recorder.listed) != 1 || recorder.listed[0] != "root-open" {
t.Fatalf("a selected document is resolved through its parent only, listed=%v", recorder.listed)
}
})
t.Run("unreadable document", func(t *testing.T) {
api := &fakeAPI{
workspaces: []workspace{{ID: "open", RootNodeID: "root-open", Name: "Open"}},
nodes: map[string][]node{
"root-open": {
{ID: "doc", Name: "Handbook", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blockErrors: map[string]error{"doc": denied},
}
selected := mustEncodeResource(t, resourceReference{WorkspaceID: "open", NodeID: "doc"})
err := testConnector(api).Validate(context.Background(), testConfig(selected))
if err == nil || !strings.Contains(err.Error(), `document "Handbook"`) {
t.Fatalf("Validate must report the unreadable selected document, got: %v", err)
}
})
t.Run("readable uploaded file", func(t *testing.T) {
api := selectedUpload(nil)
selected := mustEncodeResource(t, resourceReference{WorkspaceID: "open", NodeID: "file"})
err := testConnector(api).Validate(context.Background(), testConfigWithUploadedFiles(selected))
if err != nil {
t.Fatalf("Validate must accept a readable selected upload, got: %v", err)
}
// An uploaded file has no blocks: its download location is resolved,
// which exercises the same permissions without transferring the bytes.
if api.verifyCalls["file"] != 1 || api.dlCalls["file"] != 0 {
t.Fatalf("upload should be verified through its download location, verify=%v download=%v",
api.verifyCalls, api.dlCalls)
}
})
t.Run("unreadable uploaded file", func(t *testing.T) {
api := selectedUpload(denied)
selected := mustEncodeResource(t, resourceReference{WorkspaceID: "open", NodeID: "file"})
err := testConnector(api).Validate(context.Background(), testConfigWithUploadedFiles(selected))
if err == nil || !strings.Contains(err.Error(), `document "Handbook.pdf"`) {
t.Fatalf("Validate must report the unreadable selected upload, got: %v", err)
}
})
}
// selectedUpload is a tenant whose only selected node is an uploaded PDF, so
// the selection walk has to use the download verification path.
func selectedUpload(verifyErr error) *fakeAPI {
api := &fakeAPI{
workspaces: []workspace{{ID: "open", RootNodeID: "root-open", Name: "Open"}},
nodes: map[string][]node{
"root-open": {
{
ID: "file", Name: "Handbook.pdf", Type: "FILE",
Category: "DOCUMENT", Extension: "pdf",
},
},
},
}
if verifyErr != nil {
api.verifyErrors = map[string]error{"file": verifyErr}
}
return api
}
// One selected scope that yields a readable document proves the credentials,
// exactly as one readable workspace does for the tenant walk: the other
// selected scopes stay in the report of the sync that will follow, they do not
// reject the data source.
func TestValidateAcceptsASelectionWhenOneScopeIsReadable(t *testing.T) {
denied := errors.New("forbidden.accessDenied: the operator has no permission")
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: "locked-folder", Name: "Contracts", Type: "FOLDER"},
},
"locked-folder": {
{ID: "locked-doc", Name: "Contract", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
"root-open": {
{ID: "open-folder", Name: "Handbook", Type: "FOLDER"},
},
"open-folder": {
{ID: "open-doc", Name: "Handbook", Type: "FILE", Category: "ALIDOC", Extension: "adoc"},
},
},
blocks: map[string][]json.RawMessage{
"open-doc": {rawJSON(`{"paragraph":{"text":"hello"}}`)},
},
blockErrors: map[string]error{"locked-doc": denied},
}
selected := []string{
mustEncodeResource(t, resourceReference{WorkspaceID: "locked", NodeID: "locked-folder"}),
mustEncodeResource(t, resourceReference{WorkspaceID: "open", NodeID: "open-folder"}),
}
if err := testConnector(api).Validate(context.Background(), testConfig(selected...)); err != nil {
t.Fatalf("Validate must accept when one selected scope yields a readable document, got: %v", err)
}
if api.blockCalls["locked-doc"] != 1 || api.blockCalls["open-doc"] != 1 {
t.Fatalf("both selected scopes should be probed, calls=%v", api.blockCalls)
}
}
File diff suppressed because it is too large. Load diff