chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)

This commit is contained in:
runny committed 2026-11-13 17:54:56 +08:00
commit 9097ee699d
5769 files changed
+1446466

No files matched your search

@@ -0,0 +1,301 @@
package confluence
import (
"context"
"encoding/base64"
"errors"
"html"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"github.com/Tencent/WeKnora/internal/logger"
)
const (
// maxPageImages is the total data URI image budget one page may carry into the
// downstream docparser, which enforces a single per-page limit (maxRemoteImages)
// across every data:image URI regardless of origin. The budget is shared: it
// covers data URI images already present in the page plus the ones the resolver
// generates, and a repeated image consumes it per occurrence, not per unique URL.
// Downloads stay deduplicated by URL, and only occurrences within the remaining
// budget are collected, so the connector never emits more data URIs than the
// pipeline will keep.
maxPageImages = 30
// maxPageInlineBytes caps the total size of the data URIs one page may carry,
// both in the download cache and in the rewritten HTML. Without it an extreme
// page (maxPageImages occurrences of maxImageBytes images) would inline hundreds
// of MB of base64, copied again by every downstream conversion. Images past the
// budget keep their original src, like any other image the resolver skips.
maxPageInlineBytes = 50 << 20
// imageDownloadConcurrency bounds in-flight image downloads per page so an
// image-heavy page cannot exhaust HTTP connections or spike memory.
imageDownloadConcurrency = 4
)
// errImagePageBudget marks an image dropped because the page's inline budget
// (maxPageInlineBytes) was already used up.
var errImagePageBudget = errors.New("confluence page image budget exhausted")
// imgTagRe matches a full <img ...> start tag, tolerating '>' inside quoted
// attribute values. The \b keeps it from matching <image>.
var imgTagRe = regexp.MustCompile(`(?i)<img\b(?:[^>"']|"[^"]*"|'[^']*')*>`)
// srcAttrRe captures the src attribute value. The leading \s and the value group
// keep it from matching data-src/srcset, and support double-quoted,
// single-quoted, or bare values. Group 1 is the "src=" prefix, group 2 the value.
var srcAttrRe = regexp.MustCompile(`(?i)(\ssrc\s*=\s*)("[^"]*"|'[^']*'|[^\s"'>]+)`)
type imgAction uint8
const (
imgKeep imgAction = iota // empty, data:, external, or non-http scheme: leave untouched
imgDownload // same-origin private candidate
)
// assetResolver rewrites same-origin private Confluence images in a page's
// body.view HTML into inline data URIs. Persistence and resource:// rewriting
// are left entirely to the downstream docparser image pipeline; the resolver
// only performs the one step that pipeline cannot do on its own: an
// authenticated fetch of Confluence-private bytes.
type assetResolver struct {
client *client
}
func newAssetResolver(c *client) *assetResolver { return &assetResolver{client: c} }
// Resolve returns content with same-origin private <img src> occurrences replaced
// by data URIs, within the per-page budget that Resolve shares with any data URI
// images already in the page. It is best-effort: an image that is skipped, falls
// past the remaining budget, or fails to download keeps its original src, and image
// problems never fail the page. Downloads are deduplicated by URL, but the budget
// counts written data URIs (occurrences) to match the downstream pipeline, which
// caps every data:image URI per page regardless of where it came from.
func (r *assetResolver) Resolve(ctx context.Context, content string) string {
if r == nil || r.client == nil {
return content
}
// Data URI images already in the page consume the same downstream budget as the
// ones we generate, so reserve room for them before inlining any private image.
available := maxPageImages - countDataURIImages(content)
if available <= 0 {
return content
}
candidates := r.collect(content, available)
if len(candidates) == 0 {
return content
}
cache := r.downloadAll(ctx, candidates)
if len(cache) == 0 {
return content
}
inlined, inlinedBytes := 0, 0
budgetSpent := false
return imgTagRe.ReplaceAllStringFunc(content, func(tag string) string {
if inlined >= available || budgetSpent {
return tag
}
src, ok := extractImageSrc(tag)
if !ok {
return tag
}
action, abs := r.classify(src)
if action != imgDownload {
return tag
}
dataURI := cache[abs]
if dataURI == "" {
return tag
}
if inlinedBytes+len(dataURI) > maxPageInlineBytes {
budgetSpent = true
return tag
}
inlined++
inlinedBytes += len(dataURI)
return replaceImageSrc(tag, dataURI)
})
}
// collect returns the unique same-origin download candidates whose first
// occurrence falls within the remaining inline budget, in document order. Because
// Resolve writes at most budget data URIs, a URL first seen after that many
// occurrences can never be inlined, so it is not downloaded. Duplicates collapse to
// one entry, so a repeated image is fetched once yet may be inlined at every
// occurrence inside the budget.
func (r *assetResolver) collect(content string, budget int) []string {
tags := imgTagRe.FindAllString(content, -1)
order := make([]string, 0, len(tags))
seen := make(map[string]struct{}, len(tags))
occurrences := 0
for _, tag := range tags {
src, ok := extractImageSrc(tag)
if !ok {
continue
}
action, abs := r.classify(src)
if action != imgDownload {
continue
}
if occurrences >= budget {
break
}
occurrences++
if _, dup := seen[abs]; dup {
continue
}
seen[abs] = struct{}{}
order = append(order, abs)
}
return order
}
// countDataURIImages returns how many <img> tags in content already carry a
// data:image URI. The downstream docparser counts every data:image occurrence
// against the same per-page limit whether it came from the page or from us, so
// these must be reserved before the resolver inlines any private Confluence image.
func countDataURIImages(content string) int {
count := 0
for _, tag := range imgTagRe.FindAllString(content, -1) {
src, ok := extractImageSrc(tag)
if !ok {
continue
}
if strings.HasPrefix(strings.ToLower(src), "data:image/") {
count++
}
}
return count
}
// downloadAll fetches each candidate with bounded concurrency and returns a
// URL-keyed cache of the successful ones as data URIs, holding at most
// maxPageInlineBytes of them. Failures and images past the budget are logged
// (redacted) and omitted, so the rewrite pass leaves their original src in place.
func (r *assetResolver) downloadAll(ctx context.Context, urls []string) map[string]string {
cache := make(map[string]string, len(urls))
cachedBytes := 0
var mu sync.Mutex
var wg sync.WaitGroup
sem := make(chan struct{}, imageDownloadConcurrency)
for _, u := range urls {
if ctx.Err() != nil {
break
}
wg.Add(1)
sem <- struct{}{}
go func(abs string) {
defer wg.Done()
defer func() { <-sem }()
data, mime, err := r.client.downloadImage(ctx, abs)
if err != nil {
logImageFailure(ctx, abs, err)
return
}
uri := "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(data)
mu.Lock()
fits := cachedBytes+len(uri) <= maxPageInlineBytes
if fits {
cache[abs] = uri
cachedBytes += len(uri)
}
mu.Unlock()
if !fits {
logImageFailure(ctx, abs, errImagePageBudget)
}
}(u)
}
wg.Wait()
return cache
}
// classify decides whether src is a same-origin private candidate to download or
// should be left untouched, returning the normalized absolute URL for downloads.
func (r *assetResolver) classify(src string) (imgAction, string) {
s := strings.TrimSpace(src)
if s == "" || strings.HasPrefix(strings.ToLower(s), "data:") {
return imgKeep, ""
}
u, err := url.Parse(s)
if err != nil {
return imgKeep, ""
}
if u.Scheme != "" && u.Scheme != "http" && u.Scheme != "https" {
// file:, javascript:, and any other scheme are never fetched.
return imgKeep, ""
}
if u.Host != "" {
if u.Scheme == "" {
// Protocol-relative //host/path: only same-origin is eligible.
base, berr := url.Parse(r.client.cfg.baseURL)
if berr != nil || !strings.EqualFold(base.Host, u.Host) {
return imgKeep, ""
}
} else if !r.client.sameOrigin(u) {
// Absolute external http(s): keep, never send Confluence credentials.
return imgKeep, ""
}
}
abs, err := r.client.resolveEndpoint(s)
if err != nil {
return imgKeep, ""
}
return imgDownload, abs
}
// logImageFailure records a redacted warning: host and path only, never the
// query (which may carry signed tokens), the Authorization header, or the body.
func logImageFailure(ctx context.Context, abs string, err error) {
host, path := abs, ""
if u, perr := url.Parse(abs); perr == nil {
host, path = u.Host, u.Path
}
reason := "download_failed"
switch {
case errors.Is(err, errImageTooLarge):
reason = "oversize"
case errors.Is(err, errImageNonImageContent):
reason = "non_image_content_type"
case errors.Is(err, errImageRedirectOffOrigin):
reason = "cross_origin_redirect"
case errors.Is(err, errImagePageBudget):
reason = "page_budget"
}
var api *apiError
if errors.As(err, &api) {
reason = "status_" + strconv.Itoa(api.status)
}
logger.Warnf(ctx, "[Confluence] failed to resolve image host=%s path=%s reason=%s", host, path, reason)
}
// extractImageSrc returns the HTML-unescaped src value of an <img> tag.
func extractImageSrc(tag string) (string, bool) {
m := srcAttrRe.FindStringSubmatch(tag)
if m == nil {
return "", false
}
value := strings.TrimSpace(m[2])
if len(value) >= 2 {
if q := value[0]; (q == '"' || q == '\'') && value[len(value)-1] == q {
value = value[1 : len(value)-1]
}
}
value = strings.TrimSpace(html.UnescapeString(value))
if value == "" {
return "", false
}
return value, true
}
// replaceImageSrc swaps only the src attribute value for a double-quoted data
// URI, preserving the rest of the tag byte-for-byte.
func replaceImageSrc(tag, dataURI string) string {
loc := srcAttrRe.FindStringSubmatchIndex(tag)
if loc == nil {
return tag
}
start, end := loc[4], loc[5]
return tag[:start] + `"` + dataURI + `"` + tag[end:]
}
@@ -0,0 +1,612 @@
package confluence
import (
"bytes"
"context"
"encoding/base64"
"errors"
"io"
"net/http"
"strings"
"sync"
"testing"
)
const testBaseURL = "https://confluence.test/wiki"
func newImageTestClient(rt roundTripper) *client {
return &client{
cfg: config{baseURL: testBaseURL, username: "reader", secret: "secret"},
http: &http.Client{Transport: rt},
}
}
func imageResp(status int, contentType string, body []byte) *http.Response {
header := make(http.Header)
if contentType != "" {
header.Set("Content-Type", contentType)
}
return &http.Response{
StatusCode: status,
Header: header,
Body: io.NopCloser(bytes.NewReader(body)),
}
}
func redirectResp(location string) *http.Response {
header := make(http.Header)
header.Set("Location", location)
return &http.Response{
StatusCode: http.StatusFound,
Header: header,
Body: io.NopCloser(bytes.NewReader(nil)),
}
}
// reqLog records outbound requests. Image downloads run concurrently, so every
// access is mutex-guarded.
type reqLog struct {
mu sync.Mutex
reqs []reqRecord
}
type reqRecord struct {
host string
path string
hasAuth bool
}
func newReqLog() *reqLog { return &reqLog{} }
func (l *reqLog) add(req *http.Request) {
l.mu.Lock()
defer l.mu.Unlock()
l.reqs = append(l.reqs, reqRecord{
host: req.URL.Host,
path: req.URL.Path,
hasAuth: req.Header.Get("Authorization") != "",
})
}
func (l *reqLog) count() int {
l.mu.Lock()
defer l.mu.Unlock()
return len(l.reqs)
}
func (l *reqLog) all() []reqRecord {
l.mu.Lock()
defer l.mu.Unlock()
return append([]reqRecord(nil), l.reqs...)
}
func (l *reqLog) hasHost(host string) bool {
for _, r := range l.all() {
if r.host == host {
return true
}
}
return false
}
func (l *reqLog) hasPath(path string) bool {
for _, r := range l.all() {
if r.path == path {
return true
}
}
return false
}
func (l *reqLog) anyWithoutAuth() bool {
for _, r := range l.all() {
if !r.hasAuth {
return true
}
}
return false
}
var testPNG = []byte("private-png-bytes")
func testDataURI(body []byte) string {
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(body)
}
func TestAssetResolverKeepsPublicURL(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<p>hi</p><img src="https://cdn.example.com/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("public URL was modified:\n%s", out)
}
if log.count() != 0 {
t.Fatalf("public image was downloaded: %v", log.all())
}
}
func TestAssetResolverKeepsBase64(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img src="data:image/png;base64,QUJDRA==">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("base64 image was modified:\n%s", out)
}
if log.count() != 0 {
t.Fatalf("base64 image triggered a download: %v", log.all())
}
}
func TestAssetResolverKeepsNonHTTPScheme(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img src="file:///etc/passwd"><img src="javascript:void(0)">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("non-http scheme was modified:\n%s", out)
}
if log.count() != 0 {
t.Fatalf("non-http scheme triggered a download: %v", log.all())
}
}
func TestAssetResolverInlinesRelativeConfluenceImage(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img src="/wiki/download/attachments/123/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
want := testDataURI(testPNG)
if !strings.Contains(out, `src="`+want+`"`) {
t.Fatalf("relative image not inlined as data URI:\n%s", out)
}
if strings.Contains(out, "/wiki/download/attachments") {
t.Fatalf("original private URL survived:\n%s", out)
}
reqs := log.all()
if len(reqs) != 1 {
t.Fatalf("expected 1 download, got %d: %v", len(reqs), reqs)
}
if reqs[0].host != "confluence.test" || !reqs[0].hasAuth {
t.Fatalf("download missing credentials or wrong host: %+v", reqs[0])
}
}
func TestAssetResolverInlinesSameOriginPrivateImage(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img src="https://confluence.test/wiki/download/attachments/123/a.png" alt="x"/>`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if !strings.Contains(out, `src="`+testDataURI(testPNG)+`"`) {
t.Fatalf("same-origin image not inlined:\n%s", out)
}
// The rest of the tag must be preserved.
if !strings.Contains(out, `alt="x"`) {
t.Fatalf("sibling attribute lost:\n%s", out)
}
if log.count() != 1 {
t.Fatalf("expected 1 download, got %d", log.count())
}
}
func TestAssetResolverDoesNotSendCredentialsCrossOrigin(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img src="https://cdn.example.com/a.png">` +
`<img src="/wiki/download/attachments/1/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if log.hasHost("cdn.example.com") {
t.Fatalf("external host received a request: %v", log.all())
}
if !strings.Contains(out, "https://cdn.example.com/a.png") {
t.Fatalf("external URL was modified:\n%s", out)
}
if !strings.Contains(out, testDataURI(testPNG)) {
t.Fatalf("same-origin image was not inlined:\n%s", out)
}
if log.count() != 1 || log.anyWithoutAuth() {
t.Fatalf("expected exactly one authenticated same-origin download: %v", log.all())
}
}
func TestAssetResolverRejectsCrossOriginRedirect(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
if req.URL.Host == "confluence.test" {
return redirectResp("https://evil.example.com/a.png"), nil
}
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img src="/wiki/download/attachments/1/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("cross-origin redirect was followed and inlined:\n%s", out)
}
if log.hasHost("evil.example.com") {
t.Fatalf("credentials could have leaked to evil host: %v", log.all())
}
if log.count() != 1 {
t.Fatalf("expected only the original same-origin request, got %d: %v", log.count(), log.all())
}
}
func TestAssetResolverRejectsSameOriginRedirectOutsideContextPath(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
// The base URL is https://confluence.test/wiki. A redirect to another app on
// the same host stays same-origin but escapes the /wiki context path, and Go
// keeps sending Basic Auth on a same-host hop. It must be refused before the
// credentialed request is ever sent, not merely discarded afterward.
if strings.HasPrefix(req.URL.Path, "/wiki/") {
return redirectResp("https://confluence.test/other-app/leak.png"), nil
}
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img src="/wiki/download/attachments/1/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("same-host redirect outside the context path was followed and inlined:\n%s", out)
}
if log.hasPath("/other-app/leak.png") {
t.Fatalf("credentials followed a redirect outside the context path: %v", log.all())
}
if log.count() != 1 {
t.Fatalf("expected only the original same-origin request, got %d: %v", log.count(), log.all())
}
}
func TestAssetResolverRejectsOversizedImage(t *testing.T) {
log := newReqLog()
big := bytes.Repeat([]byte("a"), int(maxImageBytes)+1)
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", big), nil
})
in := `<img src="/wiki/download/attachments/1/big.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("oversized image was inlined:\n%s", out)
}
if strings.Contains(out, "data:image") {
t.Fatalf("oversized image produced a data URI")
}
}
func TestAssetResolverRejectsNonImageResponse(t *testing.T) {
rt := roundTripper(func(_ *http.Request) (*http.Response, error) {
return imageResp(http.StatusOK, "text/html; charset=utf-8", []byte("<html>login required</html>")), nil
})
in := `<img src="/wiki/download/attachments/1/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("login HTML was inlined as an image:\n%s", out)
}
}
func TestAssetResolverKeepsOriginalURLOnDownloadFailure(t *testing.T) {
for _, status := range []int{http.StatusForbidden, http.StatusNotFound, http.StatusInternalServerError} {
t.Run(http.StatusText(status), func(t *testing.T) {
rt := roundTripper(func(_ *http.Request) (*http.Response, error) {
return imageResp(status, "image/png", testPNG), nil
})
in := `<img src="/wiki/download/attachments/1/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("status %d modified the document:\n%s", status, out)
}
})
}
}
func TestAssetResolverDeduplicatesSamePageImages(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
src := `<img src="/wiki/download/attachments/1/a.png">`
in := strings.Repeat(src, 5)
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if got := strings.Count(out, "data:image/png;base64,"); got != 5 {
t.Fatalf("expected 5 inlined copies, got %d:\n%s", got, out)
}
if log.count() != 1 {
t.Fatalf("duplicate src downloaded %d times, want 1", log.count())
}
}
func TestAssetResolverRespectsPerPageImageCap(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
var sb strings.Builder
total := maxPageImages + 5
for i := 0; i < total; i++ {
sb.WriteString(`<img src="/wiki/download/attachments/1/img`)
sb.WriteString(strings.Repeat("x", i+1)) // unique path per image
sb.WriteString(`.png">`)
}
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), sb.String())
if got := strings.Count(out, "data:image/png;base64,"); got != maxPageImages {
t.Fatalf("inlined %d images, want cap %d", got, maxPageImages)
}
if log.count() != maxPageImages {
t.Fatalf("downloaded %d images, want cap %d", log.count(), maxPageImages)
}
if got := strings.Count(out, "/wiki/download/attachments"); got != 5 {
t.Fatalf("expected 5 images past the cap to keep original src, got %d", got)
}
}
func TestAssetResolverCapsOccurrencesNotUniqueDownloads(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
// Two unique URLs but 35 occurrences. Counting the cap by unique URL would
// download cold.png too and inline 30 + 5 data URIs, overflowing the downstream
// per-page limit that counts every occurrence. The budget must be occurrences.
hot := `<img src="/wiki/download/attachments/1/hot.png">`
cold := `<img src="/wiki/download/attachments/1/cold.png">`
in := strings.Repeat(hot, maxPageImages) + strings.Repeat(cold, 5)
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if got := strings.Count(out, "data:image/png;base64,"); got != maxPageImages {
t.Fatalf("inlined %d data URIs, want cap %d", got, maxPageImages)
}
if got := strings.Count(out, "/wiki/download/attachments/1/cold.png"); got != 5 {
t.Fatalf("expected the 5 images past the cap to keep original src, got %d", got)
}
// The repeated image downloads once; the image past the budget never downloads.
if log.count() != 1 {
t.Fatalf("downloaded %d images, want 1 (dedup + no over-budget fetch): %v", log.count(), log.all())
}
if log.hasPath("/wiki/download/attachments/1/cold.png") {
t.Fatalf("image past the occurrence cap was downloaded: %v", log.all())
}
}
// largeTestImage is just under maxImageBytes, so a handful of them overflow
// maxPageInlineBytes long before the per-page occurrence cap.
var largeTestImage = bytes.Repeat([]byte("a"), int(maxImageBytes)-1024)
func TestAssetResolverStopsInliningPastPageByteBudget(t *testing.T) {
rt := roundTripper(func(_ *http.Request) (*http.Response, error) {
return imageResp(http.StatusOK, "image/png", largeTestImage), nil
})
want := maxPageInlineBytes / len(testDataURI(largeTestImage))
total := want + 3
src := `<img src="/wiki/download/attachments/1/big.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), strings.Repeat(src, total))
if got := strings.Count(out, "data:image/png;base64,"); got != want {
t.Fatalf("inlined %d copies, want %d within the %d-byte page budget", got, want, maxPageInlineBytes)
}
if got := strings.Count(out, "/wiki/download/attachments/1/big.png"); got != total-want {
t.Fatalf("expected %d copies past the budget to keep original src, got %d", total-want, got)
}
}
func TestAssetResolverDownloadCacheRespectsPageByteBudget(t *testing.T) {
rt := roundTripper(func(_ *http.Request) (*http.Response, error) {
return imageResp(http.StatusOK, "image/png", largeTestImage), nil
})
want := maxPageInlineBytes / len(testDataURI(largeTestImage))
urls := make([]string, 0, want+3)
for i := 0; i < want+3; i++ {
urls = append(urls, testBaseURL+"/download/attachments/1/img"+strings.Repeat("x", i+1)+".png")
}
cache := newAssetResolver(newImageTestClient(rt)).downloadAll(context.Background(), urls)
if len(cache) != want {
t.Fatalf("cached %d images, want %d within the %d-byte page budget", len(cache), want, maxPageInlineBytes)
}
}
func TestAssetResolverSharesCapWithExistingDataURIImages(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
// Data URI images already in the page share the downstream 30-image budget with
// the ones we generate. With 10 existing, only 20 of the 25 private images may
// be inlined; the rest keep their original URL instead of overflowing the cap.
var sb strings.Builder
for i := 0; i < 10; i++ {
sb.WriteString(`<img src="data:image/gif;base64,EXISTING">`)
}
for i := 0; i < 25; i++ {
sb.WriteString(`<img src="/wiki/download/attachments/1/img`)
sb.WriteString(strings.Repeat("x", i+1)) // unique path per image
sb.WriteString(`.png">`)
}
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), sb.String())
// The 10 pre-existing data URIs are preserved untouched.
if got := strings.Count(out, "data:image/gif;base64,EXISTING"); got != 10 {
t.Fatalf("preserved %d existing data URIs, want 10", got)
}
// Exactly 20 private images inlined: 30 shared budget - 10 already present.
if got := strings.Count(out, testDataURI(testPNG)); got != 20 {
t.Fatalf("inlined %d private images, want 20", got)
}
// The 5 private images past the shared budget keep their original URL.
if got := strings.Count(out, "/wiki/download/attachments"); got != 5 {
t.Fatalf("expected 5 private images past the cap to keep original src, got %d", got)
}
// Only the 20 inlinable private images are downloaded.
if log.count() != 20 {
t.Fatalf("downloaded %d images, want 20: %v", log.count(), log.all())
}
}
func TestAssetResolverIgnoresDataSrcAttribute(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
// data-src must not be mistaken for src; there is no real src here.
in := `<img data-src="/wiki/download/attachments/1/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if out != in {
t.Fatalf("data-src was treated as src:\n%s", out)
}
if log.count() != 0 {
t.Fatalf("data-src triggered a download: %v", log.all())
}
}
func TestAssetResolverToleratesGreaterThanInAttribute(t *testing.T) {
log := newReqLog()
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
log.add(req)
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img alt="a > b" src="/wiki/download/attachments/1/a.png">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if !strings.Contains(out, testDataURI(testPNG)) {
t.Fatalf("image with '>' in alt was not inlined:\n%s", out)
}
if !strings.Contains(out, `alt="a > b"`) {
t.Fatalf("alt attribute was corrupted:\n%s", out)
}
}
func TestAssetResolverUnescapesAmpersandInQuery(t *testing.T) {
var gotPath string
var gotQuery string
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
gotPath = req.URL.Path
gotQuery = req.URL.RawQuery
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
in := `<img src="/wiki/download/attachments/1/a.png?api=v2&amp;v=3">`
out := newAssetResolver(newImageTestClient(rt)).Resolve(context.Background(), in)
if !strings.Contains(out, "data:image/png;base64,") {
t.Fatalf("image with &amp; query was not inlined:\n%s", out)
}
if gotPath != "/wiki/download/attachments/1/a.png" || gotQuery != "api=v2&v=3" {
t.Fatalf("query not unescaped: path=%q query=%q", gotPath, gotQuery)
}
}
func TestDownloadPrivateImageLimitsBodySize(t *testing.T) {
big := bytes.Repeat([]byte("a"), int(maxImageBytes)+1)
rt := roundTripper(func(_ *http.Request) (*http.Response, error) {
return imageResp(http.StatusOK, "image/png", big), nil
})
c := newImageTestClient(rt)
_, _, err := c.downloadImage(context.Background(), "https://confluence.test/wiki/download/attachments/1/big.png")
if !errors.Is(err, errImageTooLarge) {
t.Fatalf("downloadImage() error = %v, want errImageTooLarge", err)
}
}
func TestDownloadPrivateImageValidatesContentType(t *testing.T) {
rt := roundTripper(func(_ *http.Request) (*http.Response, error) {
return imageResp(http.StatusOK, "application/json", []byte(`{"error":"unauthorized"}`)), nil
})
c := newImageTestClient(rt)
_, _, err := c.downloadImage(context.Background(), "https://confluence.test/wiki/download/attachments/1/a.png")
if !errors.Is(err, errImageNonImageContent) {
t.Fatalf("downloadImage() error = %v, want errImageNonImageContent", err)
}
}
func TestDownloadPrivateImageSniffsWhenContentTypeMissing(t *testing.T) {
png := append([]byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, bytes.Repeat([]byte{0}, 64)...)
rt := roundTripper(func(_ *http.Request) (*http.Response, error) {
return imageResp(http.StatusOK, "", png), nil
})
c := newImageTestClient(rt)
body, mime, err := c.downloadImage(
context.Background(),
"https://confluence.test/wiki/download/attachments/1/a.png",
)
if err != nil {
t.Fatalf("downloadImage() error = %v", err)
}
if mime != "image/png" {
t.Fatalf("sniffed mime = %q, want image/png", mime)
}
if !bytes.Equal(body, png) {
t.Fatalf("body mismatch: %d bytes", len(body))
}
}
func TestDownloadPrivateImageRejectsCrossOriginRedirect(t *testing.T) {
rt := roundTripper(func(req *http.Request) (*http.Response, error) {
if req.URL.Host == "confluence.test" {
return redirectResp("https://evil.example.com/a.png"), nil
}
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
c := newImageTestClient(rt)
_, _, err := c.downloadImage(context.Background(), "https://confluence.test/wiki/download/attachments/1/a.png")
if !errors.Is(err, errImageRedirectOffOrigin) {
t.Fatalf("downloadImage() error = %v, want errImageRedirectOffOrigin", err)
}
}
// TestFetchStreamInlinesPrivateImageAsDataURI is the connector integration test:
// a body.view containing a same-origin private image flows through FetchStream
// and the emitted FetchedItem.Content carries an inline data URI (which the
// downstream docparser pipeline later persists and rewrites to resource://).
func TestFetchStreamInlinesPrivateImageAsDataURI(t *testing.T) {
api := &streamAPI{
pages: []streamPage{{id: "p1", title: "Page", version: 1}},
bodyHTML: map[string]string{"p1": `<p>hi</p><img src="/wiki/download/attachments/p1/a.png">`},
}
h := &captureHandler{}
if _, err := newStreamConnector(api).FetchStream(context.Background(), streamConfig(), nil, h); err != nil {
t.Fatal(err)
}
if len(h.items) != 1 {
t.Fatalf("emitted %d items, want 1", len(h.items))
}
content := string(h.items[0].Content)
if !strings.Contains(content, "data:image/png;base64,") {
t.Fatalf("private image was not inlined into Content:\n%s", content)
}
if strings.Contains(content, "/wiki/download/attachments") {
t.Fatalf("original private Confluence URL leaked into Content:\n%s", content)
}
if api.imageCalls != 1 {
t.Fatalf("image download calls = %d, want 1", api.imageCalls)
}
}
@@ -0,0 +1,880 @@
package confluence
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
urlpath "path"
"strconv"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
)
const (
maxJSONResponseBytes int64 = 20 << 20
maxImageBytes int64 = 10 << 20
maxImageRedirects = 10
requestAttempts = 4
maxErrorResponseRunes = 1000
maxRetryDelay = 60 * time.Second
maxPaginationHops = 10000
maxTraversalNodes = 100000
maxTransparentTraversalNodes = 10000
maxTransparentTraversalDepth = 32
// maxEmptyServerPages bounds how far a Server/Data Center page listing
// follows _links.next through empty pages.
maxEmptyServerPages = 3
maxDeletionProbes = 200
)
var (
errImageTooLarge = errors.New("confluence image exceeds size limit")
errImageNonImageContent = errors.New("confluence image response is not an image")
// errImageRedirectOffOrigin fires whenever a redirect target leaves the base
// URL boundary resolveEndpoint enforces — a different origin, or the same host
// but a path outside the configured context path (e.g. /wiki → /other-app).
errImageRedirectOffOrigin = errors.New("confluence image redirect left the configured base URL")
)
type apiError struct {
endpoint string
status int
excerpt string
}
func (e *apiError) Error() string {
if e.excerpt == "" {
return fmt.Sprintf("confluence API %s: status %d", e.endpoint, e.status)
}
return fmt.Sprintf("confluence API %s: status %d body=%q", e.endpoint, e.status, e.excerpt)
}
type client struct {
cfg config
http *http.Client
}
func newClient(cfg config) (*client, error) {
if err := datasource.ValidateConnectorBaseURL(cfg.baseURL); err != nil {
return nil, err
}
return &client{cfg: cfg, http: datasource.NewConnectorHTTPClient(60 * time.Second)}, nil
}
// authenticate applies the selected credentials to both API and private image requests.
func (c *client) authenticate(req *http.Request) {
if c.cfg.usePAT {
req.Header.Set("Authorization", "Bearer "+c.cfg.secret)
return
}
req.SetBasicAuth(c.cfg.username, c.cfg.secret)
}
func (c *client) get(ctx context.Context, endpoint string, output interface{}) error {
fullURL, err := c.resolveEndpoint(endpoint)
if err != nil {
return err
}
for attempt := 0; attempt < requestAttempts; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
if err != nil {
return err
}
c.authenticate(req)
req.Header.Set("Accept", "application/json")
resp, err := c.http.Do(req)
if err == nil {
body, readErr := io.ReadAll(io.LimitReader(resp.Body, maxJSONResponseBytes+1))
_ = resp.Body.Close()
if readErr != nil {
return readErr
}
if int64(len(body)) > maxJSONResponseBytes {
return fmt.Errorf("confluence response exceeds %d MiB limit", maxJSONResponseBytes>>20)
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
if output == nil {
return nil
}
return json.Unmarshal(body, output)
}
if resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode < 500 {
return &apiError{
endpoint: endpoint,
status: resp.StatusCode,
excerpt: responseExcerpt(body),
}
}
if attempt == requestAttempts-1 {
return &apiError{endpoint: endpoint, status: resp.StatusCode}
}
if err = waitRetry(ctx, resp.Header.Get("Retry-After"), attempt); err != nil {
return err
}
continue
}
if attempt == requestAttempts-1 {
return fmt.Errorf("confluence API %s: %w", endpoint, err)
}
if err = waitRetry(ctx, "", attempt); err != nil {
return err
}
}
return fmt.Errorf("confluence API %s: retry exhausted", endpoint)
}
func responseExcerpt(body []byte) string {
value := []rune(strings.TrimSpace(string(body)))
if len(value) <= maxErrorResponseRunes {
return string(value)
}
return string(value[:maxErrorResponseRunes]) + "..."
}
func waitRetry(ctx context.Context, retryAfter string, attempt int) error {
backoff := time.Duration(1<<attempt)*time.Second + time.Duration(time.Now().UnixNano()%250)*time.Millisecond
delay := capRetryDelay(backoff)
if secs, err := strconv.Atoi(retryAfter); err == nil {
delay = capRetryDelay(time.Duration(secs) * time.Second)
} else if t, err := http.ParseTime(retryAfter); err == nil {
delay = capRetryDelay(time.Until(t))
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func capRetryDelay(delay time.Duration) time.Duration {
if delay <= 0 {
return 100 * time.Millisecond
}
if delay > maxRetryDelay {
return maxRetryDelay
}
return delay
}
func (c *client) resolveEndpoint(endpoint string) (string, error) {
base, err := url.Parse(c.cfg.baseURL)
if err != nil {
return "", fmt.Errorf("parse Confluence base URL: %w", err)
}
next, err := url.Parse(endpoint)
if err != nil {
return "", fmt.Errorf("parse Confluence pagination URL: %w", err)
}
basePath := strings.TrimRight(urlpath.Clean(base.Path), "/")
if basePath == "." {
basePath = ""
}
if next.IsAbs() {
if next.Scheme != base.Scheme || next.Host != base.Host {
return "", fmt.Errorf("confluence pagination URL leaves configured origin")
}
cleaned, err := joinContextPath(basePath, next.Path, false)
if err != nil {
return "", err
}
next.Path = cleaned
next.RawPath = ""
return next.String(), nil
}
cleaned, err := joinContextPath(basePath, next.Path, true)
if err != nil {
return "", err
}
return (&url.URL{Scheme: base.Scheme, Host: base.Host, Path: cleaned, RawQuery: next.RawQuery}).String(), nil
}
func joinContextPath(basePath, rawPath string, prependContext bool) (string, error) {
joined := rawPath
if joined == "" {
joined = basePath
} else if prependContext && basePath != "" && joined != basePath && !strings.HasPrefix(joined, basePath+"/") {
joined = basePath + "/" + strings.TrimLeft(joined, "/")
}
cleaned := urlpath.Clean(joined)
if cleaned == "." {
cleaned = "/"
}
if basePath != "" && cleaned != basePath && !strings.HasPrefix(cleaned, basePath+"/") {
return "", fmt.Errorf("confluence pagination URL leaves configured context path")
}
return cleaned, nil
}
func (c *client) paginate(ctx context.Context, start string, step func(pageURL string) (next string, err error)) error {
next := start
seen := make(map[string]struct{}, 8)
for next != "" {
if err := ctx.Err(); err != nil {
return err
}
resolved, err := c.resolveEndpoint(next)
if err != nil {
return err
}
if _, dup := seen[resolved]; dup {
return fmt.Errorf("confluence pagination looped")
}
if len(seen) >= maxPaginationHops {
return fmt.Errorf("confluence pagination exceeded %d pages", maxPaginationHops)
}
seen[resolved] = struct{}{}
next, err = step(next)
if err != nil {
return err
}
}
return nil
}
func (c *client) resourceURL(link string) string {
if strings.TrimSpace(link) == "" {
return c.cfg.baseURL
}
resolved, err := c.resolveEndpoint(link)
if err != nil {
return c.cfg.baseURL
}
return resolved
}
// sameOrigin reports whether u shares scheme and host with the configured base
// URL. Only same-origin URLs may carry Confluence credentials.
func (c *client) sameOrigin(u *url.URL) bool {
if u == nil {
return false
}
base, err := url.Parse(c.cfg.baseURL)
if err != nil {
return false
}
return strings.EqualFold(base.Scheme, u.Scheme) && strings.EqualFold(base.Host, u.Host)
}
// withinImageScope reports whether u stays inside the boundary resolveEndpoint
// enforces for the initial image URL: the same origin AND a path inside the
// configured context path. Redirect targets are validated with this same rule,
// not merely sameOrigin, because Go forwards Basic Auth on a same-host redirect —
// so a hop like /wiki/download → /other-app/image must fail closed too.
func (c *client) withinImageScope(u *url.URL) bool {
if u == nil {
return false
}
_, err := c.resolveEndpoint(u.String())
return err == nil
}
// downloadImage fetches a same-origin private image using the connector's
// credentials. It streams with a hard size cap, fails closed if a redirect left
// the Confluence origin, and validates the response really is an image. It is a
// best-effort single attempt: a failed image degrades to keeping its original
// URL rather than retrying or failing the page.
func (c *client) downloadImage(ctx context.Context, absURL string) ([]byte, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, absURL, nil)
if err != nil {
return nil, "", err
}
c.authenticate(req)
req.Header.Set("Accept", "image/*,*/*;q=0.8")
resp, err := c.imageHTTPClient().Do(req)
if err != nil {
return nil, "", err
}
defer func() { _ = resp.Body.Close() }()
// Backstop for the redirect policy: imageHTTPClient's CheckRedirect already
// refuses any hop that leaves the base before it is followed, so this only
// re-verifies the final URL when the transport populated resp.Request. A custom
// RoundTripper may leave it nil, in which case there is no followed redirect to
// re-check and the download is allowed to proceed.
if resp.Request != nil && !c.withinImageScope(resp.Request.URL) {
return nil, "", errImageRedirectOffOrigin
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, "", &apiError{endpoint: "image", status: resp.StatusCode}
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxImageBytes+1))
if err != nil {
return nil, "", err
}
if int64(len(body)) > maxImageBytes {
return nil, "", errImageTooLarge
}
mime, ok := imageContentType(resp.Header.Get("Content-Type"), body)
if !ok {
return nil, "", errImageNonImageContent
}
return body, mime, nil
}
// imageHTTPClient reuses the connector's SSRF-safe transport and timeout but
// pins redirects to the configured Confluence base, so a private-image fetch can
// never be bounced to a third party or to another app on the same host. The
// redirect check fails closed: any hop that resolveEndpoint would reject — a
// foreign origin, or a same-host path outside the context path (which Go would
// still send Basic Auth to) — is refused outright rather than merely stripped of
// credentials.
func (c *client) imageHTTPClient() *http.Client {
return &http.Client{
Transport: c.http.Transport,
Timeout: c.http.Timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= maxImageRedirects {
return errors.New("confluence image stopped after too many redirects")
}
if !c.withinImageScope(req.URL) {
return errImageRedirectOffOrigin
}
return nil
},
}
}
// imageContentType normalizes a response Content-Type to an image MIME type. An
// empty or generic binary type falls back to content sniffing; any explicit
// non-image type (for example the text/html login page Confluence returns when a
// token expired) is rejected so it is never stored as an image.
func imageContentType(header string, body []byte) (string, bool) {
ct := strings.ToLower(strings.TrimSpace(header))
if i := strings.Index(ct, ";"); i >= 0 {
ct = strings.TrimSpace(ct[:i])
}
switch {
case strings.HasPrefix(ct, "image/"):
return ct, true
case ct != "" && ct != "application/octet-stream":
return "", false
}
if sniff := strings.ToLower(http.DetectContentType(body)); strings.HasPrefix(sniff, "image/") {
if i := strings.Index(sniff, ";"); i >= 0 {
sniff = strings.TrimSpace(sniff[:i])
}
return sniff, true
}
return "", false
}
func (c *client) ping(ctx context.Context) error {
if c.cfg.cloud() {
return c.get(ctx, "/api/v2/spaces?limit=1", nil)
}
return c.get(ctx, "/rest/api/space?limit=1", nil)
}
func (c *client) spaces(ctx context.Context) ([]space, error) {
if c.cfg.cloud() {
var all []space
err := c.paginate(ctx, "/api/v2/spaces?limit=250", func(pageURL string) (string, error) {
var result spaceList
if err := c.get(ctx, pageURL, &result); err != nil {
return "", err
}
all = append(all, result.Results...)
return result.Links.Next, nil
})
return all, err
}
var all []space
err := c.paginate(ctx, "/rest/api/space?limit=100", func(pageURL string) (string, error) {
var result serverSpaceList
if err := c.get(ctx, pageURL, &result); err != nil {
return "", err
}
for _, v := range result.Results {
all = append(all, space{ID: v.ID.String(), Key: v.Key, Name: v.Name, Links: v.Links})
}
return result.Links.Next, nil
})
return all, err
}
const serverPageExpand = "version,space"
func serverSpacePagesEndpoint(spaceKey string) string {
query := url.Values{
"expand": []string{serverPageExpand},
"limit": []string{"100"},
}
return "/rest/api/space/" + url.PathEscape(spaceKey) + "/content/page?" + query.Encode()
}
// withServerPageExpand restores expand=version,space on pagination URLs.
// Confluence _links.next is typically ?limit=&start= and drops expand, which
// would make later pages look versionless ("t:") and skip real edits.
func withServerPageExpand(next string) string {
parsed, err := url.Parse(next)
if err != nil {
return next
}
query := parsed.Query()
if strings.TrimSpace(query.Get("expand")) == "" {
query.Set("expand", serverPageExpand)
parsed.RawQuery = query.Encode()
}
return parsed.String()
}
func withCloudPageQuery(next string) string {
parsed, err := url.Parse(next)
if err != nil {
return next
}
query := parsed.Query()
if strings.TrimSpace(query.Get("status")) == "" {
query.Set("status", "current")
}
if strings.TrimSpace(query.Get("depth")) == "" {
query.Set("depth", "all")
}
parsed.RawQuery = query.Encode()
return parsed.String()
}
func (c *client) pages(ctx context.Context, s space) (pages []page, complete bool, err error) {
if c.cfg.cloud() {
var all []page
start := "/api/v2/spaces/" + url.PathEscape(s.ID) + "/pages?status=current&depth=all&limit=250"
err := c.paginate(ctx, start, func(pageURL string) (string, error) {
var result cloudPageList
if err := c.get(ctx, pageURL, &result); err != nil {
return "", err
}
for _, value := range result.Results {
p := page{ID: value.ID, Title: value.Title, Status: value.Status, Links: value.Links}
p.Space.Key, p.Space.Name = s.Key, s.Name
p.Version.Number, p.Version.CreatedAt = value.Version.Number, value.Version.CreatedAt
if p.Version.CreatedAt == "" {
p.Version.CreatedAt = value.CreatedAt
}
all = append(all, p)
}
next := result.Links.Next
if next != "" {
next = withCloudPageQuery(next)
}
return next, nil
})
return all, true, err
}
var all []page
complete = true
emptyPages := 0
err = c.paginate(ctx, serverSpacePagesEndpoint(s.Key), func(pageURL string) (string, error) {
var result serverSpacePageList
if err := c.get(ctx, pageURL, &result); err != nil {
return "", err
}
listedPages := result.pages()
for _, listed := range listedPages {
if listed.Space.Key == "" {
listed.Space.Key, listed.Space.Name = s.Key, s.Name
}
all = append(all, listed)
}
next := result.nextLink()
if next == "" {
return "", nil
}
if len(listedPages) > 0 {
emptyPages = 0
} else {
emptyPages++
if emptyPages >= maxEmptyServerPages {
complete = false
return "", nil
}
}
return withServerPageExpand(next), nil
})
return all, complete, err
}
func (c *client) pageInSpace(ctx context.Context, id, spaceKey string) (bool, error) {
var result struct {
Status string `json:"status"`
Space struct {
Key string `json:"key"`
} `json:"space"`
}
err := c.get(ctx, "/rest/api/content/"+url.PathEscape(id)+"?expand=space", &result)
var apiErr *apiError
if errors.As(err, &apiErr) && apiErr.status == http.StatusNotFound {
return false, nil
}
if err != nil {
return false, err
}
if result.Status != "" && result.Status != "current" {
return false, nil
}
return result.Space.Key == "" || result.Space.Key == spaceKey, nil
}
func (c *client) body(ctx context.Context, id string) (pageBody, error) {
if c.cfg.cloud() {
var result pageBody
err := c.get(ctx, "/api/v2/pages/"+url.PathEscape(id)+"?body-format=view", &result)
return result, err
}
var result pageBody
err := c.get(ctx, "/rest/api/content/"+url.PathEscape(id)+"?expand=body.view,version,space", &result)
return result, err
}
// pageDetail obtains identity, ownership, and version without requiring a
// rendered body. Scope enumeration must remain complete when a body is
// temporarily unavailable, otherwise a transient content error would be
// indistinguishable from a missing page during deletion reconciliation.
func (c *client) pageDetail(ctx context.Context, id string) (page, error) {
var result page
if c.cfg.cloud() {
err := c.get(ctx, "/api/v2/pages/"+url.PathEscape(id), &result)
return result, err
}
err := c.get(ctx, "/rest/api/content/"+url.PathEscape(id)+"?expand=version,space", &result)
return result, err
}
// validatePageOwnership performs the constant-cost check required before a
// picker expansion. Ancestors are deliberately not fetched here: they are only
// needed by ResolveResourceAncestors and buildSyncPlan.
func (c *client) validatePageOwnership(ctx context.Context, s space, pageID string) error {
full, err := c.pageDetail(ctx, pageID)
if err != nil {
return err
}
if c.cfg.cloud() {
if full.SpaceID != s.ID {
return fmt.Errorf("page %s belongs to space %s, not %s", pageID, full.SpaceID, s.ID)
}
return nil
}
if full.Space.Key == "" || full.Space.Key != s.Key {
return fmt.Errorf("page %s does not belong to space %s", pageID, s.ID)
}
return nil
}
func serverChildPagesEndpoint(pageID string) string {
query := url.Values{"expand": []string{serverPageExpand}, "limit": []string{"100"}}
return "/rest/api/content/" + url.PathEscape(pageID) + "/child/page?" + query.Encode()
}
func serverTopLevelPagesEndpoint(spaceKey string) string {
query := url.Values{"depth": []string{"root"}, "expand": []string{serverPageExpand}, "limit": []string{"100"}}
return "/rest/api/space/" + url.PathEscape(spaceKey) + "/content/page?" + query.Encode()
}
func (c *client) listServerPages(ctx context.Context, endpoint string) ([]page, error) {
start, _ := url.Parse(endpoint)
startQuery := start.Query()
var all []page
err := c.paginate(ctx, endpoint, func(pageURL string) (string, error) {
var result pageList
if err := c.get(ctx, pageURL, &result); err != nil {
return "", err
}
all = append(all, result.Results...)
next := result.Links.Next
if next != "" {
next = withServerListQuery(next, startQuery)
}
return next, nil
})
return all, err
}
// Server pagination links commonly retain only start/limit. Restore the query
// that defines the listing scope (notably depth=root) as well as expand.
func withServerListQuery(next string, required url.Values) string {
parsed, err := url.Parse(next)
if err != nil {
return next
}
query := parsed.Query()
for key, values := range required {
if query.Get(key) == "" && len(values) > 0 {
query[key] = values
}
}
parsed.RawQuery = query.Encode()
return parsed.String()
}
func (c *client) listCloudHierarchy(ctx context.Context, endpoint string) ([]page, error) {
var all []page
err := c.paginate(ctx, endpoint, func(pageURL string) (string, error) {
var result cloudHierarchyList
if err := c.get(ctx, pageURL, &result); err != nil {
return "", err
}
for _, item := range result.Results {
all = append(
all,
page{
ID: item.ID,
Title: item.Title,
Status: item.Status,
Kind: item.Type,
SpaceID: item.SpaceID,
Links: item.Links,
},
)
}
return result.Links.Next, nil
})
return all, err
}
// topLevelPages retrieves one level only. The Server/DC depth=root endpoint
// is paginated by the server; it deliberately never falls back to scanning all
// pages because that would defeat lazy selection for large spaces.
//
// Cloud applies the same lazy contract: depth=0 returns only root-level pages,
// and Cloud exposes no endpoint to enumerate a space's top-level folders
// (CONFCLOUD-84275), so pages nested directly under those containers stay
// unselectable in the picker for now. Recovering them would require a
// whole-space scan per expand, which is exactly what lazy loading forbids;
// selecting the whole space still syncs them. The connector flags this
// limitation through resource metadata so the picker can surface it.
func (c *client) topLevelPages(ctx context.Context, s space) ([]page, error) {
var pages []page
var err error
if c.cfg.cloud() {
pages, err = c.listCloudHierarchy(
ctx,
"/api/v2/spaces/"+url.PathEscape(s.ID)+"/pages?status=current&depth=0&limit=250",
)
if err == nil {
visible := pages[:0]
for _, page := range pages {
if page.Kind == "" || page.Kind == "page" {
visible = append(visible, page)
}
}
pages = visible
}
} else {
pages, err = c.listServerPages(ctx, serverTopLevelPagesEndpoint(s.Key))
}
if err == nil {
return pages, nil
}
// The depth=root navigation hint is Server/DC-specific; a Cloud 400/404 has
// different causes and must surface the raw API error for diagnosis.
if !c.cfg.cloud() {
var api *apiError
if errors.As(err, &api) && (api.status == http.StatusBadRequest || api.status == http.StatusNotFound) {
return nil, fmt.Errorf(
"confluence server does not support complete top-level page navigation for this space; "+
"select the Space to sync all pages: %w",
err,
)
}
}
return nil, err
}
func (c *client) directChildPages(ctx context.Context, _ space, pageID string) ([]page, error) {
if c.cfg.cloud() {
return c.visibleCloudPageChildren(ctx, pageID)
}
return c.listServerPages(ctx, serverChildPagesEndpoint(pageID))
}
func cloudDirectChildrenEndpoint(kind, id string) (string, error) {
plural := map[string]string{
"page": "pages", "folder": "folders", "database": "databases", "whiteboard": "whiteboards", "embed": "embeds",
}[kind]
if plural == "" {
return "", fmt.Errorf("unsupported Confluence Cloud hierarchy type %q", kind)
}
return "/api/v2/" + plural + "/" + url.PathEscape(id) + "/direct-children?limit=250", nil
}
// visibleCloudPageChildren projects Cloud's mixed-content hierarchy onto a
// Page-only picker. Containers remain connector-internal and are traversed
// until the next visible Page is found.
func (c *client) visibleCloudPageChildren(ctx context.Context, pageID string) ([]page, error) {
return c.walkCloudPageHierarchy(ctx, pageID, false)
}
// walkCloudPageHierarchy traverses Cloud's mixed content tree through
// direct-children endpoints. Picker expansion stops at visible pages, while a
// sync walk continues through them to return the complete page subtree.
func (c *client) walkCloudPageHierarchy(ctx context.Context, pageID string, descendPages bool) ([]page, error) {
type queuedNode struct {
id, kind string
depth int
}
queue := []queuedNode{{id: pageID, kind: "page"}}
visited := map[string]struct{}{"page:" + pageID: {}}
pages := make([]page, 0)
nodeLimit := maxTransparentTraversalNodes
if descendPages {
nodeLimit = maxTraversalNodes
}
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
endpoint, err := cloudDirectChildrenEndpoint(current.kind, current.id)
if err != nil {
return nil, err
}
children, err := c.listCloudHierarchy(ctx, endpoint)
if err != nil {
return nil, err
}
for _, child := range children {
kind := child.Kind
if kind == "" {
kind = "page"
}
key := kind + ":" + child.ID
if child.ID == "" || (kind == "page" && child.ID == pageID) {
continue
}
if _, exists := visited[key]; exists {
continue
}
if len(visited) >= nodeLimit {
return nil, fmt.Errorf(
"confluence Cloud hierarchy traversal exceeds %d nodes",
nodeLimit,
)
}
visited[key] = struct{}{}
if kind == "page" {
pages = append(pages, child)
if !descendPages {
continue
}
}
depth := 0
if kind != "page" {
depth = current.depth + 1
if current.kind == "page" {
depth = 1
}
}
if depth > maxTransparentTraversalDepth {
return nil, fmt.Errorf(
"confluence Cloud transparent traversal exceeds depth %d",
maxTransparentTraversalDepth,
)
}
if _, err := cloudDirectChildrenEndpoint(kind, child.ID); err != nil {
return nil, err
}
queue = append(queue, queuedNode{id: child.ID, kind: kind, depth: depth})
}
}
return pages, nil
}
// pageAncestors validates that pageID belongs to s and returns its path from
// the space root. A selected page is fetched even if it is top-level, so a
// forged page:{space}:{page} ID cannot cross a space boundary.
func (c *client) pageAncestors(ctx context.Context, s space, pageID string) ([]page, error) {
if c.cfg.cloud() {
full, err := c.pageDetail(ctx, pageID)
if err != nil {
return nil, err
}
if full.SpaceID != s.ID {
return nil, fmt.Errorf("page %s belongs to space %s, not %s", pageID, full.SpaceID, s.ID)
}
ancestors, err := c.listCloudHierarchy(ctx, "/api/v2/pages/"+url.PathEscape(pageID)+"/ancestors?limit=250")
if err != nil {
return nil, err
}
return ancestors, nil
}
var full page
if err := c.get(ctx, "/rest/api/content/"+url.PathEscape(pageID)+"?expand=ancestors,space", &full); err != nil {
return nil, err
}
if full.Space.Key == "" || full.Space.Key != s.Key {
return nil, fmt.Errorf("page %s does not belong to space %s", pageID, s.ID)
}
return full.Ancestors, nil
}
// pageSubtree uses direct-child traversal for Server/DC because that endpoint
// is stable across supported versions. Cloud uses the same complete
// mixed-content hierarchy walk as the picker, but continues through visible
// pages to include every page in the selected subtree.
func (c *client) pageSubtree(ctx context.Context, s space, pageID string) ([]page, error) {
full, err := c.pageDetail(ctx, pageID)
if err != nil {
return nil, err
}
if c.cfg.cloud() {
if full.SpaceID != s.ID {
return nil, fmt.Errorf("page %s does not belong to space %s", pageID, s.ID)
}
} else if full.Space.Key == "" || full.Space.Key != s.Key {
return nil, fmt.Errorf("page %s does not belong to space %s", pageID, s.ID)
}
root := full
if c.cfg.cloud() {
descendants, err := c.walkCloudPageHierarchy(ctx, pageID, true)
if err != nil {
return nil, err
}
out := []page{root}
for _, descendant := range descendants {
// Direct-child responses are intentionally compact. Hydrate each page
// before version comparison; an unknown version must never be treated
// as an unchanged stable token.
detail, err := c.pageDetail(ctx, descendant.ID)
if err != nil {
return nil, err
}
if detail.SpaceID != s.ID {
return nil, fmt.Errorf("page %s does not belong to space %s", descendant.ID, s.ID)
}
out = append(out, detail)
}
return out, nil
}
queue, out := []page{root}, []page{root}
seen := map[string]bool{root.ID: true}
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
children, err := c.directChildPages(ctx, s, current.ID)
if err != nil {
return nil, err
}
for _, child := range children {
if child.ID == "" || seen[child.ID] {
continue
}
if len(seen) >= maxTraversalNodes {
return nil, fmt.Errorf("confluence page subtree exceeds %d nodes", maxTraversalNodes)
}
seen[child.ID] = true
if child.SpaceID != "" && child.SpaceID != s.ID {
return nil, fmt.Errorf("page %s does not belong to space %s", child.ID, s.ID)
}
if !c.cfg.cloud() && child.Space.Key != "" && child.Space.Key != s.Key {
return nil, fmt.Errorf("page %s does not belong to space %s", child.ID, s.ID)
}
queue, out = append(queue, child), append(out, child)
}
}
return out, nil
}
@@ -0,0 +1,73 @@
package confluence
import (
"bytes"
"context"
"io"
"net/http"
"strings"
"testing"
)
func TestPaginateRejectsLoop(t *testing.T) {
client := &client{cfg: config{baseURL: "https://confluence.test"}}
err := client.paginate(context.Background(), "/rest/api/space?limit=100", func(string) (string, error) {
return "/rest/api/space?limit=100", nil
})
if err == nil || !strings.Contains(err.Error(), "looped") {
t.Fatalf("paginate() error = %v", err)
}
}
func TestGetIncludesClientErrorBody(t *testing.T) {
client := &client{
cfg: config{baseURL: "https://confluence.test", username: "reader", secret: "secret"},
http: &http.Client{Transport: roundTripper(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusBadRequest,
Header: make(http.Header),
Body: io.NopCloser(bytes.NewBufferString("invalid CQL expression")),
}, nil
})},
}
err := client.get(context.Background(), "/rest/api/content/search", nil)
if err == nil || !strings.Contains(err.Error(), "invalid CQL expression") {
t.Fatalf("get() error = %v", err)
}
}
func TestPingUsesEditionEndpoint(t *testing.T) {
for _, tc := range []struct {
name string
cfg config
want string
}{
{name: "server", cfg: config{baseURL: "https://confluence.test"}, want: "/rest/api/space"},
{
name: "cloud",
cfg: config{baseURL: "https://team.atlassian.net/wiki", edition: editionCloud},
want: "/wiki/api/v2/spaces",
},
} {
t.Run(tc.name, func(t *testing.T) {
var path string
transport := roundTripper(func(req *http.Request) (*http.Response, error) {
path = req.URL.Path
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader("{}")),
}, nil
})
client := &client{cfg: tc.cfg, http: &http.Client{Transport: transport}}
if err := client.ping(context.Background()); err != nil {
t.Fatal(err)
}
if path != tc.want {
t.Fatalf("ping path = %q, want %q", path, tc.want)
}
})
}
}
@@ -0,0 +1,275 @@
package confluence
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestPagesUsesOfficialFlatListAndKeepsExpandOnNext(t *testing.T) {
var expands []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/rest/api/space/ENG/content/page" {
http.NotFound(w, r)
return
}
expands = append(expands, r.URL.Query().Get("expand"))
w.Header().Set("Content-Type", "application/json")
if r.URL.Query().Get("start") == "100" {
_, _ = w.Write([]byte(`{
"results": [{"id": "2", "title": "Child", "version": {"number": 4}}]
}`))
return
}
_, _ = w.Write([]byte(`{
"_links": {"next": "/rest/api/space/ENG/content/page?limit=100&start=100"},
"results": [{"id": "1", "title": "Root", "version": {"number": 3}}]
}`))
}))
t.Cleanup(server.Close)
c := &client{cfg: config{baseURL: server.URL}, http: server.Client()}
pages, _, err := c.pages(context.Background(), space{ID: "1", Key: "ENG", Name: "Engineering"})
if err != nil {
t.Fatal(err)
}
if len(pages) != 2 || pages[0].ID != "1" || pages[1].ID != "2" {
t.Fatalf("pages = %#v", pages)
}
if pages[0].Version.Number != 3 || pages[1].Version.Number != 4 {
t.Fatalf("versions = %#v", pages)
}
if pages[0].Space.Key != "ENG" || pages[1].Space.Key != "ENG" {
t.Fatalf("space copied from parent = %#v", pages)
}
if len(expands) != 2 || expands[0] != serverPageExpand || expands[1] != serverPageExpand {
t.Fatalf("expand query = %#v", expands)
}
}
func TestServerPagesStopAfterRepeatedEmptyPages(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.Header().Set("Content-Type", "application/json")
results := `[]`
if r.URL.Query().Get("start") == "" {
results = `[{"id": "1", "title": "Root", "version": {"number": 1}}]`
}
next := fmt.Sprintf("/rest/api/space/ENG/content/page?limit=100&start=%d", calls*100)
_, _ = fmt.Fprintf(w, `{"results": %s, "_links": {"next": %q}}`, results, next)
}))
t.Cleanup(server.Close)
c := &client{cfg: config{baseURL: server.URL}, http: server.Client()}
pages, complete, err := c.pages(context.Background(), space{Key: "ENG", Name: "Engineering"})
if err != nil {
t.Fatal(err)
}
if complete {
t.Fatal("a listing cut short by empty pages must not report complete")
}
if len(pages) != 1 || pages[0].ID != "1" {
t.Fatalf("pages = %#v", pages)
}
if calls != 1+maxEmptyServerPages {
t.Fatalf("calls = %d, want %d", calls, 1+maxEmptyServerPages)
}
}
func TestServerPagesContinuePastOneEmptyPage(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.Query().Get("start") {
case "":
_, _ = w.Write([]byte(`{"results": [{"id": "1", "title": "A"}],
"_links": {"next": "/rest/api/space/ENG/content/page?limit=100&start=100"}}`))
case "100":
// Every page in this window was filtered out by permissions.
_, _ = w.Write([]byte(`{"results": [],
"_links": {"next": "/rest/api/space/ENG/content/page?limit=100&start=200"}}`))
default:
_, _ = w.Write([]byte(`{"results": [{"id": "2", "title": "B"}]}`))
}
}))
t.Cleanup(server.Close)
c := &client{cfg: config{baseURL: server.URL}, http: server.Client()}
pages, complete, err := c.pages(context.Background(), space{Key: "ENG", Name: "Engineering"})
if err != nil {
t.Fatal(err)
}
if !complete || len(pages) != 2 {
t.Fatalf("complete = %v, pages = %#v", complete, pages)
}
}
func TestPagesAcceptsNestedContentEnvelope(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"page": {
"results": [{"id": "9", "title": "Nested", "version": {"number": 1}}]
}
}`))
}))
t.Cleanup(server.Close)
c := &client{cfg: config{baseURL: server.URL}, http: server.Client()}
pages, _, err := c.pages(context.Background(), space{Key: "ENG", Name: "Engineering"})
if err != nil {
t.Fatal(err)
}
if len(pages) != 1 || pages[0].ID != "9" {
t.Fatalf("pages = %#v", pages)
}
}
func TestServerSpacePageListPrefersFlatResults(t *testing.T) {
var listed serverSpacePageList
if err := json.Unmarshal([]byte(`{
"_links": {"next": "/rest/api/space/ENG/content/page?limit=5&start=5"},
"results": [{"id": "98308", "title": "What is Confluence?"}]
}`), &listed); err != nil {
t.Fatal(err)
}
pages := listed.pages()
if len(pages) != 1 || pages[0].ID != "98308" {
t.Fatalf("pages() = %#v", pages)
}
if listed.nextLink() != "/rest/api/space/ENG/content/page?limit=5&start=5" {
t.Fatalf("nextLink() = %q", listed.nextLink())
}
}
func TestTopLevelPagesServerRestoresScopeOnNext(t *testing.T) {
var depths, expands []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/rest/api/space/ENG/content/page" {
http.NotFound(w, r)
return
}
depths = append(depths, r.URL.Query().Get("depth"))
expands = append(expands, r.URL.Query().Get("expand"))
w.Header().Set("Content-Type", "application/json")
if r.URL.Query().Get("start") == "100" {
_, _ = w.Write([]byte(`{
"results": [{"id": "2", "title": "Second", "version": {"number": 2}}]
}`))
return
}
_, _ = w.Write([]byte(`{
"_links": {"next": "/rest/api/space/ENG/content/page?limit=100&start=100"},
"results": [{"id": "1", "title": "Root", "version": {"number": 1}}]
}`))
}))
t.Cleanup(server.Close)
c := &client{cfg: config{baseURL: server.URL}, http: server.Client()}
pages, err := c.topLevelPages(context.Background(), space{ID: "1", Key: "ENG", Name: "Engineering"})
if err != nil {
t.Fatal(err)
}
if len(pages) != 2 || pages[0].ID != "1" || pages[1].ID != "2" {
t.Fatalf("pages = %#v", pages)
}
// The server's _links.next drops depth and expand; the connector must
// rebuild the listing scope or later pages would look versionless.
if len(depths) != 2 || depths[0] != "root" || depths[1] != "root" {
t.Fatalf("depth query = %#v", depths)
}
if len(expands) != 2 || expands[0] != serverPageExpand || expands[1] != serverPageExpand {
t.Fatalf("expand query = %#v", expands)
}
}
func TestTopLevelPagesCloudSurfacesRawAPIError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message":"space not found"}`))
}))
t.Cleanup(server.Close)
cloud := &client{cfg: config{baseURL: server.URL + "/wiki", edition: editionCloud}, http: server.Client()}
_, err := cloud.topLevelPages(context.Background(), space{ID: "1", Key: "ENG", Name: "Engineering"})
if err == nil {
t.Fatal("cloud topLevelPages unexpectedly succeeded")
}
if strings.Contains(err.Error(), "does not support") {
t.Fatalf("cloud 404 reused the Server/DC navigation hint: %v", err)
}
srv := &client{cfg: config{baseURL: server.URL + "/wiki"}, http: server.Client()}
_, err = srv.topLevelPages(context.Background(), space{ID: "1", Key: "ENG", Name: "Engineering"})
if err == nil || !strings.Contains(err.Error(), "confluence server does not support") {
t.Fatalf("server error = %v; want the Server/DC navigation hint", err)
}
}
func TestPagesCloudFollowsNextAndKeepsDepth(t *testing.T) {
var depths []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/wiki/api/v2/spaces/1/pages" {
http.NotFound(w, r)
return
}
depths = append(depths, r.URL.Query().Get("depth"))
w.Header().Set("Content-Type", "application/json")
if r.URL.Query().Get("cursor") == "page-two" {
_, _ = w.Write([]byte(`{"results":[{"id":"2","title":"Child","version":{"number":2}}]}`))
return
}
_, _ = w.Write([]byte(`{
"_links": {"next": "/wiki/api/v2/spaces/1/pages?limit=250&cursor=page-two"},
"results": [{"id":"1","title":"Root","version":{"number":1}}]
}`))
}))
t.Cleanup(server.Close)
c := &client{cfg: config{baseURL: server.URL + "/wiki", edition: editionCloud}, http: server.Client()}
pages, _, err := c.pages(context.Background(), space{ID: "1", Key: "ENG", Name: "Engineering"})
if err != nil {
t.Fatal(err)
}
if len(pages) != 2 || pages[0].ID != "1" || pages[1].ID != "2" {
t.Fatalf("pages = %#v", pages)
}
if len(depths) != 2 || depths[0] != "all" || depths[1] != "all" {
t.Fatalf("depth query = %#v", depths)
}
}
func TestPageInSpace(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("expand") != "space" {
t.Errorf("expand = %q, want space", r.URL.Query().Get("expand"))
}
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/rest/api/content/current":
_, _ = w.Write([]byte(`{"id": "current", "status": "current", "space": {"key": "ENG"}}`))
case "/rest/api/content/trashed":
_, _ = w.Write([]byte(`{"id": "trashed", "status": "trashed", "space": {"key": "ENG"}}`))
case "/rest/api/content/moved":
_, _ = w.Write([]byte(`{"id": "moved", "status": "current", "space": {"key": "OPS"}}`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(server.Close)
c := &client{cfg: config{baseURL: server.URL}, http: server.Client()}
for id, want := range map[string]bool{"current": true, "trashed": false, "moved": false, "deleted": false} {
got, err := c.pageInSpace(context.Background(), id, "ENG")
if err != nil {
t.Fatalf("%s: %v", id, err)
}
if got != want {
t.Errorf("pageInSpace(%s) = %v, want %v", id, got, want)
}
}
}
@@ -0,0 +1,17 @@
package confluence
import "testing"
func TestResolveEndpointNormalizesCloudPaginationLinks(t *testing.T) {
client := &client{cfg: config{baseURL: "https://team.atlassian.net/wiki"}}
cases := map[string]string{
"/api/v2/spaces?cursor=one": "https://team.atlassian.net/wiki/api/v2/spaces?cursor=one",
"/wiki/api/v2/spaces?cursor=two": "https://team.atlassian.net/wiki/api/v2/spaces?cursor=two",
}
for endpoint, want := range cases {
got, err := client.resolveEndpoint(endpoint)
if err != nil || got != want {
t.Errorf("resolveEndpoint(%q) = %q, %v; want %q", endpoint, got, err, want)
}
}
}
@@ -0,0 +1,111 @@
package confluence
import (
"net/url"
"strings"
"testing"
"time"
)
func TestResolveEndpointKeepsCloudContextPath(t *testing.T) {
client := &client{cfg: config{baseURL: "https://team.atlassian.net/wiki"}}
for _, endpoint := range []string{
"/api/v2/spaces?cursor=one",
"/wiki/api/v2/spaces?cursor=two",
"https://team.atlassian.net/wiki/api/v2/spaces?cursor=three",
} {
got, err := client.resolveEndpoint(endpoint)
if err != nil {
t.Fatalf("resolveEndpoint(%q): %v", endpoint, err)
}
if got == "https://team.atlassian.net/wiki/wiki/api/v2/spaces?cursor=two" {
t.Fatalf("resolveEndpoint(%q) duplicated /wiki: %s", endpoint, got)
}
}
}
func TestResolveEndpointRejectsForeignOrigin(t *testing.T) {
client := &client{cfg: config{baseURL: "https://team.atlassian.net/wiki"}}
if _, err := client.resolveEndpoint("https://attacker.example/api/v2/spaces"); err == nil {
t.Fatal("resolveEndpoint accepted a foreign pagination origin")
}
}
func TestServerSpacePagesEndpointEscapesPersonalKey(t *testing.T) {
endpoint := serverSpacePagesEndpoint("~personal_space")
parsed, err := url.Parse(endpoint)
if err != nil {
t.Fatalf("parse endpoint: %v", err)
}
if parsed.Path != "/rest/api/space/~personal_space/content/page" {
t.Fatalf("path = %q", parsed.Path)
}
if parsed.Query().Get("expand") != "version,space" {
t.Fatalf("expand = %q", parsed.Query().Get("expand"))
}
}
func TestCapRetryDelayBoundsRetryAfter(t *testing.T) {
if got := capRetryDelay(0); got != 100*time.Millisecond {
t.Fatalf("capRetryDelay(0) = %v", got)
}
if got := capRetryDelay(5 * time.Minute); got != maxRetryDelay {
t.Fatalf("capRetryDelay(5m) = %v", got)
}
}
func TestResolveEndpointDoesNotDoubleEncodeSpaceKeys(t *testing.T) {
client := &client{cfg: config{baseURL: "https://confluence.test"}}
endpoint := "/rest/api/space/" + url.PathEscape("~foo bar") + "/content/page"
got, err := client.resolveEndpoint(endpoint)
if err != nil {
t.Fatal(err)
}
if strings.Contains(got, "%2520") {
t.Fatalf("resolveEndpoint double-encoded path: %s", got)
}
parsed, err := url.Parse(got)
if err != nil {
t.Fatal(err)
}
if parsed.Path != "/rest/api/space/~foo bar/content/page" {
t.Fatalf("path = %q", parsed.Path)
}
}
func TestWithServerPageExpandRestoresDroppedQuery(t *testing.T) {
got := withServerPageExpand("/rest/api/space/ENG/content/page?limit=100&start=100")
parsed, err := url.Parse(got)
if err != nil {
t.Fatal(err)
}
if parsed.Query().Get("expand") != serverPageExpand || parsed.Query().Get("start") != "100" {
t.Fatalf("withServerPageExpand() = %s", got)
}
}
func TestResolveEndpointRejectsContextPathTraversal(t *testing.T) {
client := &client{cfg: config{baseURL: "https://team.atlassian.net/wiki"}}
for _, endpoint := range []string{
"/wiki/../rest/other",
"https://team.atlassian.net/wiki/../rest/other",
"../rest/other",
} {
if _, err := client.resolveEndpoint(endpoint); err == nil {
t.Fatalf("resolveEndpoint(%q) accepted a path that leaves /wiki", endpoint)
}
}
}
func TestWithCloudPageQueryRestoresDroppedFilters(t *testing.T) {
got := withCloudPageQuery("/wiki/api/v2/spaces/1/pages?cursor=abc&limit=250")
parsed, err := url.Parse(got)
if err != nil {
t.Fatal(err)
}
if parsed.Query().Get("status") != "current" ||
parsed.Query().Get("depth") != "all" ||
parsed.Query().Get("cursor") != "abc" {
t.Fatalf("withCloudPageQuery() = %s", got)
}
}
@@ -0,0 +1,641 @@
// Package confluence imports Confluence Server/Data Center and Cloud spaces as Markdown.
package confluence
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"net/http"
"sort"
"strings"
"sync"
"time"
htmltomd "github.com/JohannesKaufmann/html-to-markdown/v2"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
var (
_ datasource.StreamingConnector = (*Connector)(nil)
_ datasource.FullStreamingConnector = (*Connector)(nil)
)
// Connector implements datasource.StreamingConnector for Confluence.
type Connector struct {
newClient func(config) (*client, error)
spaceCache spaceCache
}
const pickerSpaceCacheTTL = time.Minute
type spaceCache struct {
mu sync.Mutex
entries map[string]cachedSpaces
}
type cachedSpaces struct {
values []space
expires time.Time
}
// NewConnector creates a Confluence connector.
func NewConnector() *Connector { return &Connector{newClient: newClient} }
func (c *Connector) pickerSpaces(ctx context.Context, client *client, cfg config) ([]space, error) {
key := pickerSpaceCacheKey(cfg)
now := time.Now()
c.spaceCache.mu.Lock()
if cached, ok := c.spaceCache.entries[key]; ok && now.Before(cached.expires) {
values := append([]space(nil), cached.values...)
c.spaceCache.mu.Unlock()
return values, nil
}
c.spaceCache.mu.Unlock()
spaces, err := client.spaces(ctx)
if err != nil {
return nil, err
}
c.spaceCache.mu.Lock()
if c.spaceCache.entries == nil {
c.spaceCache.entries = make(map[string]cachedSpaces)
}
for key, cached := range c.spaceCache.entries {
if !now.Before(cached.expires) {
delete(c.spaceCache.entries, key)
}
}
c.spaceCache.entries[key] = cachedSpaces{
values: append([]space(nil), spaces...),
expires: now.Add(pickerSpaceCacheTTL),
}
c.spaceCache.mu.Unlock()
return spaces, nil
}
// pickerSpaceCacheKey partitions cached space visibility by every credential
// component that can affect permissions. The secret is fingerprinted so it
// never becomes a map key retained in process memory or appears in diagnostics.
func pickerSpaceCacheKey(cfg config) string {
fingerprint := sha256.Sum256([]byte(cfg.secret))
return cfg.edition + "\x00" + cfg.baseURL + "\x00" + cfg.username + "\x00" +
fmt.Sprintf("%t:%x", cfg.usePAT, fingerprint)
}
// Type returns the connector type identifier.
func (*Connector) Type() string { return types.ConnectorTypeConfluence }
func (c *Connector) configured(ds *types.DataSourceConfig) (*client, config, error) {
cfg, err := parseConfig(ds)
if err != nil {
return nil, config{}, err
}
factory := c.newClient
if factory == nil {
factory = newClient
}
client, err := factory(cfg)
return client, cfg, err
}
// Validate pings Confluence with the supplied credentials.
func (c *Connector) Validate(ctx context.Context, ds *types.DataSourceConfig) error {
client, _, err := c.configured(ds)
if err != nil {
return err
}
return client.ping(ctx)
}
// ListResources exposes a lazy Space → Page tree. It never scans a whole
// space merely to render the picker.
func (c *Connector) ListResources(
ctx context.Context, ds *types.DataSourceConfig, parentID string,
) ([]types.Resource, error) {
client, cfg, err := c.configured(ds)
if err != nil {
return nil, err
}
if parentID == "" {
spaces, err := c.pickerSpaces(ctx, client, cfg)
if err != nil {
return nil, err
}
out := make([]types.Resource, 0, len(spaces))
for _, s := range spaces {
metadata := map[string]interface{}{"space_key": s.Key}
if cfg.cloud() {
// Cloud cannot enumerate a space's top-level folders, so pages under
// them are unselectable in the picker; the frontend surfaces this
// limitation when the space is expanded.
metadata["hierarchy_limitation"] = "cloud_top_level_containers"
}
out = append(out, types.Resource{
ExternalID: s.ID, Name: s.Name, Type: "space",
URL: client.resourceURL(s.Links.WebUI), HasChildren: true,
Metadata: metadata,
})
}
return out, nil
}
ref, err := parseResourceID(parentID)
if err != nil {
return nil, err
}
spaces, err := c.pickerSpaces(ctx, client, cfg)
if err != nil {
return nil, err
}
var selected space
found := false
for _, s := range spaces {
if s.ID == ref.SpaceID {
selected, found = s, true
break
}
}
if !found {
return nil, fmt.Errorf("confluence space %s is unavailable", ref.SpaceID)
}
var pages []page
if ref.Kind == resourceSpace {
pages, err = client.topLevelPages(ctx, selected)
} else {
if ref.Kind == resourcePage {
if err := client.validatePageOwnership(ctx, selected, ref.PageID); err != nil {
return nil, fmt.Errorf("validate Confluence page %s: %w", ref.PageID, err)
}
}
pages, err = client.directChildPages(ctx, selected, ref.PageID)
}
if err != nil {
return nil, fmt.Errorf("list Confluence resources under %s: %w", parentID, err)
}
out := make([]types.Resource, 0, len(pages))
for _, p := range pages {
out = append(out, pageResource(client, selected, parentID, p))
}
return out, nil
}
func pageResource(client *client, s space, parentID string, p page) types.Resource {
return types.Resource{
ExternalID: makePageResourceID(s.ID, p.ID), ParentID: parentID, Name: p.Title, Type: "page",
URL: client.resourceURL(p.Links.WebUI), HasChildren: true,
Metadata: map[string]interface{}{"space_id": s.ID, "page_id": p.ID},
}
}
// ResolveResourceAncestors expands only the O(depth) path required to reveal
// persisted page selections in the lazy picker. Resolution is best effort:
// a deleted page, an unavailable space, or a malformed id skips just its own
// reveal path instead of failing every saved selection; the sync path keeps
// its strict validation in buildSyncPlan.
func (c *Connector) ResolveResourceAncestors(
ctx context.Context,
ds *types.DataSourceConfig,
resourceIDs []string,
) ([]string, error) {
client, _, err := c.configured(ds)
if err != nil {
return nil, err
}
spaces, err := client.spaces(ctx)
if err != nil {
return nil, err
}
byID := make(map[string]space, len(spaces))
for _, s := range spaces {
byID[s.ID] = s
}
seen, out := map[string]bool{}, []string{}
add := func(id string) {
if id != "" && !seen[id] {
seen[id] = true
out = append(out, id)
}
}
for _, id := range resourceIDs {
ref, err := parseResourceID(id)
if err != nil {
logger.Warnf(ctx, "skip malformed Confluence resource %q during ancestor resolution: %v", id, err)
continue
}
if ref.Kind == resourceSpace {
continue
}
s, ok := byID[ref.SpaceID]
if !ok {
logger.Warnf(ctx, "skip Confluence resource %s: space %s is unavailable", id, ref.SpaceID)
continue
}
ancestors, err := client.pageAncestors(ctx, s, ref.PageID)
if err != nil {
logger.Warnf(ctx, "skip Confluence resource %s during ancestor resolution: %v", id, err)
continue
}
add(s.ID)
for _, ancestor := range ancestors {
if ancestor.Kind != "" && ancestor.Kind != "page" {
continue
}
add(makePageResourceID(s.ID, ancestor.ID))
}
}
return out, nil
}
// FetchAll syncs every selected space. Deletion reconciliation needs FetchStream.
func (c *Connector) FetchAll(
ctx context.Context, ds *types.DataSourceConfig, resourceIDs []string,
) ([]types.FetchedItem, error) {
dsCopy := *ds
dsCopy.ResourceIDs = resourceIDs
return c.collect(ctx, &dsCopy, nil)
}
// FetchIncremental syncs pages whose versions changed since the last cursor.
func (c *Connector) FetchIncremental(
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor,
) ([]types.FetchedItem, *types.SyncCursor, error) {
items, next, err := c.collectWithCursor(ctx, ds, old)
return items, next, err
}
type collector struct{ items []types.FetchedItem }
func (h *collector) Emit(_ context.Context, item types.FetchedItem) error {
h.items = append(h.items, item)
return nil
}
func (*collector) Checkpoint(context.Context, *types.SyncCursor) error { return nil }
func (c *Connector) collect(
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor,
) ([]types.FetchedItem, error) {
items, _, err := c.collectWithCursor(ctx, ds, old)
return items, err
}
func (c *Connector) collectWithCursor(
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor,
) ([]types.FetchedItem, *types.SyncCursor, error) {
h := &collector{}
next, err := c.FetchStream(ctx, ds, old, h)
return h.items, next, err
}
// FetchStream is the one sync engine. A version enters its cursor only after
// its Markdown has been fetched and Emit has succeeded, making checkpoints safe.
func (c *Connector) FetchStream(
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
return c.fetchStream(ctx, ds, old, h, false)
}
// FetchFullStream forces every page to be re-fetched while retaining old solely
// as a complete baseline for deletion reconciliation. Mid-run checkpoints keep
// that baseline plus the pages already re-fetched so Asynq retries resume
// instead of starting over.
func (c *Connector) FetchFullStream(
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
return c.fetchStream(ctx, ds, old, h, true)
}
func (c *Connector) fetchStream(
ctx context.Context,
ds *types.DataSourceConfig,
old *types.SyncCursor,
h datasource.StreamHandler,
forceFull bool,
) (*types.SyncCursor, error) {
if ds == nil || len(ds.ResourceIDs) == 0 {
return nil, fmt.Errorf("confluence requires at least one selected space")
}
client, _, err := c.configured(ds)
if err != nil {
return nil, err
}
plan, err := c.buildSyncPlan(ctx, client, ds.ResourceIDs)
if err != nil {
return nil, err
}
currentRoots := make(map[string]bool, len(plan.Roots))
for _, root := range plan.Roots {
currentRoots[root.ResourceID] = true
}
baseline, next := prepareSyncCursors(old, forceFull)
// A prior successful body is reusable when ownership moves to a different
// selected root and this run cannot fetch the new body. Keep that version in
// the new root rather than dropping it during ownership reconciliation.
priorVersionByPage := make(map[string]string)
for _, pages := range baseline.SpacePages {
for id, version := range pages {
if _, exists := priorVersionByPage[id]; !exists {
priorVersionByPage[id] = version
}
}
}
// A page may be returned by multiple overlapping roots (for example during
// a configuration change). Fetch it once, while retaining a cursor entry
// per scope root so existing cursor JSON remains compatible.
seenPages := make(map[string]struct{})
incompleteRoots := make(map[string]bool)
incompleteSpaces := make([]space, 0)
for _, root := range plan.Roots {
resourceID, s := root.ResourceID, root.Space
var pages []page
complete := true
if root.Kind == syncWholeSpace {
pages, complete, err = client.pages(ctx, s)
} else {
pages, err = client.pageSubtree(ctx, s, root.PageID)
}
if err != nil {
return nil, fmt.Errorf("list pages in Confluence scope %s: %w", resourceID, err)
}
priorPages := baseline.SpacePages[resourceID]
if !complete {
logger.Warnf(
ctx,
"[Confluence] space %s listing was cut short; checking unlisted pages before deleting",
s.Key,
)
incompleteRoots[resourceID] = true
incompleteSpaces = append(incompleteSpaces, s)
}
if next.SpacePages[resourceID] == nil {
next.SpacePages[resourceID] = map[string]string{}
}
if complete && len(pages) == 0 && len(priorPages) > 0 {
return nil, fmt.Errorf(
"refusing Confluence mirror deletion in %s: listing returned 0 pages against a %d-page baseline",
s.Key, len(priorPages),
)
}
for _, summary := range pages {
if err := ctx.Err(); err != nil {
return nil, err
}
if _, duplicate := seenPages[summary.ID]; duplicate {
// The first scope already owns the emitted document; preserve this
// root's version record so a later selection change stays incremental.
if !forceFull {
if version, ok := priorPages[summary.ID]; ok {
next.SpacePages[resourceID][summary.ID] = version
}
}
continue
}
seenPages[summary.ID] = struct{}{}
version, versionKnown := pageVersion(summary)
// An unknown version cannot prove a page unchanged, so it must
// always refresh the body instead of skipping on a stable "t:".
if versionKnown {
if forceFull {
if next.SpacePages[resourceID][summary.ID] == version {
continue
}
} else if priorPages[summary.ID] == version {
continue
}
}
full, err := client.body(ctx, summary.ID)
if err != nil {
if ctx.Err() != nil {
return nil, err
}
if emitErr := h.Emit(ctx, failedPageItem(resourceID, summary, err)); emitErr != nil {
return nil, emitErr
}
if !forceFull {
if prior, ok := priorVersionByPage[summary.ID]; ok {
next.SpacePages[resourceID][summary.ID] = prior
}
}
continue
}
item, err := markdownItem(ctx, client, resourceID, summary, full)
if err != nil {
if emitErr := h.Emit(ctx, failedPageItem(resourceID, summary, err)); emitErr != nil {
return nil, emitErr
}
if !forceFull {
if prior, ok := priorVersionByPage[summary.ID]; ok {
next.SpacePages[resourceID][summary.ID] = prior
}
}
continue
}
if err := h.Emit(ctx, item); err != nil {
return nil, err
}
next.SpacePages[resourceID][summary.ID] = version
if err := h.Checkpoint(ctx, next.syncCursor()); err != nil {
return nil, err
}
}
}
// Reconcile previous owners only after every current scope has been enumerated.
// A page may move between roots, so a missing page must be checked against every
// scope whose listing was cut short before a tombstone can be emitted.
previousPages := make(map[string]string)
for owner, pages := range baseline.SpacePages {
for id := range pages {
if _, exists := previousPages[id]; !exists {
previousPages[id] = owner
}
}
}
missing := make([]string, 0)
probeCount := 0
for id := range previousPages {
if _, present := seenPages[id]; present {
continue
}
owner := previousPages[id]
for _, s := range incompleteSpaces {
if probeCount >= maxDeletionProbes {
return nil, fmt.Errorf(
"Confluence deletion reconciliation deferred: more than %d pages need verification",
maxDeletionProbes,
)
}
probeCount++
present, err := client.pageInSpace(ctx, id, s.Key)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, fmt.Errorf(
"Confluence deletion reconciliation deferred: could not verify page %s in space %s: %w",
id, s.Key, err,
)
}
if present {
version := baseline.SpacePages[owner][id]
if next.SpacePages[s.ID] == nil {
next.SpacePages[s.ID] = make(map[string]string)
}
next.SpacePages[s.ID][id] = version
seenPages[id] = struct{}{}
break
}
}
if _, present := seenPages[id]; present {
continue
}
missing = append(missing, id)
}
// Protect still-selected roots from a suspiciously large shrink. Removed
// roots are an explicit scope change, so their out-of-scope pages can be
// tombstoned once every current scope has been enumerated safely.
owners := make([]string, 0, len(baseline.SpacePages))
for owner := range baseline.SpacePages {
owners = append(owners, owner)
}
sort.Strings(owners)
for _, owner := range owners {
// A deliberate scope change may remove most of an old root. The guard is
// only for unexpected shrinkage of a still-selected, completely listed root.
if !currentRoots[owner] || incompleteRoots[owner] {
continue
}
pages := baseline.SpacePages[owner]
missingInRoot := 0
for id := range pages {
if _, present := seenPages[id]; !present {
missingInRoot++
}
}
if len(pages) > 0 && missingInRoot >= 20 && missingInRoot*100 >= len(pages)*80 {
return nil, fmt.Errorf(
"refusing Confluence mirror deletion: %d/%d previously synced pages would be removed from scope %s",
missingInRoot, len(pages), owner,
)
}
}
sort.Strings(missing)
for _, id := range missing {
deleted := types.FetchedItem{
ExternalID: id, IsDeleted: true, SourceResourceID: previousPages[id],
Metadata: map[string]string{"channel": types.ChannelConfluence},
}
if err := h.Emit(ctx, deleted); err != nil {
return nil, err
}
// Drop the tombstoned page before checkpointing so the cursor records
// the deletion itself; an interrupted run resumes with the remaining
// candidates instead of re-emitting completed tombstones.
removePageOwnership(&next, id)
if err := h.Checkpoint(ctx, next.syncCursor()); err != nil {
return nil, err
}
}
// Commit exactly the current ownership roots only after reconciliation. This
// removes cancelled scopes while keeping the on-disk cursor field compatible.
committedRoots := make(map[string]map[string]string, len(plan.Roots))
for _, root := range plan.Roots {
if pages := next.SpacePages[root.ResourceID]; pages != nil {
committedRoots[root.ResourceID] = pages
} else {
committedRoots[root.ResourceID] = map[string]string{}
}
}
next.SpacePages = committedRoots
next.FullSync = false
next.FullSyncBaseline = nil
return next.syncCursor(), nil
}
func failedPageItem(resourceID string, summary page, err error) types.FetchedItem {
code, reason := classifyConfluenceError(err)
return types.FetchedItem{
ExternalID: summary.ID,
Title: summary.Title,
SourceResourceID: resourceID,
Metadata: map[string]string{
"channel": types.ChannelConfluence,
"error": err.Error(),
"error_reason_code": code,
"error_reason": reason,
"page_id": summary.ID,
},
}
}
func classifyConfluenceError(err error) (code, reason string) {
var api *apiError
if errors.As(err, &api) {
switch api.status {
case http.StatusUnauthorized, http.StatusForbidden:
return "confluence_auth_or_permission",
"Authentication or permission error; check credentials and space permissions"
case http.StatusNotFound:
return "confluence_not_found", "Confluence page was not found; will retry on the next sync"
case http.StatusTooManyRequests:
return "confluence_rate_limited", "Confluence API rate limited; will retry on the next sync"
default:
if api.status >= 500 {
return "confluence_server_unavailable",
"Confluence service temporarily unavailable; will retry on the next sync"
}
return "confluence_api_error", "Confluence API error; see server logs"
}
}
return "confluence_sync_failed", "Confluence page could not be synced; see server logs"
}
func markdownItem(
ctx context.Context,
client *client,
resourceID string,
summary page,
full pageBody,
) (types.FetchedItem, error) {
html := full.Body.View.Value
// Inline same-origin private Confluence images as data URIs so the generic
// docparser image pipeline can persist them and rewrite to resource:// URLs.
// Best-effort: a failed image keeps its original src and never fails the page.
html = newAssetResolver(client).Resolve(ctx, html)
markdown, err := htmltomd.ConvertString(html)
if err != nil {
return types.FetchedItem{}, err
}
if strings.TrimSpace(markdown) == "" {
markdown = "# " + summary.Title + "\n"
}
if full.Title != "" {
summary.Title = full.Title
}
if full.Version.Number > 0 || full.Version.When != "" {
summary.Version = full.Version
}
if full.Space.Key != "" {
summary.Space = full.Space
}
if webui := strings.TrimSpace(summary.Links.WebUI); webui == "" && full.Links.WebUI != "" {
summary.Links.WebUI = full.Links.WebUI
}
metadata := map[string]string{
"channel": types.ChannelConfluence, "space_key": summary.Space.Key,
"space_name": summary.Space.Name, "page_id": summary.ID,
}
if creator := strings.TrimSpace(summary.Version.By.DisplayName); creator != "" {
metadata["creator"] = creator
}
return types.FetchedItem{
ExternalID: summary.ID,
Title: summary.Title,
Content: []byte(markdown),
ContentType: "text/markdown",
FileName: pageFileName(summary.Title, summary.ID),
URL: client.resourceURL(summary.Links.WebUI),
UpdatedAt: pageUpdatedAt(summary),
SourceResourceID: resourceID,
Metadata: metadata,
}, nil
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,196 @@
package confluence
import (
"context"
"encoding/base64"
"errors"
"net/http"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/types"
)
func TestPATAuthentication(t *testing.T) {
for _, tc := range []struct {
name string
credentials map[string]interface{}
want string
invalid bool
}{
{
name: "PAT without username",
credentials: map[string]interface{}{
"token": " pat-value ",
},
want: "Bearer pat-value",
},
{
name: "PAT overrides password",
credentials: map[string]interface{}{
"username": "reader",
"password": "password",
"token": "pat-value",
},
want: "Bearer pat-value",
},
{
name: "legacy Basic",
credentials: map[string]interface{}{
"username": "reader",
"password": "password",
},
want: "Basic " + base64.StdEncoding.EncodeToString([]byte("reader:password")),
},
{
name: "blank PAT falls back to Basic",
credentials: map[string]interface{}{
"username": "reader",
"password": "password",
"token": " ",
},
want: "Basic " + base64.StdEncoding.EncodeToString([]byte("reader:password")),
},
{
name: "Cloud ignores Server PAT",
credentials: map[string]interface{}{
"edition": "cloud",
"username": "reader",
"api_token": "cloud-token",
"token": "pat-value",
},
want: "Basic " + base64.StdEncoding.EncodeToString([]byte("reader:cloud-token")),
},
{
name: "Cloud still requires username",
credentials: map[string]interface{}{
"edition": "cloud",
"api_token": "cloud-token",
"token": "pat-value",
},
invalid: true,
},
{
name: "Cloud still requires API token",
credentials: map[string]interface{}{
"edition": "cloud",
"username": "reader",
"token": "pat-value",
},
invalid: true,
},
{
name: "Basic still requires username",
credentials: map[string]interface{}{
"password": "password",
},
invalid: true,
},
{
name: "Basic still requires password",
credentials: map[string]interface{}{
"username": "reader",
},
invalid: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
tc.credentials["base_url"] = testBaseURL
cfg, err := parseConfig(&types.DataSourceConfig{Credentials: tc.credentials})
if tc.invalid {
if !errors.Is(err, datasource.ErrInvalidCredentials) {
t.Fatalf("expected invalid credentials, got %v", err)
}
return
}
if err != nil {
t.Fatal(err)
}
var calls int
transport := roundTripper(func(req *http.Request) (*http.Response, error) {
calls++
if got := req.Header.Get("Authorization"); got != tc.want {
t.Errorf("authorization = %q, want %q", got, tc.want)
}
if strings.Contains(req.URL.Path, "download") {
return imageResp(http.StatusOK, "image/png", testPNG), nil
}
return imageResp(http.StatusOK, "application/json", []byte("{}")), nil
})
c := &client{cfg: cfg, http: &http.Client{Transport: transport}}
if err := c.ping(context.Background()); err != nil {
t.Fatal(err)
}
if _, _, err := c.downloadImage(context.Background(), testBaseURL+"/download/image.png"); err != nil {
t.Fatal(err)
}
if calls != 2 {
t.Fatalf("got %d requests, want API and image requests", calls)
}
})
}
}
func TestPATPickerCachePartitionsAuthentication(t *testing.T) {
keys := make(map[string]bool)
for _, creds := range []map[string]interface{}{
{"username": "reader", "password": "same-secret"},
{"username": "reader", "token": "same-secret"},
{"username": "reader", "token": "rotated-secret"},
} {
creds["base_url"] = testBaseURL
cfg, err := parseConfig(&types.DataSourceConfig{Credentials: creds})
if err != nil {
t.Fatal(err)
}
key := pickerSpaceCacheKey(cfg)
if keys[key] {
t.Fatal("different authentication contexts share a cache key")
}
if strings.Contains(key, "same-secret") || strings.Contains(key, "rotated-secret") {
t.Fatal("cache key contains credential text")
}
keys[key] = true
}
}
func TestPATImageRedirectBoundaries(t *testing.T) {
for _, target := range []string{
testBaseURL + "/download/final.png",
"https://other.test/image.png",
"https://confluence.test/other-app/image.png",
} {
t.Run(target, func(t *testing.T) {
cfg, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]interface{}{
"base_url": testBaseURL, "token": "pat-value",
}})
if err != nil {
t.Fatal(err)
}
calls := 0
transport := roundTripper(func(req *http.Request) (*http.Response, error) {
calls++
if !strings.HasPrefix(req.URL.String(), testBaseURL+"/") {
t.Fatal("request escaped configured Confluence scope")
}
if req.Header.Get("Authorization") != "Bearer pat-value" {
t.Error("missing PAT")
}
if calls == 1 {
return redirectResp(target), nil
}
return imageResp(http.StatusOK, "image/png", testPNG), nil
})
c := &client{cfg: cfg, http: &http.Client{Transport: transport}}
_, _, err = c.downloadImage(context.Background(), testBaseURL+"/download/start.png")
if strings.HasPrefix(target, testBaseURL+"/") {
if err != nil || calls != 2 {
t.Fatalf("same-scope redirect: calls=%d err=%v", calls, err)
}
} else if !errors.Is(err, errImageRedirectOffOrigin) || calls != 1 {
t.Fatalf("unsafe redirect: calls=%d err=%v", calls, err)
}
})
}
}
@@ -0,0 +1,43 @@
package confluence
import (
"fmt"
"strings"
)
type resourceKind uint8
const (
resourceSpace resourceKind = iota
resourcePage
)
// resourceRef is the canonical, persisted representation of a selection.
// Space IDs deliberately remain unprefixed for backwards compatibility.
type resourceRef struct {
Kind resourceKind
SpaceID string
PageID string
}
func makePageResourceID(spaceID, pageID string) string {
return "page:" + spaceID + ":" + pageID
}
func parseResourceID(id string) (resourceRef, error) {
id = strings.TrimSpace(id)
if id == "" {
return resourceRef{}, fmt.Errorf("invalid empty Confluence resource ID")
}
if !strings.HasPrefix(id, "page:") {
if strings.Contains(id, ":") {
return resourceRef{}, fmt.Errorf("invalid Confluence space resource ID %q", id)
}
return resourceRef{Kind: resourceSpace, SpaceID: id}, nil
}
parts := strings.Split(id, ":")
if len(parts) != 3 || parts[0] != "page" || strings.TrimSpace(parts[1]) == "" || strings.TrimSpace(parts[2]) == "" {
return resourceRef{}, fmt.Errorf("invalid Confluence page resource ID %q", id)
}
return resourceRef{Kind: resourcePage, SpaceID: parts[1], PageID: parts[2]}, nil
}
@@ -0,0 +1,23 @@
package confluence
import "testing"
func TestParseResourceID(t *testing.T) {
space, err := parseResourceID("86802433")
if err != nil || space.Kind != resourceSpace || space.SpaceID != "86802433" {
t.Fatalf("space = %#v, %v", space, err)
}
page, err := parseResourceID("page:86802433:123456789")
if err != nil || page.Kind != resourcePage || page.SpaceID != "86802433" || page.PageID != "123456789" {
t.Fatalf("page = %#v, %v", page, err)
}
invalid := []string{
"", "page:", "page:100", "page::200", "page:100:", "page:100:200:300",
"node:86802433:folder-1", "space:100",
}
for _, id := range invalid {
if _, err := parseResourceID(id); err == nil {
t.Errorf("parseResourceID(%q) succeeded", id)
}
}
}
@@ -0,0 +1,112 @@
package confluence
import (
"context"
"fmt"
"sort"
)
type syncRootKind uint8
const (
syncWholeSpace syncRootKind = iota
syncPageSubtree
)
type syncRoot struct {
ResourceID string
SpaceID string
Space space
PageID string
Kind syncRootKind
}
type syncPlan struct{ Roots []syncRoot }
// buildSyncPlan validates selections before any destructive reconciliation and
// removes scopes which are already covered by a selected ancestor.
func (c *Connector) buildSyncPlan(ctx context.Context, client *client, resourceIDs []string) (*syncPlan, error) {
spaces, err := client.spaces(ctx)
if err != nil {
return nil, fmt.Errorf("list Confluence spaces: %w", err)
}
byID := make(map[string]space, len(spaces))
for _, s := range spaces {
byID[s.ID] = s
}
plan := &syncPlan{}
wholeSpaces := make(map[string]bool)
pageRoots := make(map[string]syncRoot)
ancestorPaths := make(map[string][]page)
for _, resourceID := range resourceIDs {
ref, err := parseResourceID(resourceID)
if err != nil {
return nil, err
}
s, ok := byID[ref.SpaceID]
if !ok {
return nil, fmt.Errorf(
"selected Confluence space %s is unavailable; refusing destructive reconciliation",
ref.SpaceID,
)
}
if ref.Kind == resourceSpace {
wholeSpaces[ref.SpaceID] = true
continue
}
// pageAncestors fetches the page itself on Server/DC and Cloud; that is
// also the authoritative check that a client did not forge its space ID.
ancestors, err := client.pageAncestors(ctx, s, ref.PageID)
if err != nil {
return nil, fmt.Errorf("validate selected Confluence page %s: %w", ref.PageID, err)
}
pageRoots[resourceID] = syncRoot{
ResourceID: resourceID,
SpaceID: ref.SpaceID,
Space: s,
PageID: ref.PageID,
Kind: syncPageSubtree,
}
ancestorPaths[resourceID] = ancestors
for _, ancestor := range ancestors {
if ancestor.ID == ref.PageID {
return nil, fmt.Errorf("invalid cyclic Confluence page ancestry for %s", ref.PageID)
}
}
}
spaceIDs := make([]string, 0, len(wholeSpaces))
for id := range wholeSpaces {
spaceIDs = append(spaceIDs, id)
}
sort.Strings(spaceIDs)
for _, id := range spaceIDs {
plan.Roots = append(plan.Roots, syncRoot{ResourceID: id, SpaceID: id, Space: byID[id], Kind: syncWholeSpace})
}
pageIDs := make([]string, 0, len(pageRoots))
for id := range pageRoots {
pageIDs = append(pageIDs, id)
}
sort.Strings(pageIDs)
for _, id := range pageIDs {
root := pageRoots[id]
if wholeSpaces[root.SpaceID] {
continue
}
ancestors := ancestorPaths[id]
covered := false
for _, ancestor := range ancestors {
if ancestor.Kind != "" && ancestor.Kind != "page" {
continue
}
if _, ok := pageRoots[makePageResourceID(root.SpaceID, ancestor.ID)]; ok {
covered = true
break
}
}
if !covered {
plan.Roots = append(plan.Roots, pageRoots[id])
}
}
return plan, nil
}
@@ -0,0 +1,377 @@
package confluence
import (
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/types"
)
const (
editionCloud = "cloud"
editionServer = "server"
)
type config struct {
edition, baseURL, username, secret string
usePAT bool
}
func (c config) cloud() bool { return c.edition == editionCloud }
func configValue(ds *types.DataSourceConfig, name string) string {
if ds == nil {
return ""
}
if v, ok := ds.Credentials[name].(string); ok {
if trimmed := strings.TrimSpace(v); trimmed != "" {
return trimmed
}
}
if v, ok := ds.Settings[name].(string); ok {
return strings.TrimSpace(v)
}
return ""
}
func parseConfig(ds *types.DataSourceConfig) (config, error) {
if ds == nil {
return config{}, datasource.ErrInvalidConfig
}
cfg := config{
edition: strings.ToLower(configValue(ds, "edition")),
baseURL: strings.TrimRight(configValue(ds, "base_url"), "/"),
username: configValue(ds, "username"),
}
if cfg.edition == "" {
cfg.edition = editionServer
}
if cfg.edition != editionServer && cfg.edition != editionCloud {
return config{}, fmt.Errorf("%w: unsupported edition %q", datasource.ErrInvalidCredentials, cfg.edition)
}
if !cfg.cloud() {
cfg.secret = configValue(ds, "token")
cfg.usePAT = cfg.secret != ""
}
if cfg.username == "" && !cfg.usePAT {
return config{}, fmt.Errorf("%w: base_url and username are required", datasource.ErrInvalidCredentials)
}
normalized, err := normalizeBaseURL(cfg.baseURL, cfg.cloud())
if err != nil {
return config{}, err
}
cfg.baseURL = normalized
if cfg.cloud() {
cfg.secret = configValue(ds, "api_token")
} else if !cfg.usePAT {
cfg.secret = configValue(ds, "password")
}
if cfg.secret == "" {
return config{}, fmt.Errorf("%w: credentials are required", datasource.ErrInvalidCredentials)
}
return cfg, nil
}
func normalizeBaseURL(raw string, cloud bool) (string, error) {
raw = strings.TrimSpace(strings.TrimRight(raw, "/"))
if raw == "" {
return "", fmt.Errorf("%w: base_url and username are required", datasource.ErrInvalidCredentials)
}
if !strings.Contains(raw, "://") {
raw = "https://" + raw
}
parsed, err := url.Parse(raw)
if err != nil || parsed.Host == "" || parsed.Scheme == "" {
return "", fmt.Errorf("%w: invalid base_url", datasource.ErrInvalidCredentials)
}
if cloud && isAtlassianCloudHost(parsed.Host) && strings.Trim(parsed.Path, "/") == "" {
parsed.Path = "/wiki"
}
return strings.TrimRight(parsed.String(), "/"), nil
}
func isAtlassianCloudHost(host string) bool {
host = strings.ToLower(host)
return host == "atlassian.net" || strings.HasSuffix(host, ".atlassian.net")
}
type space struct {
ID string `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
HomepageID string `json:"homepageId"`
Links struct {
WebUI string `json:"webui"`
} `json:"_links"`
}
type spaceList struct {
Results []space `json:"results"`
Links struct {
Next string `json:"next"`
} `json:"_links"`
}
type serverSpaceList struct {
Results []struct {
ID json.Number `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
Links struct {
WebUI string `json:"webui"`
} `json:"_links"`
} `json:"results"`
Links struct {
Next string `json:"next"`
} `json:"_links"`
}
type page struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
Kind string `json:"-"`
SpaceID string `json:"spaceId"`
Ancestors []page `json:"ancestors"`
Space struct {
Key string `json:"key"`
Name string `json:"name"`
} `json:"space"`
Version struct {
Number int `json:"number"`
When string `json:"when"`
CreatedAt string `json:"createdAt"`
By struct {
DisplayName string `json:"displayName"`
} `json:"by"`
} `json:"version"`
Links struct {
WebUI string `json:"webui"`
} `json:"_links"`
}
type pageList struct {
Results []page `json:"results"`
Links struct {
Next string `json:"next"`
} `json:"_links"`
}
// serverSpacePageList accepts both Server envelopes:
// - GET /rest/api/space/{key}/content/page → flat RestList {results,_links.next}
// - GET /rest/api/space/{key}/content → nested {page:{results,_links}}
type serverSpacePageList struct {
pageList
Page pageList `json:"page"`
}
func (l serverSpacePageList) pages() []page {
if len(l.Page.Results) > 0 {
return l.Page.Results
}
return l.Results
}
func (l serverSpacePageList) nextLink() string {
if l.Page.Links.Next != "" {
return l.Page.Links.Next
}
return l.Links.Next
}
type cloudPage struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
SpaceID string `json:"spaceId"`
CreatedAt string `json:"createdAt"`
Version struct {
Number int `json:"number"`
CreatedAt string `json:"createdAt"`
} `json:"version"`
Links struct {
WebUI string `json:"webui"`
} `json:"_links"`
}
// cloudHierarchyItem is shared by Cloud direct-children, descendants, and
// ancestors. Non-page items are intentionally retained by the API model so we
// can filter them explicitly at the navigation/import boundary.
type cloudHierarchyItem struct {
ID string `json:"id"`
Type string `json:"type"`
Title string `json:"title"`
SpaceID string `json:"spaceId"`
Status string `json:"status"`
Links struct {
WebUI string `json:"webui"`
} `json:"_links"`
}
type cloudHierarchyList struct {
Results []cloudHierarchyItem `json:"results"`
Links struct {
Next string `json:"next"`
} `json:"_links"`
}
type cloudPageList struct {
Results []cloudPage `json:"results"`
Links struct {
Next string `json:"next"`
} `json:"_links"`
}
type pageBody struct {
page
Body struct {
View struct {
Value string `json:"value"`
} `json:"view"`
} `json:"body"`
}
// cursor records a semantic version token per page. Cloud and Server/DC both
// expose version.number on supported APIs.
//
// FullSync / FullSyncBaseline exist only while a force-full run is in progress:
// the service overwrites LastSyncCursor on every checkpoint, so the original
// deletion baseline has to travel inside the checkpoint or retries would either
// re-fetch everything or treat unprocessed pages as deletions.
type cursor struct {
SpacePages map[string]map[string]string `json:"space_pages"`
FullSyncBaseline map[string]map[string]string `json:"full_sync_baseline,omitempty"`
FullSync bool `json:"full_sync,omitempty"`
}
func decodeCursor(old *types.SyncCursor) cursor {
c := cursor{SpacePages: map[string]map[string]string{}}
if old == nil {
return c
}
raw, _ := json.Marshal(old.ConnectorCursor)
_ = json.Unmarshal(raw, &c)
if c.SpacePages == nil {
c.SpacePages = map[string]map[string]string{}
}
return c
}
func clonePageMap(in map[string]map[string]string) map[string]map[string]string {
out := make(map[string]map[string]string, len(in))
for resource, pages := range in {
out[resource] = make(map[string]string, len(pages))
for id, version := range pages {
out[resource][id] = version
}
}
return out
}
func (c cursor) clone() cursor {
return cursor{
SpacePages: clonePageMap(c.SpacePages),
FullSyncBaseline: clonePageMap(c.FullSyncBaseline),
FullSync: c.FullSync,
}
}
func (c cursor) syncCursor() *types.SyncCursor {
raw, _ := json.Marshal(c)
fields := map[string]interface{}{}
_ = json.Unmarshal(raw, &fields)
return &types.SyncCursor{LastSyncTime: time.Now().UTC(), ConnectorCursor: fields}
}
func prepareSyncCursors(old *types.SyncCursor, forceFull bool) (baseline, next cursor) {
previous := decodeCursor(old)
if !forceFull {
next = previous.clone()
next.FullSync = false
next.FullSyncBaseline = nil
return previous, next
}
next = previous.clone()
if !next.FullSync {
next.FullSyncBaseline = clonePageMap(previous.SpacePages)
next.SpacePages = map[string]map[string]string{}
next.FullSync = true
}
baseline.SpacePages = next.FullSyncBaseline
if baseline.SpacePages == nil {
baseline.SpacePages = map[string]map[string]string{}
}
return baseline, next
}
// removePageOwnership drops a page from every root ownership in the cursor.
// It runs after each tombstone emit so the checkpoint mirrors the deletion;
// otherwise the page would linger as a ghost, be re-tombstoned on every later
// run, and eventually trip the mass-deletion guard. During a full sync the
// deletion baseline lives in FullSyncBaseline, not SpacePages (which is being
// rebuilt from scratch), so both maps must record the completed tombstone for
// a retry to resume with the remaining candidates only.
func removePageOwnership(c *cursor, pageID string) {
removeFromPageMap(c.SpacePages, pageID)
if c.FullSync {
removeFromPageMap(c.FullSyncBaseline, pageID)
}
}
func removeFromPageMap(m map[string]map[string]string, pageID string) {
for _, pages := range m {
delete(pages, pageID)
}
}
func pageVersion(p page) (string, bool) {
if p.Version.Number > 0 {
return fmt.Sprintf("v:%d", p.Version.Number), true
}
if p.Version.When != "" {
return "t:" + p.Version.When, true
}
if p.Version.CreatedAt != "" {
return "t:" + p.Version.CreatedAt, true
}
return "", false
}
func pageUpdatedAt(p page) time.Time {
for _, value := range []string{p.Version.When, p.Version.CreatedAt} {
if t, err := time.Parse(time.RFC3339, value); err == nil {
return t
}
}
return time.Time{}
}
func pageFileName(title, id string) string {
base := safeFilename(title)
id = strings.TrimSpace(id)
if id == "" {
return base + ".md"
}
return base + "-" + safeFilename(id) + ".md"
}
func safeFilename(name string) string {
name = strings.Map(func(r rune) rune {
if r < 32 || strings.ContainsRune(`<>:"/\\|?*`, r) {
return '_'
}
return r
}, strings.TrimSpace(name))
if name == "" {
return "untitled"
}
runes := []rune(name)
if len(runes) > 200 {
return string(runes[:200])
}
return name
}
@@ -0,0 +1,117 @@
package confluence
import (
"strings"
"testing"
"unicode/utf8"
"github.com/Tencent/WeKnora/internal/types"
)
func TestSafeFilenameKeepsUTF8ValidAtLimit(t *testing.T) {
name := strings.Repeat("知识库", 150)
got := safeFilename(name)
if !utf8.ValidString(got) || len([]rune(got)) != 200 {
t.Fatalf("safeFilename() truncated UTF-8 incorrectly: %q", got)
}
}
func TestDecodeCursorCloneDoesNotMutateBaseline(t *testing.T) {
old := &types.SyncCursor{ConnectorCursor: map[string]interface{}{
"space_pages": map[string]interface{}{"space": map[string]interface{}{"page": "v:2"}},
}}
baseline := decodeCursor(old)
next := baseline.clone()
next.SpacePages["space"]["page"] = "v:3"
if baseline.SpacePages["space"]["page"] != "v:2" {
t.Fatal("cursor clone mutated previous checkpoint")
}
}
func TestParseConfigUsesCloudToken(t *testing.T) {
cfg, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]interface{}{
"edition": "cloud",
"base_url": "https://team.atlassian.net/wiki",
"username": "user@example.com",
"api_token": "token",
}})
if err != nil || !cfg.cloud() || cfg.secret != "token" {
t.Fatalf("parseConfig() = %#v, %v", cfg, err)
}
}
func TestParseConfigReadsPublicFieldsFromSettings(t *testing.T) {
cfg, err := parseConfig(&types.DataSourceConfig{
Credentials: map[string]interface{}{"api_token": "token"},
Settings: map[string]interface{}{
"edition": "cloud", "base_url": "https://team.atlassian.net/wiki", "username": "user@example.com",
},
})
if err != nil || !cfg.cloud() || cfg.username != "user@example.com" || cfg.secret != "token" {
t.Fatalf("parseConfig() = %#v, %v", cfg, err)
}
}
func TestParseConfigNormalizesSchemeAndCloudWikiPath(t *testing.T) {
server, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]interface{}{
"base_url": "confluence.example.com:8090", "username": "reader", "password": "secret",
}})
if err != nil || server.baseURL != "https://confluence.example.com:8090" {
t.Fatalf("server parseConfig() = %#v, %v", server, err)
}
cloud, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]interface{}{
"edition": "cloud", "base_url": "https://team.atlassian.net",
"username": "user@example.com", "api_token": "token",
}})
if err != nil || cloud.baseURL != "https://team.atlassian.net/wiki" {
t.Fatalf("cloud parseConfig() = %#v, %v", cloud, err)
}
}
func TestPageFileNameIncludesID(t *testing.T) {
if got := pageFileName("Overview", "98308"); got != "Overview-98308.md" {
t.Fatalf("pageFileName() = %q", got)
}
}
func TestPageVersionUnknown(t *testing.T) {
withNumber := page{}
withNumber.Version.Number = 7
withWhen := page{}
withWhen.Version.When = "2026-01-02T03:04:05Z"
withCreatedAt := page{}
withCreatedAt.Version.CreatedAt = "2026-01-02T03:04:05Z"
for _, tc := range []struct {
name string
in page
want string
wantKnown bool
}{
{"number", withNumber, "v:7", true},
{"when", withWhen, "t:2026-01-02T03:04:05Z", true},
{"createdAt", withCreatedAt, "t:2026-01-02T03:04:05Z", true},
{"unknown", page{}, "", false},
} {
t.Run(tc.name, func(t *testing.T) {
got, known := pageVersion(tc.in)
if got != tc.want || known != tc.wantKnown {
t.Fatalf("pageVersion() = (%q, %v); want (%q, %v)", got, known, tc.want, tc.wantKnown)
}
})
}
}
func TestPrepareSyncCursorsPreservesFullSyncBaseline(t *testing.T) {
old := streamCursor(map[string]string{"p1": "v:1", "p2": "v:1"})
baseline, next := prepareSyncCursors(old, true)
if len(next.SpacePages) != 0 || baseline.SpacePages["1"]["p1"] != "v:1" || !next.FullSync {
t.Fatalf("first full sync baseline=%#v next=%#v", baseline, next)
}
next.SpacePages["1"] = map[string]string{"p1": "v:1"}
resumeBaseline, resumeNext := prepareSyncCursors(next.syncCursor(), true)
if resumeNext.SpacePages["1"]["p1"] != "v:1" || resumeBaseline.SpacePages["1"]["p2"] != "v:1" {
t.Fatalf("resume baseline=%#v next=%#v", resumeBaseline, resumeNext)
}
}
@@ -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"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/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 WeKnora stores it under. Only formats WeKnora 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 WeKnora'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"
"github.com/Tencent/WeKnora/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"
"github.com/Tencent/WeKnora/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"
"github.com/Tencent/WeKnora/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"
"github.com/Tencent/WeKnora/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 WeKnora 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"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/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"
"github.com/Tencent/WeKnora/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
@@ -0,0 +1,734 @@
package core
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
)
// Feishu docx block_type integer enum (subset this connector handles).
// https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/docx-structure
const (
BlockTypePage = 1
BlockTypeText = 2
BlockTypeHeading1 = 3
blockTypeHeading9 = 11
BlockTypeBullet = 12
BlockTypeOrdered = 13
BlockTypeCode = 14
BlockTypeQuote = 15
BlockTypeTodo = 17
BlockTypeBitable = 18
BlockTypeCallout = 19
BlockTypeChatCard = 20
BlockTypeDiagram = 21
BlockTypeDivider = 22
BlockTypeFile = 23
BlockTypeGrid = 24
BlockTypeGridColumn = 25
BlockTypeIframe = 26
BlockTypeImage = 27
BlockTypeISV = 28
BlockTypeMindnote = 29
BlockTypeSheet = 30
BlockTypeTable = 31
BlockTypeTableCell = 32
BlockTypeView = 33
BlockTypeQuoteContainer = 34
BlockTypeTask = 35
BlockTypeOKR = 36
BlockTypeOKRObjective = 37
BlockTypeOKRKeyResult = 38
BlockTypeOKRProgress = 39
BlockTypeAddOns = 40
BlockTypeJiraIssue = 41
BlockTypeWikiCatalog = 42
BlockTypeBoard = 43
BlockTypeAgenda = 44
BlockTypeAgendaItem = 45
BlockTypeAgendaItemTitle = 46
BlockTypeAgendaItemContent = 47
BlockTypeLinkPreview = 48
BlockTypeSourceSynced = 49
BlockTypeReferenceSynced = 50
BlockTypeSubPageList = 51
BlockTypeAITemplate = 52
)
// maxDocumentBlocks caps how many blocks a single document contributes, guarding
// against pathological/adversarial documents. Far above any real Feishu doc.
const maxDocumentBlocks = 50000
// TextElementStyle is the inline style of a text element
// (official docx-v1 TextElementStyle; color enums carry no GFM equivalent and
// are not parsed).
type TextElementStyle struct {
Bold bool `json:"bold"`
Italic bool `json:"italic"`
Strikethrough bool `json:"strikethrough"`
InlineCode bool `json:"inline_code"`
Link *TextElementLink `json:"link"`
}
// TextElementLink is the hyperlink payload of TextElementStyle.
type TextElementLink struct {
URL string `json:"url"`
}
// TextRun is the text_run payload of a TextElement.
type TextRun struct {
Content string `json:"content"`
TextElementStyle *TextElementStyle `json:"text_element_style"`
}
// MentionDoc is the mention_doc payload (@-mention of a cloud document). The
// API carries no document title — only the link.
type MentionDoc struct {
URL string `json:"url"`
TextElementStyle *TextElementStyle `json:"text_element_style"`
}
// MentionUser is the mention_user payload. It carries only the user OpenID —
// never a display name — so the renderer can only Emit a generic @ marker.
type MentionUser struct {
UserID string `json:"user_id"`
TextElementStyle *TextElementStyle `json:"text_element_style"`
}
// Equation is the equation payload; Content is KaTeX syntax.
type Equation struct {
Content string `json:"content"`
TextElementStyle *TextElementStyle `json:"text_element_style"`
}
type TextElement struct {
TextRun *TextRun `json:"text_run"`
MentionUser *MentionUser `json:"mention_user"`
MentionDoc *MentionDoc `json:"mention_doc"`
Equation *Equation `json:"equation"`
// file / reminder / inline_block elements carry no renderable text (file
// is token-only and its token must never leak; reminder has no text body;
// inline_block is an ID reference), so they are not parsed.
}
// BlockTextStyle is the block-level style of text-bearing blocks. Code blocks
// carry Language (CodeLanguage enum 1-75); ordered blocks carry Sequence (the
// real list number: a specific value or "auto"; absent in historical docs and
// docs created via OpenAPI).
type BlockTextStyle struct {
Language int `json:"language"`
Sequence string `json:"sequence"`
Done bool `json:"done"` // todo blocks: item completed
// Align: 1 left / 2 center / 3 right. Absent from the API unless the
// author set an explicit non-default alignment.
Align int `json:"align"`
}
// BlockText is the shared shape of text-bearing blocks (text, headingN, bullet…).
type BlockText struct {
Elements []TextElement `json:"elements"`
Style *BlockTextStyle `json:"style"`
}
// BlockTokenRef is the shared shape of sheet/bitable/image block payloads
// (the JSON tag differs per field; only the token matters).
type BlockTokenRef struct {
Token string `json:"token"`
}
// BlockFileRef is the file block payload: the attachment token plus its name.
type BlockFileRef struct {
Token string `json:"token"`
Name string `json:"name"`
}
// Payload structs for the remaining docx block types (official docx-v1 block
// data structures). Only the fields a renderer needs are parsed; the rest are
// dropped by encoding/json.
// BlockChatCard is block_type 20: a group-chat card embedded in the document.
type BlockChatCard struct {
ChatID string `json:"chat_id"`
Align int `json:"align"`
}
// BlockDiagram is block_type 21: a flowchart / UML diagram reference (no
// public render API — rendered as a placeholder note).
type BlockDiagram struct {
DiagramType int `json:"diagram_type"`
}
// BlockGrid is block_type 24: a multi-column layout container; its children
// are BlockGridColumn (25) wrappers rendered in column order.
type BlockGrid struct {
ColumnSize int `json:"column_size"`
}
// BlockGridColumn is block_type 25: one column inside a BlockGrid.
type BlockGridColumn struct {
WidthRatio int `json:"width_ratio"`
}
// BlockIframeComponent is the embedded-webpage payload of BlockIframe.
type BlockIframeComponent struct {
Type int `json:"type"`
URL string `json:"url"`
}
// BlockIframe is block_type 26: an embedded webpage, rendered as a link.
type BlockIframe struct {
Component *BlockIframeComponent `json:"component"`
}
// BlockView is block_type 33: a view container (e.g. tab views); its children
// render in place, so the wrapper itself is transparent.
type BlockView struct {
ViewType int `json:"view_type"`
}
// BlockAddOns is block_type 40: a document widget (timeline etc.) carrying its
// full data inline in Record; recognized component types render as Markdown.
type BlockAddOns struct {
ComponentID string `json:"component_id"`
ComponentTypeID string `json:"component_type_id"`
Record string `json:"record"`
}
// BlockJiraIssue is block_type 41: a Jira issue card (placeholder only — no
// public content API).
type BlockJiraIssue struct {
ID string `json:"id"`
Key string `json:"key"`
}
// BlockWikiCatalog is block_type 42: a Wiki child-page list (placeholder).
type BlockWikiCatalog struct {
WikiToken string `json:"wiki_token"`
}
// BlockBoard is block_type 43: a whiteboard (mind notes ride the same path);
// Token is exported via download_as_image and inlined as an image.
type BlockBoard struct {
Token string `json:"token"`
Align int `json:"align"`
Width int `json:"width"`
Height int `json:"height"`
}
// BlockLinkPreview is block_type 48: a link preview card (placeholder).
type BlockLinkPreview struct {
URL string `json:"url"`
URLType string `json:"url_type"`
}
// BlockTableMergeInfo is one entry of TableProperty.merge_info, parallel to the
// table's cells array: entry i describes the merge anchored at cell i
// (row = i / column_size, col = i % column_size). GFM has no cell span, so the
// renderer fills covered cells with the anchor value.
type BlockTableMergeInfo struct {
RowSpan int `json:"row_span"`
ColSpan int `json:"col_span"`
}
// BlockTableProperty carries the table grid shape.
type BlockTableProperty struct {
ColumnSize int `json:"column_size"`
MergeInfo []BlockTableMergeInfo `json:"merge_info"`
}
// BlockTable is the table block payload: cell block IDs plus grid property.
type BlockTable struct {
Cells []string `json:"cells"`
Property *BlockTableProperty `json:"property"`
}
// DocxBlock is one node in the flat block array returned by the blocks API.
type DocxBlock struct {
BlockID string `json:"block_id"`
ParentID string `json:"parent_id"`
BlockType int `json:"block_type"`
Children []string `json:"children"`
Text *BlockText `json:"text"`
Heading1 *BlockText `json:"heading1"`
Heading2 *BlockText `json:"heading2"`
Heading3 *BlockText `json:"heading3"`
Heading4 *BlockText `json:"heading4"`
Heading5 *BlockText `json:"heading5"`
Heading6 *BlockText `json:"heading6"`
Heading7 *BlockText `json:"heading7"`
Heading8 *BlockText `json:"heading8"`
Heading9 *BlockText `json:"heading9"`
Bullet *BlockText `json:"bullet"`
Ordered *BlockText `json:"ordered"`
Code *BlockText `json:"code"`
Quote *BlockText `json:"quote"`
Todo *BlockText `json:"todo"`
Callout *BlockText `json:"callout"`
ChatCard *BlockChatCard `json:"chat_card"`
Diagram *BlockDiagram `json:"diagram"`
Grid *BlockGrid `json:"grid"`
GridColumn *BlockGridColumn `json:"grid_column"`
Iframe *BlockIframe `json:"iframe"`
Mindnote *BlockTokenRef `json:"mindnote"`
View *BlockView `json:"view"`
AddOns *BlockAddOns `json:"add_ons"`
JiraIssue *BlockJiraIssue `json:"jira_issue"`
WikiCatalog *BlockWikiCatalog `json:"wiki_catalog"`
Board *BlockBoard `json:"board"`
LinkPreview *BlockLinkPreview `json:"link_preview"`
Sheet *BlockTokenRef `json:"sheet"`
Bitable *BlockTokenRef `json:"bitable"`
File *BlockFileRef `json:"file"`
Image *BlockTokenRef `json:"image"`
Table *BlockTable `json:"table"`
}
// DocxBlocksData is the data payload of DocxBlocksResponse.
type DocxBlocksData struct {
Items []DocxBlock `json:"items"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
}
// DocxBlocksResponse is the response for GET .../documents/:id/blocks.
type DocxBlocksResponse struct {
ApiResponse
Data DocxBlocksData `json:"data"`
}
// listDocumentBlocks returns every block of a docx document as a flat,
// pre-order array. Paginates at 500 blocks/page. documentID is the obj_token.
func (c *Client) listDocumentBlocks(ctx context.Context, documentID string) ([]DocxBlock, error) {
var all []DocxBlock
pageToken := ""
for {
path := fmt.Sprintf("/open-apis/docx/v1/documents/%s/blocks?page_size=500&document_revision_id=-1",
url.PathEscape(documentID))
if pageToken != "" {
path += "&page_token=" + url.QueryEscape(pageToken)
}
var resp DocxBlocksResponse
if err := c.DoRequest(ctx, http.MethodGet, path, nil, &resp); err != nil {
return nil, fmt.Errorf("list document blocks: %w", err)
}
if resp.Code != 0 {
return nil, fmt.Errorf("list document blocks error: code=%d msg=%s", resp.Code, resp.Msg)
}
all = append(all, resp.Data.Items...)
if len(resp.Data.Items) == 0 {
// Defensive: a malformed page (empty items but has_more=true and a
// non-empty page_token) would otherwise loop until the task deadline,
// burning API quota. There is nothing more to collect, so stop.
break
}
if len(all) >= maxDocumentBlocks {
logger.Warnf(ctx, "[Feishu] document %s exceeded %d blocks; truncating", documentID, maxDocumentBlocks)
break
}
if !resp.Data.HasMore || resp.Data.PageToken == "" {
break
}
pageToken = resp.Data.PageToken
}
return all, nil
}
// maxTableRows caps how many rows of an embedded sheet/bitable are rendered,
// protecting chunking from pathologically large tables. Beyond this the table
// is truncated and the caller annotates the omission.
const maxTableRows = 500
// sheetValueRange is the valueRange payload of sheetValuesData.
type sheetValueRange struct {
Values [][]any `json:"values"`
}
// sheetValuesData is the data payload of sheetValuesResponse.
type sheetValuesData struct {
ValueRange sheetValueRange `json:"valueRange"`
}
// sheetValuesResponse is the response for sheets-v2 values read.
type sheetValuesResponse struct {
ApiResponse
Data sheetValuesData `json:"data"`
}
// flexInt decodes a JSON value that may be a number or a numeric string —
// Feishu sheet APIs mix both spellings for row/column indices.
type flexInt int
func (f *flexInt) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `"`)
v, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("invalid integer value %s", s)
}
*f = flexInt(v)
return nil
}
// sheetMergeRange is one merged-cell region of a sheet: 0-based CLOSED
// row/column indices [start..end] as reported by the sheets-v3 metadata API.
type sheetMergeRange struct {
StartRow flexInt `json:"start_row_index"`
EndRow flexInt `json:"end_row_index"`
StartCol flexInt `json:"start_column_index"`
EndCol flexInt `json:"end_column_index"`
}
// sheetQueryResponse is the response for the sheets-v3
// spreadsheets/:spreadsheet_token/sheets/query metadata read.
type sheetQueryResponse struct {
ApiResponse
Data struct {
Sheets []struct {
SheetID string `json:"sheet_id"`
Merges []sheetMergeRange `json:"merges"`
} `json:"sheets"`
} `json:"data"`
}
// sheetMerges returns the merged-cell regions of one sheet of a spreadsheet,
// addressed by the sheet embed token ("spreadsheetToken_sheetId"). The sheet
// entry is looked up by its sheet_id; a spreadsheet without merges carries no
// merges field, which degrades to nil. Errors surface to the caller, which
// silently skips merge filling — the information is cosmetic, never fatal.
// Permission scope: sheets:spreadsheet:readonly (same token as the values read).
func (c *Client) sheetMerges(ctx context.Context, embedToken string) ([]sheetMergeRange, error) {
idx := strings.LastIndex(embedToken, "_")
if idx < 0 {
return nil, fmt.Errorf("invalid sheet embed token: %q", embedToken)
}
spreadsheetToken, sheetID := embedToken[:idx], embedToken[idx+1:]
path := "/open-apis/sheets/v3/spreadsheets/" + url.PathEscape(spreadsheetToken) + "/sheets/query"
var resp sheetQueryResponse
if err := c.DoRequest(ctx, http.MethodGet, path, nil, &resp); err != nil {
return nil, fmt.Errorf("query sheet metadata: %w", err)
}
if resp.Code != 0 {
return nil, fmt.Errorf("query sheet metadata error: code=%d msg=%s", resp.Code, resp.Msg)
}
for _, s := range resp.Data.Sheets {
if s.SheetID == sheetID {
return s.Merges, nil
}
}
return nil, nil
}
// readSheetRange reads the cell values of an embedded spreadsheet block.
// embedToken is the block's sheet.token, formatted "spreadsheetToken_sheetId".
// Cells are stringified (display value) for RAG text retrieval. Rows are capped
// at maxTableRows; truncated is true when the source had more rows than that.
func (c *Client) readSheetRange(ctx context.Context, embedToken string) ([][]string, bool, error) {
idx := strings.LastIndex(embedToken, "_")
if idx < 0 {
return nil, false, fmt.Errorf("invalid sheet embed token: %q", embedToken)
}
spreadsheetToken, sheetID := embedToken[:idx], embedToken[idx+1:]
path := fmt.Sprintf("/open-apis/sheets/v2/spreadsheets/%s/values/%s?valueRenderOption=ToString",
url.PathEscape(spreadsheetToken), url.PathEscape(sheetID))
var resp sheetValuesResponse
if err := c.DoRequest(ctx, http.MethodGet, path, nil, &resp); err != nil {
return nil, false, fmt.Errorf("read sheet range: %w", err)
}
if resp.Code != 0 {
return nil, false, fmt.Errorf("read sheet range error: code=%d msg=%s", resp.Code, resp.Msg)
}
raw, truncated := capRows(resp.Data.ValueRange.Values)
return stringifyMatrix(raw), truncated, nil
}
// capRows limits rows to maxTableRows, reporting whether truncation happened. It
// is generic so the sheet ([][]any) and bitable ([][]string) read paths share one
// truncation rule instead of each inlining their own.
func capRows[T any](rows []T) ([]T, bool) {
if len(rows) > maxTableRows {
return rows[:maxTableRows], true
}
return rows, false
}
// stringifyMatrix renders arbitrary cell values to strings; nil → "".
func stringifyMatrix(in [][]any) [][]string {
out := make([][]string, len(in))
for i, row := range in {
cells := make([]string, len(row))
for j, v := range row {
cells[j] = cellToString(v)
}
out[i] = cells
}
return out
}
// cellToString renders a single JSON cell value to a string; nil → "".
func cellToString(v any) string {
switch t := v.(type) {
case nil:
return ""
case string:
return t
case float64:
return strconv.FormatFloat(t, 'f', -1, 64)
case bool:
return strconv.FormatBool(t)
default:
return fmt.Sprintf("%v", t)
}
}
// bitableFieldTypeDateTime is the Feishu bitable field type for a date/datetime
// column. Its cell value is a bare Unix-millisecond number, so without type-aware
// formatting it would render as a 13-digit integer instead of a readable date.
// https://open.feishu.cn/document/server-docs/docs/bitable-v1/app-table-field/guide
const bitableFieldTypeDateTime = 5
// bitableColumn describes one bitable field: its name, integer type, and (for a
// date column) its date_formatter, which distinguishes a date-only column
// ("yyyy/MM/dd") from a datetime one ("yyyy-MM-dd HH:mm").
type bitableColumn struct {
name string
fieldType int
dateFormatter string
}
// bitableFieldCell renders one bitable cell. Date columns carry a Unix-millisecond
// UTC instant; the calendar date a user sees is that instant in the table's
// timezone, so it is formatted in loc (rendering in UTC would shift the date, e.g.
// a GMT+8 "2024-04-01" would show as "2024-03-31 16:00:00"). A date-only formatter
// yields "2006-01-02"; a datetime formatter adds the "15:04" time. Every other
// type falls through to bitableCellToString.
func bitableFieldCell(v any, col bitableColumn, loc *time.Location) string {
if col.fieldType == bitableFieldTypeDateTime {
// Empty date cells arrive as nil (→ fall through to blank); ms==0 (epoch) is
// not a real Feishu date value either — render blank, not "1970-01-01" or "0".
if ms, ok := v.(float64); ok {
if ms == 0 {
return ""
}
t := time.UnixMilli(int64(ms)).In(loc)
if dateFormatterHasTime(col.dateFormatter) {
return t.Format("2006-01-02 15:04")
}
return t.Format("2006-01-02")
}
}
return bitableCellToString(v)
}
// dateFormatterHasTime reports whether a Feishu date_formatter includes a time
// component. Feishu formatters are Java-style: 'H'/'h' hour, lowercase 'm' minute,
// uppercase 'M' month — so a time part is present iff the string carries an hour or
// a lowercase-'m' minute token (e.g. "yyyy-MM-dd HH:mm"). An empty formatter
// (Feishu's default "yyyy/MM/dd") is date-only.
func dateFormatterHasTime(f string) bool {
return strings.ContainsAny(f, "Hh") || strings.Contains(f, "m")
}
// bitableCellToString renders a bitable field value — which may be text segments,
// a person/link object, or an attachment/multi-select array — to a readable
// string for RAG. Scalars delegate to cellToString.
func bitableCellToString(v any) string {
switch t := v.(type) {
case []any:
parts := make([]string, 0, len(t))
for _, e := range t {
if s := bitableCellToString(e); s != "" {
parts = append(parts, s)
}
}
return strings.Join(parts, ", ")
case map[string]any:
for _, k := range []string{"text", "name", "en_name", "link"} {
if s, ok := t[k].(string); ok && s != "" {
return s
}
}
return ""
default:
return cellToString(v)
}
}
// bitableFieldProperty carries a field's type-specific settings.
type bitableFieldProperty struct {
// DateFormatter distinguishes a date-only column from a datetime one.
DateFormatter string `json:"date_formatter"`
}
// bitableField is one entry of bitableFieldsData.Items.
type bitableField struct {
FieldName string `json:"field_name"`
Type int `json:"type"`
Property *bitableFieldProperty `json:"property"`
}
// bitableFieldsData is the data payload of bitableFieldsResponse.
type bitableFieldsData struct {
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
Items []bitableField `json:"items"`
}
type bitableFieldsResponse struct {
ApiResponse
Data bitableFieldsData `json:"data"`
}
// maxBitableFieldPageSize is the documented per-page cap for the bitable
// list-fields endpoint (100). Unlike list-records (max 500), passing a larger
// page_size here is rejected, so fields must be fetched 100 at a time and paged.
const maxBitableFieldPageSize = 100
// maxBitableFields caps how many fields one embedded table contributes. The
// list-fields endpoint pages at 100, so this allows 50 pages; a table that keeps
// handing out fresh page tokens stops here instead of growing the header without
// bound.
const maxBitableFields = 5000
// bitableRecord is one entry of bitableRecordsData.Items.
type bitableRecord struct {
Fields map[string]any `json:"fields"`
}
// bitableRecordsData is the data payload of bitableRecordsResponse.
type bitableRecordsData struct {
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
Items []bitableRecord `json:"items"`
}
type bitableRecordsResponse struct {
ApiResponse
Data bitableRecordsData `json:"data"`
}
// readBitableRecords reads an embedded bitable block as a table: a header row of
// field names followed by one row per record. embedToken is the block's
// bitable.token, formatted "appToken_tableId". Record rows are capped at
// maxTableRows; truncated is true when the source had more records than that.
func (c *Client) readBitableRecords(ctx context.Context, embedToken string) ([][]string, bool, error) {
idx := strings.LastIndex(embedToken, "_")
if idx < 0 {
return nil, false, fmt.Errorf("invalid bitable embed token: %q", embedToken)
}
appToken, tableID := embedToken[:idx], embedToken[idx+1:]
var cols []bitableColumn
baseFPath := fmt.Sprintf("/open-apis/bitable/v1/apps/%s/tables/%s/fields?page_size=%d",
url.PathEscape(appToken), url.PathEscape(tableID), maxBitableFieldPageSize)
fieldPageToken := ""
seenFieldPageTokens := make(map[string]struct{})
for {
fpath := baseFPath
if fieldPageToken != "" {
fpath += "&page_token=" + url.QueryEscape(fieldPageToken)
}
var fieldsResp bitableFieldsResponse
if err := c.DoRequest(ctx, http.MethodGet, fpath, nil, &fieldsResp); err != nil {
return nil, false, fmt.Errorf("read bitable fields: %w", err)
}
if fieldsResp.Code != 0 {
return nil, false, fmt.Errorf("read bitable fields error: code=%d msg=%s", fieldsResp.Code, fieldsResp.Msg)
}
for _, f := range fieldsResp.Data.Items {
formatter := ""
if f.Property != nil {
formatter = f.Property.DateFormatter
}
cols = append(cols, bitableColumn{name: f.FieldName, fieldType: f.Type, dateFormatter: formatter})
}
if len(fieldsResp.Data.Items) == 0 {
// Defensive: an empty page with has_more=true never advances, so the
// size cap below would never trip — stop instead of looping until the
// task deadline. Nothing more to read.
break
}
if !fieldsResp.Data.HasMore || fieldsResp.Data.PageToken == "" {
break
}
if len(cols) >= maxBitableFields {
logger.Warnf(ctx, "[Feishu] bitable %s exceeded %d fields; truncating", embedToken, maxBitableFields)
break
}
// A repeated non-empty token means the vendor is re-serving a page we
// already read; without this the loop would re-append the same fields
// until the task deadline (same guard as the wiki/drive pagination).
if _, exists := seenFieldPageTokens[fieldsResp.Data.PageToken]; exists {
return nil, false, fmt.Errorf("feishu bitable field pagination repeated page token %q",
fieldsResp.Data.PageToken)
}
seenFieldPageTokens[fieldsResp.Data.PageToken] = struct{}{}
fieldPageToken = fieldsResp.Data.PageToken
}
header := make([]string, len(cols))
for i, col := range cols {
header[i] = col.name
}
loc := c.tz()
var dataRows [][]string
truncated := false
// Use the Search-records endpoint (POST .../records/search). The legacy
// GET .../records is officially deprecated ("已不推荐使用,可使用[查询记录]替代").
// An empty body queries the table's default view, paginated via page_token
// (we page to the end below), so a default view with a filter would omit the
// filtered-out records — acceptable for RAG, but not literally "all records".
baseRPath := fmt.Sprintf("/open-apis/bitable/v1/apps/%s/tables/%s/records/search?page_size=500",
url.PathEscape(appToken), url.PathEscape(tableID))
pageToken := ""
for {
rpath := baseRPath
if pageToken != "" {
rpath += "&page_token=" + url.QueryEscape(pageToken)
}
var rec bitableRecordsResponse
if err := c.DoRequest(ctx, http.MethodPost, rpath, map[string]any{}, &rec); err != nil {
return nil, false, fmt.Errorf("search bitable records: %w", err)
}
if rec.Code != 0 {
return nil, false, fmt.Errorf("read bitable records error: code=%d msg=%s", rec.Code, rec.Msg)
}
for _, item := range rec.Data.Items {
row := make([]string, len(cols))
for i, col := range cols {
row[i] = bitableFieldCell(item.Fields[col.name], col, loc)
}
dataRows = append(dataRows, row)
}
if len(rec.Data.Items) == 0 {
// Defensive: an empty page with has_more=true never advances dataRows,
// so the maxTableRows cap below would never trip — stop instead of
// looping until the task deadline.
break
}
if len(dataRows) >= maxTableRows {
if len(dataRows) > maxTableRows || rec.Data.HasMore {
truncated = true
}
break
}
if !rec.Data.HasMore || rec.Data.PageToken == "" {
break
}
pageToken = rec.Data.PageToken
}
dataRows, capped := capRows(dataRows)
truncated = truncated || capped
rows := append([][]string{header}, dataRows...)
return rows, truncated, nil
}
@@ -0,0 +1,696 @@
package core
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/logger"
)
func TestListDocumentBlocks_Paginates(t *testing.T) {
var gotTokens []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
return
}
gotTokens = append(gotTokens, r.URL.Query().Get("page_token"))
if r.URL.Query().Get("page_size") != "500" {
t.Errorf("page_size = %q, want 500", r.URL.Query().Get("page_size"))
}
if r.URL.Query().Get("page_token") == "" {
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"items": []map[string]any{{"block_id": "b1", "block_type": 2}, {"block_id": "b2", "block_type": 2}},
"has_more": true,
"page_token": "p2",
}})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"items": []map[string]any{{"block_id": "b3", "block_type": 2}},
"has_more": false,
}})
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
blocks, err := c.listDocumentBlocks(context.Background(), "doc123")
if err != nil {
t.Fatalf("listDocumentBlocks: %v", err)
}
if len(blocks) != 3 {
t.Fatalf("got %d blocks, want 3", len(blocks))
}
if blocks[0].BlockID != "b1" || blocks[2].BlockID != "b3" {
t.Errorf("order not preserved: %+v", blocks)
}
if len(gotTokens) != 2 || gotTokens[1] != "p2" {
t.Errorf("page tokens = %v, want ['', 'p2']", gotTokens)
}
}
func TestReadSheetRange_SplitsTokenAndReadsValues(t *testing.T) {
var gotPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
return
}
gotPath = r.URL.Path
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"valueRange": map[string]any{"values": [][]any{{"名称", "数量"}, {"苹果", 3}, {"梨", nil}}},
}})
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
rows, truncated, err := c.readSheetRange(context.Background(), "sht_abc_0")
if err != nil {
t.Fatalf("readSheetRange: %v", err)
}
if gotPath != "/open-apis/sheets/v2/spreadsheets/sht_abc/values/0" {
t.Errorf("path = %q", gotPath)
}
if truncated {
t.Errorf("did not expect truncation for 3 rows")
}
if len(rows) != 3 || rows[0][0] != "名称" || rows[1][1] != "3" || rows[2][1] != "" {
t.Errorf("rows = %+v", rows)
}
}
// TestSheetMerges_SplitsTokenAndReturnsRegions anchors the v3 metadata read:
// the embed token splits on the last "_", the sheet entry is matched by
// sheet_id, and merge indices decode from both JSON numbers and strings.
func TestSheetMerges_SplitsTokenAndReturnsRegions(t *testing.T) {
var gotPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
return
}
gotPath = r.URL.Path
// One sheet with numeric merge indices, one with string form, and one
// with no merges field at all (a spreadsheet without merged cells).
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"sheets": []any{
map[string]any{"sheet_id": "0", "merges": []any{
map[string]any{
"start_row_index": 0, "end_row_index": 1,
"start_column_index": 1, "end_column_index": 2,
},
}},
map[string]any{"sheet_id": "9", "merges": []any{
map[string]any{
"start_row_index": "2", "end_row_index": "3",
"start_column_index": "0", "end_column_index": "0",
},
}},
map[string]any{"sheet_id": "7"},
},
}})
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
merges, err := c.sheetMerges(context.Background(), "sht_abc_0")
if err != nil {
t.Fatalf("sheetMerges: %v", err)
}
if gotPath != "/open-apis/sheets/v3/spreadsheets/sht_abc/sheets/query" {
t.Errorf("path = %q", gotPath)
}
if len(merges) != 1 ||
merges[0].StartRow != 0 || merges[0].EndRow != 1 ||
merges[0].StartCol != 1 || merges[0].EndCol != 2 {
t.Errorf("numeric merges = %+v", merges)
}
mergesStr, err := c.sheetMerges(context.Background(), "sht_abc_9")
if err != nil {
t.Fatalf("sheetMerges (string form): %v", err)
}
if len(mergesStr) != 1 || mergesStr[0].StartRow != 2 || mergesStr[0].EndCol != 0 {
t.Errorf("string merges = %+v", mergesStr)
}
mergesNone, err := c.sheetMerges(context.Background(), "sht_abc_7")
if err != nil {
t.Fatalf("sheetMerges (no merges field): %v", err)
}
if len(mergesNone) != 0 {
t.Errorf("expected no merges, got %+v", mergesNone)
}
}
func TestReadSheetRange_TruncatesLargeTable(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
return
}
values := make([][]any, 600)
for i := range values {
values[i] = []any{i}
}
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"valueRange": map[string]any{"values": values},
}})
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
rows, truncated, err := c.readSheetRange(context.Background(), "sht_x_0")
if err != nil {
t.Fatalf("err: %v", err)
}
if !truncated {
t.Errorf("expected truncated=true for 600 rows")
}
if len(rows) != 500 {
t.Errorf("rows capped to %d, want 500", len(rows))
}
}
func TestBitableCellToString(t *testing.T) {
// text-segment array: [{type:text, text:"你好"}] → "你好"
textSeg := []any{map[string]any{"type": "text", "text": "你好"}}
if got := bitableCellToString(textSeg); got != "你好" {
t.Errorf("text segment: got %q, want %q", got, "你好")
}
// person array: [{id:u1, name:"张三"}] → "张三"
person := []any{map[string]any{"id": "u1", "name": "张三"}}
if got := bitableCellToString(person); got != "张三" {
t.Errorf("person: got %q, want %q", got, "张三")
}
// plain number (float64) → "3"
if got := bitableCellToString(float64(3)); got != "3" {
t.Errorf("float64: got %q, want %q", got, "3")
}
// plain string → passthrough
if got := bitableCellToString("abc"); got != "abc" {
t.Errorf("string: got %q, want %q", got, "abc")
}
}
func TestBitableFieldCell_DateColumn(t *testing.T) {
gmt8 := resolveLocation("") // default GMT+8
dateOnly := bitableColumn{fieldType: bitableFieldTypeDateTime, dateFormatter: "yyyy/MM/dd"}
dateTime := bitableColumn{fieldType: bitableFieldTypeDateTime, dateFormatter: "yyyy-MM-dd HH:mm"}
number := bitableColumn{fieldType: 2}
// Feishu stores a date as a UTC instant at the table-timezone midnight. The
// official sample 1711900800000 is 2024-04-01 00:00:00 GMT+8 (== 2024-03-31
// 16:00:00 UTC); a date-only column must render the GMT+8 calendar date, NOT
// the UTC-shifted "2024-03-31 16:00:00" the old code produced.
if got := bitableFieldCell(float64(1711900800000), dateOnly, gmt8); got != "2024-04-01" {
t.Errorf("date-only cell: got %q, want %q", got, "2024-04-01")
}
// A datetime column keeps the time, rendered in the same timezone.
// 1719802800000 == 2024-07-01 03:00 UTC == 2024-07-01 11:00 GMT+8.
if got := bitableFieldCell(float64(1719802800000), dateTime, gmt8); got != "2024-07-01 11:00" {
t.Errorf("datetime cell: got %q, want %q", got, "2024-07-01 11:00")
}
// A non-date numeric field is left as its plain value, not a date.
if got := bitableFieldCell(float64(42), number, gmt8); got != "42" {
t.Errorf("number cell: got %q, want %q", got, "42")
}
// An empty date cell (nil, or epoch 0) renders blank, not "1970-01-01".
if got := bitableFieldCell(nil, dateOnly, gmt8); got != "" {
t.Errorf("empty date cell: got %q, want empty", got)
}
if got := bitableFieldCell(float64(0), dateOnly, gmt8); got != "" {
t.Errorf("epoch-0 date cell: got %q, want empty", got)
}
}
func TestDateFormatterHasTime(t *testing.T) {
withTime := []string{"yyyy-MM-dd HH:mm", "HH:mm", "yyyy/MM/dd hh:mm", "MM-dd HH:mm"}
dateOnly := []string{"", "yyyy/MM/dd", "MM-dd", "MM/dd/yyyy", "dd/MM/yyyy"}
for _, f := range withTime {
if !dateFormatterHasTime(f) {
t.Errorf("dateFormatterHasTime(%q) = false, want true", f)
}
}
for _, f := range dateOnly {
if dateFormatterHasTime(f) {
t.Errorf("dateFormatterHasTime(%q) = true, want false", f)
}
}
}
func TestResolveLocation(t *testing.T) {
// Empty and unknown names both fall back to a fixed GMT+8, with no dependency
// on system tzdata (minimal container images may omit it).
for _, name := range []string{"", "Not/AZone"} {
ref := time.Date(2024, 4, 1, 0, 0, 0, 0, resolveLocation(name))
if _, off := ref.Zone(); off != defaultTimezoneOffsetSeconds {
t.Errorf("resolveLocation(%q) offset = %d, want %d", name, off, defaultTimezoneOffsetSeconds)
}
}
}
// TestReadBitableRecords_DateColumnUsesFormatterAndTimezone proves the date fix
// end-to-end: property.date_formatter is parsed from the fields response, a type-5
// column is detected, and the ms instant is rendered in the client timezone
// (GMT+8) — date-only vs datetime distinguished by the formatter.
func TestReadBitableRecords_DateColumnUsesFormatterAndTimezone(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"items": []map[string]any{
{"field_name": "截止日期", "type": 5, "property": map[string]any{"date_formatter": "yyyy/MM/dd"}},
{"field_name": "提醒时间", "type": 5, "property": map[string]any{"date_formatter": "yyyy-MM-dd HH:mm"}},
},
}})
case strings.HasSuffix(r.URL.Path, "/records/search"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": false, "items": []map[string]any{
{"fields": map[string]any{"截止日期": float64(1711900800000), "提醒时间": float64(1719802800000)}},
},
}})
}
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client(), location: resolveLocation("")}
rows, _, err := c.readBitableRecords(context.Background(), "bascabc_tblxyz")
if err != nil {
t.Fatalf("readBitableRecords: %v", err)
}
if len(rows) != 2 {
t.Fatalf("rows = %+v, want header + 1 record", rows)
}
if rows[1][0] != "2024-04-01" {
t.Errorf("date-only column = %q, want 2024-04-01 (GMT+8, not UTC-shifted)", rows[1][0])
}
if rows[1][1] != "2024-07-01 11:00" {
t.Errorf("datetime column = %q, want 2024-07-01 11:00 (GMT+8)", rows[1][1])
}
}
func TestReadBitableRecords_SplitsTokenAndBuildsTable(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"items": []map[string]any{{"field_name": "任务"}, {"field_name": "状态"}},
}})
case strings.HasSuffix(r.URL.Path, "/records/search"):
// Must use the current Search-records endpoint (POST), not the
// deprecated GET .../records legacy interface.
if r.Method != http.MethodPost {
t.Errorf("records read method = %s, want POST (search endpoint)", r.Method)
}
if !strings.Contains(r.URL.Path, "/apps/bascabc/tables/tblxyz/") {
t.Errorf("bad path %q", r.URL.Path)
}
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": false,
"items": []map[string]any{
{"fields": map[string]any{"任务": "写文档", "状态": "进行中"}},
},
}})
}
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
rows, truncated, err := c.readBitableRecords(context.Background(), "bascabc_tblxyz")
if err != nil {
t.Fatalf("readBitableRecords: %v", err)
}
if truncated {
t.Errorf("did not expect truncation")
}
if len(rows) != 2 || rows[0][0] != "任务" || rows[0][1] != "状态" || rows[1][0] != "写文档" || rows[1][1] != "进行中" {
t.Errorf("rows = %+v", rows)
}
}
// TestReadBitableRecords_PaginatesFieldsAtMax100 guards the real-API constraint
// that the list-fields endpoint caps page_size at 100 (unlike list-records, which
// allows 500). The connector must request page_size=100 and page through fields,
// or a table with >100 columns would silently lose its header tail (or the whole
// bitable would degrade if Feishu rejects page_size=500). Verified against the
// official docs: bitable-v1/app-table-field/list "最大值:100".
func TestReadBitableRecords_PaginatesFieldsAtMax100(t *testing.T) {
const totalFields = 150 // spans two pages: 100 + 50
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
if ps := r.URL.Query().Get("page_size"); ps != "100" {
t.Errorf("fields page_size = %q, want 100 (endpoint max)", ps)
}
// Page 1 (no token): first 100 fields, has_more. Page 2 (token=f2): last 50.
var items []map[string]any
hasMore := false
nextTok := ""
if r.URL.Query().Get("page_token") == "" {
for i := 0; i < 100; i++ {
items = append(items, map[string]any{"field_name": fieldName(i)})
}
hasMore, nextTok = true, "f2"
} else {
for i := 100; i < totalFields; i++ {
items = append(items, map[string]any{"field_name": fieldName(i)})
}
}
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"items": items, "has_more": hasMore, "page_token": nextTok,
}})
case strings.HasSuffix(r.URL.Path, "/records/search"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": false, "items": []map[string]any{},
}})
}
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
rows, _, err := c.readBitableRecords(context.Background(), "bascabc_tblxyz")
if err != nil {
t.Fatalf("readBitableRecords: %v", err)
}
if len(rows) < 1 {
t.Fatal("expected at least a header row")
}
header := rows[0]
if len(header) != totalFields {
t.Fatalf("header has %d fields, want %d (fields pagination lost columns)", len(header), totalFields)
}
if header[0] != fieldName(0) || header[totalFields-1] != fieldName(totalFields-1) {
t.Errorf("header endpoints wrong: first=%q last=%q", header[0], header[totalFields-1])
}
}
func fieldName(i int) string { return "f" + strconv.Itoa(i) }
// bitableRows builds n bitable record items each carrying a single "col" field.
func bitableRows(n int) []map[string]any {
items := make([]map[string]any, n)
for i := range items {
items[i] = map[string]any{"fields": map[string]any{"col": "v" + strconv.Itoa(i)}}
}
return items
}
// TestReadBitableRecords_PaginatesAndTruncatesRecords exercises the record-side
// pagination advance and the >maxTableRows truncation — the boundary logic that
// no prior test reached (every other bitable test returns a single sub-cap page).
func TestReadBitableRecords_PaginatesAndTruncatesRecords(t *testing.T) {
var secondPageToken string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"items": []map[string]any{{"field_name": "col"}},
}})
case strings.HasSuffix(r.URL.Path, "/records/search"):
if tok := r.URL.Query().Get("page_token"); tok == "" {
// Page 1: 300 records, more to come.
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": true, "page_token": "r2", "items": bitableRows(300),
}})
} else {
secondPageToken = tok
// Page 2: 250 more → 550 total, capped to maxTableRows.
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": false, "items": bitableRows(250),
}})
}
}
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
rows, truncated, err := c.readBitableRecords(context.Background(), "bascabc_tblxyz")
if err != nil {
t.Fatalf("readBitableRecords: %v", err)
}
if secondPageToken != "r2" {
t.Errorf("second records page must be fetched with page_token=r2, got %q", secondPageToken)
}
if len(rows) != maxTableRows+1 { // header + maxTableRows capped data rows
t.Errorf("rows = %d, want %d (header + %d capped)", len(rows), maxTableRows+1, maxTableRows)
}
if !truncated {
t.Error("a >maxTableRows bitable must report truncated=true")
}
}
// TestReadBitableRecords_Exactly500NotTruncated guards the off-by-one at the cap:
// exactly maxTableRows records in a single page must NOT be flagged truncated.
func TestReadBitableRecords_Exactly500NotTruncated(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"items": []map[string]any{{"field_name": "col"}},
}})
case strings.HasSuffix(r.URL.Path, "/records/search"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": false, "items": bitableRows(maxTableRows),
}})
}
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
rows, truncated, err := c.readBitableRecords(context.Background(), "bascabc_tblxyz")
if err != nil {
t.Fatalf("readBitableRecords: %v", err)
}
if truncated {
t.Error("exactly maxTableRows records must not be flagged truncated")
}
if len(rows) != maxTableRows+1 {
t.Errorf("rows = %d, want %d (header + %d)", len(rows), maxTableRows+1, maxTableRows)
}
}
// TestReadBitableRecords_EmptyRecordPageTerminates guards the pagination
// zero-progress break: a malformed page (empty items but has_more=true and a
// non-empty page_token) must terminate instead of looping until the task
// deadline. A short context deadline is a safety net so a regression fails fast
// rather than hanging the suite.
func TestReadBitableRecords_EmptyRecordPageTerminates(t *testing.T) {
recordCalls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"items": []map[string]any{{"field_name": "col"}},
}})
case strings.HasSuffix(r.URL.Path, "/records/search"):
recordCalls++
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": true, "page_token": "loop", "items": []map[string]any{},
}})
}
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
rows, _, err := c.readBitableRecords(ctx, "bascabc_tblxyz")
if err != nil {
t.Fatalf("empty-page pagination must terminate cleanly, got err: %v", err)
}
if recordCalls != 1 {
t.Errorf("records endpoint called %d times, want 1 (loop must break on the empty page)", recordCalls)
}
if len(rows) != 1 { // header only
t.Errorf("rows = %d, want 1 (header only, no records)", len(rows))
}
}
// TestReadBitableRecords_EmptyFieldsPageTerminates guards the fields loop: an
// empty page with has_more=true must still break.
func TestReadBitableRecords_EmptyFieldsPageTerminates(t *testing.T) {
fieldCalls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
fieldCalls++
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": true, "page_token": "loop", "items": []map[string]any{},
}})
case strings.HasSuffix(r.URL.Path, "/records/search"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": false, "items": []map[string]any{},
}})
}
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
if _, _, err := c.readBitableRecords(ctx, "bascabc_tblxyz"); err != nil {
t.Fatalf("empty fields page must terminate cleanly, got err: %v", err)
}
if fieldCalls != 1 {
t.Errorf("fields endpoint called %d times, want 1 (loop must break on the empty page)", fieldCalls)
}
}
// TestListDocumentBlocks_EmptyPageTerminates guards the blocks pagination loop.
func TestListDocumentBlocks_EmptyPageTerminates(t *testing.T) {
blockCalls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/blocks"):
blockCalls++
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": true, "page_token": "loop", "items": []map[string]any{},
}})
}
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
blocks, err := c.listDocumentBlocks(ctx, "doc-1")
if err != nil {
t.Fatalf("empty blocks page must terminate cleanly, got err: %v", err)
}
if blockCalls != 1 {
t.Errorf("blocks endpoint called %d times, want 1 (loop must break on the empty page)", blockCalls)
}
if len(blocks) != 0 {
t.Errorf("blocks = %d, want 0", len(blocks))
}
}
// TestReadBitableRecords_RejectsRepeatedFieldPageToken guards the list-fields
// pagination against a vendor that answers every page with has_more=true and
// the same non-empty page_token: the second occurrence must fail loudly instead
// of re-reading (and re-appending) the same page until the task deadline.
// Same guard shape as the wiki space/node and drive file pagination.
func TestReadBitableRecords_RejectsRepeatedFieldPageToken(t *testing.T) {
fieldCalls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
fieldCalls++
if fieldCalls > 2 {
http.Error(w, "pagination should have stopped", http.StatusBadGateway)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": true,
"page_token": "constant-token",
"items": []map[string]any{{"field_name": "col-a"}},
}})
}
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
_, _, err := c.readBitableRecords(ctx, "bascabc_tblxyz")
if err == nil || !strings.Contains(err.Error(), "repeated page token") {
t.Fatalf("expected repeated-page-token error, got %v", err)
}
if fieldCalls != 2 {
t.Errorf("fields endpoint called %d times, want 2 (the repeated token must fail fast)", fieldCalls)
}
}
// TestReadBitableRecords_CapsFieldPages guards the size cap on the fields loop:
// a vendor handing out a fresh page_token on every page must stop at
// maxBitableFields with a warning, not grow the header without bound.
func TestReadBitableRecords_CapsFieldPages(t *testing.T) {
const fieldsPerPage = 2
fieldCalls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
case strings.HasSuffix(r.URL.Path, "/fields"):
fieldCalls++
page := r.URL.Query().Get("page_token")
if page == "" {
page = "page-0"
}
n, err := strconv.Atoi(strings.TrimPrefix(page, "page-"))
if err != nil {
t.Errorf("unexpected page_token %q", page)
}
items := make([]map[string]any, 0, fieldsPerPage)
for i := 0; i < fieldsPerPage; i++ {
items = append(items, map[string]any{"field_name": fieldName(n*fieldsPerPage + i)})
}
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": true,
"page_token": "page-" + strconv.Itoa(n+1),
"items": items,
}})
case strings.HasSuffix(r.URL.Path, "/records/search"):
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": false, "items": []map[string]any{},
}})
}
}))
defer srv.Close()
var buf bytes.Buffer
logger.SetOutput(&buf)
defer logger.SetOutput(os.Stdout)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
rows, _, err := c.readBitableRecords(ctx, "bascabc_tblxyz")
if err != nil {
t.Fatalf("capped pagination must stop cleanly, got err: %v", err)
}
if len(rows) == 0 {
t.Fatal("expected a header row")
}
if got := len(rows[0]); got != maxBitableFields {
t.Errorf("header has %d fields, want the %d-field cap", got, maxBitableFields)
}
if want := maxBitableFields / fieldsPerPage; fieldCalls != want {
t.Errorf("fields endpoint called %d times, want %d (the cap must stop the loop)", fieldCalls, want)
}
if log := buf.String(); !strings.Contains(log, "exceeded") || !strings.Contains(log, "truncating") {
t.Errorf("hitting the cap must log a warning, log tail: %s", log)
}
}
@@ -0,0 +1,172 @@
package core
import (
"bytes"
"context"
"fmt"
"image"
"image/draw"
"image/jpeg"
"image/png"
"net/url"
)
// board.go covers the docx board block (block_type 43): whiteboards embedded in
// documents are exported to an image via the official download_as_image API and
// ride the parent document's embedded-image pipeline.
//
// API: GET /open-apis/board/v1/whiteboards/:whiteboard_id/download_as_image —
// responds with the raw image bytes (Content-Type image/png|jpeg|gif|svg+xml).
// The render covers the WHOLE board canvas, not the content bounding box, and
// editors routinely leave the canvas far larger than the drawing, so exports
// surface with large blank areas (mostly below the content). trimBoardImage
// crops those blank borders after download.
//
// Scope: board:whiteboard:node:read. 403 (code 2890005) means the app lacks
// read permission on the board; the caller degrades to a Markdown note rather
// than failing the document.
// blankTolerance is the per-channel delta under which a pixel counts as the
// background color — generous enough to absorb JPEG edge artifacts.
const blankTolerance = 14
// trimMargin keeps a visible white frame around the content bounding box —
// the border reads as the content's edge rather than a tight crop.
const trimMargin = 32
// maxTrimPixels bounds the decode/scan cost; larger images pass through
// untrimmed rather than risking a huge RGBA allocation.
const maxTrimPixels = 64 << 20
type boardPixel struct{ r, g, b, a uint8 }
// downloadBoardAsImage fetches a whiteboard's thumbnail image bytes and crops
// blank canvas borders. Transient failures (429/5xx/transport) retry via the
// shared downloadRawBytes policy; the 512 MB maxFeishuDownloadBytes cap
// applies too (a real whiteboard PNG is orders of magnitude smaller).
func (c *Client) downloadBoardAsImage(ctx context.Context, boardToken string) ([]byte, error) {
path := fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/download_as_image", url.PathEscape(boardToken))
data, err := c.downloadRawBytes(ctx, path)
if err != nil {
return nil, err
}
return trimBoardImage(data), nil
}
// trimBoardImage crops near-uniform blank borders from a board export (PNG or
// JPEG; anything undecodable or in another format returns unchanged). The
// background color is the majority of the four corner pixels (>=3 must
// agree); on a split vote content reaches the corners and the image passes
// through untrimmed. Border rows/columns entirely within blankTolerance of
// the background are trimmed, keeping trimMargin pixels around the content.
func trimBoardImage(data []byte) []byte {
// Read dimensions before decoding: compressed exports can describe a huge
// canvas even when their download fits within the byte limit.
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || (format != "png" && format != "jpeg") ||
cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxTrimPixels/cfg.Height {
return data
}
img, format, err := image.Decode(bytes.NewReader(data))
if err != nil || (format != "png" && format != "jpeg") {
return data
}
b := img.Bounds()
w, h := b.Dx(), b.Dy()
if w <= 0 || h <= 0 || w > maxTrimPixels/h {
return data
}
at := func(x, y int) boardPixel {
r, g, bl, a := img.At(x, y).RGBA()
return boardPixel{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), uint8(a >> 8)}
}
withinTolerance := func(p, q boardPixel) bool {
d := func(a, c uint8) int {
diff := int(a) - int(c)
if diff < 0 {
return -diff
}
return diff
}
return d(p.r, q.r) <= blankTolerance && d(p.g, q.g) <= blankTolerance &&
d(p.b, q.b) <= blankTolerance && d(p.a, q.a) <= blankTolerance
}
// The background color must be unambiguous: require at least three of the
// four corners to agree on one color, else content reaches the corners and
// trimming could eat it (rows fully matching the seed would read as blank).
corners := [4]boardPixel{
at(b.Min.X, b.Min.Y), at(b.Max.X-1, b.Min.Y),
at(b.Min.X, b.Max.Y-1), at(b.Max.X-1, b.Max.Y-1),
}
bg, ok := boardPixel{}, false
for _, c := range corners {
n := 0
for _, d := range corners {
if withinTolerance(c, d) {
n++
}
}
if n >= 3 {
bg, ok = c, true
break
}
}
if !ok {
return data
}
rowBlank := func(y int) bool {
for x := b.Min.X; x < b.Max.X; x++ {
if !withinTolerance(at(x, y), bg) {
return false
}
}
return true
}
colBlank := func(x int) bool {
for y := b.Min.Y; y < b.Max.Y; y++ {
if !withinTolerance(at(x, y), bg) {
return false
}
}
return true
}
top, bottom := b.Min.Y, b.Max.Y-1
for top < bottom && rowBlank(top) {
top++
}
for bottom > top && rowBlank(bottom) {
bottom--
}
left, right := b.Min.X, b.Max.X-1
for left < right && colBlank(left) {
left++
}
for right > left && colBlank(right) {
right--
}
cw, ch := right-left+1, bottom-top+1
if cw <= 2 || ch <= 2 {
// Nothing but background (degenerate content box) — keep the original.
return data
}
if cw == w && ch == h {
return data
}
x0 := max(b.Min.X, left-trimMargin)
y0 := max(b.Min.Y, top-trimMargin)
x1 := min(b.Max.X, right+1+trimMargin)
y1 := min(b.Max.Y, bottom+1+trimMargin)
out := image.NewRGBA(image.Rect(0, 0, x1-x0, y1-y0))
draw.Draw(out, out.Bounds(), img, image.Point{X: x0, Y: y0}, draw.Src)
var buf bytes.Buffer
switch format {
case "jpeg":
err = jpeg.Encode(&buf, out, &jpeg.Options{Quality: 80})
case "png":
err = png.Encode(&buf, out)
}
if err != nil {
return data
}
return buf.Bytes()
}
@@ -0,0 +1,453 @@
package core
import (
"bytes"
"context"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
// P3 embedded-object pipeline tests: board blocks (block_type 43) exported via
// download_as_image, oversize attachments degraded inline, and the marker →
// image_map contract. These run against the real Client + Feishu-shaped fake
// endpoints, exercising FetchDocxWithBlocks end to end.
func fakeFeishuForBoard(t *testing.T, blocks []DocxBlock, boardStatus int, boardBody []byte) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, DocxBlocksResponse{
ApiResponse: ApiResponse{Code: 0},
Data: DocxBlocksData{Items: blocks},
})
})
mux.HandleFunc("/open-apis/board/v1/whiteboards/brd-1/download_as_image",
func(w http.ResponseWriter, _ *http.Request) {
if boardStatus != http.StatusOK {
http.Error(w, string(boardBody), boardStatus)
return
}
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(boardBody)
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
return ts
}
func boardBlocks() []DocxBlock {
return []DocxBlock{
{BlockID: "b1", BlockType: BlockTypePage},
{
BlockID: "b2", BlockType: BlockTypeText, Text: &BlockText{
Elements: []TextElement{{TextRun: &TextRun{Content: "见画板"}}},
},
},
{BlockID: "b3", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
}
}
func boardFetchInput() DocxFetchInput {
return DocxFetchInput{
DocToken: "nt-board",
ObjToken: "obj-board",
Title: "Board Doc",
URL: "https://example.feishu.cn/wiki/nt-board",
ResourceID: "space1:nt-board",
BaseMeta: map[string]string{"channel": types.ChannelFeishu},
}
}
func TestFetchDocxWithBlocks_BoardExportSuccess(t *testing.T) {
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), MinAttachmentBytes)...)
ts := fakeFeishuForBoard(t, boardBlocks(), http.StatusOK, png)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
if err != nil {
t.Fatalf("FetchDocxWithBlocks: %v", err)
}
// Orthodox flow: the board rides inline in the parent markdown as a
// base64 data URI — no image sub-item, no image_map.
if len(items) != 1 {
t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
}
main := items[0]
if !strings.Contains(string(main.Content), "![图片](data:image/png;base64,") {
t.Errorf("board not inlined as base64 data URI:\n%s", main.Content)
}
if strings.Contains(string(main.Content), "weknora-img://") {
t.Errorf("internal marker leaked into stored markdown:\n%s", main.Content)
}
if main.Metadata["image_map"] != "" {
t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
}
if !strings.Contains(string(main.Content), "见画板") {
t.Errorf("main markdown lost body text:\n%s", main.Content)
}
}
func TestFetchDocxWithBlocks_BoardExportForbiddenDegrades(t *testing.T) {
// 403 = app lacks board:whiteboard:node:read. No board item, no failure:
// the marker degrades to an inline note and the document still syncs.
ts := fakeFeishuForBoard(t, boardBlocks(), http.StatusForbidden, []byte(`{"code":2890005,"msg":"forbidden"}`))
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
if err != nil {
t.Fatalf("board export failure must not fail the document: %v", err)
}
if len(items) != 1 {
t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
}
main := items[0]
if !strings.Contains(string(main.Content), "![图片]()") {
t.Errorf("markdown missing board degrade note:\n%s", main.Content)
}
if strings.Contains(string(main.Content), "weknora-img") {
t.Errorf("unresolved board marker left in markdown:\n%s", main.Content)
}
if main.Metadata["image_map"] != "" {
t.Errorf("failed board must not appear in image_map, got %q", main.Metadata["image_map"])
}
if !strings.Contains(string(main.Content), "见画板") {
t.Errorf("main markdown lost body text:\n%s", main.Content)
}
}
func TestFetchDocxWithBlocks_AttachmentOverCapDegrades(t *testing.T) {
// The fake declares a Content-Length above maxFeishuDownloadBytes with a
// tiny body: downloadRawBytes must reject early on the header, without
// needing to serve half a gigabyte.
bigPDF := bytes.Repeat([]byte("A"), 1024)
blocks := []DocxBlock{
{BlockID: "b1", BlockType: BlockTypePage},
{BlockID: "b2", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ft-huge", Name: "report.pdf"}},
}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, DocxBlocksResponse{
ApiResponse: ApiResponse{Code: 0},
Data: DocxBlocksData{Items: blocks},
})
})
mux.HandleFunc("/open-apis/drive/v1/medias/ft-huge/download", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Length", strconv.FormatInt(maxFeishuDownloadBytes+1, 10))
_, _ = w.Write(bigPDF)
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
in := boardFetchInput()
in.ObjToken = "obj-board"
items, err := FetchDocxWithBlocks(context.Background(), client, in)
if err != nil {
t.Fatalf("over-cap attachment must not fail the document: %v", err)
}
if len(items) != 1 {
t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
}
main := items[0]
// The over-cap file degrades to an inline reference carrying the source link.
if !strings.Contains(string(main.Content), "> [附件: report.pdf](") {
t.Errorf("markdown missing over-cap attachment placeholder:\n%s", main.Content)
}
if strings.Contains(string(main.Content), "- report.pdf") {
t.Errorf("over-cap attachment must not stay in the file-name list:\n%s", main.Content)
}
if main.Metadata["attachment_ids"] != "" {
t.Errorf("over-cap attachment must not appear in attachment_ids, got %q", main.Metadata["attachment_ids"])
}
}
// Regression for the line-text patch bug: an earlier bullet that happens to
// carry the attachment's display name must survive the over-cap degrade, and
// the attachment's own marker line is the one replaced.
func TestFetchDocxWithBlocks_OverCapPatchHitsMarkerNotEarlierBullet(t *testing.T) {
bigPDF := bytes.Repeat([]byte("A"), 1024)
blocks := []DocxBlock{
{BlockID: "b1", BlockType: BlockTypePage},
{BlockID: "b3", BlockType: BlockTypeBullet, Bullet: &BlockText{Elements: []TextElement{
{TextRun: &TextRun{Content: "report.pdf"}},
}}},
{BlockID: "b4", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ft-huge", Name: "report.pdf"}},
}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, DocxBlocksResponse{
ApiResponse: ApiResponse{Code: 0},
Data: DocxBlocksData{Items: blocks},
})
})
mux.HandleFunc("/open-apis/drive/v1/medias/ft-huge/download", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Length", strconv.FormatInt(maxFeishuDownloadBytes+1, 10))
_, _ = w.Write(bigPDF)
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
in := boardFetchInput()
in.ObjToken = "obj-board"
items, err := FetchDocxWithBlocks(context.Background(), client, in)
if err != nil {
t.Fatalf("over-cap attachment must not fail the document: %v", err)
}
main := items[len(items)-1]
if n := strings.Count(string(main.Content), "- report.pdf"); n != 1 {
t.Errorf("earlier bullet must survive exactly once, got %d:\n%s", n, main.Content)
}
if !strings.Contains(string(main.Content), "> [附件: report.pdf]") {
t.Errorf("over-cap degrade note missing:\n%s", main.Content)
}
}
// TestSupportedImageExtSVG pins the svg recovery: Go's sniffer reports SVG
// markup as text/xml, but a board export carrying an <svg> document must be
// treated as an inlinable image, not degraded to a placeholder.
func TestSupportedImageExtSVG(t *testing.T) {
svg := []byte(`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`)
ext, ct, ok := SupportedImageExt(svg)
if !ok || ext != ".svg" || ct != "image/svg+xml" {
t.Fatalf("SupportedImageExt(svg) = %q %q %v, want .svg image/svg+xml true", ext, ct, ok)
}
if _, _, ok := SupportedImageExt([]byte("<?xml version=\"1.0\"?><not-svg/>")); ok {
t.Fatal("non-svg xml must not be treated as an image")
}
}
// trimBoardImage tests: the board API renders the whole canvas, so exports
// carry large blank borders (mostly below the content) — they must be cropped.
func encodeTestImage(t *testing.T, img image.Image, format string) []byte {
t.Helper()
var buf bytes.Buffer
var err error
if format == "jpeg" {
err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80})
} else {
err = png.Encode(&buf, img)
}
if err != nil {
t.Fatalf("encode %s: %v", format, err)
}
return buf.Bytes()
}
func TestTrimBoardImage_CropsBlankBottomAndRight(t *testing.T) {
for _, format := range []string{"png", "jpeg"} {
src := image.NewRGBA(image.Rect(0, 0, 120, 200))
content := color.RGBA{R: 30, G: 60, B: 200, A: 255}
for y := 0; y < 40; y++ {
for x := 0; x < 80; x++ {
src.Set(x, y, content)
}
}
trimmed := trimBoardImage(encodeTestImage(t, src, format))
out, gotFormat, err := image.Decode(bytes.NewReader(trimmed))
if err != nil {
t.Fatalf("%s: decode trimmed: %v", format, err)
}
if gotFormat != format {
t.Fatalf("%s: format changed to %s", format, gotFormat)
}
b := out.Bounds()
if b.Dx() > 80+2*trimMargin || b.Dy() > 40+2*trimMargin {
t.Fatalf("%s: blank canvas not trimmed, got %dx%d", format, b.Dx(), b.Dy())
}
if b.Dx() < 40 || b.Dy() < 20 {
t.Fatalf("%s: content lost, got %dx%d", format, b.Dx(), b.Dy())
}
if r, _, _, _ := out.At(b.Min.X+4, b.Min.Y+4).RGBA(); uint8(r>>8) != 30 {
t.Fatalf("%s: content pixel lost at margin", format)
}
}
}
func TestTrimBoardImage_NoBlankBorderReturnsOriginal(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 50, 50))
for y := 0; y < 50; y++ {
for x := 0; x < 50; x++ {
src.Set(x, y, color.RGBA{R: uint8(x * 5), G: uint8(y * 5), B: 90, A: 255})
}
}
data := encodeTestImage(t, src, "png")
if got := trimBoardImage(data); !bytes.Equal(got, data) {
t.Fatal("fully painted image must pass through byte-identical")
}
}
func TestTrimBoardImage_FullyBlankAndGarbagePassThrough(t *testing.T) {
blank := image.NewRGBA(image.Rect(0, 0, 60, 60))
data := encodeTestImage(t, blank, "png")
if got := trimBoardImage(data); !bytes.Equal(got, data) {
t.Fatal("fully blank export must pass through unchanged")
}
if got := trimBoardImage([]byte("not an image")); !bytes.Equal(got, []byte("not an image")) {
t.Fatal("undecodable bytes must pass through unchanged")
}
}
// Content spanning two opposite corners makes the corner vote 2:2 — trimming
// must bail entirely rather than trust either color as the background.
func TestTrimBoardImage_SplitCornerVoteSkipsTrimming(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 120, 200))
white := color.RGBA{R: 255, G: 255, B: 255, A: 255}
red := color.RGBA{R: 200, G: 30, B: 30, A: 255}
for y := 0; y < 200; y++ {
for x := 0; x < 120; x++ {
src.Set(x, y, white)
}
}
// Red band down the full left side: touches top-left and bottom-left.
for y := 0; y < 200; y++ {
for x := 0; x < 50; x++ {
src.Set(x, y, red)
}
}
data := encodeTestImage(t, src, "png")
if got := trimBoardImage(data); !bytes.Equal(got, data) {
t.Fatal("split corner vote (2:2) must pass through untrimmed")
}
}
// Content touching exactly one corner keeps the majority vote at 3 — the
// blank borders away from that corner are still trimmed.
func TestTrimBoardImage_ContentAtOneCornerStillTrims(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 120, 200))
white := color.RGBA{R: 255, G: 255, B: 255, A: 255}
red := color.RGBA{R: 200, G: 30, B: 30, A: 255}
for y := 0; y < 200; y++ {
for x := 0; x < 120; x++ {
src.Set(x, y, white)
}
}
// Content only in the top-left corner region.
for y := 0; y < 40; y++ {
for x := 0; x < 40; x++ {
src.Set(x, y, red)
}
}
trimmed := trimBoardImage(encodeTestImage(t, src, "png"))
out, _, err := image.Decode(bytes.NewReader(trimmed))
if err != nil {
t.Fatalf("decode trimmed: %v", err)
}
b := out.Bounds()
if b.Dy() > 40+2*trimMargin || b.Dx() > 40+2*trimMargin {
t.Fatalf("blank canvas not trimmed, got %dx%d", b.Dx(), b.Dy())
}
if r, _, _, _ := out.At(2, 2).RGBA(); uint8(r>>8) != 200 {
t.Fatal("corner-touching content must survive at its position")
}
}
// 云文档 mention links: FetchDocxWithBlocks backfills link text with the
// referenced document's title via the drive metadata batch API; unresolved
// refs (no permission, 403) degrade to the URL-as-text form.
func TestFetchDocxWithBlocks_MentionDocTitleBackfill(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "r", BlockType: BlockTypePage},
{BlockID: "p", BlockType: BlockTypeText, Text: &BlockText{
Elements: []TextElement{{MentionDoc: &MentionDoc{
URL: "https://my.feishu.cn/docx/RefDoc001",
}}},
}},
}
run := func(metasStatus int, metasBody string, _ string) *types.FetchedItem {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/docx/v1/documents/obj-doc/blocks", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, DocxBlocksResponse{
ApiResponse: ApiResponse{Code: 0},
Data: DocxBlocksData{Items: blocks},
})
})
mux.HandleFunc("/open-apis/drive/v1/metas/batch_query", func(w http.ResponseWriter, _ *http.Request) {
if metasStatus != http.StatusOK {
http.Error(w, metasBody, metasStatus)
return
}
_, _ = w.Write([]byte(metasBody))
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})
items, err := FetchDocxWithBlocks(context.Background(), client, DocxFetchInput{
DocToken: "nt-doc", ObjToken: "obj-doc", Title: "父文档",
URL: "https://my.feishu.cn/docx/obj-doc",
})
if err != nil {
t.Fatalf("fetch: %v", err)
}
return items[len(items)-1]
}
main := run(http.StatusOK,
`{"code":0,"data":{"metas":[{"doc_token":"RefDoc001","doc_type":"docx","title":"引用的文档"}]}}`,
"引用的文档")
if !strings.Contains(string(main.Content), "[引用的文档](https://my.feishu.cn/docx/RefDoc001)") {
t.Errorf("title not backfilled, got:\n%s", main.Content)
}
// Permission denied on the metadata API → falls back to URL-as-text.
main = run(http.StatusForbidden, `forbidden`, "")
if !strings.Contains(string(main.Content),
"[https://my.feishu.cn/docx/RefDoc001](https://my.feishu.cn/docx/RefDoc001)") {
t.Errorf("fallback form missing, got:\n%s", main.Content)
}
}
// A header can advertise dimensions far beyond the compressed download size.
// The sentinel codec proves that the full pixel decoder is never invoked.
func TestTrimBoardImageRejectsOversizeBeforeDecode(t *testing.T) {
const magic = "weknora-oversized-board-test"
image.RegisterFormat("png", magic,
func(io.Reader) (image.Image, error) {
panic("oversized board reached pixel decoder")
},
func(io.Reader) (image.Config, error) {
return image.Config{Width: maxTrimPixels + 1, Height: 1}, nil
})
data := []byte(magic)
if got := trimBoardImage(data); !bytes.Equal(got, data) {
t.Fatal("oversized image must pass through unchanged")
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,303 @@
package core
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// retryTestServer builds a server that always answers the auth-token call and
// routes the given target path to h, so tests can drive DoRequest's retry loop.
func retryTestServer(t *testing.T, target string, h http.HandlerFunc) (*httptest.Server, *Config) {
t.Helper()
resetFeishuRequestGates(t)
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token",
Expire: 7200,
})
})
mux.HandleFunc(target, h)
ts := httptest.NewServer(mux)
return ts, &Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL}
}
func TestDoRequest_RetriesOn429ThenSucceeds(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
if attempts.Load() == 1 {
// "0" is coerced to a short delay inside the client so the test stays fast.
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = io.WriteString(w, `{"code":99991400,"msg":"rate limited"}`)
return
}
writeJSON(w, ApiResponse{Code: 0})
})
defer ts.Close()
c := NewClient(cfg)
var resp ApiResponse
if err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, &resp); err != nil {
t.Fatalf("expected success after retry, got %v", err)
}
if attempts.Load() < 2 {
t.Errorf("attempts = %d, want >= 2 (should retry after 429)", attempts.Load())
}
}
func TestDoRequest_429ExhaustsRetries(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = io.WriteString(w, `{"code":99991400,"msg":"rate limited"}`)
})
defer ts.Close()
c := NewClient(cfg)
err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil)
if err == nil {
t.Fatal("expected error when 429s exceed the retry budget")
}
if attempts.Load() != 4 { // initial + 3 retries
t.Errorf("attempts = %d, want 4 (1 + 3 retries)", attempts.Load())
}
}
func TestDoRequest_5xxRetriesOnce(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.WriteHeader(http.StatusInternalServerError)
_, _ = io.WriteString(w, `{"code":1,"msg":"internal error"}`)
})
defer ts.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := NewClient(cfg)
if err := c.DoRequest(ctx, http.MethodGet, "/target", nil, nil); err == nil {
t.Fatal("expected error after 5xx exhaustion")
}
if attempts.Load() != 2 { // initial + 1 retry
t.Errorf("attempts = %d, want 2 (5xx retries exactly once)", attempts.Load())
}
}
func TestDoRequest_4xxNotRetried(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"code":1,"msg":"bad request"}`)
})
defer ts.Close()
c := NewClient(cfg)
if err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil); err == nil {
t.Fatal("expected error on 400")
}
if attempts.Load() != 1 {
t.Errorf("attempts = %d, want 1 (non-429/5xx 4xx must not retry)", attempts.Load())
}
}
func TestDownloadRawBytes_RetriesOn429ThenSucceeds(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/dl", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
if attempts.Load() == 1 {
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("payload-bytes"))
})
defer ts.Close()
c := NewClient(cfg)
data, err := c.downloadRawBytes(context.Background(), "/dl")
if err != nil {
t.Fatalf("expected success after retry, got %v", err)
}
if string(data) != "payload-bytes" {
t.Errorf("data = %q, want %q", string(data), "payload-bytes")
}
if attempts.Load() < 2 {
t.Errorf("attempts = %d, want >= 2 (should retry download after 429)", attempts.Load())
}
}
func TestDownloadRawBytes_4xxNotRetried(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/dl", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.WriteHeader(http.StatusForbidden)
})
defer ts.Close()
c := NewClient(cfg)
if _, err := c.downloadRawBytes(context.Background(), "/dl"); err == nil {
t.Fatal("expected error on 403")
}
if attempts.Load() != 1 {
t.Errorf("attempts = %d, want 1 (403 must not retry)", attempts.Load())
}
}
func TestFeishuRateLimitWait(t *testing.T) {
now := time.Now().Truncate(time.Second)
tests := []struct {
reset string
retry string
want time.Duration
}{
{"", "", 10 * time.Second},
{"", "0", 100 * time.Millisecond},
{"", "-1", 100 * time.Millisecond},
{"3", "", 3 * time.Second},
{"3", "5", 5 * time.Second},
{"5", "3", 5 * time.Second},
{"abc", "2", 2 * time.Second},
{"", now.Add(4 * time.Second).UTC().Format(http.TimeFormat), 4 * time.Second},
{"NaN", "Inf", 10 * time.Second},
{"1e30", "abc", 10 * time.Second},
}
t.Setenv("FEISHU_RATE_LIMIT_RETRY_WAIT", "")
for _, tt := range tests {
headers := http.Header{}
headers.Set("x-ogw-ratelimit-reset", tt.reset)
headers.Set("Retry-After", tt.retry)
if got := feishuRateLimitWait(headers, now); got != tt.want {
t.Errorf("wait(reset=%q, retry=%q) = %v, want %v", tt.reset, tt.retry, got, tt.want)
}
}
}
func TestDoRequest_RejectsOversizedResponse(t *testing.T) {
var hits atomic.Int32
ts, cfg := retryTestServer(t, "/open-apis/docx/v1/documents", func(w http.ResponseWriter, _ *http.Request) {
hits.Add(1)
_, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))
})
defer ts.Close()
c := NewClient(cfg)
c.jsonLimit = 1 << 20
err := c.DoRequest(context.Background(), http.MethodGet, "/open-apis/docx/v1/documents", nil, &map[string]any{})
if err == nil {
t.Fatal("DoRequest accepted a response larger than the cap, want error")
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
// The same document is just as large on every attempt; retrying only burns
// the rate-limit budget and re-reads the full cap each time.
if got := hits.Load(); got != 1 {
t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)
}
}
// The token response is decoded under tokenMu on every refresh and Ping, so it
// must honour the same cap as every other API response.
func TestGetTenantAccessToken_RejectsOversizedResponse(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
// Valid JSON, so only the size cap can reject it.
_, _ = io.WriteString(w, `{"code":0,"tenant_access_token":"fake-token","expire":7200,"pad":"`)
_, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20))
_, _ = io.WriteString(w, `"}`)
})
ts := httptest.NewServer(mux)
defer ts.Close()
c := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})
c.jsonLimit = 1 << 20
_, err := c.GetTenantAccessToken(context.Background())
if err == nil {
t.Fatal("GetTenantAccessToken accepted a response larger than the cap, want error")
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
}
// countingBody records how much of a response body the client consumed.
type countingBody struct {
io.ReadCloser
n *atomic.Int64
}
func (b countingBody) Read(p []byte) (int, error) {
n, err := b.ReadCloser.Read(p)
b.n.Add(int64(n))
return n, err
}
type countingTransport struct {
base http.RoundTripper
n *atomic.Int64
}
func (t countingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.base.RoundTrip(req)
if err == nil && strings.Contains(req.URL.Path, "/download") {
resp.Body = countingBody{ReadCloser: resp.Body, n: t.n}
}
return resp, err
}
// Download error bodies are only a diagnostic preview: they must be read with a
// small bound and never copied whole into the returned error.
func TestDownloadRawBytes_BoundsErrorBodies(t *testing.T) {
const bodySize = 1 << 20
for _, status := range []int{
http.StatusTooManyRequests, http.StatusBadRequest, http.StatusInternalServerError, http.StatusForbidden,
} {
t.Run(http.StatusText(status), func(t *testing.T) {
handler := func(w http.ResponseWriter, _ *http.Request) {
if status == http.StatusTooManyRequests {
w.Header().Set("Retry-After", "0")
}
w.WriteHeader(status)
_, _ = w.Write(bytes.Repeat([]byte("a"), bodySize))
}
ts, cfg := retryTestServer(t, "/open-apis/drive/v1/files/f/download", handler)
defer ts.Close()
c := NewClient(cfg)
var read atomic.Int64
hc := *c.httpClient
base := hc.Transport
if base == nil {
base = http.DefaultTransport
}
hc.Transport = countingTransport{base: base, n: &read}
c.httpClient = &hc
_, err := c.DownloadDriveFile(context.Background(), "f")
if err == nil {
t.Fatalf("status %d: want error", status)
}
if len(err.Error()) > 1024 {
t.Fatalf("error carries %d bytes of response body, want a short preview", len(err.Error()))
}
if got := read.Load(); got >= bodySize {
t.Fatalf("read %d bytes of error bodies, want a bounded preview per response", got)
}
})
}
}
@@ -0,0 +1,108 @@
package core
import (
"errors"
"strings"
"testing"
)
// feishuFailure classifies a raw connector/API error into a stable i18n code
// (+ optional numeric feishu code) and an English fallback message. The frontend
// localises by code; the raw status/body/log_id stays in the server logs and
// must never appear in the code, codeValue or fallback.
func TestFeishuFailure(t *testing.T) {
cases := []struct {
name string
err error
wantCode string
wantCodeValue string
fallbackHas []string
noLeak []string // must appear in neither code nor fallback
}{
{
name: "rate limited",
err: errors.New("feishu rate limited: status=429 body={\"code\":99991400,\"msg\":\"too many request\"}"),
wantCode: "feishu_rate_limited",
fallbackHas: []string{"retry"},
noLeak: []string{"body=", "{", "99991400"},
},
{
name: "server 5xx",
err: errors.New("feishu server error: status=500 body={\"code\":1663}"),
wantCode: "feishu_server_unavailable",
noLeak: []string{"body=", "{"},
},
{
name: "export timeout",
err: errors.New("export 季度报告 (docx): export task timed out after 60s (ticket=abc)"),
wantCode: "feishu_timeout",
noLeak: []string{"ticket=", "abc"},
},
{
name: "api error carries the feishu code as a param",
err: errors.New("feishu api error: status=500 body={\"code\":1663,\"msg\":\"internal error\",\"Error\":{\"log_id\":\"20260\"}}"),
wantCode: "feishu_api_error",
wantCodeValue: "1663",
noLeak: []string{"log_id", "body=", "{"},
},
{
name: "api error without a code is generic",
err: errors.New("feishu api error: status=502 body=bad gateway"),
wantCode: "feishu_api_error_generic",
},
{
name: "auth failure is actionable, not a retry",
err: errors.New("feishu auth error: code=99991663 msg=Invalid access token"),
wantCode: "feishu_auth_or_permission",
noLeak: []string{"Invalid access token", "99991663"},
},
{
name: "unknown error falls back to sync_failed",
err: errors.New("some totally unexpected failure"),
wantCode: "sync_failed",
noLeak: []string{"totally unexpected"},
},
{
// "decode"/"encode"/"unicode" all contain the substring "code" but
// are not Feishu API errors — they must not be classified as one.
name: "decode error is not a feishu api error",
err: errors.New("failed to decode response body"),
wantCode: "sync_failed",
},
{
// The failed item is retried on the next sync (the cursor is not
// advanced), which for a manual-only source is not automatic. The
// message must not promise an unconditional automatic retry.
name: "transient message promises retry on next sync, not automatic",
err: errors.New("feishu rate limited: status=429"),
wantCode: "feishu_rate_limited",
fallbackHas: []string{"next sync"},
noLeak: []string{"automatically"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
code, codeValue, fallback := feishuFailure(tc.err)
if code != tc.wantCode {
t.Errorf("code = %q, want %q", code, tc.wantCode)
}
if codeValue != tc.wantCodeValue {
t.Errorf("codeValue = %q, want %q", codeValue, tc.wantCodeValue)
}
if strings.TrimSpace(fallback) == "" {
t.Errorf("fallback message must not be empty")
}
for _, s := range tc.fallbackHas {
if !strings.Contains(strings.ToLower(fallback), s) {
t.Errorf("fallback %q missing %q", fallback, s)
}
}
for _, s := range tc.noLeak {
if strings.Contains(code, s) || strings.Contains(fallback, s) {
t.Errorf("raw detail %q leaked into code/fallback (code=%q fallback=%q)", s, code, fallback)
}
}
})
}
}
@@ -0,0 +1,289 @@
package core
import (
"context"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// engine.go holds the single generic streaming sync engine shared by the wiki
// Connector and the Drive DriveConnector. The per-connector differences (node
// type, listing API, edit-time field, cursor wire format, fetch dispatch,
// log tag) are isolated behind the NodeOps adapter interface. FetchAll /
// FetchIncremental are thin wrappers over the same engine that collect Emits
// instead of streaming them.
//
// Behaviour note (deliberate, see ADR-0005 / design §2.4):
// - Resume/incremental fast-path: a node recorded at its current edit time
// is skipped, keeping the cursor entry.
// - A fetch failure does NOT advance the cursor: the prior edit time is
// retained so the node is retried next run instead of being permanently
// skipped on a transient export failure (Tencent/WeKnora#2136). This now
// also holds for the FetchIncremental path (previously it advanced the
// cursor before fetching, a latent #2136 bug).
// - Logs use the "stream progress/summary" wording uniformly; the
// FetchIncremental path additionally gains per-100 progress + tally
// summary logs it did not Emit before (log-only change).
// NodeOps adapts one connector's node type to the shared sync engine. Every
// method is a pure accessor or a thin wrapper - no engine logic lives here.
type NodeOps[N any] interface {
// List returns every syncable node under resourceID. A non-nil partial
// (with err == nil) signals a partial listing: nodes is still usable and
// the sync continues, but the caller surfaces the failed sub-trees via
// ListFailureItems. A non-nil err is fatal and aborts the sync.
List(ctx context.Context, client *Client, resourceID string) (nodes []N, partial error, err error)
Token(n N) string
Title(n N) string
ObjType(n N) string
// EditTime is an opaque change key stored in the cursor (time and/or path).
EditTime(n N) string
// fetch retrieves one node's content; (nil, nil) means an unsupported
// type that yields no item.
Fetch(ctx context.Context, client *Client, n N, resourceID string) ([]*types.FetchedItem, error)
// ListFailureItems converts a partial-listing error into error FetchedItems.
ListFailureItems(resourceID string, partial error) []types.FetchedItem
// ResourceNoun is the noun in user-visible error text: "nodes" / "files".
ResourceNoun() string
// EmptyResourceIDsError is the connector-specific message when no resource
// IDs are configured (wiki/drive text differs and is preserved verbatim).
EmptyResourceIDsError() string
// LogTag is the log prefix: "[Feishu]" / "[FeishuDrive]".
LogTag() string
// DecodeCursorTimes extracts the per-resource edit-time map from a
// persisted ConnectorCursor (nil-safe: returns nil when absent).
DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string
// EncodeCursor wraps the engine's internal times map into the connector's
// wire-format SyncCursor. JSON-marshals for snapshot isolation, mirroring
// the original FeishuCursor.toSyncCursor / FeishuDriveCursor.toSyncCursor.
EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor
}
// CollectHandler is the StreamHandler used by FetchAll / FetchIncremental to
// gather every Emitted item into a slice instead of streaming. Checkpoint is a
// no-op: those paths return a single cursor at the end.
type CollectHandler struct {
items []types.FetchedItem
}
func (h *CollectHandler) Emit(_ context.Context, item types.FetchedItem) error {
h.items = append(h.items, item)
return nil
}
func (h *CollectHandler) Checkpoint(_ context.Context, _ *types.SyncCursor) error { return nil }
// fullSyncPending is checkpoint-only state. A retried full pass must skip work
// completed before the checkpoint while keeping unseen deletion identities.
const fullSyncPending = "feishu_full_sync_pending"
// runSync is the single implementation behind FetchStream / FetchAll /
// FetchIncremental. With cursor == nil it fetches everything (full sync);
// with a cursor it skips nodes whose recorded edit time is unchanged
// (incremental + resume), unless forceFull is set. Full runs retain cursor
// identities for deletion tracking. resourceIDs comes from the caller: FetchStream /
// FetchIncremental pass config.ResourceIDs (after a non-empty check),
// FetchAll passes its own argument without one.
func runSync[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
resourceIDs []string, cursor *types.SyncCursor, h datasource.StreamHandler,
ops NodeOps[N], forceFull bool,
) (*types.SyncCursor, error) {
var prevTimes map[string]map[string]string
if cursor != nil && cursor.ConnectorCursor != nil {
prevTimes = ops.DecodeCursorTimes(cursor.ConnectorCursor)
}
resumingFull := false
if cursor != nil {
resumingFull, _ = cursor.ConnectorCursor[fullSyncPending].(bool)
}
fullRun := forceFull || resumingFull
forceFull = forceFull && !resumingFull
// Keep unseen entries in checkpoints until a complete listing proves them
// deleted. This also preserves later resources if a run is interrupted.
newTimes := make(map[string]map[string]string)
for _, resourceID := range resourceIDs {
newTimes[resourceID] = make(map[string]string)
for token, edit := range prevTimes[resourceID] {
if forceFull {
// Invalidating the value (not the identity) makes failed full
// fetches retryable even if the source timestamp is unchanged.
edit = "!pending-full-fetch"
}
newTimes[resourceID][token] = edit
}
}
lastSync := time.Now()
processed := 0
lastCheckpoint := time.Now()
for _, resourceID := range resourceIDs {
nodes, partial, err := ops.List(ctx, client, resourceID)
if err != nil {
return nil, fmt.Errorf("list %s for resource %s: %w", ops.ResourceNoun(), resourceID, err)
}
if partial != nil {
for _, item := range ops.ListFailureItems(resourceID, partial) {
if eerr := h.Emit(ctx, item); eerr != nil {
return nil, eerr
}
}
}
currentNodes := make(map[string]bool)
tally := newFetchTally(len(nodes))
for i, node := range nodes {
tok := ops.Token(node)
currentNodes[tok] = true
editTimeStr := ops.EditTime(node)
var prevEdit string
var hadPrev bool
if prevTimes != nil {
if prev, ok := prevTimes[resourceID]; ok {
prevEdit, hadPrev = prev[tok]
}
}
// Resume/incremental fast-path: a node recorded at its current edit
// time is unchanged (or already synced this run) - keep the record
// and Skip re-fetching.
if !forceFull && hadPrev && prevEdit == editTimeStr {
newTimes[resourceID][tok] = editTimeStr
continue
}
items, ferr := ops.Fetch(ctx, client, node, resourceID)
if ferr != nil {
tally.fail()
// Do NOT advance the cursor: the content was never fetched.
// Retain the prior edit time (if any) so prev != current next
// run and the node is retried, instead of being permanently
// skipped on a transient export failure (Tencent/WeKnora#2136).
// The seeded entry keeps the prior key, or the invalidated
// full-fetch key, without losing its deletion identity.
if eerr := h.Emit(ctx, types.FetchedItem{
ExternalID: tok,
Title: ops.Title(node),
SourceResourceID: resourceID,
Metadata: FeishuErrorItemMeta(ferr, nil),
}); eerr != nil {
return nil, eerr
}
} else {
// Fetched, or an unsupported type (nothing to fetch): record
// the current edit time so the node is not re-processed next run.
newTimes[resourceID][tok] = editTimeStr
if len(items) > 0 {
tally.fetch()
for _, it := range items {
if eerr := h.Emit(ctx, *it); eerr != nil {
return nil, eerr
}
}
} else {
// Unsupported type (mindnote/slides/…): no item.
tally.Skip(ops.ObjType(node))
}
}
processed++
if processed%FeishuStreamCheckpointInterval == 0 || time.Since(lastCheckpoint) >= FeishuStreamCheckpointMaxInterval {
checkpoint := ops.EncodeCursor(newTimes, lastSync)
if fullRun {
checkpoint.ConnectorCursor[fullSyncPending] = true
}
if cerr := h.Checkpoint(ctx, checkpoint); cerr != nil {
logger.Warnf(ctx, "%s stream Checkpoint failed: %v", ops.LogTag(), cerr)
}
lastCheckpoint = time.Now()
}
if n := i + 1; n%100 == 0 {
logger.Infof(ctx, "%s stream progress resource=%s %d/%d (%s)",
ops.LogTag(), resourceID, n, len(nodes), tally.summary())
}
}
// Detect deleted nodes (only when the full tree was listed successfully).
// A partial listing did not enumerate the whole subtree, so deletion
// detection would false-positive.
if partial == nil && prevTimes != nil {
if prev, ok := prevTimes[resourceID]; ok {
for tok := range prev {
if !currentNodes[tok] {
if eerr := h.Emit(ctx, types.FetchedItem{
ExternalID: tok,
IsDeleted: true,
SourceResourceID: resourceID,
}); eerr != nil {
return nil, eerr
}
delete(newTimes[resourceID], tok)
}
}
}
}
logger.Infof(ctx, "%s stream summary resource=%s %s", ops.LogTag(), resourceID, tally.summary())
}
return ops.EncodeCursor(newTimes, lastSync), nil
}
// FetchStreamEngine runs the streaming sync. FetchStream / FetchIncremental
// shells differ only in whether they pass a cursor and how they collect
// results; both route here.
func FetchStreamEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler, ops NodeOps[N],
) (*types.SyncCursor, error) {
return runSync(ctx, client, config, config.ResourceIDs, cursor, h, ops, false)
}
// FetchFullStreamEngine refetches all nodes while retaining deletion identities.
func FetchFullStreamEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler, ops NodeOps[N],
) (*types.SyncCursor, error) {
return runSync(ctx, client, config, config.ResourceIDs, cursor, h, ops, true)
}
// FetchAllEngine runs a full sync, collecting every item into a slice. It
// passes the caller-supplied resourceIDs without a non-empty check (mirroring
// the original FetchAll which accepted an empty list and returned no items).
// On error any partially collected items are discarded, matching the original
// behaviour (a fatal list error dropped everything collected so far).
func FetchAllEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
resourceIDs []string, ops NodeOps[N],
) ([]types.FetchedItem, error) {
ch := &CollectHandler{}
if _, err := runSync(ctx, client, config, resourceIDs, nil, ch, ops, false); err != nil {
return nil, err
}
return ch.items, nil
}
// FetchIncrementalEngine runs an incremental sync against cursor, collecting
// items. resourceIDs come from config.ResourceIDs (non-empty check is the
// caller's responsibility).
func FetchIncrementalEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
cursor *types.SyncCursor, ops NodeOps[N],
) ([]types.FetchedItem, *types.SyncCursor, error) {
ch := &CollectHandler{}
next, err := runSync(ctx, client, config, config.ResourceIDs, cursor, ch, ops, false)
if err != nil {
return nil, nil, err
}
return ch.items, next, nil
}
@@ -0,0 +1,146 @@
package core
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
type fullSyncOps struct {
nodes map[string][]string
partial bool
fail map[string]bool
fetched []string
}
func (o *fullSyncOps) List(_ context.Context, _ *Client, resource string) ([]string, error, error) {
if o.partial {
return o.nodes[resource], errors.New("partial listing"), nil
}
return o.nodes[resource], nil, nil
}
func (*fullSyncOps) Token(n string) string { return n }
func (*fullSyncOps) Title(n string) string { return n }
func (*fullSyncOps) ObjType(string) string { return "file" }
func (*fullSyncOps) EditTime(string) string { return "100" }
func (o *fullSyncOps) Fetch(_ context.Context, _ *Client, n, resource string) ([]*types.FetchedItem, error) {
o.fetched = append(o.fetched, n)
if o.fail[n] {
return nil, errors.New("transient fetch failure")
}
return []*types.FetchedItem{{ExternalID: n, SourceResourceID: resource}}, nil
}
func (*fullSyncOps) ListFailureItems(string, error) []types.FetchedItem { return nil }
func (*fullSyncOps) ResourceNoun() string { return "nodes" }
func (*fullSyncOps) EmptyResourceIDsError() string { return "empty resources" }
func (*fullSyncOps) LogTag() string { return "[test]" }
func (*fullSyncOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
return m["times"].(map[string]map[string]string)
}
func (*fullSyncOps) EncodeCursor(m map[string]map[string]string, _ time.Time) *types.SyncCursor {
snapshot := make(map[string]map[string]string)
for resource, times := range m {
snapshot[resource] = make(map[string]string)
for k, v := range times {
snapshot[resource][k] = v
}
}
return &types.SyncCursor{ConnectorCursor: map[string]interface{}{"times": snapshot}}
}
type fullSyncHandler struct {
CollectHandler
checkpoint *types.SyncCursor
stopAfterCheckpoint bool
}
func (h *fullSyncHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if h.stopAfterCheckpoint && h.checkpoint != nil {
return errors.New("interrupted")
}
return h.CollectHandler.Emit(ctx, item)
}
func (h *fullSyncHandler) Checkpoint(_ context.Context, cur *types.SyncCursor) error {
h.checkpoint = cur
return nil
}
func TestFullSyncRefetchesAndReconcilesDeletions(t *testing.T) {
ops := &fullSyncOps{nodes: map[string][]string{"r": {"kept"}}}
cfg := &types.DataSourceConfig{ResourceIDs: []string{"r"}}
old := ops.EncodeCursor(map[string]map[string]string{"r": {"kept": "100", "gone": "100"}}, time.Now())
h := &fullSyncHandler{}
next, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
require.NoError(t, err)
require.Equal(t, []string{"kept"}, ops.fetched)
require.Len(t, h.items, 2)
require.True(t, h.items[1].IsDeleted)
require.Equal(t, "gone", h.items[1].ExternalID)
require.Equal(t, map[string]string{"kept": "100"}, ops.DecodeCursorTimes(next.ConnectorCursor)["r"])
require.Contains(t, ops.DecodeCursorTimes(old.ConnectorCursor)["r"], "gone", "input baseline must remain immutable")
}
func TestFullSyncFailuresRetryWithoutLosingDeletionIdentity(t *testing.T) {
ops := &fullSyncOps{nodes: map[string][]string{"r": {"kept"}}, partial: true, fail: map[string]bool{"kept": true}}
cfg := &types.DataSourceConfig{ResourceIDs: []string{"r"}}
old := ops.EncodeCursor(map[string]map[string]string{"r": {"kept": "100", "unseen": "100"}}, time.Now())
h := &fullSyncHandler{}
next, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
require.NoError(t, err)
require.Len(t, h.items, 1)
require.NotEmpty(t, h.items[0].Metadata["error"])
require.Contains(t, ops.DecodeCursorTimes(next.ConnectorCursor)["r"], "unseen")
ops.partial = false
ops.fail = nil
ops.fetched = nil
h = &fullSyncHandler{}
_, err = FetchStreamEngine(context.Background(), nil, cfg, next, h, ops)
require.NoError(t, err)
require.Equal(t, []string{"kept"}, ops.fetched,
"failed full fetch must retry despite an unchanged source timestamp")
require.Len(t, h.items, 2)
require.True(t, h.items[1].IsDeleted)
require.Equal(t, "unseen", h.items[1].ExternalID)
}
func TestFullSyncCheckpointRetainsUnseenDeletionBaseline(t *testing.T) {
ops := &fullSyncOps{nodes: map[string][]string{"first": {}}}
for i := 0; i < FeishuStreamCheckpointInterval+1; i++ {
ops.nodes["first"] = append(ops.nodes["first"], fmt.Sprintf("node%d", i))
}
cfg := &types.DataSourceConfig{ResourceIDs: []string{"first", "later"}}
old := ops.EncodeCursor(map[string]map[string]string{
"first": {"gone": "100"}, "later": {"gone-later": "100"},
}, time.Now())
h := &fullSyncHandler{stopAfterCheckpoint: true}
_, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
require.Error(t, err)
require.NotNil(t, h.checkpoint)
require.Equal(t, true, h.checkpoint.ConnectorCursor[fullSyncPending])
ops.fetched = nil
resume := &fullSyncHandler{}
next, err := FetchFullStreamEngine(context.Background(), nil, cfg, h.checkpoint, resume, ops)
require.NoError(t, err)
deleted := []string{}
for _, item := range resume.items {
if item.IsDeleted {
deleted = append(deleted, item.ExternalID)
}
}
require.ElementsMatch(t, []string{"gone", "gone-later"}, deleted)
require.Equal(t, []string{fmt.Sprintf("node%d", FeishuStreamCheckpointInterval)}, ops.fetched,
"a retried full pass must not repeat successfully checkpointed fetches")
require.NotContains(t, next.ConnectorCursor, fullSyncPending)
ops.fetched = nil
_, err = FetchFullStreamEngine(context.Background(), nil, cfg, next, &fullSyncHandler{}, ops)
require.NoError(t, err)
require.Len(t, ops.fetched, len(ops.nodes["first"]),
"a later independent full sync must refetch everything")
}
@@ -0,0 +1,54 @@
package core
import (
"encoding/json"
"net/http"
"os"
"testing"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
func TestMain(m *testing.M) {
os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost,open.feishu.cn,open.larksuite.com")
secutils.ResetSSRFWhitelistForTest()
os.Exit(m.Run())
}
func writeJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
// blk constructors mirroring wiki/connector_golden_test.go, for core-internal
// block-rendering tests (DocxBlock is same-package here, no core. prefix).
func sheetBlk(id, token string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeSheet, Sheet: &BlockTokenRef{Token: token}}
}
func bitableBlk(id, token string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeBitable, Bitable: &BlockTokenRef{Token: token}}
}
func imageBlk(id, token string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeImage, Image: &BlockTokenRef{Token: token}}
}
func fileBlk(id, token, name string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeFile, File: &BlockFileRef{Token: token, Name: name}}
}
func cellBlk(id string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeTableCell, Children: []string{id + "_txt"}}
}
func cellTextBlk(id, text string) DocxBlock {
return DocxBlock{BlockID: id + "_txt", BlockType: BlockTypeText, Text: txt(text)}
}
func tableBlk(id string, cols int, cellIDs ...string) DocxBlock {
b := DocxBlock{BlockID: id, BlockType: BlockTypeTable}
b.Table = &BlockTable{Cells: cellIDs}
b.Table.Property = &BlockTableProperty{ColumnSize: cols}
return b
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,33 @@
package core
import (
"math"
"testing"
"github.com/stretchr/testify/require"
)
func TestNativeTableBoundsUntrustedColumnCount(t *testing.T) {
block := DocxBlock{BlockType: BlockTypeTable, Table: &BlockTable{
Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: math.MaxInt},
}}
byID := map[string]DocxBlock{
"cell": {BlockID: "cell", Children: []string{"text"}},
"text": {BlockID: "text", BlockType: BlockTypeText, Text: txt("kept")},
}
require.NotPanics(t, func() { require.Contains(t, renderNativeTable(block, byID), "kept") })
block.Table.Cells = nil
require.NotPanics(t, func() { require.Empty(t, renderNativeTable(block, byID)) })
}
func TestNativeTableBoundsMergedRegions(t *testing.T) {
rows := [][]string{{"anchor", ""}, {""}, {"", ""}}
fillMergedCells(rows, 2, []BlockTableMergeInfo{{RowSpan: math.MaxInt, ColSpan: math.MaxInt}})
require.Equal(t, [][]string{{"anchor", "anchor"}, {"anchor"}, {"anchor", "anchor"}}, rows)
// A merge entry beyond the supplied cells cannot index or iterate an absent row.
fillMergedCells(rows, 2, []BlockTableMergeInfo{
{}, {}, {}, {}, {}, {}, {RowSpan: math.MaxInt, ColSpan: math.MaxInt},
})
require.Equal(t, "anchor", rows[0][0])
require.NotPanics(t, func() { fillMergedCells(rows, 0, []BlockTableMergeInfo{{RowSpan: 2, ColSpan: 2}}) })
}
@@ -0,0 +1,72 @@
package core
import (
"context"
"strings"
"testing"
)
func textBlk(id, text string, children ...string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeText, Text: txt(text), Children: children}
}
// A table cell is a container: list or callout blocks nested in it are
// consumed by tableDescendants, so the cell must render their text.
func TestNativeTablePreservesNestedCellTextOnce(t *testing.T) {
blocks := []DocxBlock{
tableBlk("table", 1, "cell"),
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"callout", "after"}},
{BlockID: "callout", BlockType: BlockTypeCallout, Children: []string{"item"}},
{BlockID: "item", BlockType: BlockTypeBullet, Bullet: txt("初始化参数"), Children: []string{"nested"}},
textBlk("nested", "appKey 必填"),
textBlk("after", "最后启动"),
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(md), "| 初始化参数 appKey 必填 最后启动 |") {
t.Fatalf("nested cell text missing or reordered:\n%s", md)
}
for _, text := range []string{"初始化参数", "appKey 必填", "最后启动"} {
if strings.Count(string(md), text) != 1 {
t.Fatalf("cell text %q duplicated:\n%s", text, md)
}
}
}
func TestNativeTableNestedCellTextHandlesRepeatedAndCyclicReferences(t *testing.T) {
blocks := []DocxBlock{
tableBlk("table", 1, "cell"),
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"container", "leaf", "missing"}},
{BlockID: "container", BlockType: BlockTypeCallout, Children: []string{"leaf", "cell", "container"}},
textBlk("leaf", "保留一次"),
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatal(err)
}
if strings.Count(string(md), "保留一次") != 1 {
t.Fatalf("repeated or cyclic reference duplicated text:\n%s", md)
}
}
// Media keeps its own handling in the flat loop, and so does text nested
// under it; the cell must not render it a second time.
func TestNativeTableNestedCellTextSkipsMediaSubtrees(t *testing.T) {
for _, kind := range []int{BlockTypeFile, BlockTypeImage, BlockTypeBoard} {
blocks := []DocxBlock{
tableBlk("table", 1, "cell"),
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"media"}},
{BlockID: "media", BlockType: kind, Children: []string{"caption"}},
textBlk("caption", "媒体说明"),
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(md), "| 媒体说明 |") {
t.Fatalf("media subtree rendered inside the cell for block type %d:\n%s", kind, md)
}
}
}
@@ -0,0 +1,130 @@
package core
import (
"bytes"
"context"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestContainerPreservesNestedListContent(t *testing.T) {
for _, kind := range []int{BlockTypeCallout, BlockTypeQuoteContainer, BlockTypeGrid, BlockTypeView} {
t.Run(blockNameForTest(kind), func(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "container", BlockType: kind, Children: []string{"list"}},
{
BlockID: "list", ParentID: "container", BlockType: BlockTypeBullet,
Bullet: txt("parent"), Children: []string{"nested"},
},
{
BlockID: "nested", ParentID: "list", BlockType: BlockTypeOrdered,
Ordered: txt("nested"), Children: []string{"text", "image", "file"},
},
{BlockID: "text", ParentID: "nested", BlockType: BlockTypeText, Text: txt("important nested content")},
{BlockID: "image", ParentID: "nested", BlockType: BlockTypeImage, Image: &BlockTokenRef{Token: "img"}},
{
BlockID: "file", ParentID: "nested", BlockType: BlockTypeFile,
File: &BlockFileRef{Token: "pdf", Name: "report.pdf"},
},
}
if kind == BlockTypeGrid {
blocks[0].Children = []string{"column"}
blocks = append(blocks, DocxBlock{
BlockID: "column", BlockType: BlockTypeGridColumn, Children: []string{"list"},
})
}
md, atts, imgs, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
require.NoError(t, err)
for _, text := range []string{"parent", "nested content", "weknora-att://pdf", "weknora-img://"} {
require.Equal(t, 1, strings.Count(string(md), text), "content must appear exactly once: %s", md)
}
require.Len(t, atts, 1)
require.Len(t, imgs, 1)
require.Contains(t, string(md), " 1. nested")
})
}
}
func blockNameForTest(kind int) string {
switch kind {
case BlockTypeCallout:
return "callout"
case BlockTypeQuoteContainer:
return "quote"
case BlockTypeGrid:
return "grid"
default:
return "view"
}
}
func TestContainerNestedOrderedListKeepsParentSequence(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "container", BlockType: BlockTypeView, Children: []string{"first", "second"}},
{
BlockID: "first", ParentID: "container", BlockType: BlockTypeOrdered,
Ordered: txt("parent one"), Children: []string{"nested"},
},
{BlockID: "nested", ParentID: "first", BlockType: BlockTypeOrdered, Ordered: txt("child one")},
{BlockID: "second", ParentID: "container", BlockType: BlockTypeOrdered, Ordered: txt("parent two")},
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
require.NoError(t, err)
require.Contains(t, string(md), "1. parent one\n\n 1. child one\n2. parent two")
}
func TestBoardInNativeTableIsDownloaded(t *testing.T) {
for _, inContainer := range []bool{false, true} {
t.Run(map[bool]string{false: "table", true: "table in callout"}[inContainer], func(t *testing.T) {
blocks := []DocxBlock{
{
BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"},
Table: &BlockTable{Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: 1}},
},
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"text", "board"}},
{BlockID: "text", BlockType: BlockTypeText, Text: txt("board caption")},
{BlockID: "board", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
}
if inContainer {
blocks = append([]DocxBlock{
{BlockID: "callout", BlockType: BlockTypeCallout, Children: []string{"table"}},
}, blocks...)
}
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), MinAttachmentBytes)...)
server := fakeFeishuForBoard(t, blocks, http.StatusOK, png)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: server.URL})
items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
require.NoError(t, err)
require.Len(t, items, 1)
md := string(items[0].Content)
require.Equal(t, 1, strings.Count(md, "data:image/png;base64,"))
require.Equal(t, 1, strings.Count(md, "board caption"))
require.NotContains(t, md, "weknora-img://")
})
}
}
func TestContainerPreservesMalformedTableChildren(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "view", BlockType: BlockTypeView, Children: []string{"table"}},
{BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"}},
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"text"}},
{BlockID: "text", BlockType: BlockTypeText, Text: txt("retained content")},
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
require.NoError(t, err)
require.Equal(t, 1, strings.Count(string(md), "retained content"))
}
func TestContainerCyclicChildrenTerminate(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "view", BlockType: BlockTypeView, Children: []string{"list"}},
{BlockID: "list", BlockType: BlockTypeBullet, Bullet: txt("cyclic content"), Children: []string{"list"}},
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
require.NoError(t, err)
require.Equal(t, 1, strings.Count(string(md), "cyclic content"))
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,76 @@
package core
import (
"bytes"
"context"
"image"
"image/color"
"image/draw"
"image/png"
"net/http"
"strings"
"testing"
)
func TestTableViewKeepsFileAndBoard(t *testing.T) {
for _, kind := range []int{BlockTypeView, BlockTypeCallout, BlockTypeQuoteContainer, BlockTypeGrid} {
t.Run(blockNameForTest(kind), func(t *testing.T) {
blocks := []DocxBlock{
{
BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"},
Table: &BlockTable{Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: 1}},
},
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"view"}},
{BlockID: "view", BlockType: kind, Children: []string{"file", "board"}},
{BlockID: "file", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "pdf", Name: "report.pdf"}},
{BlockID: "board", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
}
for _, outer := range []bool{false, true} {
if outer {
blocks = append([]DocxBlock{
{BlockID: "outer", BlockType: BlockTypeView, Children: []string{"table"}},
}, blocks...)
}
md, atts, imgs, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatal(err)
}
if len(atts) != 1 || len(imgs) != 1 {
t.Fatalf("table view media lost: attachments=%d images=%d markdown=%q", len(atts), len(imgs), md)
}
if strings.Count(string(md), "weknora-att://pdf") != 1 ||
strings.Count(string(md), "weknora-img://") != 1 {
t.Fatalf("media must render exactly once: %s", md)
}
}
})
}
}
func TestTrimmedBoardKeepsMeaningfulDiagram(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 1600, 1200))
draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
draw.Draw(img, image.Rect(400, 400, 700, 600), image.NewUniform(color.Black), image.Point{}, draw.Src)
var b bytes.Buffer
if err := png.Encode(&b, img); err != nil {
t.Fatal(err)
}
cropped := trimBoardImage(b.Bytes())
cfg, _, err := image.DecodeConfig(bytes.NewReader(cropped))
if err != nil {
t.Fatal(err)
}
if len(cropped) >= MinAttachmentBytes || cfg.Width < 64 || cfg.Height < 64 {
t.Fatalf("fixture must be a sub-2KB diagram with meaningful dimensions: bytes=%d dims=%dx%d",
len(cropped), cfg.Width, cfg.Height)
}
server := fakeFeishuForBoard(t, boardBlocks(), http.StatusOK, b.Bytes())
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: server.URL})
items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(items[len(items)-1].Content), "data:image/png;base64,") {
t.Fatalf("valid board disappeared: %s", items[len(items)-1].Content)
}
}
@@ -0,0 +1,180 @@
package core
import (
"context"
"net/http"
"strings"
"sync/atomic"
"testing"
)
// mentionBlk builds a text block whose only inline element is an @mention of
// the given OpenID.
func mentionBlk(id, openID string) DocxBlock {
return DocxBlock{
BlockID: id, BlockType: BlockTypeText,
Text: &BlockText{Elements: []TextElement{{MentionUser: &MentionUser{UserID: openID}}}},
}
}
// mentionUserCase renders blocks and asserts the resolved display names hit
// (named) and miss/403-degrade (generic @成员) paths.
func mentionUserCase(t *testing.T, name string, resolver func(string) string, blocks []DocxBlock, want []string) {
t.Helper()
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver)
if err != nil {
t.Fatalf("%s: err: %v", name, err)
}
for _, w := range want {
if !strings.Contains(string(md), w) {
t.Errorf("%s: missing %q, got:\n%s", name, w, md)
}
}
}
func TestBlocksToMarkdown_MentionUserName(t *testing.T) {
// Hit: OpenID resolves to a real display name.
resolved := map[string]string{"ou_zhang": "张三", "ou_li": "李四"}
mentionUserCase(t, "hit", func(id string) string { return resolved[id] },
[]DocxBlock{
{BlockID: "p1", BlockType: BlockTypeText, Text: &BlockText{Elements: []TextElement{
{TextRun: &TextRun{Content: "请 "}},
{MentionUser: &MentionUser{UserID: "ou_zhang"}},
}}},
mentionBlk("p2", "ou_li"),
},
[]string{"@张三", "@李四"})
// Miss (unknown user / API failure): degrade to the generic marker, and
// the document still renders — the failure never surfaces as an error.
var calls int
mentionUserCase(t, "miss", func(_ string) string {
calls++
return ""
}, []DocxBlock{mentionBlk("p1", "ou_gone")},
[]string{"@成员"})
if calls != 1 {
t.Errorf("resolver calls = %d, want 1", calls)
}
}
func TestBlocksToMarkdown_MentionUserName_OncePerElement(t *testing.T) {
var calls int
resolver := func(_ string) string {
calls++
return "张三"
}
blocks := []DocxBlock{mentionBlk("p1", "ou_x"), mentionBlk("p2", "ou_x"), mentionBlk("p3", "ou_y")}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver)
if err != nil {
t.Fatalf("err: %v", err)
}
// The renderer consults the resolver once per mention element; dedup
// caching lives in the userNameResolver closure (tested with real HTTP
// traffic in TestUserNameResolver_NegativeCache).
if calls != 3 {
t.Errorf("resolver calls = %d, want 3 (one per mention element)", calls)
}
if got := strings.Count(string(md), "@张三"); got != 3 {
t.Errorf("mentions rendered = %d, want 3, got:\n%s", got, md)
}
}
func TestBlocksToMarkdown_NoMention_ZeroResolverCalls(t *testing.T) {
var calls int
resolver := func(_ string) string {
calls++
return "张三"
}
blocks := []DocxBlock{
{BlockID: "p1", BlockType: BlockTypeText, Text: txt("没有提及的普通段落")},
{BlockID: "p2", BlockType: BlockTypeText, Text: txt("另一段")},
}
if _, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver); err != nil {
t.Fatalf("err: %v", err)
}
if calls != 0 {
t.Errorf("resolver calls = %d, want 0 (no API traffic without mentions)", calls)
}
}
func TestUserName(t *testing.T) {
ts, cfg := retryTestServer(t, "/open-apis/contact/v3/users/ou_1", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("user_id_type") != "open_id" {
t.Errorf("user_id_type = %q, want open_id", r.URL.Query().Get("user_id_type"))
}
writeJSON(w, map[string]any{"code": 0, "data": map[string]any{
"user": map[string]any{"name": "张三"},
}})
})
defer ts.Close()
c := NewClient(cfg)
name, err := c.UserName(context.Background(), "ou_1")
if err != nil {
t.Fatalf("err: %v", err)
}
if name != "张三" {
t.Errorf("name = %q, want 张三", name)
}
// 403 (no contact scope): error, caller degrades.
ts403, cfg403 := retryTestServer(t, "/open-apis/contact/v3/users/ou_1",
func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"code":99991679,"msg":"permission denied"}`))
})
defer ts403.Close()
if _, err := NewClient(cfg403).UserName(context.Background(), "ou_1"); err == nil {
t.Error("403 must return an error for the caller to degrade")
}
// HTTP 200 but business error code: also an error.
tsCode, cfgCode := retryTestServer(t, "/open-apis/contact/v3/users/ou_1",
func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, map[string]any{"code": 99991672, "msg": "no permission"})
})
defer tsCode.Close()
if _, err := NewClient(cfgCode).UserName(context.Background(), "ou_1"); err == nil {
t.Error("non-zero body code must return an error")
}
}
func TestUserNameResolver_NegativeCache(t *testing.T) {
var hits atomic.Int64
ts, cfg := retryTestServer(t, "/open-apis/contact/v3/users/", func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
if strings.Contains(r.URL.Path, "ou_ok") {
writeJSON(w, map[string]any{"code": 0, "data": map[string]any{
"user": map[string]any{"name": "张三"},
}})
return
}
// No permission for the other user, forever.
w.WriteHeader(http.StatusForbidden)
})
defer ts.Close()
resolver := userNameResolver(context.Background(), NewClient(cfg))
// Same user three times: resolved once; failed user three times: one
// negative-cached attempt. Total HTTP traffic must be 2.
got := []string{
resolver("ou_ok"), resolver("ou_ok"), resolver("ou_ok"),
resolver("ou_bad"), resolver("ou_bad"), resolver("ou_bad"),
}
for i, g := range got {
want := "张三"
if i >= 3 {
want = ""
}
if g != want {
t.Errorf("resolver[%d] = %q, want %q", i, g, want)
}
}
if n := hits.Load(); n != 2 {
t.Errorf("contact API hits = %d, want 2 (per-user cache incl. negative)", n)
}
if _, err := NewClient(cfg).UserName(context.Background(), ""); err == nil {
t.Error("empty user id must be rejected without an API call")
}
}
@@ -0,0 +1,112 @@
package core
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// parseModeConfig builds a minimal valid DataSourceConfig with the given
// Settings, enough for ParseFeishuConfig to succeed.
func parseModeConfig(settings map[string]interface{}) *types.DataSourceConfig {
return &types.DataSourceConfig{
Type: types.ConnectorTypeFeishu,
Credentials: map[string]interface{}{"app_id": "cli-x", "app_secret": "sec"},
ResourceIDs: []string{"space1"},
Settings: settings,
}
}
// ParseFeishuConfig resolves Settings["parse_mode"] into Config.ParseMode.
// The default is blocks since parse_mode moved to the data source (2026-09
// deep adaptation): unset and empty both mean blocks, an explicit export is
// preserved as the image-association escape hatch, and an unrecognized value
// falls back to blocks instead of failing the sync. The retired
// FEISHU_DOCX_PARSE_MODE env var is still honored as a deprecated fallback
// while the per-source setting is unset.
func TestParseFeishuConfig_ParseMode(t *testing.T) {
// Hermetic baseline: neutralize any ambient FEISHU_DOCX_PARSE_MODE so the
// default cases below never depend on the host environment.
t.Setenv("FEISHU_DOCX_PARSE_MODE", "")
t.Run("unset settings default to blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("settings without parse_mode default to blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(
parseModeConfig(map[string]interface{}{"timezone": "Asia/Shanghai"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("explicit blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "blocks"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("explicit export is preserved", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "export"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeExport, cfg.ParseMode)
})
t.Run("case and whitespace insensitive", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": " Export "}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeExport, cfg.ParseMode)
})
t.Run("invalid value falls back to blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "yaml"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("empty value falls back to blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": " "}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("deprecated env fallback honored while settings unset", func(t *testing.T) {
t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeExport, cfg.ParseMode)
})
t.Run("deprecated env fallback is case and whitespace insensitive", func(t *testing.T) {
t.Setenv("FEISHU_DOCX_PARSE_MODE", " Export ")
cfg, err := ParseFeishuConfig(
parseModeConfig(map[string]interface{}{"timezone": "Asia/Shanghai"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeExport, cfg.ParseMode)
})
t.Run("per-source parse_mode overrides deprecated env", func(t *testing.T) {
t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "blocks"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("invalid deprecated env value falls back to blocks", func(t *testing.T) {
t.Setenv("FEISHU_DOCX_PARSE_MODE", "yaml")
cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
}
// ParseMode threading: DocxFetchInput.ParseMode is the single transport
// (connector entry resolves it via ParseFeishuConfig and passes it through
// ops → fetchNodeContent → DocxFetchInput). Empty degrades to blocks inside
// FetchDocxWithBlocks; resolution itself is covered by
// TestParseFeishuConfig_ParseMode above, and the wiki/drive suites exercise
// the blocks default end-to-end with ops built without an explicit mode.
@@ -0,0 +1,81 @@
package core
import "github.com/Tencent/WeKnora/internal/types"
// Open Platform API origins. Feishu and Lark are the same product deployed on
// two isolated clouds; the wiki/docx/drive APIs this connector uses are
// identical, only the host differs.
const (
feishuOpenBaseURL = "https://open.feishu.cn"
larkOpenBaseURL = "https://open.larksuite.com"
)
// Web origins used to build human-facing links to wiki spaces and nodes. These
// are the end-user app hosts, not the API hosts.
const (
feishuWebBaseURL = "https://feishu.cn"
larkWebBaseURL = "https://larksuite.com"
)
// Region selects which cloud the connector syncs from. Apps, tenants, tokens
// and document tokens are scoped to a single cloud and are never valid on the
// other, so a Region is fixed per connector instance at registration.
type Region struct {
// ConnectorType is the types.ConnectorType* identifier this instance serves.
ConnectorType string
// OpenBaseURL is the Open Platform API origin, without a trailing slash.
// It is only the default: a data source may override it via base_url.
OpenBaseURL string
// WebBaseURL is the app origin used to build wiki links shown to users.
WebBaseURL string
// Label prefixes log lines so operators can tell the clouds apart.
Label string
}
var (
// RegionFeishu is the Chinese mainland cloud (飞书).
RegionFeishu = Region{
ConnectorType: types.ConnectorTypeFeishu,
OpenBaseURL: feishuOpenBaseURL,
WebBaseURL: feishuWebBaseURL,
Label: "Feishu",
}
// RegionLark is the international cloud (Lark).
RegionLark = Region{
ConnectorType: types.ConnectorTypeLark,
OpenBaseURL: larkOpenBaseURL,
WebBaseURL: larkWebBaseURL,
Label: "Lark",
}
// RegionFeishuDrive is the Chinese mainland cloud, Drive (云盘) mode.
// Shares the feishu connector package with RegionFeishu; only the connector
// type differs so the registry dispatches to the Drive connector.
RegionFeishuDrive = Region{
ConnectorType: types.ConnectorTypeFeishuDrive,
OpenBaseURL: feishuOpenBaseURL,
WebBaseURL: feishuWebBaseURL,
Label: "FeishuDrive",
}
// RegionLarkDrive is the international cloud, Drive mode.
RegionLarkDrive = Region{
ConnectorType: types.ConnectorTypeLarkDrive,
OpenBaseURL: larkOpenBaseURL,
WebBaseURL: larkWebBaseURL,
Label: "LarkDrive",
}
)
// WikiURL builds the user-facing link to a wiki space or node on this cloud.
// The token is either a space_id or a node_token; both live under /wiki/.
func (r Region) WikiURL(token string) string {
return r.WebBaseURL + "/wiki/" + token
}
// DriveFolderURL builds the user-facing link to a Drive folder on this cloud.
// A folder_token lives under /drive/folder/.
func (r Region) DriveFolderURL(folderToken string) string {
return r.WebBaseURL + "/drive/folder/" + folderToken
}
@@ -0,0 +1,76 @@
package core
import (
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestRegions_AreDistinct(t *testing.T) {
if RegionFeishu.ConnectorType == RegionLark.ConnectorType {
t.Errorf("regions share ConnectorType %q", RegionFeishu.ConnectorType)
}
if RegionFeishu.OpenBaseURL == RegionLark.OpenBaseURL {
t.Errorf("regions share OpenBaseURL %q", RegionFeishu.OpenBaseURL)
}
if RegionFeishu.WebBaseURL == RegionLark.WebBaseURL {
t.Errorf("regions share WebBaseURL %q", RegionFeishu.WebBaseURL)
}
if RegionFeishu.ConnectorType != types.ConnectorTypeFeishu {
t.Errorf("RegionFeishu.ConnectorType = %q, want %q", RegionFeishu.ConnectorType, types.ConnectorTypeFeishu)
}
if RegionLark.ConnectorType != types.ConnectorTypeLark {
t.Errorf("RegionLark.ConnectorType = %q, want %q", RegionLark.ConnectorType, types.ConnectorTypeLark)
}
}
// TestConnectorType_FollowsRegion lives in package wiki (it exercises
// wiki.NewConnector); see wiki/connector_test.go TestConnectorType.
// The wiki link shown in the resource picker must point at the cloud the data
// actually lives on. Feishu's value is the pre-existing one and must not drift.
func TestRegion_WikiURL(t *testing.T) {
if got, want := RegionFeishu.WikiURL("spc123"), "https://feishu.cn/wiki/spc123"; got != want {
t.Errorf("Feishu WikiURL = %q, want %q", got, want)
}
if got, want := RegionLark.WikiURL("spc123"), "https://larksuite.com/wiki/spc123"; got != want {
t.Errorf("Lark WikiURL = %q, want %q", got, want)
}
// A Lark link must never point at the Feishu host — that was the bug.
if strings.Contains(RegionLark.WikiURL("x"), "feishu") {
t.Errorf("Lark WikiURL leaks the Feishu host: %q", RegionLark.WikiURL("x"))
}
}
// base_url stays an override so data sources created before the lark connector
// existed — a "feishu" connector pointed at open.larksuite.com — keep working.
func TestParseFeishuConfig_BaseURLDefaultsToRegion(t *testing.T) {
cases := []struct {
name string
region Region
baseURL string
want string
}{
{"feishu default", RegionFeishu, "", "https://open.feishu.cn"},
{"lark default", RegionLark, "", "https://open.larksuite.com"},
{"explicit override wins on feishu", RegionFeishu, "https://open.larksuite.com", "https://open.larksuite.com"},
{"explicit override wins on lark", RegionLark, "https://open.feishu.cn", "https://open.feishu.cn"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
creds := map[string]interface{}{"app_id": "cli_x", "app_secret": "s"}
if c.baseURL != "" {
creds["base_url"] = c.baseURL
}
cfg, err := ParseFeishuConfig(&types.DataSourceConfig{Credentials: creds}, c.region)
if err != nil {
t.Fatalf("ParseFeishuConfig: %v", err)
}
if got := cfg.GetBaseURL(); got != c.want {
t.Errorf("GetBaseURL() = %q, want %q", got, c.want)
}
})
}
}
@@ -0,0 +1,238 @@
package core
import (
"bytes"
"context"
"encoding/json"
"math"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
const (
defaultFeishuRequestsPerMinute = 80
defaultFeishuRateLimitWait = 10 * time.Second
defaultFeishuMaxCooldown = 5 * time.Minute
defaultFeishuExportMaxPolls = 30
defaultFeishuExportPollInterval = 2 * time.Second
)
// Feishu defines this code in its API protocol. Derive the prefilter from the
// same value used for the decoded response so the two checks cannot drift.
const feishuRateLimitCode = 99991400
var feishuRateLimitCodeBytes = []byte(strconv.Itoa(feishuRateLimitCode))
// Export APIs each allow 100 requests/minute. Reserve headroom and pace requests
// without bursts. Wiki listing has its own budget; other APIs have separate
// reactive cooldowns by API path template. The registry spans clients, data
// sources and task retries in this process. Different App IDs and API hosts
// have independent budgets.
var feishuRequestGates sync.Map
type feishuRequestGateKey struct {
baseURL string
appID string
api string
}
type feishuRequestGate struct {
api string
mu sync.Mutex
interval time.Duration
nextRequest time.Time
blockedUntil time.Time
}
func feishuRequestInterval() time.Duration {
rpm, err := strconv.Atoi(strings.TrimSpace(os.Getenv("FEISHU_API_REQUESTS_PER_MINUTE")))
if err != nil || rpm <= 0 || int64(rpm) > int64(time.Minute) {
rpm = defaultFeishuRequestsPerMinute
}
return time.Minute / time.Duration(rpm)
}
func feishuRequestAPI(method, path string) (string, bool) {
path, _, _ = strings.Cut(path, "?")
path = strings.TrimRight(path, "/")
if method == http.MethodPost && path == "/open-apis/drive/v1/export_tasks" {
return "export-create", true
}
if method == http.MethodGet && strings.HasPrefix(path, "/open-apis/drive/v1/export_tasks/") {
if strings.HasPrefix(path, "/open-apis/drive/v1/export_tasks/file/") && strings.HasSuffix(path, "/download") {
return "export-download", true
}
return "export-status", true
}
if method == http.MethodGet &&
strings.HasPrefix(path, "/open-apis/wiki/v2/spaces/") && strings.HasSuffix(path, "/nodes") {
return "wiki-node-list", true
}
// Normalize the connector's remaining API paths without retaining document
// tokens, sheet ranges or query parameters. Methods have independent quotas.
parts := strings.Split(path, "/")
for _, template := range []string{
"/open-apis/drive/v1/files/:token/download",
"/open-apis/drive/v1/medias/:token/download",
"/open-apis/drive/explorer/v2/folder/:token/meta",
"/open-apis/docx/v1/documents/:token/raw_content",
"/open-apis/docx/v1/documents/:token/blocks",
"/open-apis/sheets/v2/spreadsheets/:token/values/:range",
"/open-apis/bitable/v1/apps/:token/tables/:table/fields",
"/open-apis/bitable/v1/apps/:token/tables/:table/records/search",
"/open-apis/wiki/v2/spaces/get_node",
} {
pattern := strings.Split(template, "/")
if len(parts) != len(pattern) {
continue
}
match := true
for i, segment := range pattern {
if !strings.HasPrefix(segment, ":") && segment != parts[i] {
match = false
break
}
}
if match {
return method + " " + template, false
}
}
// Unknown endpoints share only their service/version/resource prefix, never
// a process-wide "other" gate or a gate per document token.
parts = strings.Split(strings.Trim(path, "/"), "/")
return method + " /" + strings.Join(parts[:min(4, len(parts))], "/"), false
}
func feishuConfiguredDuration(name string, fallback time.Duration) time.Duration {
configured, err := time.ParseDuration(strings.TrimSpace(os.Getenv(name)))
if err == nil && configured > 0 {
return configured
}
return fallback
}
func feishuExportMaxPolls() int {
configured, err := strconv.Atoi(strings.TrimSpace(os.Getenv("FEISHU_EXPORT_MAX_POLLS")))
if err == nil && configured > 0 {
return configured
}
return defaultFeishuExportMaxPolls
}
func (c *Client) requestGate(method, path string) *feishuRequestGate {
api, paced := feishuRequestAPI(method, path)
key := feishuRequestGateKey{strings.TrimRight(c.baseURL, "/"), c.appID, api}
if existing, ok := feishuRequestGates.Load(key); ok {
return existing.(*feishuRequestGate)
}
gate := &feishuRequestGate{api: api}
if paced {
gate.interval = feishuRequestInterval()
}
actual, _ := feishuRequestGates.LoadOrStore(key, gate)
return actual.(*feishuRequestGate)
}
// wait reserves the next free slot before sleeping, so callers are granted in
// arrival order instead of racing for each slot after a shared wake-up. A
// cooldown imposed while sleeping invalidates the reservation; the caller waits
// it out and reserves again. Cancelled reservations are not reused, which only
// errs towards sending fewer requests.
func (g *feishuRequestGate) wait(ctx context.Context) error {
for {
if err := ctx.Err(); err != nil {
return err
}
g.mu.Lock()
now := time.Now()
if blocked := g.blockedUntil.Sub(now); blocked > 0 {
g.mu.Unlock()
if err := sleepCtx(ctx, blocked); err != nil {
return err
}
continue
}
slot := now
if g.nextRequest.After(slot) {
slot = g.nextRequest
}
g.nextRequest = slot.Add(g.interval)
g.mu.Unlock()
if err := sleepCtx(ctx, slot.Sub(now)); err != nil {
return err
}
g.mu.Lock()
blocked := g.blockedUntil.After(time.Now())
g.mu.Unlock()
if !blocked {
return nil
}
}
}
// Even an exhausted retry delays the next document, rather than letting a long
// sync continue hammering an API which has already rejected this application.
func (g *feishuRequestGate) cooldown(wait time.Duration) {
wait = min(wait, feishuConfiguredDuration("FEISHU_RATE_LIMIT_MAX_WAIT", defaultFeishuMaxCooldown))
g.mu.Lock()
defer g.mu.Unlock()
until := time.Now().Add(wait)
if until.After(g.blockedUntil) {
g.blockedUntil = until
}
}
func isFeishuRateLimited(status int, body []byte) bool {
if status == http.StatusTooManyRequests {
return true
}
if status != http.StatusBadRequest && status != http.StatusOK {
return false
}
// Successful block/record responses can be large. Only JSON-decode the
// envelope when it could contain the legacy rate-limit code.
if !bytes.Contains(body, feishuRateLimitCodeBytes) {
return false
}
var response struct {
Code int `json:"code"`
}
return json.Unmarshal(body, &response) == nil && response.Code == feishuRateLimitCode
}
func feishuRateLimitWait(headers http.Header, now time.Time) time.Duration {
var wait time.Duration
valid := false
for _, name := range []string{"x-ogw-ratelimit-reset", "Retry-After"} {
value := strings.TrimSpace(headers.Get(name))
if value == "" {
continue
}
seconds, err := strconv.ParseFloat(value, 64)
if err != nil && name == "Retry-After" {
if date, dateErr := http.ParseTime(value); dateErr == nil {
seconds, err = date.Sub(now).Seconds(), nil
}
}
if err != nil || math.IsNaN(seconds) || math.IsInf(seconds, 0) ||
seconds >= float64(math.MaxInt64)/float64(time.Second) {
continue
}
valid = true
candidate := 100 * time.Millisecond
if seconds > 0 {
candidate = time.Duration(seconds * float64(time.Second))
}
if candidate > wait {
wait = candidate
}
}
if !valid {
wait = feishuConfiguredDuration("FEISHU_RATE_LIMIT_RETRY_WAIT", defaultFeishuRateLimitWait)
}
return min(wait, feishuConfiguredDuration("FEISHU_RATE_LIMIT_MAX_WAIT", defaultFeishuMaxCooldown))
}
@@ -0,0 +1,530 @@
package core
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
)
func TestFeishuRequestIntervalConfiguration(t *testing.T) {
for _, tt := range []struct {
value string
want time.Duration
}{
{"", 750 * time.Millisecond},
{"80", 750 * time.Millisecond},
{"60", time.Second},
{"0", 750 * time.Millisecond},
{"-1", 750 * time.Millisecond},
{"invalid", 750 * time.Millisecond},
} {
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", tt.value)
if got := feishuRequestInterval(); got != tt.want {
t.Errorf("interval(%q)=%s, want %s", tt.value, got, tt.want)
}
}
t.Setenv("FEISHU_RATE_LIMIT_RETRY_WAIT", "7s")
if got := feishuRateLimitWait(http.Header{}, time.Now()); got != 7*time.Second {
t.Fatalf("configured fallback = %s", got)
}
}
func TestFeishuGatesShareAppAndAPIIndependentOfDocument(t *testing.T) {
resetFeishuRequestGates(t)
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "80")
first := NewClient(&Config{AppID: t.Name(), BaseURL: "http://limits-test"})
second := NewClient(&Config{AppID: t.Name(), BaseURL: "http://limits-test/"})
poll := first.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/ticket-one?token=one")
if poll != second.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/ticket-two?token=two") {
t.Fatal("ticket and query must not create independent rate budgets")
}
if poll.interval != 750*time.Millisecond {
t.Fatalf("default interval = %s", poll.interval)
}
create := first.requestGate(http.MethodPost, "/open-apis/drive/v1/export_tasks")
download := first.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/file/one/download")
if create == poll || create == download || poll == download {
t.Fatal("export APIs must have separate budgets")
}
if download != second.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/file/two/download") {
t.Fatal("download tokens must share one budget")
}
otherApp := NewClient(&Config{AppID: t.Name() + "-other", BaseURL: first.baseURL})
otherHost := NewClient(&Config{AppID: t.Name(), BaseURL: "http://other-host"})
if create == otherApp.requestGate(http.MethodPost, "/open-apis/drive/v1/export_tasks") ||
create == otherHost.requestGate(http.MethodPost, "/open-apis/drive/v1/export_tasks") {
t.Fatal("different applications and API hosts must not share a budget")
}
nodes := first.requestGate(http.MethodGet, "/open-apis/wiki/v2/spaces/one/nodes?parent_node_token=one")
if nodes != second.requestGate(http.MethodGet, "/open-apis/wiki/v2/spaces/two/nodes?parent_node_token=two") ||
nodes.interval != poll.interval {
t.Fatal("wiki list paths must share a paced budget")
}
}
func TestFeishuGatePacesConcurrentClients(t *testing.T) {
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "3000") // 20ms for a bounded test.
var mu sync.Mutex
var arrivals []time.Time
ts, cfg := retryTestServer(t, "/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
arrivals = append(arrivals, time.Now())
mu.Unlock()
writeJSON(w, ApiResponse{Code: 0})
})
defer ts.Close()
clients := []*Client{NewClient(cfg), NewClient(cfg)}
var wg sync.WaitGroup
for i := 0; i < 6; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
err := clients[i%2].DoRequest(context.Background(),
http.MethodPost, "/open-apis/drive/v1/export_tasks", nil, nil)
if err != nil {
t.Errorf("request: %v", err)
}
}(i)
}
wg.Wait()
sort.Slice(arrivals, func(i, j int) bool { return arrivals[i].Before(arrivals[j]) })
if len(arrivals) != 6 {
t.Fatalf("received %d requests", len(arrivals))
}
if elapsed := arrivals[5].Sub(arrivals[0]); elapsed < 90*time.Millisecond {
t.Fatalf("clients burst through shared budget: elapsed=%s", elapsed)
}
}
func TestFeishuLegacyRateLimitRetriesJSONAndDownload(t *testing.T) {
for _, tt := range []struct {
name string
download bool
status int
}{
{"json_400", false, http.StatusBadRequest},
{"json_200", false, http.StatusOK},
{"download_400", true, http.StatusBadRequest},
} {
t.Run(tt.name, func(t *testing.T) {
var attempts atomic.Int32
var firstAttempt atomic.Int64
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
if attempts.Add(1) == 1 {
firstAttempt.Store(time.Now().UnixNano())
w.Header().Set("x-ogw-ratelimit-reset", "0.05")
w.WriteHeader(tt.status)
_, _ = io.WriteString(w, `{"code":99991400,"msg":"request trigger frequency limit"}`)
return
}
if time.Since(time.Unix(0, firstAttempt.Load())) < 50*time.Millisecond {
t.Error("request retried before Feishu reset time")
}
if tt.download {
_, _ = io.WriteString(w, "file-content")
} else {
writeJSON(w, ApiResponse{Code: 0})
}
})
defer ts.Close()
c := NewClient(cfg)
if tt.download {
data, err := c.downloadRawBytes(context.Background(), "/target")
if err != nil || string(data) != "file-content" {
t.Fatalf("download=%q err=%v", data, err)
}
} else if err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil); err != nil {
t.Fatal(err)
}
if attempts.Load() != 2 {
t.Fatalf("attempts=%d, want 2", attempts.Load())
}
})
}
}
func TestFeishuCooldownBlocksOtherClientAndHonorsCancellation(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.Header().Set("x-ogw-ratelimit-reset", "0.2")
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"code":99991400}`)
})
defer ts.Close()
first := NewClient(cfg)
ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancel()
if err := first.DoRequest(ctx, http.MethodGet, "/target", nil, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("wait should be cancellable: %v", err)
}
second := NewClient(cfg)
ctx2, cancel2 := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel2()
if err := second.DoRequest(ctx2, http.MethodGet, "/target", nil, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("other client must inherit cooldown: %v", err)
}
if got := attempts.Load(); got != 1 {
t.Fatalf("cooldown allowed extra requests: %d", got)
}
}
func TestFeishuRateLimitExhaustionProtectsNextDocument(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.Header().Set("Retry-After", "0.05")
w.WriteHeader(http.StatusTooManyRequests)
})
defer ts.Close()
c := NewClient(cfg)
if err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil); err == nil {
t.Fatal("persistent rate limit must not report success")
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
err := NewClient(cfg).DoRequest(ctx, http.MethodGet, "/target", nil, nil)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("next document must wait after exhausted retries: %v", err)
}
if got := attempts.Load(); got != 4 {
t.Fatalf("attempts=%d, want bounded 4", got)
}
}
// Gate tests are serial (no t.Parallel): clear before and after each test so
// even a reused httptest port cannot inherit pacing or cooldown state.
func resetFeishuRequestGates(t *testing.T) {
t.Helper()
feishuRequestGates.Clear()
t.Cleanup(feishuRequestGates.Clear)
}
func TestFeishuRequestGateReset(t *testing.T) {
config := &Config{AppID: t.Name(), BaseURL: "http://reused-test-host"}
path := "/open-apis/drive/v1/export_tasks"
old := NewClient(config).requestGate(http.MethodPost, path)
old.cooldown(time.Minute)
t.Run("reset", func(t *testing.T) {
resetFeishuRequestGates(t)
fresh := NewClient(config).requestGate(http.MethodPost, path)
if fresh == old || !fresh.blockedUntil.IsZero() || !fresh.nextRequest.IsZero() {
t.Fatal("reused host/app/API inherited gate state")
}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := fresh.wait(ctx); err != nil {
t.Fatalf("fresh gate still blocked: %v", err)
}
})
key := feishuRequestGateKey{config.BaseURL, config.AppID, "export-create"}
if _, exists := feishuRequestGates.Load(key); exists {
t.Fatal("test cleanup left a gate in the registry")
}
}
func TestFeishuCooldownConfigurationAndBounds(t *testing.T) {
t.Setenv("FEISHU_RATE_LIMIT_MAX_WAIT", "25ms")
t.Setenv("FEISHU_RATE_LIMIT_RETRY_WAIT", "1h")
if got := feishuRateLimitWait(http.Header{}, time.Now()); got != 25*time.Millisecond {
t.Fatalf("fallback escaped cap: %s", got)
}
headers := http.Header{"Retry-After": {"86400"}}
if got := feishuRateLimitWait(headers, time.Now()); got != 25*time.Millisecond {
t.Fatalf("header escaped configured cap: %s", got)
}
headers.Set("Retry-After", time.Now().Add(24*time.Hour).UTC().Format(http.TimeFormat))
if got := feishuRateLimitWait(headers, time.Now()); got != 25*time.Millisecond {
t.Fatalf("HTTP date escaped configured cap: %s", got)
}
gate := &feishuRequestGate{}
gate.cooldown(time.Hour)
// Check the remaining cooldown, excluding any time the test was descheduled
// before cooldown() ran. Scheduler latency must not look like an excessive cap.
if remaining := time.Until(gate.blockedUntil); remaining > 25*time.Millisecond {
t.Fatalf("shared gate escaped cap: %s", remaining)
}
for _, invalid := range []string{"", "0s", "-1s", "bad"} {
t.Setenv("FEISHU_RATE_LIMIT_MAX_WAIT", invalid)
if got := feishuRateLimitWait(headers, time.Now()); got != 5*time.Minute {
t.Fatalf("invalid cap %q: got %s", invalid, got)
}
}
}
func BenchmarkFeishuRateLimitSuccess(b *testing.B) {
body := append([]byte(`{"code":0,"data":"`), bytes.Repeat([]byte("x"), 16<<20)...)
body = append(body, []byte(`"}`)...)
b.SetBytes(int64(len(body)))
b.ResetTimer()
for b.Loop() {
if isFeishuRateLimited(http.StatusOK, body) {
b.Fatal("successful response classified as a rate limit")
}
}
}
func TestFeishuReactiveCooldownsArePerAPI(t *testing.T) {
resetFeishuRequestGates(t)
c := NewClient(&Config{AppID: t.Name(), BaseURL: "http://limits-test"})
pairs := [][2]string{
{"/open-apis/drive/v1/files/one/download", "/open-apis/drive/v1/files/two/download?x=y"},
{"/open-apis/drive/v1/medias/one/download", "/open-apis/drive/v1/medias/two/download"},
{"/open-apis/docx/v1/documents/one/blocks", "/open-apis/docx/v1/documents/two/blocks?page_token=x"},
{"/open-apis/docx/v1/documents/one/raw_content", "/open-apis/docx/v1/documents/two/raw_content"},
{"/open-apis/sheets/v2/spreadsheets/one/values/A1", "/open-apis/sheets/v2/spreadsheets/two/values/B2"},
{"/open-apis/bitable/v1/apps/one/tables/t1/fields", "/open-apis/bitable/v1/apps/two/tables/t2/fields"},
{
"/open-apis/bitable/v1/apps/one/tables/t1/records/search",
"/open-apis/bitable/v1/apps/two/tables/t2/records/search",
},
{"/open-apis/drive/explorer/v2/folder/one/meta", "/open-apis/drive/explorer/v2/folder/two/meta"},
{"/open-apis/wiki/v2/spaces/get_node?token=one", "/open-apis/wiki/v2/spaces/get_node?token=two"},
{"/open-apis/wiki/v2/spaces?page_token=one", "/open-apis/wiki/v2/spaces?page_token=two"},
}
seen := make(map[*feishuRequestGate]bool)
for _, pair := range pairs {
gate := c.requestGate(http.MethodGet, pair[0])
if gate != c.requestGate(http.MethodGet, pair[1]) || gate.interval != 0 {
t.Fatalf("reactive gate must normalize tokens and query: %v", pair)
}
if seen[gate] {
t.Fatalf("unrelated APIs share a cooldown: %v", pair)
}
seen[gate] = true
if gate == c.requestGate(http.MethodPost, pair[0]) {
t.Fatalf("HTTP methods share a cooldown: %v", pair)
}
}
media := c.requestGate(http.MethodGet, pairs[1][0])
media.cooldown(time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if err := c.requestGate(http.MethodGet, pairs[2][0]).wait(ctx); err != nil {
t.Fatalf("media cooldown blocked docx: %v", err)
}
if err := media.wait(ctx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("media did not retain its own cooldown: %v", err)
}
}
func TestFeishuRateLimitDetection(t *testing.T) {
for _, tt := range []struct {
status int
body string
want bool
}{
{http.StatusOK, `{"code":0,"data":{"text":"99991400"}}`, false},
{http.StatusOK, `{"code":99991400}`, true},
{http.StatusBadRequest, `{"code":99991400}`, true},
{http.StatusOK, `{"code":0}`, false},
{http.StatusOK, `invalid 99991400`, false},
{http.StatusForbidden, `{"code":99991400}`, false},
{http.StatusTooManyRequests, ``, true},
} {
if got := isFeishuRateLimited(tt.status, []byte(tt.body)); got != tt.want {
t.Errorf("rate limited(%d, %s) = %v, want %v", tt.status, tt.body, got, tt.want)
}
}
}
// Run HTTP handlers in process so synctest can advance time without real sockets.
type feishuHandlerTransport struct {
http.Handler
}
func (tr feishuHandlerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
recorder := httptest.NewRecorder()
tr.ServeHTTP(recorder, r)
return recorder.Result(), nil
}
func TestFeishuExportPollingRetainsTicketAcrossCooldown(t *testing.T) {
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "80")
t.Setenv("FEISHU_RATE_LIMIT_RETRY_WAIT", "70s")
t.Setenv("FEISHU_RATE_LIMIT_MAX_WAIT", "5m")
t.Setenv("FEISHU_EXPORT_MAX_POLLS", "2")
t.Setenv("FEISHU_EXPORT_POLL_INTERVAL", "2s")
synctest.Test(t, func(t *testing.T) {
resetFeishuRequestGates(t)
var creates, polls, downloads int
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, _ *http.Request) {
creates++
_, _ = io.WriteString(w, `{"code":0,"data":{"ticket":"same-ticket"}}`)
})
mux.HandleFunc("/open-apis/drive/v1/export_tasks/same-ticket", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("token") != "document" {
t.Error("poll did not retain the document token")
}
polls++
switch polls {
case 1:
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"code":99991400}`)
case 2:
_, _ = io.WriteString(w, `{"code":0,"data":{"result":{"job_status":2}}}`)
default:
_, _ = io.WriteString(w,
`{"code":0,"data":{"result":{"job_status":0,"file_token":"file","file_name":"doc.pdf"}}}`)
}
})
mux.HandleFunc("/open-apis/drive/v1/export_tasks/file/file/download",
func(w http.ResponseWriter, _ *http.Request) {
downloads++
_, _ = io.WriteString(w, "export-content")
})
cfg := &Config{AppID: t.Name(), BaseURL: "http://feishu-export.test"}
c := NewClient(cfg)
c.httpClient.Transport = feishuHandlerTransport{mux}
c.tokenCache, c.tokenExpAt = "cached-token", time.Now().Add(time.Hour)
// Both shared and in-poll cooldowns exceed the previous 60-second deadline.
started := time.Now()
other := NewClient(cfg)
other.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/other-ticket").cooldown(70 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
data, name, err := c.ExportAndDownload(ctx, "document", "docx")
if err != nil || name != "doc.pdf" || string(data) != "export-content" {
t.Fatalf("export across cooldown: data=%q name=%q err=%v", data, name, err)
}
if creates != 1 || polls != 3 || downloads != 1 {
t.Fatalf("create/poll/download=%d/%d/%d, want 1/3/1", creates, polls, downloads)
}
if elapsed := time.Since(started); elapsed < 140*time.Second {
t.Fatalf("export skipped the shared or in-poll cooldown: %s", elapsed)
}
})
}
func TestFeishuExportPollingIsBoundedAndCancellable(t *testing.T) {
for _, cancelWhileWaiting := range []bool{false, true} {
t.Run(fmt.Sprint(cancelWhileWaiting), func(t *testing.T) {
t.Setenv("FEISHU_EXPORT_MAX_POLLS", "3")
t.Setenv("FEISHU_EXPORT_POLL_INTERVAL", "1ms")
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "60000")
var creates, polls atomic.Int32
createHandler := func(w http.ResponseWriter, _ *http.Request) {
creates.Add(1)
_, _ = io.WriteString(w, `{"code":0,"data":{"ticket":"pending"}}`)
}
ts, cfg := retryTestServer(t, "/open-apis/drive/v1/export_tasks", createHandler)
defer ts.Close()
ts.Config.Handler.(*http.ServeMux).HandleFunc("/open-apis/drive/v1/export_tasks/pending",
func(w http.ResponseWriter, _ *http.Request) {
polls.Add(1)
_, _ = io.WriteString(w, `{"code":0,"data":{"result":{"job_status":2}}}`)
})
c := NewClient(cfg)
if cancelWhileWaiting {
c.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/pending").cooldown(time.Second)
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
_, _, err := c.ExportAndDownload(ctx, "document", "docx")
if cancelWhileWaiting {
if !errors.Is(err, context.DeadlineExceeded) || polls.Load() != 0 {
t.Fatalf("polling ignored cancellation: polls=%d err=%v", polls.Load(), err)
}
} else if err == nil || !strings.Contains(err.Error(), "after 3 polls") || polls.Load() != 3 {
t.Fatalf("polling is unbounded: polls=%d err=%v", polls.Load(), err)
}
// Exercise the same wrapping and metadata path used by the connectors.
metadata := FeishuErrorItemMeta(fmt.Errorf("export document: %w", err), nil)
if metadata["error_reason_code"] != "feishu_timeout" {
t.Fatalf("polling lost its timeout classification: %v", metadata)
}
if strings.Contains(metadata["error_reason"], "ticket=") {
t.Fatal("export ticket leaked into the user-facing failure reason")
}
if creates.Load() != 1 {
t.Fatalf("created %d tasks, want 1", creates.Load())
}
})
}
}
func TestFeishuRefreshesTokenAfterCooldown(t *testing.T) {
for _, download := range []bool{false, true} {
t.Run(fmt.Sprint(download), func(t *testing.T) {
resetFeishuRequestGates(t)
var auths, attempts atomic.Int32
var c *Client
mux := http.NewServeMux()
authHandler := func(w http.ResponseWriter, _ *http.Request) {
token := fmt.Sprintf("token-%d", auths.Add(1))
writeJSON(w, TokenResponse{TenantAccessToken: token, Expire: 7200})
}
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", authHandler)
mux.HandleFunc("/target", func(w http.ResponseWriter, r *http.Request) {
if attempts.Add(1) == 1 {
c.tokenMu.Lock()
c.tokenExpAt = time.Now().Add(5 * time.Millisecond)
c.tokenMu.Unlock()
w.Header().Set("Retry-After", "0.03")
w.WriteHeader(http.StatusTooManyRequests)
return
}
if r.Header.Get("Authorization") != "Bearer token-2" {
t.Error("request reused the token that expired during cooldown")
}
_, _ = io.WriteString(w, `{"code":0}`)
})
ts := httptest.NewServer(mux)
defer ts.Close()
c = NewClient(&Config{AppID: t.Name(), BaseURL: ts.URL})
var err error
if download {
_, err = c.downloadRawBytes(context.Background(), "/target")
} else {
err = c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil)
}
if err != nil || auths.Load() != 2 || attempts.Load() != 2 {
t.Fatalf("auth/attempts=%d/%d err=%v", auths.Load(), attempts.Load(), err)
}
})
}
}
func TestFeishuGateGrantsInArrivalOrder(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
gate := &feishuRequestGate{interval: time.Second}
start := time.Now()
var mu sync.Mutex
var order []int
var grants []time.Duration
var wg sync.WaitGroup
for i := range 5 {
wg.Add(1)
go func() {
defer wg.Done()
if err := gate.wait(context.Background()); err != nil {
t.Error(err)
return
}
mu.Lock()
order = append(order, i)
grants = append(grants, time.Since(start))
mu.Unlock()
}()
synctest.Wait()
}
wg.Wait()
for i := range 5 {
if order[i] != i || grants[i] != time.Duration(i)*time.Second {
t.Fatalf("grants out of arrival order or pace: order=%v grants=%v", order, grants)
}
}
})
}
@@ -0,0 +1,121 @@
package core
import (
"context"
"io"
"net/http"
"net/http/httptest"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
)
// Cached-token requests first check Err when entering gate.wait. Observe that
// boundary so the test expires the token only after every caller authenticated.
type feishuGateWaitContext struct {
context.Context
once sync.Once
entered chan<- struct{}
}
func (c *feishuGateWaitContext) Err() error {
c.once.Do(func() { c.entered <- struct{}{} })
return c.Context.Err()
}
func TestFeishuTokenRefreshPreservesPacingAndCooldown(t *testing.T) {
for _, mode := range []string{"json", "download"} {
t.Run(mode, func(t *testing.T) {
resetFeishuRequestGates(t)
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "600")
t.Setenv("FEISHU_RATE_LIMIT_MAX_WAIT", "5m")
const count = 4
const interval = 100 * time.Millisecond
var mu sync.Mutex
var arrivals []time.Time
var earliestRequest time.Time
var auths atomic.Int32
var gate *feishuRequestGate
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
auths.Add(1)
// Slow enough for every caller to pass the gate in the broken
// implementation and queue behind the refreshing caller's tokenMu.
time.Sleep(time.Duration(count+1) * interval)
mu.Lock()
earliestRequest = time.Now().Add(3 * interval)
mu.Unlock()
// A concurrent data source can extend this shared cooldown while
// our token is refreshing. All callers must honor the new delay.
gate.cooldown(3 * interval)
writeJSON(w, TokenResponse{TenantAccessToken: "fresh-token", Expire: 7200})
return
}
if r.Header.Get("Authorization") != "Bearer fresh-token" {
t.Error("request sent the token that expired while waiting")
}
mu.Lock()
arrivals = append(arrivals, time.Now())
mu.Unlock()
_, _ = io.WriteString(w, `{"code":0}`)
}))
defer server.Close()
c := NewClient(&Config{AppID: t.Name(), BaseURL: server.URL})
c.tokenCache = "cached-token"
c.tokenExpAt = time.Now().Add(time.Hour)
method, path := http.MethodPost, "/open-apis/drive/v1/export_tasks"
if mode == "download" {
method, path = http.MethodGet, "/open-apis/drive/v1/export_tasks/file/export-token/download"
}
gate = c.requestGate(method, path)
gate.cooldown(500 * time.Millisecond)
entered := make(chan struct{}, count)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var wg sync.WaitGroup
for range count {
wg.Add(1)
go func() {
defer wg.Done()
observed := &feishuGateWaitContext{Context: ctx, entered: entered}
var err error
if mode == "download" {
_, err = c.downloadRawBytes(observed, path)
} else {
err = c.DoRequest(observed, method, path, nil, nil)
}
if err != nil {
t.Errorf("request: %v", err)
}
}()
}
for range count {
select {
case <-entered:
case <-ctx.Done():
t.Fatal("requests failed to reach the gate")
}
}
c.tokenMu.Lock()
c.tokenExpAt = time.Now().Add(-time.Second)
c.tokenMu.Unlock()
wg.Wait()
mu.Lock()
defer mu.Unlock()
if len(arrivals) != count || auths.Load() != 1 {
t.Fatalf("requests/refreshes=%d/%d, want %d/1", len(arrivals), auths.Load(), count)
}
sort.Slice(arrivals, func(i, j int) bool { return arrivals[i].Before(arrivals[j]) })
if arrivals[0].Before(earliestRequest) {
t.Errorf("request ignored the cooldown imposed during token refresh")
}
for i := 1; i < len(arrivals); i++ {
if gap := arrivals[i].Sub(arrivals[i-1]); gap < interval/2 {
t.Errorf("requests burst after token refresh: gap=%s, interval=%s", gap, interval)
}
}
})
}
}
@@ -0,0 +1,720 @@
package core
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
const FeishuWikiNodeResourceSeparator = ":"
// shared.go holds the helpers used by BOTH the wiki Connector (connector.go)
// and the Drive DriveConnector (connector.go): error classification,
// config parsing, stream-Checkpoint tuning, the fetch tally, filename/time
// utilities, attachment rules, and the docx blocks fetch path. Anything that
// is specific to one connector stays in that connector's own file.
// FeishuStreamCheckpointInterval is how many processed nodes pass between
// cursor checkpoints during a streaming fetch. Small enough that a timed-out
// sync loses little work on resume, large enough that Checkpoint persistence
// (a DB write) does not dominate. Overridable in tests. See FetchStream.
var FeishuStreamCheckpointInterval = 50
// FeishuStreamCheckpointMaxInterval bounds checkpointing by wall-clock time as
// well as node count. Without it, a sync of fewer than
// FeishuStreamCheckpointInterval very slow (rate-limited) exports could reach
// the 2h task timeout having never checkpointed, and resume from scratch every
// retry — the #2136 "never fully syncs" case. Overridable in tests.
var FeishuStreamCheckpointMaxInterval = 30 * time.Second
// fetchTally accumulates the outcome of fetching a wiki node subtree so the
// connector can Emit a single actionable summary. Without it, unsupported nodes
// (mindnote/slides/etc.) vanish with no item, no error and no log, leaving users
// unable to explain why "13 documents synced only 3" (Tencent/WeKnora#2136).
type fetchTally struct {
discovered int
fetched int
failed int
skippedByType map[string]int
}
func newFetchTally(discovered int) *fetchTally {
return &fetchTally{discovered: discovered, skippedByType: map[string]int{}}
}
func (t *fetchTally) fetch() { t.fetched++ }
func (t *fetchTally) fail() { t.failed++ }
func (t *fetchTally) Skip(objType string) { t.skippedByType[objType]++ }
func (t *fetchTally) skipped() int {
n := 0
for _, c := range t.skippedByType {
n += c
}
return n
}
func (t *fetchTally) summary() string {
return fmt.Sprintf("discovered=%d fetched=%d failed=%d skipped_unsupported=%d by_type=%v",
t.discovered, t.fetched, t.failed, t.skipped(), t.skippedByType)
}
var reFeishuErrorCode = regexp.MustCompile(`code["\s]*[:=]\s*(\d+)`)
// feishuErrorCode extracts the numeric Feishu error code from a raw error string
// (e.g. `body={"code":1663,...}` or `code=1663`), best-effort.
func feishuErrorCode(raw string) string {
if m := reFeishuErrorCode.FindStringSubmatch(raw); len(m) == 2 {
return m[1]
}
return ""
}
// feishuFailure classifies a raw connector/API error into a stable i18n code
// (mapped to a localized string on the frontend), an optional numeric Feishu
// error code for interpolation, and an English fallback message for clients
// without the i18n key. The raw status/JSON body/log_id is never returned here —
// it stays in the server logs. Dumping it in the UI is the anti-pattern
// Airbyte/Fivetran/Onyx warn against. Transient errors are retried next sync
// (the cursor is retained); auth/permission errors point at the fix instead.
func feishuFailure(err error) (code, codeValue, fallback string) {
if err == nil {
return "sync_failed", "", "Sync failed; will retry on the next sync"
}
s := strings.ToLower(err.Error())
switch {
case strings.Contains(s, "auth error"),
strings.Contains(s, "invalid access token"),
strings.Contains(s, "permission"),
strings.Contains(s, "forbidden"),
strings.Contains(s, "status=403"):
return "feishu_auth_or_permission", "", "Authentication or permission error; check credentials and app scopes"
case strings.Contains(s, "rate limited"), strings.Contains(s, "status=429"):
return "feishu_rate_limited", "", "Feishu API rate limited; will retry on the next sync"
case errors.Is(err, errExportPollsExhausted),
strings.Contains(s, "timed out"),
strings.Contains(s, "timeout"),
strings.Contains(s, "deadline exceeded"):
return "feishu_timeout", "", "Export or request timed out; will retry on the next sync"
case strings.Contains(s, "server error"):
return "feishu_server_unavailable", "", "Feishu service temporarily unavailable; will retry on the next sync"
case strings.Contains(s, "api error"),
strings.Contains(s, "export task failed"),
strings.Contains(s, "download failed"):
if v := feishuErrorCode(err.Error()); v != "" {
return "feishu_api_error", v, fmt.Sprintf("Feishu API error (code=%s); will retry on the next sync", v)
}
return "feishu_api_error_generic", "", "Feishu API error; will retry on the next sync"
default:
return "sync_failed", "", "Sync failed; will retry on the next sync"
}
}
// FeishuErrorItemMeta builds the metadata for a failed item: the raw error (for
// server logs) plus the classified i18n code / param / fallback (for a
// localisable SyncItemError in the UI), merged with any caller-supplied extras.
func FeishuErrorItemMeta(err error, extra map[string]string) map[string]string {
code, codeValue, fallback := feishuFailure(err)
m := map[string]string{
"error": err.Error(),
"error_reason_code": code,
"error_reason": fallback,
}
if codeValue != "" {
m["error_reason_code_value"] = codeValue
}
maps.Copy(m, extra)
return m
}
// parseableAttachmentExts are attachment extensions worth ingesting as their
// own knowledge entries. This is the shared contract list (pdf/md/markdown/
// xlsx/xls/csv/doc/docx/ppt/pptx); everything else — images (which ride the
// embedded-image pipeline instead), videos, archives — degrades to an inline
// Markdown reference. markdown.go's attachment rendering reads this same map,
// so the inline `- 文件名` list and the produced sub-items can never disagree.
var parseableAttachmentExts = map[string]bool{
".pdf": true, ".md": true, ".markdown": true,
".xlsx": true, ".xls": true, ".csv": true,
".doc": true, ".docx": true, ".ppt": true, ".pptx": true,
}
// MinAttachmentBytes filters out decorative micro-files.
const MinAttachmentBytes = 2 * 1024
// maxInlineImageBytes caps a single image inlined as a base64 data URI. It
// mirrors the document-processing image resolver's per-image budget
// (docparser maxRemoteImageSize): anything larger would be downloaded,
// base64-expanded ~1.37x into the markdown, then silently skipped by the
// resolver — a permanent raw-base64 blob in stored content.
const maxInlineImageBytes = 10 * 1024 * 1024
// SupportedImageExt sniffs image bytes and returns the filename extension and
// content type WeKnora accepts for a standalone image knowledge item (png/jpg/
// gif — the image set isValidFileType admits). ok is false for non-image or
// unsupported formats (e.g. webp/bmp), which the caller skips rather than
// mislabel — a wrong extension would fail parsing. The detected content type is
// returned even when ok is false so the caller can log it without re-sniffing.
func SupportedImageExt(data []byte) (ext, contentType string, ok bool) {
switch ct := http.DetectContentType(data); ct {
case "image/png":
return ".png", ct, true
case "image/jpeg":
return ".jpg", ct, true
case "image/gif":
return ".gif", ct, true
default:
// Go's sniffer reports SVG markup as text/xml; recover the real type
// when the payload is an <svg> document (board download_as_image may
// return SVG), and the platform resolver stores .svg natively.
if strings.HasPrefix(ct, "text/xml") && bytes.Contains(data[:min(len(data), 512)], []byte("<svg")) {
return ".svg", "image/svg+xml", true
}
return "", ct, false
}
}
// ParseFeishuConfig extracts and validates Feishu/Lark-specific configuration.
//
// base_url stays an explicit override so existing data sources that pointed a
// "feishu" connector at open.larksuite.com keep working; when it is unset the
// region's own host is filled in, making the resolved Config.BaseURL concrete
// for everything downstream.
func ParseFeishuConfig(config *types.DataSourceConfig, region Region) (*Config, error) {
if config == nil {
return nil, fmt.Errorf("config is nil")
}
credBytes, err := json.Marshal(config.Credentials)
if err != nil {
return nil, fmt.Errorf("marshal credentials: %w", err)
}
var feishuConfig Config
if err := json.Unmarshal(credBytes, &feishuConfig); err != nil {
return nil, fmt.Errorf("parse %s credentials: %w", region.ConnectorType, err)
}
if feishuConfig.AppID == "" || feishuConfig.AppSecret == "" {
return nil, fmt.Errorf("%s app_id and app_secret are required", region.ConnectorType)
}
if feishuConfig.BaseURL == "" {
feishuConfig.BaseURL = region.OpenBaseURL
}
// Timezone is a display setting (bitable date rendering), not a credential, so
// it lives in Settings. Empty falls back to GMT+8 in resolveLocation.
if feishuConfig.Timezone == "" && config.Settings != nil {
if tz, ok := config.Settings["timezone"].(string); ok {
feishuConfig.Timezone = strings.TrimSpace(tz)
}
}
// parse_mode is likewise a per-data-source display setting, read from
// Settings (set on the data source edit form). When the per-source setting
// is unset, the deprecated FEISHU_DOCX_PARSE_MODE env var is still honored
// for one release (with a warning) so deployments that pinned "export"
// keep their behavior across the upgrade. Everything unset (or
// unrecognized) resolves to blocks — the default; an unrecognized value
// falls back to blocks with a warning rather than failing the whole sync.
parseMode := ""
if config.Settings != nil {
if pm, ok := config.Settings["parse_mode"].(string); ok {
parseMode = strings.ToLower(strings.TrimSpace(pm))
}
}
if parseMode == "" {
if legacy := strings.TrimSpace(os.Getenv("FEISHU_DOCX_PARSE_MODE")); legacy != "" {
logger.Warnf(context.Background(),
"[Feishu] FEISHU_DOCX_PARSE_MODE=%q is deprecated and will be removed; "+
"set parse_mode on the data source edit form instead",
legacy)
parseMode = strings.ToLower(legacy)
}
}
switch parseMode {
case "", ParseModeBlocks:
feishuConfig.ParseMode = ParseModeBlocks
case ParseModeExport:
// keep the explicit export selection
feishuConfig.ParseMode = ParseModeExport
default:
logger.Warnf(context.Background(),
"[Feishu] invalid parse_mode %q, falling back to %q",
parseMode, ParseModeBlocks)
feishuConfig.ParseMode = ParseModeBlocks
}
if err := datasource.ValidateConnectorBaseURL(feishuConfig.GetBaseURL()); err != nil {
return nil, err
}
return &feishuConfig, nil
}
// DocxChangeKey invalidates cached docx content when its effective parser changes.
// Other file types do not depend on the docx parser setting.
func DocxChangeKey(editTime, objType, parseMode string) string {
if objType != "docx" {
return editTime
}
if parseMode == "" {
parseMode = ParseModeBlocks
}
return editTime + ":parse=" + parseMode
}
// IsSupportedDocType checks if a Feishu document type can be synced.
// mindnote and slides have no content read API and are skipped.
func IsSupportedDocType(objType string) bool {
switch objType {
case "docx", "doc", "sheet", "bitable", "file":
return true
default:
// mindnote, slides — no content retrieval API available
return false
}
}
// ParseFeishuTimestamp parses a Feishu unix timestamp string (seconds) into time.Time.
func ParseFeishuTimestamp(ts string) time.Time {
if ts == "" {
return time.Time{}
}
sec, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return time.Time{}
}
return time.Unix(sec, 0)
}
// SanitizeFileName removes characters that are invalid in filenames and
// truncates at a UTF-8 rune boundary. Raw byte truncation would split a
// multi-byte codepoint (Chinese chars are 3 bytes) and produce invalid UTF-8
// that downstream validation (utf8.ValidString) rejects.
//
// The extension is preserved across truncation: only the base name is trimmed,
// so a long attachment name like "很长的名字….pdf" keeps its ".pdf" suffix that
// downstream file-type classification depends on.
func SanitizeFileName(name string) string {
if name == "" {
return "untitled"
}
replacer := strings.NewReplacer(
"/", "_", "\\", "_", ":", "_", "*", "_",
"?", "_", "\"", "_", "<", "_", ">", "_", "|", "_",
)
result := replacer.Replace(name)
const maxBytes = 200
if len(result) <= maxBytes {
return result
}
ext := filepath.Ext(result)
if len(ext) >= maxBytes {
// pathological: extension alone overflows the budget → drop it
ext = ""
}
base := truncateUTF8(result[:len(result)-len(ext)], maxBytes-len(ext))
return base + ext
}
// truncateUTF8 shortens s to at most maxBytes bytes without splitting a
// multi-byte rune: after a hard byte cut it trims any trailing partial codepoint.
func truncateUTF8(s string, maxBytes int) string {
if len(s) <= maxBytes {
return s
}
s = s[:maxBytes]
for len(s) > 0 {
r, size := utf8.DecodeLastRuneInString(s)
if r != utf8.RuneError || size != 1 {
break
}
s = s[:len(s)-1]
}
return s
}
// userNameResolver returns a per-document @mention display-name resolver for
// the contact API. The cache (OpenID → name) means each user costs at most one
// contact call per document; failures and empty names negative-cache too, so a
// user without contact permission renders every later mention of themselves as
// the generic @成员 without re-hitting the API. Errors never propagate — they
// only log at debug level; ingestion is never blocked or failed by this.
func userNameResolver(ctx context.Context, client *Client) func(string) string {
var cache sync.Map // OpenID → display name ("" = lookup failed)
return func(userID string) string {
if userID == "" {
return ""
}
if v, ok := cache.Load(userID); ok {
return v.(string)
}
name, err := client.UserName(ctx, userID)
if err != nil {
logger.Debugf(ctx, "[Feishu] resolve mention user %s: %v (degrading to @成员)", userID, err)
name = ""
}
cache.Store(userID, name)
return name
}
}
// DocxFetchInput is the unified description of one docx document from either
// source (wiki node or Drive file) that FetchDocxWithBlocks needs.
type DocxFetchInput struct {
// WeKnora external_id: wiki=node.NodeToken, drive=file.Token
DocToken string
// Feishu docx document token
ObjToken string
Title string
URL string
ResourceID string
EditTime time.Time
// CreateTime is the document creation time in Feishu; zero when unknown.
CreateTime time.Time
BaseMeta map[string]string
// ParseMode selects the docx parsing path ("blocks" | "export"), resolved
// from Settings["parse_mode"] by ParseFeishuConfig and threaded from the
// connector entry points. Empty means blocks (the default).
ParseMode string
}
// FetchDocxWithBlocks retrieves a docx document via the blocks API, converts
// it to Markdown, and returns the main item with attachment sub-items. Image
// and board blocks render as nonce-tagged markers that this function patches
// in place with inline base64 data URIs (placeholders on failure); the
// document-processing image resolver stores them later. Falls back to the
// export API if the blocks API errors or renders empty. Shared by the wiki
// Connector and the Drive DriveConnector.
func FetchDocxWithBlocks(ctx context.Context, client *Client, in DocxFetchInput) ([]*types.FetchedItem, error) {
// The parse mode comes from the data source's Settings["parse_mode"],
// resolved by ParseFeishuConfig and threaded in via DocxFetchInput.ParseMode.
// The blocks path (default) inlines images/boards into the parent
// Markdown as base64 data URIs (via weknora-img://N markers) and fans
// attachments out into sub-items wired to the parent via attachment_ids
// metadata. The export path yields a .docx that docreader
// parses inline, so images are bound to the parent document via
// parent_chunk_id (same as a regular docx upload) — kept as the per-data-
// source escape hatch.
parsingMode := in.ParseMode
if parsingMode == "" {
parsingMode = ParseModeBlocks
}
if strings.EqualFold(parsingMode, ParseModeExport) {
item, err := exportDocxFallback(ctx, client, in)
if err != nil {
return nil, err
}
return []*types.FetchedItem{item}, nil
}
blocks, err := client.listDocumentBlocks(ctx, in.ObjToken)
if err != nil {
logger.Warnf(ctx, "[Feishu] blocks API failed for %s (%s), falling back to export: %v",
in.Title, in.ObjToken, err)
item, ferr := exportDocxFallback(ctx, client, in)
if ferr != nil {
return nil, ferr
}
// Do NOT set ReplacesSubtree here (see the wiki history: a transient
// blocks failure must not sweep good attachment children from the prior
// blocks-path sync with nothing to replace them).
return []*types.FetchedItem{item}, nil
}
// Images/boards ride the marker pipeline: the renderer numbers them in
// document order, and the patches below inline each image's bytes as a
// base64 data URI (or a plain placeholder on failure) in a single pass.
mdBytes, atts, imgs, docNames, err := blocksToMarkdown(ctx, client, blocks, in.URL, userNameResolver(ctx, client))
if err != nil {
return nil, fmt.Errorf("convert blocks %s: %w", in.Title, err)
}
md := string(mdBytes)
// Export image-heavy documents before downloading any media or attachments.
// The native document parser carries images as ImageRefs, which do not use
// the Markdown data-URI count budget. Never silently leave excess base64
// in persisted Markdown, and do not raise the shared parser's resource cap.
var exported *types.FetchedItem
if len(imgs) > types.MaxInlineDocumentImages {
logger.Infof(ctx, "[Feishu] doc %s has %d images; falling back to export", in.ObjToken, len(imgs))
item, ferr := exportDocxFallback(ctx, client, in)
if ferr != nil {
return nil, ferr
}
exported = item
}
if len(strings.TrimSpace(md)) == 0 {
logger.Infof(ctx, "[Feishu] doc %s (%s): blocks rendered empty Markdown, falling back to export",
in.Title, in.ObjToken)
item, ferr := exportDocxFallback(ctx, client, in)
if ferr != nil {
return nil, ferr
}
return []*types.FetchedItem{item}, nil
}
// Attachments stay sub-items (they are documents in their own right and
// are emitted BEFORE the parent so SubtreeKeep/sweep semantics hold).
var children []*types.FetchedItem
keep := make([]string, 0, len(atts))
attachmentIDs := make([]string, 0, len(atts))
childMeta := func() map[string]string {
m := maps.Clone(in.BaseMeta)
m["parent_node_token"] = in.DocToken
m["parent_doc_id"] = in.DocToken
m["attachment"] = "true"
return m
}
// patchMarker swaps one numbered image marker in the rendered Markdown for
// its final form: an inline base64 data URI on success, a plain
// ![图片]() placeholder or a degrade note on failure. Markers are unique
// per N, and N is assigned once per image/board block.
patchMarker := func(n int, replacement string) {
needle := fmt.Sprintf("![图片](weknora-img://%d-%s)", n, imageMarkerNonce(in.URL))
md = strings.Replace(md, needle, replacement, 1)
}
// ── file attachments ──
for _, a := range atts {
childID := types.SubtreeChildID(in.DocToken, "file", a.FileToken)
keep = append(keep, childID) // present in the doc → never sweep as stale
// The renderer emitted the unique line "- weknora-att://<token>" for
// this attachment; patch that exact line so an identical earlier
// bullet can never be replaced by mistake. Anchoring on the token's
// end (newline or end of markdown) keeps a token that is a strict
// prefix of another attachment's token from matching inside it.
patchAtt := func(line string) {
needle := "- weknora-att://" + a.FileToken
if anchored := needle + "\n"; strings.Contains(md, anchored) {
md = strings.Replace(md, anchored, line+"\n", 1)
return
}
if strings.HasSuffix(md, needle) {
md = md[:len(md)-len(needle)] + line
}
}
// The renderer only collects whitelisted extensions into atts, so
// non-whitelisted/video files never reach this loop (their inline
// `> [附件: …]` reference is already in the Markdown).
data, derr := client.downloadMediaFile(ctx, a.FileToken)
if derr != nil {
if errors.Is(derr, ErrDownloadTooLarge) {
// The file is fine, just over the sync cap: degrade inline
// instead of failing or error-iteming the document.
logger.Warnf(ctx,
"[Feishu] doc %s: attachment %q (token=%s) over download cap, degrading to placeholder",
in.ObjToken, a.Name, a.FileToken)
displayName := a.Name
if displayName == "" {
displayName = a.FileToken
}
note := "> [附件: " + displayName + "]"
if in.URL != "" {
note = "> [附件: " + displayName + "](" + escapeURL(in.URL) + ")"
}
patchAtt(note)
continue
}
logger.Warnf(ctx, "[Feishu] doc %s: attachment %q (token=%s) download failed: %v",
in.ObjToken, a.Name, a.FileToken, derr)
patchAtt("- " + a.Name)
children = append(children, &types.FetchedItem{
ExternalID: childID,
Title: a.Name,
SourceResourceID: in.ResourceID,
Metadata: FeishuErrorItemMeta(derr, childMeta()),
})
continue
}
if len(data) < MinAttachmentBytes {
logger.Infof(ctx, "[Feishu] doc %s: skipping tiny attachment %q (token=%s, %d bytes < %d)",
in.ObjToken, a.Name, a.FileToken, len(data), MinAttachmentBytes)
patchAtt("- " + a.Name)
continue
}
patchAtt("- " + a.Name)
children = append(children, &types.FetchedItem{
ExternalID: childID,
Title: a.Name,
Content: data,
ContentType: "application/octet-stream",
FileName: SanitizeFileName(a.Name),
URL: in.URL,
UpdatedAt: in.EditTime,
CreatedAt: in.CreateTime,
SourceResourceID: in.ResourceID,
Metadata: childMeta(),
})
attachmentIDs = append(attachmentIDs, childID)
}
if exported != nil {
// A successful blocks listing still provides authoritative attachments.
// Preserve those children even though the parent's images use native
// export parsing; ordinary export alone omits file block attachments.
exported.ReplacesSubtree = true
exported.SubtreeKeep = keep
if len(attachmentIDs) > 0 {
if exported.Metadata == nil {
exported.Metadata = make(map[string]string)
}
ids, _ := json.Marshal(attachmentIDs)
exported.Metadata["attachment_ids"] = string(ids)
}
return append(children, exported), nil
}
// ── 云文档 mention links: backfill document titles ──
// The renderer emits "[weknora-docname://<token>](<url>)" placeholders; the
// drive metadata batch API resolves every title in one call. Refs that
// cannot be resolved (no permission, deleted, unsupported type) keep the
// URL as the link text — exactly the form rendered before this backfill.
if len(docNames) > 0 {
titles := client.DocTitles(ctx, docNames)
for _, dn := range docNames {
needle := "[weknora-docname://" + dn.Token + "](" + escapeURL(dn.URL) + ")"
repl := "[" + dn.URL + "](" + escapeURL(dn.URL) + ")"
if title := titles[dn.Token]; title != "" {
clean := strings.NewReplacer("[", "[", "]", "]", "\n", " ", "\r", "").Replace(title)
repl = "[" + clean + "](" + escapeURL(dn.URL) + ")"
} else {
logger.Warnf(ctx, "[Feishu] doc %s: no metadata for referenced doc %s (%s), keeping URL as link text",
in.Title, dn.Token, dn.DocType)
}
md = strings.ReplaceAll(md, needle, repl)
}
}
// ── embedded images and whiteboard blocks (block_type 43) ──
// Orthodox platform flow (same as the docparser for parsed PDFs/Word):
// the image bytes ride INSIDE the parent markdown as a base64 data URI;
// the document-processing pipeline's image resolver stores them on the
// tenant file service, swaps in the persistent provider:// URL and (when
// a VLM is configured) produces OCR/caption child chunks. No image
// knowledge rows are created.
for _, pi := range imgs {
if pi.Token == "" {
// Malformed block: degrade the marker to a plain placeholder.
patchMarker(pi.N, "![图片]()")
continue
}
var (
data []byte
derr error
)
if pi.Kind == "board" {
data, derr = client.downloadBoardAsImage(ctx, pi.Token)
} else {
data, derr = client.downloadMediaFile(ctx, pi.Token)
}
if derr != nil {
// 403 (no board:whiteboard:node:read for boards) or transient
// failure: degrade inline, never fail the document.
logger.Warnf(ctx, "[Feishu] doc %s: %s %s download failed: %v",
in.ObjToken, pi.Kind, pi.Token, derr)
patchMarker(pi.N, "![图片]()")
continue
}
ext, contentType, ok := SupportedImageExt(data)
if !ok {
// Reject non-images here. The image resolver filters icons by
// dimensions; compressed diagrams can be well below 2 KB.
logger.Infof(ctx, "[Feishu] doc %s: %s %s not a usable image (type=%q bytes=%d)",
in.ObjToken, pi.Kind, pi.Token, contentType, len(data))
patchMarker(pi.N, "![图片]()")
continue
}
if len(data) > maxInlineImageBytes {
// The document-processing image resolver skips data URIs over its
// 10 MB budget (image_resolver maxRemoteImageSize); inlining one
// would leave a raw base64 blob in the stored markdown forever.
// Degrade here instead — same handling as an oversized attachment.
logger.Warnf(ctx, "[Feishu] doc %s: %s %s (%d bytes) over inline image cap, degrading to placeholder",
in.ObjToken, pi.Kind, pi.Token, len(data))
patchMarker(pi.N, "![图片]()")
continue
}
dataURI := "data:" + contentType + ";base64," + base64.StdEncoding.EncodeToString(data)
patchMarker(pi.N, "![图片]("+dataURI+")")
_ = ext // ext is implied by contentType in the data URI
}
meta := maps.Clone(in.BaseMeta)
if len(attachmentIDs) > 0 {
if b, merr := json.Marshal(attachmentIDs); merr == nil {
meta["attachment_ids"] = string(b)
}
}
main := &types.FetchedItem{
ExternalID: in.DocToken,
Title: in.Title,
Content: []byte(md),
ContentType: "text/markdown",
FileName: SanitizeFileName(in.Title) + ".md",
URL: in.URL,
UpdatedAt: in.EditTime,
CreatedAt: in.CreateTime,
SourceResourceID: in.ResourceID,
Metadata: meta,
ReplacesSubtree: true, // sweep stale attachment sub-items on re-sync
}
main.SubtreeKeep = keep
return append(children, main), nil
}
// exportDocxFallback exports a docx document via the async export API and
// returns a single FetchedItem containing the exported .docx binary. Used by
// FetchDocxWithBlocks when the blocks API is unavailable or renders empty.
func exportDocxFallback(ctx context.Context, client *Client, in DocxFetchInput) (*types.FetchedItem, error) {
data, fileName, err := client.ExportAndDownload(ctx, in.ObjToken, "docx")
if err != nil {
return nil, fmt.Errorf("export %s (docx): %w", in.Title, err)
}
ext := ExportFileExtToSuffix[ObjTypeToExportFileExtension["docx"]]
if fileName == "" {
fileName = SanitizeFileName(in.Title) + ext
} else if !strings.HasSuffix(strings.ToLower(fileName), ext) {
fileName = SanitizeFileName(fileName) + ext
}
return &types.FetchedItem{
ExternalID: in.DocToken,
Title: in.Title,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: in.URL,
UpdatedAt: in.EditTime,
CreatedAt: in.CreateTime,
SourceResourceID: in.ResourceID,
Metadata: in.BaseMeta,
}, nil
}
@@ -0,0 +1,45 @@
package core
import (
"strings"
"testing"
)
func TestFetchTally_CountsAndSummary(t *testing.T) {
tally := newFetchTally(13)
tally.fetch()
tally.fetch()
tally.fetch()
tally.Skip("mindnote")
tally.Skip("mindnote")
tally.Skip("slides")
tally.fail()
if got := tally.skipped(); got != 3 {
t.Errorf("skipped() = %d, want 3", got)
}
summary := tally.summary()
for _, want := range []string{
"discovered=13",
"fetched=3",
"failed=1",
"skipped_unsupported=3",
"mindnote:2",
"slides:1",
} {
if !strings.Contains(summary, want) {
t.Errorf("summary() = %q, missing %q", summary, want)
}
}
}
func TestFetchTally_EmptyHasNoSkips(t *testing.T) {
tally := newFetchTally(0)
if got := tally.skipped(); got != 0 {
t.Errorf("skipped() = %d, want 0", got)
}
if !strings.Contains(tally.summary(), "skipped_unsupported=0") {
t.Errorf("summary() = %q, want skipped_unsupported=0", tally.summary())
}
}
@@ -0,0 +1,60 @@
package core
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/sirupsen/logrus"
)
func TestTenantAccessTokenNeverAppearsInLogs(t *testing.T) {
for _, token := range []string{"synthetic-access-value-for-logging-test", "xyz"} {
t.Run(token, func(t *testing.T) {
var logs bytes.Buffer
recorder := logrus.New()
recorder.SetOutput(&logs)
recorder.SetLevel(logrus.DebugLevel)
ctx := context.WithValue(context.Background(), types.LoggerContextKey, logrus.NewEntry(recorder))
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.URL.Path != "/open-apis/auth/v3/tenant_access_token/internal" || r.Method != http.MethodPost {
t.Errorf("unexpected token request")
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": token, "expire": 7200})
}))
defer server.Close()
client := &Client{
baseURL: server.URL,
appID: "test-app",
appSecret: "synthetic-credential",
httpClient: server.Client(),
}
for i := 0; i < 2; i++ {
got, err := client.GetTenantAccessToken(ctx)
if err != nil || got != token {
t.Fatalf("token retrieval or cache failed: %v", err)
}
}
if calls != 1 {
t.Errorf("cached token should avoid a second request; got %d", calls)
}
prefix, suffix := token[:min(8, len(token))], token[max(0, len(token)-4):]
for _, secret := range []string{token, prefix, suffix, "synthetic-credential"} {
if strings.Contains(logs.String(), secret) {
t.Error("authentication secret or fragment was logged")
}
}
if !strings.Contains(logs.String(), "expire=7200s") {
t.Error("safe token expiry diagnostics must remain")
}
})
}
}
@@ -0,0 +1,39 @@
package core
import (
"strings"
"testing"
"unicode/utf8"
)
// truncate caps a connector error preview with a plain byte slice. Connector error
// text is often Chinese, so the cut can land inside a multi-byte rune; these
// previews reach sync_logs and data_sources through the sync error message, and
// PostgreSQL rejects the invalid UTF-8 that a partial rune produces.
func TestTruncateKeepsValidUTF8AcrossCaps(t *testing.T) {
body := strings.Repeat("错", 400)
for _, maxLen := range []int{499, 500, 501, 1000, 1} {
got := truncate(body, maxLen)
if !utf8.ValidString(got) {
t.Fatalf("%s(%d): preview is not valid UTF-8", "truncate", maxLen)
}
if len(got) > maxLen+len("...") {
t.Fatalf("%s(%d): preview is %d bytes", "truncate", maxLen, len(got))
}
if !strings.HasPrefix(body, strings.TrimSuffix(got, "...")) {
t.Fatalf("%s(%d): preview is not a prefix of the input", "truncate", maxLen)
}
}
}
func TestTruncateLeavesShortAndASCIIInputAlone(t *testing.T) {
for _, s := range []string{"", "ok", "服务返回 500", "短"} {
if got := truncate(s, 500); got != s {
t.Fatalf("%s(%q, 500) = %q, want the input unchanged", "truncate", s, got)
}
}
if got := truncate("abcdef", 3); got != "abc..." {
t.Fatalf("truncate keeps the ASCII cut: %q", got)
}
}
@@ -0,0 +1,376 @@
// Package feishu implements the Feishu (飞书/Lark) data source connector for WeKnora.
//
// It syncs documents from Feishu Wiki spaces and cloud documents into WeKnora knowledge bases.
//
// Feishu API docs:
// - Wiki spaces: https://open.feishu.cn/document/server-docs/docs/wiki-v2/space/list
// - Wiki nodes: https://open.feishu.cn/document/server-docs/docs/wiki-v2/space-node/list
// - Export tasks: https://open.feishu.cn/document/server-docs/docs/drive-v1/export_task/export-user-guide
// - File download: https://open.feishu.cn/document/server-docs/docs/drive-v1/file/download
// - Auth: https://open.feishu.cn/document/server-docs/authentication-management/access-token/tenant_access_token_internal
package core
import (
"strings"
"time"
)
// Config holds Feishu-specific configuration for the data source connector.
// Uses the self-built app (企业自建应用) authentication model.
type Config struct {
// App ID from Feishu developer console
AppID string `json:"app_id"`
// App Secret from Feishu developer console
AppSecret string `json:"app_secret"`
// Base URL for Feishu API (default: https://open.feishu.cn)
// Use https://open.larksuite.com for Lark (international) deployments
BaseURL string `json:"base_url,omitempty"`
// Timezone is the IANA name (e.g. "Asia/Shanghai", "America/New_York") used to
// render bitable date cells. Feishu stores a date as a UTC instant, but the
// calendar date a user sees is that instant in the table's timezone, so
// rendering in UTC shifts the date. Empty defaults to GMT+8, which matches
// Feishu (mainland) tenants; set it for Lark tenants in other zones.
Timezone string `json:"timezone,omitempty"`
// ParseMode selects the docx parsing path: "blocks" (default) renders the
// blocks API into Markdown with attachment sub-items; "export" exports
// a .docx binary that docreader parses inline, keeping image↔document
// association via parent_chunk_id. Parsed from Settings["parse_mode"] by
// ParseFeishuConfig and threaded via DocxFetchInput.ParseMode; see
// FetchDocxWithBlocks.
ParseMode string `json:"parse_mode,omitempty"`
}
// Docx parse modes (Config.ParseMode, from Settings["parse_mode"]).
const (
// ParseModeBlocks renders docx via the blocks API into Markdown (default).
ParseModeBlocks = "blocks"
// ParseModeExport exports docx as a binary and lets docreader parse it
// inline — the escape hatch when image↔document association matters.
ParseModeExport = "export"
)
// defaultTimezoneOffsetSeconds is GMT+8 (the Feishu mainland default), used when
// no timezone is configured. A fixed zone avoids any dependency on system tzdata,
// which minimal container images may omit.
const defaultTimezoneOffsetSeconds = 8 * 3600
// resolveLocation returns the *time.Location used to render bitable date cells.
// An empty name yields a fixed GMT+8 zone (no tzdata dependency); a named zone is
// loaded from the system tz database, falling back to GMT+8 if it is unavailable.
func resolveLocation(name string) *time.Location {
if name != "" {
if loc, err := time.LoadLocation(name); err == nil {
return loc
}
}
return time.FixedZone("GMT+8", defaultTimezoneOffsetSeconds)
}
// defaultBaseURL is the default Feishu Open Platform API base URL.
const defaultBaseURL = "https://open.feishu.cn"
// larkBaseURL is the Lark (international) API base URL.
const larkBaseURL = "https://open.larksuite.com"
// GetBaseURL returns the effective base URL, defaulting to Feishu if not set.
func (c *Config) GetBaseURL() string {
if c.BaseURL != "" {
return c.BaseURL
}
return defaultBaseURL
}
// --- Export format constants ---
// Used by the export task API: POST /drive/v1/export_tasks
const (
// ExportTypeDocx exports Feishu documents to .docx format.
ExportTypeDocx = "docx"
// ExportTypeXlsx exports spreadsheets / bitable to .xlsx format.
ExportTypeXlsx = "xlsx"
// ExportTypePDF exports documents to .pdf format (fallback).
ExportTypePDF = "pdf"
)
// ObjTypeToExportFileExtension maps Feishu obj_type to the best export file_extension.
var ObjTypeToExportFileExtension = map[string]string{
"docx": ExportTypeDocx,
"doc": ExportTypeDocx,
"sheet": ExportTypeXlsx,
"bitable": ExportTypeXlsx,
}
// ObjTypeToExportType maps Feishu obj_type to the export API "type" parameter.
// See: https://open.feishu.cn/document/server-docs/docs/drive-v1/export_task/create
var ObjTypeToExportType = map[string]string{
"docx": "docx",
"doc": "doc",
"sheet": "sheet",
"bitable": "bitable",
}
// ExportFileExtToSuffix maps export file_extension to the file suffix for FileName.
var ExportFileExtToSuffix = map[string]string{
ExportTypeDocx: ".docx",
ExportTypeXlsx: ".xlsx",
ExportTypePDF: ".pdf",
}
// --- Feishu API response structures ---
// ApiResponse is the common Feishu API response wrapper.
type ApiResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
// TokenResponse is the response for tenant_access_token API.
type TokenResponse struct {
ApiResponse
TenantAccessToken string `json:"tenant_access_token"`
Expire int `json:"expire"` // seconds
}
// WikiSpaceListData is the data payload of WikiSpaceListResponse.
type WikiSpaceListData struct {
Items []WikiSpace `json:"items"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
}
// WikiSpaceListResponse is the response for GET /open-apis/wiki/v2/spaces.
type WikiSpaceListResponse struct {
ApiResponse
Data WikiSpaceListData `json:"data"`
}
// WikiSpace represents a Feishu Wiki space.
type WikiSpace struct {
SpaceID string `json:"space_id"`
Name string `json:"name"`
Description string `json:"description"`
Visibility string `json:"visibility"` // "public" or "private"
}
// WikiNodeListData is the data payload of WikiNodeListResponse.
type WikiNodeListData struct {
Items []WikiNode `json:"items"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
}
// WikiNodeListResponse is the response for GET /open-apis/wiki/v2/spaces/:space_id/nodes.
type WikiNodeListResponse struct {
ApiResponse
Data WikiNodeListData `json:"data"`
}
// WikiNode represents a node (document or folder) in a Feishu Wiki space.
type WikiNode struct {
SpaceID string `json:"space_id"`
NodeToken string `json:"node_token"`
ObjToken string `json:"obj_token"` // document token
ObjType string `json:"obj_type"` // "doc", "sheet", "mindnote", "bitable", "file", "docx", "slides"
ParentNodeID string `json:"parent_node_token"`
NodeType string `json:"node_type"` // "origin" or "shortcut"
OriginNodeID string `json:"origin_node_token"`
OriginSpaceID string `json:"origin_space_id"`
HasChild bool `json:"has_child"`
Title string `json:"title"`
Creator string `json:"creator"`
Owner string `json:"owner"`
ObjCreateTime string `json:"obj_create_time"` // document creation time (unix timestamp string)
ObjEditTime string `json:"obj_edit_time"` // document last edit time (unix timestamp string) — tracks content changes
NodeCreateTime string `json:"node_create_time"` // node creation time (unix timestamp string)
NodeEditTime string `json:"node_edit_time"` // node edit time (unix timestamp string) — only tracks node attribute changes
}
// WikiNodeInfoData is the data payload of WikiNodeInfoResponse.
type WikiNodeInfoData struct {
Node WikiNode `json:"node"`
}
// WikiNodeInfoResponse is the response for GET /open-apis/wiki/v2/spaces/get_node.
type WikiNodeInfoResponse struct {
ApiResponse
Data WikiNodeInfoData `json:"data"`
}
// --- Export task API responses ---
// docRawContentData is the data payload of docRawContentResponse.
type docRawContentData struct {
Content string `json:"content"`
}
// docRawContentResponse is the response for GET /open-apis/docx/v1/documents/:document_id/raw_content.
// Deprecated: prefer export API for full-fidelity document export.
type docRawContentResponse struct {
ApiResponse
Data docRawContentData `json:"data"`
}
// ExportTaskCreateData is the data payload of ExportTaskCreateResponse.
type ExportTaskCreateData struct {
Ticket string `json:"ticket"`
}
// ExportTaskCreateResponse is the response for POST /drive/v1/export_tasks.
type ExportTaskCreateResponse struct {
ApiResponse
Data ExportTaskCreateData `json:"data"`
}
// ExportTaskResult is the per-task result inside ExportTaskStatusData.
type ExportTaskResult struct {
FileToken string `json:"file_token"`
FileSize int64 `json:"file_size"`
// JobStatus: 0=success, 1=initializing, 2=processing
JobStatus int `json:"job_status"`
JobErrorMsg string `json:"job_error_msg"`
FileName string `json:"file_name"`
}
// ExportTaskStatusData is the data payload of ExportTaskStatusResponse.
type ExportTaskStatusData struct {
Result ExportTaskResult `json:"result"`
}
// ExportTaskStatusResponse is the response for GET /drive/v1/export_tasks/{ticket}.
type ExportTaskStatusResponse struct {
ApiResponse
Data ExportTaskStatusData `json:"data"`
}
// --- File download response ---
// driveFileMeta is one entry of driveFileMetaData.Metas.
type driveFileMeta struct {
DocToken string `json:"doc_token"`
DocType string `json:"doc_type"`
Title string `json:"title"`
}
// driveFileMetaData is the data payload of driveFileMetaResponse.
type driveFileMetaData struct {
Metas []driveFileMeta `json:"metas"`
}
// driveFileMetaResponse is the response for GET /drive/v1/metas for file type nodes.
type driveFileMetaResponse struct {
ApiResponse
Data driveFileMetaData `json:"data"`
}
// FeishuCursor stores incremental sync state for Feishu.
type FeishuCursor struct {
// LastSyncTime is the timestamp of the last successful sync.
LastSyncTime time.Time `json:"last_sync_time"`
// SpaceNodeTimes maps space_id -> node_token -> last known edit time.
// Used to detect which nodes have changed since last sync.
SpaceNodeTimes map[string]map[string]string `json:"space_node_times,omitempty"`
}
// --- Drive (云盘) file listing types (feishu_drive / lark_drive connectors) ---
// Added by feat/datasource-feishu-drive. These are independent of the wiki
// types above and do not affect the wiki connector.
// DriveFile represents a file/folder in Feishu Drive (云空间). Returned by
// GET /open-apis/drive/v1/files?folder_token=xxx. The list API returns
// modified_time directly (verified), so no batch_query/metas call is needed for
// incremental detection - see ADR-0002.
type DriveFile struct {
Token string `json:"token"`
Name string `json:"name"`
Type string `json:"type"` // doc/docx/sheet/bitable/file/folder/shortcut/mindnote/slides/board
ParentToken string `json:"parent_token"`
URL string `json:"url"`
CreatedTime string `json:"created_time"` // unix seconds string
ModifiedTime string `json:"modified_time"` // unix seconds string - 等价知识库 obj_edit_time
OwnerID string `json:"owner_id"`
// ShortcutInfo is populated only for type=="shortcut". target_type can only
// be doc/sheet/mindnote/bitable/file/docx (Feishu does not allow shortcuts to
// folders, verified) - see ADR-0002 / glossary shortcut entry.
ShortcutInfo *driveShortcutInfo `json:"shortcut_info,omitempty"`
}
// driveShortcutInfo is the target metadata of a Drive shortcut.
type driveShortcutInfo struct {
TargetToken string `json:"target_token"`
TargetType string `json:"target_type"`
}
// DriveFileListData is the data payload of DriveFileListResponse.
type DriveFileListData struct {
Files []DriveFile `json:"files"`
HasMore bool `json:"has_more"`
NextPageToken string `json:"next_page_token"`
}
// DriveFileListResponse is the response for GET /open-apis/drive/v1/files.
type DriveFileListResponse struct {
ApiResponse
Data DriveFileListData `json:"data"`
}
// driveFolderMetaData is the data payload of driveFolderMetaResponse.
type driveFolderMetaData struct {
ID string `json:"id"`
Name string `json:"name"`
Token string `json:"token"`
CreateUid string `json:"createUid"`
EditUid string `json:"editUid"`
ParentID string `json:"parentId"`
OwnUid string `json:"ownUid"`
}
// driveFolderMetaResponse is the response for GET /open-apis/drive/explorer/v2/folder/:folderToken/meta.
// Used to resolve a root folder's human-readable name (the list API only returns
// the folder's children, not the folder itself).
type driveFolderMetaResponse struct {
ApiResponse
Data driveFolderMetaData `json:"data"`
}
// DriveFileListFailure records a single sub-folder listing that failed during a
// recursive walk. Mirrors WikiNodeListFailure.
type DriveFileListFailure struct {
FolderToken string
Err error
}
// PartialDriveFileListError aggregates per-folder listing failures so the walk
// can continue and the caller can still surface the partial result. Mirrors
// PartialWikiNodeListError.
type PartialDriveFileListError struct {
Failures []DriveFileListFailure
}
func (e *PartialDriveFileListError) Error() string {
if e == nil || len(e.Failures) == 0 {
return "partial drive file listing failed"
}
parts := make([]string, 0, len(e.Failures))
for _, failure := range e.Failures {
parts = append(parts, failure.Err.Error())
}
return strings.Join(parts, "; ")
}
// FeishuDriveCursor stores incremental sync state for Feishu Drive (云盘).
// Structurally symmetric with FeishuCursor: outer key = resourceID
// ("folderToken" or "folderToken:fileToken"), inner key = file_token,
// value = modified_time. See ADR-0001.
type FeishuDriveCursor struct {
// LastSyncTime is the timestamp of the last successful sync.
LastSyncTime time.Time `json:"last_sync_time"`
// FileTimes maps resourceID -> file_token -> last known modified_time.
// Used to detect which files have changed since last sync.
FileTimes map[string]map[string]string `json:"file_times,omitempty"`
}
@@ -0,0 +1,145 @@
package core
import (
"context"
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/logger"
)
// ListWikiNodesWithShortcuts supplements the existing traversal with descendants
// of shortcuts. The original traversal and its partial failures are preserved.
func (c *Client) ListWikiNodesWithShortcuts(ctx context.Context, spaceID, nodeToken string) ([]WikiNode, error) {
nodes, err := c.ListWikiNodesRecursiveFrom(ctx, spaceID, nodeToken)
var failures []WikiNodeListFailure
if err != nil {
var partial *PartialWikiNodeListError
if !errors.As(err, &partial) {
return nodes, err
}
failures = append(failures, partial.Failures...)
}
return c.expandWikiShortcuts(ctx, spaceID, nodes, failures)
}
func (c *Client) expandWikiShortcuts(
ctx context.Context, spaceID string, nodes []WikiNode, failures []WikiNodeListFailure,
) ([]WikiNode, error) {
if err := ctx.Err(); err != nil {
return nodes, err
}
// Existing nodes have already been emitted. The original traversal handles
// ordinary nodes and shortcuts reporting children; only unexpanded shortcuts
// need processing in this extension.
seen := make(map[string]bool)
processed := make(map[string]bool)
expanded := make(map[string]bool)
origins := make(map[string]WikiNode)
var shortcuts []WikiNode
for _, node := range nodes {
if node.SpaceID == "" {
node.SpaceID = spaceID
}
key := node.SpaceID + ":" + node.NodeToken
seen[key] = true
origins[key] = node
if node.NodeType == "shortcut" && !node.HasChild {
shortcuts = append(shortcuts, node)
} else {
processed[key] = true
// Failed listings remain partial failures rather than being retried
// through another alias during the same sync.
if node.HasChild {
expanded[key] = true
}
}
}
var walk func(string, []WikiNode) error
walk = func(parentSpace string, children []WikiNode) error {
for _, node := range children {
if err := ctx.Err(); err != nil {
return err
}
if node.SpaceID == "" {
node.SpaceID = parentSpace
}
key := node.SpaceID + ":" + node.NodeToken
if processed[key] {
continue
}
processed[key] = true
if !seen[key] {
seen[key] = true
nodes = append(nodes, node)
}
target, err := c.resolveWikiShortcut(ctx, node, origins)
if err == nil && target.HasChild {
key = target.SpaceID + ":" + target.NodeToken
if expanded[key] {
continue
}
expanded[key] = true
var descendants []WikiNode
descendants, err = c.ListWikiNodes(ctx, target.SpaceID, target.NodeToken)
if err == nil {
if node.NodeType == "shortcut" {
// Keep the discovered subtree under the selected shortcut
// for directory mapping, while retaining source space IDs.
for i := range descendants {
descendants[i].ParentNodeID = node.NodeToken
}
}
if err := walk(target.SpaceID, descendants); err != nil {
return err
}
}
}
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
wrapped := fmt.Errorf("list children of %s: %w", node.NodeToken, err)
failures = append(failures, WikiNodeListFailure{Node: node, Err: wrapped})
logger.Warnf(ctx, "[Feishu] partial wiki node listing failure: space=%s node=%s err=%v",
node.SpaceID, node.NodeToken, wrapped)
}
}
return nil
}
if err := walk(spaceID, shortcuts); err != nil {
return nodes, err
}
if len(failures) > 0 {
return nodes, &PartialWikiNodeListError{Failures: failures}
}
return nodes, nil
}
func (c *Client) resolveWikiShortcut(ctx context.Context, node WikiNode, cache map[string]WikiNode) (WikiNode, error) {
visited := make(map[string]bool)
for node.NodeType == "shortcut" {
key := node.SpaceID + ":" + node.NodeToken
if visited[key] {
return WikiNode{}, fmt.Errorf("wiki shortcut cycle at %s", node.NodeToken)
}
visited[key] = true
if node.OriginNodeID == "" || node.OriginSpaceID == "" {
return WikiNode{}, fmt.Errorf("wiki shortcut %s is missing its original node or space", node.NodeToken)
}
key = node.OriginSpaceID + ":" + node.OriginNodeID
original, ok := cache[key]
if !ok {
var err error
original, err = c.GetWikiNode(ctx, node.OriginSpaceID, node.OriginNodeID)
if err != nil {
return WikiNode{}, fmt.Errorf("resolve wiki shortcut %s: %w", node.NodeToken, err)
}
cache[key] = original
}
node = original
}
return node, nil
}
@@ -0,0 +1,615 @@
package drive
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// DriveConnector implements the datasource.Connector (and StreamingConnector)
// interface for Feishu/Lark Drive (云盘) mode. It shares core.Client/core.Config/core.Region
// and the export/download logic with the wiki Connector; only resource
// enumeration and Fetch dispatch differ. See 飞书云盘数据源设计.md and
// ADR-0001..0004.
type DriveConnector struct {
region core.Region
}
// NewDriveConnector creates a Drive connector for the given region
// (RegionFeishuDrive or RegionLarkDrive).
func NewDriveConnector(region core.Region) *DriveConnector {
return &DriveConnector{region: region}
}
// Drive supports resumable streaming sync; the service prefers FetchStream over
// FetchAll/FetchIncremental when a connector implements StreamingConnector.
var _ datasource.StreamingConnector = (*DriveConnector)(nil)
var _ datasource.FullStreamingConnector = (*DriveConnector)(nil)
// Type returns the connector type identifier.
func (c *DriveConnector) Type() string {
return c.region.ConnectorType
}
// Validate verifies that the Drive configuration is valid by testing
// connectivity. It does not validate folder_token here - that is done in
// ListResources when the user loads the tree root. Mirrors the wiki Connector.
func (c *DriveConnector) Validate(ctx context.Context, config *types.DataSourceConfig) error {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return err
}
client := core.NewClient(feishuConfig)
if err := client.Ping(ctx); err != nil {
return fmt.Errorf("%s connection failed: %w", c.region.Label, err)
}
return nil
}
// ListResources lists Feishu Drive resources for selection, loading the tree
// lazily one level at a time. Mirrors the wiki Connector.ListResources shape
// but with the Drive difference that the root is user-supplied (config.
// ResourceIDs[0]) rather than enumerated via ListWikiSpaces.
//
// - parentID == "" -> return the user-supplied root
// folder (from config.ResourceIDs[0]) as the single root resource
// (HasChildren=true). Drive has no "space list" API, so the root is
// user-supplied. folder_token == "" is rejected (ADR-0004).
// - parentID == folderToken -> ListDriveFiles(folderToken)
// returns the direct children.
// - parentID == "folderToken:subFolderToken" -> ListDriveFiles(subFolderToken)
// returns that sub-folder's direct children.
//
// Each core.DriveFile becomes a Resource: folder HasChildren=true, others false.
// resourceID encoding: root = folderToken; child = folderToken + ":" + fileToken
// (reuses core.FeishuWikiNodeResourceSeparator). See ADR-0001 §3.4.
func (c *DriveConnector) ListResources(
ctx context.Context, config *types.DataSourceConfig, parentID string,
) ([]types.Resource, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
if parentID == "" {
// Root load: read the user-supplied folder_token from config.ResourceIDs.
rootFolderToken := driveRootFolderToken(config)
if rootFolderToken == "" {
return nil, fmt.Errorf("folder_token is required; specify a Drive folder token")
}
// Validate access by listing the root's direct children (also lazy-loads
// the first level for the picker). Reuse the list call rather than a
// separate ping.
files, err := client.ListDriveFilesAllPages(ctx, rootFolderToken)
if err != nil {
return nil, fmt.Errorf("list feishu drive folder %s: %w", rootFolderToken, err)
}
_ = files // children returned via the parentID == rootFolderToken branch below
// Resolve the root folder's human-readable name via the folder meta API.
// Best-effort: on failure (no permission / not found) fall back to the
// folder_token so the picker still renders something usable.
folderName := rootFolderToken
if meta, mErr := client.GetDriveFolderMeta(ctx, rootFolderToken); mErr != nil {
logger.Warnf(ctx, "[FeishuDrive] resolve root folder name failed: %v (falling back to token)", mErr)
} else if meta.Data.Name != "" {
folderName = meta.Data.Name
}
return []types.Resource{c.driveFolderToResource(rootFolderToken, "", rootFolderToken, folderName)}, nil
}
// Lazy load: list only the direct children of the given folder.
rootFolderToken, folderToken := parseDriveResourceID(parentID)
if folderToken == "" {
// parentID is a bare root folder token -> list its children.
folderToken = rootFolderToken
}
files, err := client.ListDriveFilesAllPages(ctx, folderToken)
if err != nil {
return nil, fmt.Errorf("list feishu drive files under %s: %w", parentID, err)
}
resources := make([]types.Resource, 0, len(files))
for _, f := range files {
resources = append(resources, c.driveFileToResource(rootFolderToken, f))
}
return resources, nil
}
// ResolveResourceAncestors returns the resource IDs of every parent folder that
// has to be expanded so the lazily-loaded picker can reveal each selection.
//
// The wiki connector walks up via GetWikiNode (parent_node_token) in O(depth)
// single-node queries. Drive has no single-file parent query API (verified -
// metas/batch_query does not return parent), so we walk top-down from the root
// folder with ListDriveFiles and share the traversal across all selections in
// the same root. Best-effort: a broken path just stays collapsed. See ADR-0003.
func (c *DriveConnector) ResolveResourceAncestors(
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
) ([]string, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
seen := make(map[string]bool)
ancestors := make([]string, 0)
add := func(id string) {
if id != "" && !seen[id] {
seen[id] = true
ancestors = append(ancestors, id)
}
}
// Group selections by root folder so one shared traversal covers them all.
type selection struct {
fileToken string
}
rootSelections := make(map[string][]selection)
for _, rid := range resourceIDs {
rootFolderToken, fileToken := parseDriveResourceID(rid)
if fileToken == "" {
// A root-level selection is already a top-level node; nothing to reveal.
continue
}
add(rootFolderToken)
rootSelections[rootFolderToken] = append(rootSelections[rootFolderToken], selection{fileToken})
}
// For each root, BFS from the root: at each folder, ListDriveFiles and check
// which selections are direct children (record their parent chain) and which
// sub-folders may still contain selections (enqueue). Shared traversal means
// selections in the same subtree reuse list calls.
for rootFolderToken, sels := range rootSelections {
remaining := make(map[string]bool, len(sels))
for _, s := range sels {
remaining[s.fileToken] = true
}
// parentChain[fileToken] = resourceID of its parent folder
parentChain := make(map[string]string)
queue := []string{rootFolderToken}
for len(queue) > 0 && len(remaining) > 0 {
cur := queue[0]
queue = queue[1:]
files, err := client.ListDriveFilesAllPages(ctx, cur)
if err != nil {
logger.Warnf(ctx, "[FeishuDrive] resolve ancestors: list %s: %v", cur, err)
break // best-effort: stop this root's traversal
}
for _, f := range files {
if remaining[f.Token] {
delete(remaining, f.Token)
// Record the parent chain from root down to this file's parent.
chain := buildDriveAncestorChain(rootFolderToken, cur, parentChain)
for _, a := range chain {
add(a)
}
}
if f.Type == "folder" {
parentChain[f.Token] = makeDriveResourceID(rootFolderToken, cur)
queue = append(queue, f.Token)
}
}
}
}
return ancestors, nil
}
// buildDriveAncestorChain walks the parentChain map from cur up to root,
// returning the resourceIDs (root, ... , cur's parent) in root-first order.
func buildDriveAncestorChain(rootFolderToken, cur string, parentChain map[string]string) []string {
var chain []string
node := cur
for node != "" && node != rootFolderToken {
parent, ok := parentChain[node]
if !ok {
break
}
chain = append([]string{parent}, chain...)
_, parentFolderToken := parseDriveResourceID(parent)
node = parentFolderToken
}
return chain
}
// FetchAll performs a full sync of all documents from the selected Drive
// folders. Defensive fallback path - the service prefers FetchStream when the
// connector implements StreamingConnector.
func (c *DriveConnector) FetchAll(
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
) ([]types.FetchedItem, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
return core.FetchAllEngine(ctx, client, config, resourceIDs,
&driveOps{region: c.region, parseMode: feishuConfig.ParseMode})
}
// FetchIncremental performs an incremental sync by comparing file modified_time
// against the previously recorded state. Defensive fallback path - the service
// prefers FetchStream. Routed through the same engine as FetchStream, so the
// #2136 failure-doesn't-advance-cursor semantics apply here too.
func (c *DriveConnector) FetchIncremental(
ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor,
) ([]types.FetchedItem, *types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, nil, err
}
client := core.NewClient(feishuConfig)
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchIncrementalEngine(ctx, client, config, cursor, ops)
}
// FetchStream performs a resumable, memory-bounded sync. It unifies the full
// and incremental paths: with cursor == nil it fetches everything, and with a
// cursor it skips files whose recorded modified_time is unchanged - the same
// mechanism that lets a sync which timed out mid-traversal resume from the last
// checkpoint instead of restarting (Tencent/WeKnora#2136).
//
// The per-node loop lives in the shared engine (engine.go); this shell only
// wires the Drive NodeOps adapter.
func (c *DriveConnector) FetchStream(
ctx context.Context, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchStreamEngine(ctx, client, config, cursor, h, ops)
}
// FetchFullStream refetches content without discarding the deletion baseline.
func (c *DriveConnector) FetchFullStream(
ctx context.Context, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchFullStreamEngine(ctx, client, config, cursor, h, ops)
}
// driveOps adapts the Drive DriveConnector to the generic sync engine. It
// carries the region (for channel + URL), encodes/decodes the Drive cursor
// wire format (core.FeishuDriveCursor / file_times), and holds the per-run
// directory mapping state (P1): folderNames caches resolved folder display
// names, dirPaths maps folder token → cleaned directory path for the resource
// being synced. List builds the state; Fetch reads it. runSync processes one
// resource at a time, so the mutation is race-free.
type driveOps struct {
region core.Region
parseMode string
folderNames map[string]string
dirPaths map[string]string
rootEntries map[string][]core.DriveFile // successful shallow listings, per run
}
func (o *driveOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.DriveFile, error, error) {
files, err := o.listDriveFilesForResource(ctx, client, resourceID)
if err == nil {
return files, nil, nil
}
var partial *core.PartialDriveFileListError
if errors.As(err, &partial) {
return files, err, nil
}
return files, nil, err
}
func (o *driveOps) Token(n core.DriveFile) string { return n.Token }
func (o *driveOps) Title(n core.DriveFile) string { return n.Name }
func (o *driveOps) ObjType(n core.DriveFile) string { return n.Type }
func (o *driveOps) EditTime(n core.DriveFile) string {
return core.DocxChangeKey(n.ModifiedTime, n.Type, o.parseMode)
}
func (o *driveOps) Fetch(
ctx context.Context, client *core.Client, n core.DriveFile, resourceID string,
) ([]*types.FetchedItem, error) {
items, err := fetchDriveFileContent(ctx, client, n, resourceID, o.region, o.parseMode)
if err != nil {
return nil, err
}
// P1 directory mapping: prefix the FileName with the containing folder's
// cleaned directory path so ingestion derives the KB folder_path from it.
qualifyItemFileNames(items, o.dirPaths[n.ParentToken])
return items, nil
}
func (o *driveOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
var pe *core.PartialDriveFileListError
if errors.As(partial, &pe) {
return appendDriveFileListFailureItems(nil, resourceID, o.channel(), pe.Failures)
}
return nil
}
func (o *driveOps) channel() string {
if o.region.ConnectorType == types.ConnectorTypeLarkDrive {
return types.ChannelLarkDrive
}
return types.ChannelFeishuDrive
}
func (o *driveOps) ResourceNoun() string { return "files" }
func (o *driveOps) EmptyResourceIDsError() string {
return "no resource IDs (Drive folder tokens) configured"
}
func (o *driveOps) LogTag() string { return "[FeishuDrive]" }
func (o *driveOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
var prev core.FeishuDriveCursor
b, _ := json.Marshal(m)
_ = json.Unmarshal(b, &prev)
return prev.FileTimes
}
func (o *driveOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
fc := core.FeishuDriveCursor{LastSyncTime: lastSync, FileTimes: times}
m := make(map[string]interface{})
b, _ := json.Marshal(fc)
_ = json.Unmarshal(b, &m)
return &types.SyncCursor{LastSyncTime: lastSync, ConnectorCursor: m}
}
// fetchDriveFileContent fetches the content of a single Drive file and converts
// it to FetchedItems. Dispatches by file.Type, mirroring the wiki
// fetchNodeContent. Shortcuts have already been expanded to their target by
// walkDriveTree, so this only sees the target type.
//
// - docx -> blocks API (Markdown) with export fallback; may return attachments/images
// - doc/sheet/bitable -> ExportAndDownload -> docx/xlsx
// - file -> DownloadDriveFile -> original file
// - mindnote/slides/board -> Skip (no API), returns (nil, nil)
func fetchDriveFileContent(
ctx context.Context, client *core.Client, file core.DriveFile,
resourceID string, region core.Region, parseMode string,
) ([]*types.FetchedItem, error) {
if !core.IsSupportedDocType(file.Type) {
return nil, nil
}
editTime := core.ParseFeishuTimestamp(file.ModifiedTime)
createTime := core.ParseFeishuTimestamp(file.CreatedTime)
// Channel marks the knowledge "source" label. Drive uses its own channel
// (feishu_drive / lark_drive) so Drive docs show "飞书云盘" / "Lark 云盘"
// distinct from the wiki connector's "飞书".
channel := types.ChannelFeishuDrive
if region.ConnectorType == types.ConnectorTypeLarkDrive {
channel = types.ChannelLarkDrive
}
baseMeta := map[string]string{
"obj_token": file.Token,
"obj_type": file.Type,
"file_token": file.Token,
"folder_token": file.ParentToken,
"channel": channel,
}
switch file.Type {
case "docx":
return core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
DocToken: file.Token,
ObjToken: file.Token,
Title: file.Name,
URL: file.URL,
ResourceID: resourceID,
EditTime: editTime,
CreateTime: createTime,
ParseMode: parseMode,
BaseMeta: baseMeta,
})
case "doc", "sheet", "bitable":
data, fileName, err := client.ExportAndDownload(ctx, file.Token, file.Type)
if err != nil {
return nil, fmt.Errorf("export %s (%s): %w", file.Name, file.Type, err)
}
ext := core.ExportFileExtToSuffix[core.ObjTypeToExportFileExtension[file.Type]]
if fileName == "" {
fileName = core.SanitizeFileName(file.Name) + ext
} else if !strings.HasSuffix(strings.ToLower(fileName), ext) {
fileName = core.SanitizeFileName(fileName) + ext
}
return []*types.FetchedItem{{
ExternalID: file.Token,
Title: file.Name,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: file.URL,
UpdatedAt: editTime,
CreatedAt: createTime,
SourceResourceID: resourceID,
Metadata: baseMeta,
}}, nil
case "file":
data, err := client.DownloadDriveFile(ctx, file.Token)
if err != nil {
return nil, fmt.Errorf("download file %s (%s): %w", file.Name, file.Token, err)
}
fileName := core.SanitizeFileName(file.Name)
if fileName == "" {
fileName = file.Token
}
return []*types.FetchedItem{{
ExternalID: file.Token,
Title: file.Name,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: file.URL,
UpdatedAt: editTime,
CreatedAt: createTime,
SourceResourceID: resourceID,
Metadata: baseMeta,
}}, nil
default:
return nil, nil
}
}
// --- Helpers ---
// makeDriveResourceID encodes a Drive ResourceID: "folderToken" (root) or
// "folderToken:fileToken" (child). Reuses core.FeishuWikiNodeResourceSeparator.
func makeDriveResourceID(rootFolderToken, fileToken string) string {
if fileToken == "" {
return rootFolderToken
}
return rootFolderToken + core.FeishuWikiNodeResourceSeparator + fileToken
}
// parseDriveResourceID splits a Drive resourceID into (rootFolderToken, fileToken).
// Mirrors parseWikiResourceID.
func parseDriveResourceID(resourceID string) (rootFolderToken, fileToken string) {
rootFolderToken, fileToken, _ = strings.Cut(resourceID, core.FeishuWikiNodeResourceSeparator)
return rootFolderToken, fileToken
}
// isDriveNotFolderError reports whether err indicates the token was not a
// folder (1061002 params error from the list API when a file token is passed).
func isDriveNotFolderError(err error) bool {
s := strings.ToLower(err.Error())
return strings.Contains(s, "1061002") || strings.Contains(s, "params error")
}
// filterDriveFileByToken returns only the entries whose Token matches token.
func filterDriveFileByToken(files []core.DriveFile, token string) []core.DriveFile {
var out []core.DriveFile
for _, f := range files {
if f.Token == token {
out = append(out, f)
}
}
return out
}
// driveRootFolderToken extracts the user-supplied root folder_token from the
// data source config (ResourceIDs[0]).
func driveRootFolderToken(config *types.DataSourceConfig) string {
if config == nil || len(config.ResourceIDs) == 0 {
return ""
}
root, _ := parseDriveResourceID(config.ResourceIDs[0])
return root
}
// driveFolderToResource builds the root Resource for a Drive folder. The root
// folder's name is resolved via GetDriveFolderMeta by the caller (best-effort,
// falling back to the token). For sub-folders, use driveFileToResource instead -
// the list API returns each child folder's Name.
//
// The root folder's ExternalID is the bare rootFolderToken (no ":fileToken"
// suffix) so it matches the resource_id the user saved in
// form.config.resource_ids = [folderToken]. A "token:token" encoding would
// break selection matching on edit.
func (c *DriveConnector) driveFolderToResource(rootFolderToken, parentToken, folderToken, name string) types.Resource {
if name == "" {
name = folderToken
}
return types.Resource{
ExternalID: rootFolderToken,
Name: name,
Type: "drive_folder",
URL: c.region.DriveFolderURL(folderToken),
HasChildren: true,
Metadata: map[string]interface{}{
"folder_token": folderToken,
},
}
}
// driveFileToResource converts a core.DriveFile (list result) into a picker Resource.
// The ParentID must match the parent folder's ExternalID: the root folder's
// ExternalID is the bare rootFolderToken (see driveFolderToResource), while any
// sub-folder's ExternalID is "rootFolderToken:folderToken". Direct children of
// the root have file.ParentToken == rootFolderToken, so their ParentID is the
// bare rootFolderToken; deeper descendants use the encoded form.
func (c *DriveConnector) driveFileToResource(rootFolderToken string, file core.DriveFile) types.Resource {
name := file.Name
if name == "" {
name = file.Token
}
modifiedAt := core.ParseFeishuTimestamp(file.ModifiedTime)
parentID := makeDriveResourceID(rootFolderToken, file.ParentToken)
if file.ParentToken == rootFolderToken || file.ParentToken == "" {
// Direct child of the root folder: parent is the root, whose
// ExternalID is the bare rootFolderToken (no ":token" suffix).
parentID = rootFolderToken
}
return types.Resource{
ExternalID: makeDriveResourceID(rootFolderToken, file.Token),
Name: name,
Type: file.Type,
URL: file.URL,
ParentID: parentID,
HasChildren: file.Type == "folder",
ModifiedAt: modifiedAt,
Metadata: map[string]interface{}{
"file_token": file.Token,
"obj_type": file.Type,
"folder_token": file.ParentToken,
},
}
}
// appendDriveFileListFailureItems converts Drive listing failures into error
// FetchedItems so the sync log surfaces which sub-folders could not be listed.
// Mirrors appendWikiNodeListFailureItems.
func appendDriveFileListFailureItems(items []types.FetchedItem, resourceID, channel string, failures []core.DriveFileListFailure) []types.FetchedItem {
for _, failure := range failures {
items = append(items, types.FetchedItem{
ExternalID: failure.FolderToken,
Title: failure.FolderToken,
SourceResourceID: resourceID,
Metadata: core.FeishuErrorItemMeta(failure.Err, map[string]string{
"channel": channel,
"folder_token": failure.FolderToken,
"failure_stage": "list_children",
}),
})
}
return items
}
@@ -0,0 +1,428 @@
package drive
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
)
// ──────────────────────────────────────────────────────────────────────
// P1 directory mapping tests for the Drive connector: path-qualified
// FileName, deletion mirroring, partial-listing suppression, move following.
// ──────────────────────────────────────────────────────────────────────
// fakeDriveTree serves a mutable Drive folder tree keyed by folder_token.
// folders maps folder token → direct children (folders recurse, files sync);
// failing folders return HTTP 500 to model a partial listing; metaNames maps
// folder token → display name for the folder meta endpoint (absent = error).
type fakeDriveTree struct {
folders map[string][]core.DriveFile
failing map[string]bool
metaNames map[string]string
// listCalls / metaCalls count API hits per token, so tests can assert a
// file token is never probed with folder APIs.
listCalls map[string]int
metaCalls map[string]int
ts *httptest.Server
cfg *core.Config
}
func newFakeDriveTree(t *testing.T, folders map[string][]core.DriveFile) *fakeDriveTree {
t.Helper()
f := &fakeDriveTree{
folders: folders, failing: map[string]bool{},
listCalls: map[string]int{}, metaCalls: map[string]int{},
}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal",
func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.TokenResponse{
ApiResponse: core.ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
// Folder listing (paged endpoint, exact path) and file download (subtree).
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("folder_token")
f.listCalls[token]++
if f.failing[token] {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"code":1663,"msg":"internal error"}`))
return
}
writeJSON(w, core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{Files: f.folders[token]},
})
})
mux.HandleFunc("/open-apis/drive/v1/files/", func(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/download") {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("fake-drive-file-content"))
})
mux.HandleFunc("/open-apis/drive/explorer/v2/folder/", func(w http.ResponseWriter, r *http.Request) {
// path: /open-apis/drive/explorer/v2/folder/<token>/meta
p := strings.TrimPrefix(r.URL.Path, "/open-apis/drive/explorer/v2/folder/")
token := strings.TrimSuffix(p, "/meta")
f.metaCalls[token]++
name, ok := f.metaNames[token]
if !ok {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"code":1061004,"msg":"not found"}`))
return
}
writeJSON(w, map[string]interface{}{
"code": 0,
"data": map[string]interface{}{"name": name},
})
})
f.ts = httptest.NewServer(mux)
t.Cleanup(f.ts.Close)
f.cfg = &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: f.ts.URL}
return f
}
// driveFile builds a regular file entry; folder builds a folder entry.
func driveFile(token, name, parent string, modified string) core.DriveFile {
return core.DriveFile{Token: token, Name: name, Type: "file", ParentToken: parent, ModifiedTime: modified}
}
func driveFolder(token, name, parent string) core.DriveFile {
return core.DriveFile{Token: token, Name: name, Type: "folder", ParentToken: parent}
}
// fetchedByToken indexes emitted non-deleted items by external_id.
func fetchedByToken(items []types.FetchedItem) map[string]types.FetchedItem {
m := make(map[string]types.FetchedItem, len(items))
for _, it := range items {
if !it.IsDeleted {
m[it.ExternalID] = it
}
}
return m
}
func deletedIDs(items []types.FetchedItem) []string {
var ids []string
for _, it := range items {
if it.IsDeleted {
ids = append(ids, it.ExternalID)
}
}
return ids
}
// TestDriveFetchIncremental_PathQualifiedMultiLevel anchors the directory
// mapping: the selected root folder mirrors as a top-level KB folder named
// after it, so paths are <根名>/<子目录...>/<文件名>, Chinese names kept,
// "/" in a folder name sanitised to "_", multi-level nesting resolved from
// the same walk.
func TestDriveFetchIncremental_PathQualifiedMultiLevel(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFolder("fold-spec", "规格", "fold-root"),
driveFolder("fold-bad", "a/b", "fold-root"), // "/" in the name → "_"
driveFile("f-root", "说明.pdf", "fold-root", "100"),
},
"fold-spec": {driveFile("f-spec", "详细.pdf", "fold-spec", "200")},
"fold-bad": {driveFile("f-bad", "child.pdf", "fold-bad", "300")},
})
f.metaNames = map[string]string{"fold-root": "团队资料"}
c := NewDriveConnector(core.RegionFeishuDrive)
items, _, err := c.FetchIncremental(context.Background(), makeDriveConfig(f.cfg, []string{"fold-root"}), nil)
if err != nil {
t.Fatalf("FetchIncremental() error: %v", err)
}
want := map[string]string{
// The selected root folder mirrors as a top-level KB folder ("团队资料"
// via the meta mock): every item's path starts with the root name,
// deeper ones then carry the sub-directory path.
"f-root": "团队资料/说明.pdf",
"f-spec": "团队资料/规格/详细.pdf",
"f-bad": "团队资料/a_b/child.pdf",
}
got := fetchedByToken(items)
if len(got) != len(want) {
t.Fatalf("got %d items (%v), want %d", len(got), got, len(want))
}
for id, wantPath := range want {
if got[id].FileName != wantPath {
t.Errorf("FileName for %s = %q, want %q", id, got[id].FileName, wantPath)
}
}
}
// TestDriveFetchIncremental_DeletionMirror anchors the deletion engine: a
// second full listing that misses a previously synced token emits exactly one
// IsDeleted item for it; the first sync (no cursor) emits none.
func TestDriveFetchIncremental_DeletionMirror(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFile("f-a", "a.pdf", "fold-root", "100"),
driveFile("f-b", "b.pdf", "fold-root", "200"),
},
})
f.metaNames = map[string]string{"fold-root": "团队资料"}
c := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first sync error: %v", err)
}
if ids := deletedIDs(items1); len(ids) != 0 {
t.Errorf("first sync emitted IsDeleted items %v — deletion must be suppressed without a prior cursor", ids)
}
// f-a disappears from the tree.
f.folders["fold-root"] = []core.DriveFile{driveFile("f-b", "b.pdf", "fold-root", "200")}
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second sync error: %v", err)
}
ids := deletedIDs(items2)
if len(ids) != 1 || ids[0] != "f-a" {
t.Errorf("second sync deleted ids = %v, want [f-a]", ids)
}
}
// TestDriveFetchIncremental_PartialListingDoesNotDelete anchors the partial
// safety: when a sub-folder cannot be listed, deletion detection is suppressed
// even though a previously seen token is missing from the (incomplete) listing.
func TestDriveFetchIncremental_PartialListingDoesNotDelete(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFolder("fold-doomed", "doomed", "fold-root"),
driveFile("f-a", "a.pdf", "fold-root", "100"),
},
"fold-doomed": {driveFile("f-deep", "deep.pdf", "fold-doomed", "300")},
})
f.metaNames = map[string]string{"fold-root": "团队资料"}
f.failing["fold-doomed"] = true
c := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first sync error: %v", err)
}
if _, ok := fetchedByToken(items1)["f-a"]; !ok {
t.Fatalf("first sync missing f-a: %+v", items1)
}
// f-a disappears while the sub-folder listing stays broken: the listing is
// partial, so the missing token must NOT be reported as deleted.
f.folders["fold-root"] = []core.DriveFile{driveFolder("fold-doomed", "doomed", "fold-root")}
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second sync error: %v", err)
}
if ids := deletedIDs(items2); len(ids) != 0 {
t.Errorf("partial listing emitted IsDeleted items %v — deletion must be suppressed on a partial listing", ids)
}
}
// TestDriveFetchIncremental_MoveFollowsNewPath anchors the move story at the
// connector level: the same external_id re-fetched after being moved between
// folders comes back with the NEW path-qualified FileName (ingestion's
// update=delete+recreate then lands it in the new folder_path).
func TestDriveFetchIncremental_MoveFollowsNewPath(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFolder("fold-a", "目录A", "fold-root"),
},
"fold-a": {driveFile("f-doc", "文档.pdf", "fold-a", "100")},
})
f.metaNames = map[string]string{"fold-root": "团队资料"}
c := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first sync error: %v", err)
}
if got := fetchedByToken(items1)["f-doc"].FileName; got != "团队资料/目录A/文档.pdf" {
t.Fatalf("first sync f-doc FileName = %q, want 团队资料/目录A/文档.pdf", got)
}
// Move f-doc to a new folder 目录B and bump its modified time.
f.folders["fold-root"] = []core.DriveFile{
driveFolder("fold-a", "目录A", "fold-root"),
driveFolder("fold-b", "目录B", "fold-root"),
}
f.folders["fold-b"] = []core.DriveFile{driveFile("f-doc", "文档.pdf", "fold-b", "200")}
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second sync error: %v", err)
}
moved, ok := fetchedByToken(items2)["f-doc"]
if !ok {
t.Fatalf("moved file not re-fetched on second sync: %+v", items2)
}
if moved.FileName != "团队资料/目录B/文档.pdf" {
t.Errorf("moved file FileName = %q, want 团队资料/目录B/文档.pdf (same external_id, new folder)", moved.FileName)
}
}
// TestDriveFetchIncremental_SingleFileSelectionSkipsFolderProbes anchors the
// sub-selection fix: a selected file's kind is read off the root subtree
// listing, so no folder meta/list API is ever called with the file token —
// probing used to fail with 91202/1061002 and log API errors on every sync.
func TestDriveFetchIncremental_SingleFileSelectionSkipsFolderProbes(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {driveFile("f-doc", "文档.docx", "fold-root", "100")},
})
c := NewDriveConnector(core.RegionFeishuDrive)
items, _, err := c.FetchIncremental(context.Background(), makeDriveConfig(f.cfg, []string{"fold-root:f-doc"}), nil)
if err != nil {
t.Fatalf("FetchIncremental() error: %v", err)
}
got := fetchedByToken(items)
if len(got) != 1 || got["f-doc"].FileName != "文档.docx" {
t.Fatalf("got %d items (%v), want exactly f-doc with its own name", len(got), got)
}
if f.listCalls["f-doc"] != 0 {
t.Errorf("folder list probed the file token %d time(s)", f.listCalls["f-doc"])
}
if f.metaCalls["f-doc"] != 0 {
t.Errorf("folder meta probed the file token %d time(s)", f.metaCalls["f-doc"])
}
}
// TestDriveFetchIncremental_SubFolderSelection pins the sub-folder semantics:
// only the selected subtree syncs, prefixed with the sub-folder's own name.
func TestDriveFetchIncremental_SubFolderSelection(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFolder("fold-spec", "规格", "fold-root"),
driveFile("f-root", "说明.pdf", "fold-root", "100"),
},
"fold-spec": {driveFile("f-spec", "详细.pdf", "fold-spec", "200")},
})
f.metaNames = map[string]string{"fold-spec": "规格"}
c := NewDriveConnector(core.RegionFeishuDrive)
items, _, err := c.FetchIncremental(
context.Background(), makeDriveConfig(f.cfg, []string{"fold-root:fold-spec"}), nil)
if err != nil {
t.Fatalf("FetchIncremental() error: %v", err)
}
got := fetchedByToken(items)
if len(got) != 1 {
t.Fatalf("got %d items (%v), want only the selected subtree", len(got), got)
}
if got["f-spec"].FileName != "规格/详细.pdf" {
t.Errorf("FileName for f-spec = %q, want %q", got["f-spec"].FileName, "规格/详细.pdf")
}
}
func TestDriveSubfolderDoesNotWalkUnselectedSiblings(t *testing.T) {
for _, nested := range []bool{false, true} {
t.Run(map[bool]string{false: "direct", true: "nested"}[nested], func(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"root": {
driveFolder("selected", "Selected", "root"), driveFolder("unselected", "Unselected", "root"),
},
"selected": {driveFile("doc", "doc.pdf", "selected", "100")},
})
if nested {
f.folders["root"] = []core.DriveFile{driveFolder("unselected", "Unselected", "root")}
}
f.metaNames = map[string]string{"root": "Root", "selected": "Selected"}
// A failure in an unrelated folder must not add retries or partial errors.
f.failing["unselected"] = true
conn := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"root:selected"})
items, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].FileName != "Root/Selected/doc.pdf" {
t.Fatalf("unexpected items: %+v", items)
}
if f.listCalls["unselected"] != 0 || f.listCalls["selected"] != 1 {
t.Fatalf("unexpected list calls: %v", f.listCalls)
}
f.folders["selected"] = nil
items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatal(err)
}
if ids := deletedIDs(items); len(ids) != 1 || ids[0] != "doc" {
t.Fatalf("selected deletion lost: %+v", items)
}
})
}
}
func TestDriveSelectionsShareShallowRootListing(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"root": {
driveFolder("a", "A", "root"), driveFolder("b", "B", "root"), driveFile("doc", "root.pdf", "root", "100"),
},
"a": {driveFile("doc-a", "a.pdf", "a", "100")},
"b": {driveFile("doc-b", "b.pdf", "b", "100")},
})
f.metaNames = map[string]string{"root": "Root"}
conn := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"root:a", "root:b", "root:doc"})
items, _, err := conn.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 3 {
t.Fatalf("items=%+v", items)
}
if f.listCalls["root"] != 1 || f.listCalls["a"] != 1 || f.listCalls["b"] != 1 || f.listCalls["doc"] != 0 {
t.Fatalf("unexpected calls: %v", f.listCalls)
}
}
func TestDriveSelectedShortcutKeepsDisplayNameAndTarget(t *testing.T) {
for _, selected := range []string{"shortcut", "target"} {
t.Run(selected, func(t *testing.T) {
var shortcut core.DriveFile
raw := `{"token":"shortcut","type":"shortcut","name":"reference.pdf","modified_time":"100",
"shortcut_info":{"target_token":"target","target_type":"file"}}`
if err := json.Unmarshal([]byte(raw), &shortcut); err != nil {
t.Fatal(err)
}
f := newFakeDriveTree(t, map[string][]core.DriveFile{"root": {shortcut}})
f.metaNames = map[string]string{"root": "Root"}
conn := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"root:" + selected})
items, _, err := conn.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].ExternalID != "target" || items[0].FileName != "Root/reference.pdf" {
t.Fatalf("unexpected shortcut item: %+v", items)
}
if f.listCalls["target"] != 0 || f.listCalls["shortcut"] != 0 || f.listCalls["root"] != 1 {
t.Fatalf("shortcut must not trigger folder probes: %v", f.listCalls)
}
})
}
}
@@ -0,0 +1,42 @@
package drive
import (
"testing"
"time"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
)
// TestDriveCursorRoundTrip verifies driveOps.EncodeCursor/DecodeCursorTimes
// survive a JSON marshal/unmarshal cycle (snapshot isolation), mirroring the
// wiki TestFeishuCursorRoundTrip. Design §3.2: driveOps is new code that
// previously had no direct test.
func TestDriveCursorRoundTrip(t *testing.T) {
ops := driveOps{region: core.RegionFeishuDrive}
times := map[string]map[string]string{
"folder1": {"fdoc1": "100", "fdoc2": "200"},
"folder1:fdoc1": {"fdoc1": "100"},
"folder2:subA": {"fdoc3": "300"},
}
cur := ops.EncodeCursor(times, time.Unix(1000, 0))
if cur == nil {
t.Fatal("EncodeCursor returned nil")
}
got := ops.DecodeCursorTimes(cur.ConnectorCursor)
if len(got) != len(times) {
t.Fatalf("decoded %d resources, want %d", len(got), len(times))
}
for rid, files := range times {
gotFiles, ok := got[rid]
if !ok {
t.Errorf("resource %q missing from decoded cursor", rid)
continue
}
for tok, mt := range files {
if gotFiles[tok] != mt {
t.Errorf("decoded[%q][%q] = %q, want %q", rid, tok, gotFiles[tok], mt)
}
}
}
}
@@ -0,0 +1,417 @@
package drive
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
)
// makeDriveConfig builds a DataSourceConfig for the Drive connector, mirroring
// makeConfig but with the drive connector type.
func makeDriveConfig(cfg *core.Config, resourceIDs []string) *types.DataSourceConfig {
c := makeConfig(cfg, resourceIDs)
c.Type = types.ConnectorTypeFeishuDrive
return c
}
// fakeFeishuDriveDocx serves the Drive list endpoint plus the docx blocks /
// media / export endpoints. blocksMode controls the blocks API behaviour:
// - "ok": serve the given blocks
// - "fail": HTTP 500 (missing scope) → exercises the export fallback
// - "empty": serve only a page block → empty Markdown → export fallback
//
// The export trio is always registered so both fallback modes can complete.
func fakeFeishuDriveDocx(t *testing.T, files []core.DriveFile, docToken string,
blocks []core.DocxBlock, blocksMode string, mediaContent []byte,
) (*httptest.Server, *core.Config) {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
})
// Drive file listing (single page).
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{Files: files},
})
})
// Blocks API for the given docx document.
blocksPath := "/open-apis/docx/v1/documents/" + docToken + "/blocks"
switch blocksMode {
case "fail":
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"code":99991400,"msg":"insufficient scope"}`))
})
case "empty":
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.DocxBlocksResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DocxBlocksData{Items: []core.DocxBlock{{BlockID: "b1", BlockType: core.BlockTypePage}}},
})
})
default: // "ok"
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.DocxBlocksResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DocxBlocksData{Items: blocks},
})
})
}
// Media download for File/Image block tokens.
mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/download") {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write(mediaContent)
return
}
http.NotFound(w, r)
})
// Export trio for the fallback path.
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.ExportTaskCreateResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskCreateData{Ticket: "ticket-drv"},
})
})
mux.HandleFunc("/open-apis/drive/v1/export_tasks/ticket-drv", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.ExportTaskStatusResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskStatusData{
Result: core.ExportTaskResult{FileToken: "ft-export-drv", FileSize: 512, JobStatus: 0, FileName: "drive-fallback.docx"},
},
})
})
mux.HandleFunc("/open-apis/drive/v1/export_tasks/file/ft-export-drv/download", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("fake-drive-export-binary"))
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
}
func driveDocxBlocks(attToken, attName string) []core.DocxBlock {
return []core.DocxBlock{
{BlockID: "b1", BlockType: core.BlockTypePage},
{BlockID: "b2", BlockType: core.BlockTypeText, Text: &core.BlockText{
Elements: []core.TextElement{{TextRun: &core.TextRun{Content: "Hello drive"}}},
}},
{BlockID: "b3", BlockType: core.BlockTypeFile, File: &core.BlockFileRef{Token: attToken, Name: attName}},
}
}
const driveDocxFileToken = "fdoc1"
func driveDocxFile() core.DriveFile {
return core.DriveFile{
Token: driveDocxFileToken,
Type: "docx",
Name: "Drive Doc",
ModifiedTime: "500",
ParentToken: "folder1",
URL: "https://example.feishu.cn/file/" + driveDocxFileToken,
}
}
// A drive docx goes through the blocks path: main Markdown item (external_id =
// file token, channel = feishu_drive) plus the attachment sub-item.
func TestDriveFetchStream_DocxBlocksMultiItem(t *testing.T) {
const (
attToken = "ft-drv-att"
attName = "report.pdf"
)
attContent := bytes.Repeat([]byte("x"), core.MinAttachmentBytes+1)
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
driveDocxBlocks(attToken, attName), "ok", attContent)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 2 {
t.Fatalf("expected 2 emitted items (attachment + main doc), got %d: %+v", len(h.emitted), h.emitted)
}
// P3 contract: sub-items are emitted BEFORE the parent document.
att := h.emitted[0]
wantAttID := driveDocxFileToken + "#file#" + attToken
if att.ExternalID != wantAttID {
t.Errorf("items[0].ExternalID = %q, want %q", att.ExternalID, wantAttID)
}
if att.Metadata["attachment"] != "true" {
t.Errorf("items[0].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
}
if att.Metadata["parent_doc_id"] != driveDocxFileToken {
t.Errorf("items[0].Metadata[parent_doc_id] = %q, want %q", att.Metadata["parent_doc_id"], driveDocxFileToken)
}
main := h.emitted[1]
if main.ExternalID != driveDocxFileToken {
t.Errorf("items[1].ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
}
if main.ContentType != "text/markdown" {
t.Errorf("items[1].ContentType = %q, want text/markdown", main.ContentType)
}
if !main.ReplacesSubtree {
t.Errorf("items[1].ReplacesSubtree = false, want true")
}
if main.Metadata["channel"] != types.ChannelFeishuDrive {
t.Errorf("items[1].Metadata[channel] = %q, want %q", main.Metadata["channel"], types.ChannelFeishuDrive)
}
if main.URL != "https://example.feishu.cn/file/"+driveDocxFileToken {
t.Errorf("items[1].URL = %q, want drive file URL passthrough", main.URL)
}
if !strings.Contains(string(main.Content), "Hello drive") {
t.Errorf("items[1].Content missing expected text; got %q", string(main.Content))
}
}
// Blocks API failure falls back to export: exactly one octet-stream item, no
// ReplacesSubtree (must not sweep good prior children on a transient failure).
func TestDriveFetchStream_DocxBlocksFailFallsBackToExport(t *testing.T) {
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, nil, "fail", nil)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 1 {
t.Fatalf("expected 1 emitted item (export fallback), got %d: %+v", len(h.emitted), h.emitted)
}
item := h.emitted[0]
if item.ExternalID != driveDocxFileToken {
t.Errorf("item.ExternalID = %q, want %q", item.ExternalID, driveDocxFileToken)
}
if item.ContentType != "application/octet-stream" {
t.Errorf("item.ContentType = %q, want application/octet-stream", item.ContentType)
}
if !strings.HasSuffix(item.FileName, ".docx") {
t.Errorf("item.FileName = %q, want .docx suffix", item.FileName)
}
if item.ReplacesSubtree {
t.Error("export-fallback item must not set ReplacesSubtree")
}
}
// Blocks rendering to empty Markdown also falls back to export (a blank page
// would otherwise ingest as a login-gated URL core.Fetch and fail).
func TestDriveFetchStream_DocxBlocksEmptyFallsBackToExport(t *testing.T) {
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, nil, "empty", nil)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 1 {
t.Fatalf("expected 1 emitted item (export fallback), got %d: %+v", len(h.emitted), h.emitted)
}
item := h.emitted[0]
if item.ContentType != "application/octet-stream" {
t.Errorf("item.ContentType = %q, want application/octet-stream", item.ContentType)
}
if item.ReplacesSubtree {
t.Error("export-fallback item must not set ReplacesSubtree")
}
}
// Image items are unconditional (not gated by the KB multimodal switch): the
// download produces a PNG sub-item, the parent's Markdown carries the numbered
// marker, and the external_id stays in SubtreeKeep.
func TestDriveFetchStream_DocxImageEmitted(t *testing.T) {
const imgToken = "img-drv-1"
blocks := []core.DocxBlock{
{BlockID: "b1", BlockType: core.BlockTypePage},
{BlockID: "b2", BlockType: core.BlockTypeText, Text: &core.BlockText{
Elements: []core.TextElement{{TextRun: &core.TextRun{Content: "has image"}}},
}},
{BlockID: "b3", BlockType: core.BlockTypeImage, Image: &core.BlockTokenRef{Token: imgToken}},
}
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", png)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
// Orthodox flow: the image rides inline in the parent markdown as a base64
// data URI — one emitted item, no image sub-item, no image_map.
if len(h.emitted) != 1 {
t.Fatalf("expected 1 emitted item (main only), got %d: %+v", len(h.emitted), h.emitted)
}
main := h.emitted[0]
if main.ExternalID != driveDocxFileToken {
t.Errorf("main ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
}
wantURI := "![图片](data:image/png;base64," + base64.StdEncoding.EncodeToString(png) + ")"
if !strings.Contains(string(main.Content), wantURI) {
t.Errorf("image not inlined as base64 data URI:\n%s", main.Content)
}
if main.Metadata["image_map"] != "" {
t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
}
}
func TestDriveParseModeChangeRefetchesExistingDocument(t *testing.T) {
ts, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
driveDocxBlocks("", ""), "ok", nil)
defer ts.Close()
conf := makeDriveConfig(cfg, []string{"folder1"})
conf.Settings = map[string]interface{}{"parse_mode": "export"}
c := NewDriveConnector(core.RegionFeishu)
items, cursor, err := c.FetchIncremental(context.Background(), conf, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("initial sync: %d items", len(items))
}
for _, mode := range []string{"blocks", "export"} {
conf.Settings["parse_mode"] = mode
items, cursor, err = c.FetchIncremental(context.Background(), conf, cursor)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("mode %s: want one refreshed document, got %d", mode, len(items))
}
items, _, err = c.FetchIncremental(context.Background(), conf, cursor)
if err != nil {
t.Fatal(err)
}
if len(items) != 0 {
t.Fatalf("unchanged mode %s unexpectedly refetched", mode)
}
}
}
// Image-heavy documents must take the native export path, whose ImageRefs do
// not have the Markdown data-URI count limit. In particular, no excess base64
// may be persisted as searchable document text.
func TestDriveImageBudgetFallsBackToNativeExport(t *testing.T) {
for _, count := range []int{types.MaxInlineDocumentImages, types.MaxInlineDocumentImages + 1, 61} {
t.Run(strconv.Itoa(count), func(t *testing.T) {
blocks := []core.DocxBlock{{BlockID: "page", BlockType: core.BlockTypePage}}
for i := 0; i < count; i++ {
blocks = append(blocks, core.DocxBlock{
BlockID: fmt.Sprintf("img%d", i), BlockType: core.BlockTypeImage,
Image: &core.BlockTokenRef{Token: "img"},
})
}
data := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", data)
items, err := core.FetchDocxWithBlocks(context.Background(), core.NewClient(cfg), core.DocxFetchInput{
DocToken: driveDocxFileToken, ObjToken: driveDocxFileToken, Title: "Images",
BaseMeta: map[string]string{}, ParseMode: core.ParseModeBlocks,
})
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("want one document, got %d", len(items))
}
if count <= types.MaxInlineDocumentImages {
if n := strings.Count(string(items[0].Content), "data:image/png;base64,"); n != count {
t.Fatalf("inline images=%d, want %d", n, count)
}
} else {
if !strings.HasSuffix(items[0].FileName, ".docx") ||
string(items[0].Content) != "fake-drive-export-binary" {
t.Fatalf("image-heavy document was not exported: %s", items[0].FileName)
}
if !items[0].ReplacesSubtree {
t.Fatal("complete blocks listing must retain attachment reconciliation")
}
}
})
}
}
func TestDriveImageBudgetPreservesAttachmentsAndExportFailures(t *testing.T) {
for _, failExport := range []bool{false, true} {
t.Run(strconv.FormatBool(failExport), func(t *testing.T) {
blocks := driveDocxBlocks("attachment", "report.pdf")
for i := 0; i < 61; i++ {
blocks = append(blocks, core.DocxBlock{
BlockID: fmt.Sprintf("img%d", i), BlockType: core.BlockTypeImage,
Image: &core.BlockTokenRef{Token: "img"},
})
}
ts, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
blocks, "ok", bytes.Repeat([]byte("pdf"), 1024))
handler := ts.Config.Handler
var mediaDownloads atomic.Int32
ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/medias/") {
mediaDownloads.Add(1)
}
if failExport && r.URL.Path == "/open-apis/drive/v1/export_tasks" {
writeJSON(w, core.ApiResponse{Code: 1, Msg: "export unavailable"})
return
}
handler.ServeHTTP(w, r)
})
items, err := core.FetchDocxWithBlocks(context.Background(), core.NewClient(cfg), core.DocxFetchInput{
DocToken: driveDocxFileToken, ObjToken: driveDocxFileToken, Title: "Images",
BaseMeta: map[string]string{}, ParseMode: core.ParseModeBlocks,
})
if failExport {
if err == nil || len(items) != 0 {
t.Fatalf("failed export must remain retryable: err=%v items=%d", err, len(items))
}
if mediaDownloads.Load() != 0 {
t.Fatal("media downloaded despite failed parent export")
}
return
}
if err != nil {
t.Fatal(err)
}
if len(items) != 2 {
t.Fatalf("want attachment and exported parent, got %d", len(items))
}
parent := items[1]
childID := types.SubtreeChildID(driveDocxFileToken, "file", "attachment")
if items[0].ExternalID != childID || items[0].Metadata["parent_doc_id"] != parent.ExternalID {
t.Fatal("lost attachment association")
}
if !parent.ReplacesSubtree || len(parent.SubtreeKeep) != 1 || parent.SubtreeKeep[0] != childID ||
!strings.Contains(parent.Metadata["attachment_ids"], childID) {
t.Fatalf("lost attachment keep list: %+v", parent)
}
if mediaDownloads.Load() != 1 {
t.Fatalf("want only attachment download, got %d", mediaDownloads.Load())
}
})
}
}
@@ -0,0 +1,61 @@
package drive
import (
"context"
"encoding/json"
"net/http"
"os"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
func TestMain(m *testing.M) {
os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
secutils.ResetSSRFWhitelistForTest()
os.Exit(m.Run())
}
func writeJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
func makeConfig(cfg *core.Config, resourceIDs []string) *types.DataSourceConfig {
creds := map[string]interface{}{
"app_id": cfg.AppID,
"app_secret": cfg.AppSecret,
"base_url": cfg.BaseURL,
}
return &types.DataSourceConfig{
Type: types.ConnectorTypeFeishu,
Credentials: creds,
ResourceIDs: resourceIDs,
}
}
type recordingHandler struct {
emitted []types.FetchedItem
checkpoints []core.FeishuDriveCursor
emitErr func(item types.FetchedItem) error
}
func (h *recordingHandler) Emit(_ context.Context, item types.FetchedItem) error {
if h.emitErr != nil {
if err := h.emitErr(item); err != nil {
return err
}
}
h.emitted = append(h.emitted, item)
return nil
}
func (h *recordingHandler) Checkpoint(_ context.Context, cursor *types.SyncCursor) error {
var fc core.FeishuDriveCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
h.checkpoints = append(h.checkpoints, fc)
return nil
}
@@ -0,0 +1,145 @@
package drive
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
)
// TestClientDriveListFilesPagination is the Drive (云盘) counterpart of the wiki
// test added in #3645 (TestClientWikiPaginationRejectsRepeatedPageToken):
// ListDriveFilesAllPages used to stop only on an empty next_page_token, so a
// repeated token (or has_more=false with a stale token) made it re-request the
// same page forever. Each case runs under a short deadline so a regression
// fails fast instead of hanging the suite.
func TestClientDriveListFilesPagination(t *testing.T) {
tests := []struct {
name string
response func(page int) core.DriveFileListResponse
wantErr string
wantRequests int
wantFiles []string
}{
{
// Feishu can hand back has_more=true with a token it already
// returned; that is exactly what #3645 hit on the wiki endpoints.
name: "repeated page token",
response: func(page int) core.DriveFileListResponse {
return core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{
Files: []core.DriveFile{{Token: fmt.Sprintf("file-%d", page)}},
HasMore: true,
NextPageToken: "repeated-token",
},
}
},
wantErr: "repeated page token",
wantRequests: 2,
},
{
// has_more=false is the authoritative stop signal: a residual
// non-empty token must not trigger another round trip.
name: "has_more false with stale token",
response: func(int) core.DriveFileListResponse {
return core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{
Files: []core.DriveFile{{Token: "file-1"}},
HasMore: false,
NextPageToken: "stale-token",
},
}
},
wantRequests: 1,
wantFiles: []string{"file-1"},
},
{
// The guard must not truncate a genuinely paginated folder.
name: "two real pages are still merged",
response: func(page int) core.DriveFileListResponse {
if page == 1 {
return core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{
Files: []core.DriveFile{{Token: "file-1"}},
HasMore: true,
NextPageToken: "token-2",
},
}
}
return core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{
Files: []core.DriveFile{{Token: "file-2"}},
HasMore: false,
NextPageToken: "",
},
}
},
wantRequests: 2,
wantFiles: []string{"file-1", "file-2"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mux := http.NewServeMux()
authPath := "/open-apis/auth/v3/tenant_access_token/internal"
mux.HandleFunc(authPath, func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.TokenResponse{
ApiResponse: core.ApiResponse{Code: 0},
TenantAccessToken: "fake-token",
Expire: 7200,
})
})
var requests atomic.Int64
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, tt.response(int(requests.Add(1))))
})
ts := httptest.NewServer(mux)
defer ts.Close()
client := core.NewClient(&core.Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
files, err := client.ListDriveFilesAllPages(ctx, "folder1")
if ctx.Err() != nil {
t.Fatalf("pagination never terminated (requests=%d, err=%v)", requests.Load(), err)
}
if tt.wantErr == "" {
if err != nil {
t.Fatalf("ListDriveFilesAllPages() error = %v, want nil", err)
}
} else if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("ListDriveFilesAllPages() error = %v, want error containing %q", err, tt.wantErr)
}
if got := int(requests.Load()); got != tt.wantRequests {
t.Fatalf("drive list requests = %d, want %d", got, tt.wantRequests)
}
gotFiles := make([]string, 0, len(files))
seen := make(map[string]bool, len(files))
for _, f := range files {
if seen[f.Token] {
t.Fatalf("file token %q was appended more than once", f.Token)
}
seen[f.Token] = true
gotFiles = append(gotFiles, f.Token)
}
if tt.wantFiles != nil && !reflect.DeepEqual(gotFiles, tt.wantFiles) {
t.Fatalf("files = %v, want %v", gotFiles, tt.wantFiles)
}
})
}
}
@@ -0,0 +1,158 @@
package drive
import (
"context"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// This file implements the P1 directory mapping for the Drive connector:
// FetchedItem.FileName becomes "<根文件夹名>/<子目录...>/<文件名>" rooted at
// the selected sync root's own display name (the root folder = a top-level KB
// folder) so ingestion's types.SplitKnowledgeRelativePath derives the KB
// folder_path. The recursive
// walk itself is core.WalkDriveTree (the Drive connector's single walker,
// shared with core): DFS order, shortcut expansion, partial-failure
// aggregation — plus a folder-token → cleaned directory path table built in
// the same pass, so no extra API calls are made. This file only resolves the
// per-resource root and feeds the walk results into Fetch.
// driveFolderName resolves a folder's display name via GetDriveFolderMeta,
// one call per token per sync run (cached on success only — a failure is not
// cached, so the next resource in the same run retries). resolved is false
// when the meta call failed or returned no name — that folder's path prefix
// segment (root or sub-folder) is then skipped.
func (o *driveOps) driveFolderName(
ctx context.Context, client *core.Client, folderToken string,
) (name string, resolved bool) {
if o.folderNames == nil {
o.folderNames = make(map[string]string)
}
if name, ok := o.folderNames[folderToken]; ok {
return name, true
}
meta, err := client.GetDriveFolderMeta(ctx, folderToken)
if err != nil {
logger.Warnf(ctx, "[FeishuDrive] resolve folder name for %s: %v (falling back)", folderToken, err)
return "", false
}
if meta.Data.Name == "" {
return "", false
}
name = core.SanitizeFileName(meta.Data.Name)
o.folderNames[folderToken] = name
return name, true
}
// listDriveFilesForResource lists the files to sync for a resourceID and
// records the directory-path table for Fetch. A resourceID is either a bare
// rootFolderToken (sync the whole subtree) or "rootFolderToken:fileToken"
// (sync a single selected file or sub-folder). Every walk is rooted at the
// root folder's own display name, so the synced folder appears as a top-level
// KB folder holding its subtree (an unresolved root name falls back to no
// prefix, mirroring pre-root-mirror behaviour).
func (o *driveOps) listDriveFilesForResource(
ctx context.Context, client *core.Client, resourceID string,
) ([]core.DriveFile, error) {
rootFolderToken, fileToken := parseDriveResourceID(resourceID)
rootBase := ""
if rootName, ok := o.driveFolderName(ctx, client, rootFolderToken); ok {
rootBase = rootName
}
if fileToken == "" {
// The selected root folder maps to a top-level KB folder named after
// it: documents directly under it land in folder_path "<根名>".
files, dirPaths, failures := core.WalkDriveTree(ctx, client, rootFolderToken, rootBase)
o.dirPaths = dirPaths
return files, partialDriveError(failures)
}
// A shallow root listing identifies direct files without probing them with
// folder APIs, and direct folders without visiting unselected siblings.
if o.rootEntries == nil {
o.rootEntries = make(map[string][]core.DriveFile)
}
entries, cached := o.rootEntries[rootFolderToken]
if !cached {
if listed, err := client.ListDriveFilesAllPages(ctx, rootFolderToken); err == nil {
entries = listed
o.rootEntries[rootFolderToken] = listed
}
}
base := rootBase
folderFound := false
for _, entry := range entries {
f, ok := core.ExpandDriveShortcut(entry)
if !ok || (entry.Token != fileToken && f.Token != fileToken) {
continue
}
if f.Type != "folder" {
// Some list responses omit parent_token; the listing itself tells
// us the containing directory.
f.ParentToken = rootFolderToken
o.dirPaths = map[string]string{rootFolderToken: rootBase}
return []core.DriveFile{f}, nil
}
folderFound = true
base = joinDriveDir(rootBase, core.SanitizeFileName(f.Name))
break
}
if !folderFound {
// A nested selected folder can be walked directly, even when the
// caller cannot list its parent. No full-root discovery is needed.
if subName, ok := o.driveFolderName(ctx, client, fileToken); ok {
base = joinDriveDir(rootBase, subName)
}
}
files, dirPaths, failures := core.WalkDriveTree(ctx, client, fileToken, base)
for _, failure := range failures {
if failure.FolderToken == fileToken && isDriveNotFolderError(failure.Err) {
// Only nested single files need the legacy root search: Drive
// exposes no single-file parent query. Never use this fallback for
// permission/transport failures, which must retain the old cursor.
rootFiles, rootDirs, rootFailures := core.WalkDriveTree(ctx, client, rootFolderToken, rootBase)
o.dirPaths = rootDirs
return filterDriveFileByToken(rootFiles, fileToken), partialDriveError(rootFailures)
}
}
o.dirPaths = dirPaths
return files, partialDriveError(failures)
}
func joinDriveDir(parent, name string) string {
if parent == "" {
return name
}
if name == "" {
return parent
}
return parent + "/" + name
}
// partialDriveError wraps collected failures into a
// *core.PartialDriveFileListError (nil when there are none).
func partialDriveError(failures []core.DriveFileListFailure) error {
if len(failures) == 0 {
return nil
}
return &core.PartialDriveFileListError{Failures: failures}
}
// qualifyItemFileNames prefixes every fetched item's FileName with dir so
// ingestion derives the KB folder path. The prefix applies to the main item
// and to attachment/image sub-items alike — they all live in the same folder.
// An empty dir (parent folder not in the current walk) or FileName is untouched.
func qualifyItemFileNames(items []*types.FetchedItem, dir string) {
if dir == "" {
return
}
for _, it := range items {
if it != nil && it.FileName != "" {
it.FileName = dir + "/" + it.FileName
}
}
}
@@ -0,0 +1,598 @@
package wiki
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// Connector implements the datasource.Connector interface for Feishu and, with
// the same code, for Lark: the two clouds expose an identical wiki/docx/drive
// API surface. A core.Region picks the cloud — see region.go.
type Connector struct {
region core.Region
}
// NewConnector creates a connector for the given region (RegionFeishu or RegionLark).
func NewConnector(region core.Region) *Connector {
return &Connector{region: region}
}
// Feishu supports resumable streaming sync; the service prefers FetchStream over
// FetchAll/FetchIncremental when a connector implements StreamingConnector.
var _ datasource.StreamingConnector = (*Connector)(nil)
var _ datasource.FullStreamingConnector = (*Connector)(nil)
// Type returns the connector type identifier.
func (c *Connector) Type() string {
return c.region.ConnectorType
}
// Validate verifies that the Feishu configuration is valid by testing connectivity.
func (c *Connector) Validate(ctx context.Context, config *types.DataSourceConfig) error {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return err
}
client := core.NewClient(feishuConfig)
if err := client.Ping(ctx); err != nil {
return fmt.Errorf("feishu connection failed: %w", err)
}
return nil
}
// ListResources lists Feishu Wiki resources for selection, loading the tree
// lazily one level at a time to avoid traversing the entire wiki up front.
//
// - parentID == "" → list all accessible wiki spaces.
// - parentID == spaceID → list the top-level nodes of that space.
// - parentID == "spaceID:nodeToken" → list the direct children of that node.
//
// Eagerly recursing the whole tree here used to time out for large wikis
// (Tencent/WeKnora#1672); the recursive walk now happens only at sync time.
func (c *Connector) ListResources(
ctx context.Context, config *types.DataSourceConfig, parentID string,
) ([]types.Resource, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
if parentID == "" {
spaces, err := client.ListWikiSpaces(ctx)
if err != nil {
return nil, fmt.Errorf("list feishu wiki spaces: %w", err)
}
resources := make([]types.Resource, 0, len(spaces))
for _, space := range spaces {
resources = append(resources, types.Resource{
ExternalID: space.SpaceID,
Name: space.Name,
Type: "wiki_space",
Description: space.Description,
URL: c.region.WikiURL(space.SpaceID),
HasChildren: true,
Metadata: map[string]interface{}{
"visibility": space.Visibility,
"space_id": space.SpaceID,
},
})
}
return resources, nil
}
// Lazy load: list only the direct children of the given space / node.
spaceID, nodeToken := parseWikiResourceID(parentID)
nodes, err := client.ListWikiNodes(ctx, spaceID, nodeToken)
if err != nil {
return nil, fmt.Errorf("list feishu wiki nodes under %s: %w", parentID, err)
}
resources := make([]types.Resource, 0, len(nodes))
for _, node := range nodes {
resources = append(resources, c.wikiNodeToResource(spaceID, node))
}
return resources, nil
}
// ResolveResourceAncestors returns the resource IDs of every parent that has to
// be expanded so the lazily-loaded picker can reveal each given selection. For a
// selected node "spaceID:nodeToken" that is its space plus every intermediate
// node up the tree; the walk uses GetWikiNode (parent_node_token) and is O(depth)
// per selection, so it never re-traverses the whole wiki.
func (c *Connector) ResolveResourceAncestors(
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
) ([]string, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
seen := make(map[string]bool)
ancestors := make([]string, 0)
add := func(id string) {
if id != "" && !seen[id] {
seen[id] = true
ancestors = append(ancestors, id)
}
}
for _, rid := range resourceIDs {
spaceID, nodeToken := parseWikiResourceID(rid)
if spaceID == "" || nodeToken == "" {
// A space-level selection is already a top-level node in the picker;
// there is nothing above it to reveal.
continue
}
// The space's direct children must be loaded to reveal the top-level node.
add(spaceID)
// Walk up from the selection to the top, loading each intermediate
// parent so the path down to the selection becomes visible.
current := nodeToken
for current != "" {
node, err := client.GetWikiNode(ctx, spaceID, current)
if err != nil {
// Best-effort: a broken path just stays collapsed, the rest of
// the selections are still revealed.
logger.Warnf(ctx, "[Feishu] resolve ancestors: get node %s:%s: %v", spaceID, current, err)
break
}
if node.ParentNodeID == "" {
break
}
add(makeWikiNodeResourceID(spaceID, node.ParentNodeID))
current = node.ParentNodeID
}
}
return ancestors, nil
}
// FetchAll performs a full sync of all documents from the specified wiki spaces.
// Defensive fallback path - the service prefers FetchStream when the connector
// implements StreamingConnector.
func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig, resourceIDs []string) ([]types.FetchedItem, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
return core.FetchAllEngine(ctx, client, config, resourceIDs,
&wikiOps{region: c.region, parseMode: feishuConfig.ParseMode})
}
// FetchIncremental performs an incremental sync by comparing node edit times
// against the previously recorded state. Defensive fallback path - the service
// prefers FetchStream. Routed through the same engine, so the #2136
// failure-doesn't-advance-cursor semantics apply here too (previously this path
// advanced the cursor before fetching, a latent #2136 bug).
func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor) ([]types.FetchedItem, *types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, nil, err
}
client := core.NewClient(feishuConfig)
ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchIncrementalEngine(ctx, client, config, cursor, ops)
}
// FetchStream performs a resumable, memory-bounded sync. It unifies the full
// and incremental paths: with cursor == nil it fetches everything, and with a
// cursor it skips nodes whose recorded edit time is unchanged - the same
// mechanism that lets a sync which timed out mid-traversal resume from the last
// checkpoint instead of restarting (Tencent/WeKnora#2136).
//
// The per-node loop lives in the shared engine (engine.go); this shell only
// wires the wiki NodeOps adapter.
func (c *Connector) FetchStream(
ctx context.Context, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchStreamEngine(ctx, client, config, cursor, h, ops)
}
// FetchFullStream refetches content without discarding the deletion baseline.
func (c *Connector) FetchFullStream(
ctx context.Context, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchFullStreamEngine(ctx, client, config, cursor, h, ops)
}
// wikiOps adapts the wiki Connector to the generic sync engine. It carries the
// region (for URL rendering), encodes/decodes the wiki cursor wire format
// (core.FeishuCursor / space_node_times), and holds the per-run directory
// mapping state (P1): dirPaths maps node token → cleaned directory prefix
// rooted at the space's own name, so every synced space lands in a top-level
// KB folder named after the space. List builds the state for the resource
// being synced; Fetch reads it. runSync processes one resource at a time, so
// the mutation is race-free.
type wikiOps struct {
region core.Region
parseMode string
dirPaths map[string]string
// spacePrefixes caches spaceID → sanitized folder prefix for the run, so
// syncing K selected spaces costs one ListWikiSpaces paging pass total
// instead of one per space (failures cache "" and do not retry mid-run).
spacePrefixes map[string]string
}
// spaceDirPrefix resolves the synced space's display name (sanitized) as the
// top-level KB folder for this run, cached per space for the whole run.
// An unresolved name yields "" and the documents fall back to landing at the
// KB root (pre-mirror behaviour) rather than failing the sync.
func (o *wikiOps) spaceDirPrefix(ctx context.Context, client *core.Client, spaceID string) string {
if o.spacePrefixes == nil {
o.spacePrefixes = make(map[string]string)
}
if prefix, ok := o.spacePrefixes[spaceID]; ok {
return prefix
}
prefix := ""
spaces, err := client.ListWikiSpaces(ctx)
if err != nil {
logger.Warnf(ctx, "[Feishu] list wiki spaces for space folder prefix %s: %v", spaceID, err)
} else {
for _, s := range spaces {
if s.SpaceID == spaceID && s.Name != "" {
prefix = core.SanitizeFileName(s.Name)
break
}
}
}
o.spacePrefixes[spaceID] = prefix
return prefix
}
func (o *wikiOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.WikiNode, error, error) {
spaceID, nodeToken := parseWikiResourceID(resourceID)
nodes, err := client.ListWikiNodesWithShortcuts(ctx, spaceID, nodeToken)
if err != nil {
var partial *core.PartialWikiNodeListError
if !errors.As(err, &partial) {
// Total listing failure: nothing usable — abort the sync.
return nodes, nil, err
}
// Partial listing: nodes are still usable; the failed sub-trees are
// surfaced via ListFailureItems, and the sync continues.
}
// On a partial listing the original's descendants may be missing even
// when the original node itself is present. Keep the accessible shortcut.
if err == nil {
nodes = filterShortcutSubtrees(nodes)
}
o.prepareDirPaths(nodes, o.spaceDirPrefix(ctx, client, spaceID))
if err != nil {
return nodes, err, nil
}
return nodes, nil, nil
}
func (o *wikiOps) Token(n core.WikiNode) string { return n.NodeToken }
func (o *wikiOps) Title(n core.WikiNode) string { return n.Title }
func (o *wikiOps) ObjType(n core.WikiNode) string { return n.ObjType }
// EditTime is an opaque change key including the effective destination path.
// An ancestor rename/move changes that path without touching this node's times.
// Timestamp-only legacy cursors refresh once; source_updated_at still uses
// contentEditTime and never contains the path fingerprint.
func (o *wikiOps) EditTime(n core.WikiNode) string {
timestamp := core.DocxChangeKey(wikiNodeEditTime(n), n.ObjType, o.parseMode)
if dir, ok := o.dirPaths[n.NodeToken]; ok {
pathHash := sha256.Sum256([]byte(dir + "\x00" + core.SanitizeFileName(n.Title)))
return fmt.Sprintf("%s:%x", timestamp, pathHash)
}
return timestamp
}
func wikiNodeEditTime(n core.WikiNode) string {
obj, objErr := strconv.ParseInt(n.ObjEditTime, 10, 64)
node, nodeErr := strconv.ParseInt(n.NodeEditTime, 10, 64)
switch {
case objErr != nil && nodeErr != nil:
return n.ObjEditTime
case objErr != nil:
return n.NodeEditTime
case nodeErr != nil:
return n.ObjEditTime
case node > obj:
return n.NodeEditTime
default:
return n.ObjEditTime
}
}
func (o *wikiOps) Fetch(
ctx context.Context, client *core.Client, n core.WikiNode, resourceID string,
) ([]*types.FetchedItem, error) {
spaceID, _ := parseWikiResourceID(resourceID)
if n.SpaceID != "" {
spaceID = n.SpaceID
}
items, err := fetchNodeContent(ctx, client, n, spaceID, resourceID, o.region, o.parseMode)
if err != nil {
return nil, err
}
// P1 directory mapping: prefix the FileName with the node's cleaned
// directory path so ingestion derives the KB folder_path from it.
qualifyItemFileNames(items, o.dirPaths[n.NodeToken])
return items, nil
}
func (o *wikiOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
spaceID, _ := parseWikiResourceID(resourceID)
var pe *core.PartialWikiNodeListError
if errors.As(partial, &pe) {
return appendWikiNodeListFailureItems(nil, spaceID, resourceID, pe.Failures)
}
return nil
}
func (o *wikiOps) ResourceNoun() string { return "nodes" }
func (o *wikiOps) EmptyResourceIDsError() string {
return "no resource IDs (wiki space IDs or wiki node IDs) configured"
}
func (o *wikiOps) LogTag() string { return "[Feishu]" }
func (o *wikiOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
var prev core.FeishuCursor
b, _ := json.Marshal(m)
_ = json.Unmarshal(b, &prev)
return prev.SpaceNodeTimes
}
func (o *wikiOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
fc := core.FeishuCursor{LastSyncTime: lastSync, SpaceNodeTimes: times}
m := make(map[string]interface{})
b, _ := json.Marshal(fc)
_ = json.Unmarshal(b, &m)
return &types.SyncCursor{LastSyncTime: lastSync, ConnectorCursor: m}
}
func appendWikiNodeListFailureItems(items []types.FetchedItem, spaceID string, resourceID string, failures []core.WikiNodeListFailure) []types.FetchedItem {
for _, failure := range failures {
node := failure.Node
nodeSpaceID := node.SpaceID
if nodeSpaceID == "" {
nodeSpaceID = spaceID
}
title := node.Title
if title == "" {
title = node.NodeToken
}
items = append(items, types.FetchedItem{
ExternalID: node.NodeToken,
Title: title,
SourceResourceID: resourceID,
Metadata: core.FeishuErrorItemMeta(failure.Err, map[string]string{
"channel": types.ChannelFeishu,
"node_token": node.NodeToken,
"space_id": nodeSpaceID,
"failure_stage": "list_children",
}),
})
}
return items
}
// fetchNodeContent fetches the content of a single wiki node and converts it to a
// slice of FetchedItems. For docx nodes it fans out into a main Markdown document
// plus optional attachment sub-items. Dispatches to different retrieval strategies
// based on obj_type:
// - docx → blocks API (Markdown) with export fallback; may return attachments
// - doc/sheet/bitable → export API → binary file
// - file → drive download → original file (PDF/Word/image/etc.)
// - mindnote → Skip (no API)
// - slides → Skip (no API)
func fetchNodeContent(
ctx context.Context, client *core.Client, node core.WikiNode,
spaceID string, resourceID string, region core.Region, parseMode string,
) ([]*types.FetchedItem, error) {
if !core.IsSupportedDocType(node.ObjType) {
return nil, nil
}
editTime := contentEditTime(node)
createTime := contentCreateTime(node)
baseMeta := map[string]string{
"obj_token": node.ObjToken,
"obj_type": node.ObjType,
"node_token": node.NodeToken,
"space_id": spaceID,
"creator": node.Creator,
"owner": node.Owner,
"channel": types.ChannelFeishu,
}
switch node.ObjType {
case "docx":
return core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
DocToken: node.NodeToken,
ObjToken: node.ObjToken,
Title: node.Title,
URL: region.WikiURL(node.NodeToken),
ResourceID: resourceID,
EditTime: editTime,
CreateTime: createTime,
ParseMode: parseMode,
BaseMeta: baseMeta,
})
case "doc", "sheet", "bitable":
item, err := fetchViaExport(ctx, client, node, resourceID, editTime, baseMeta, region)
if err != nil {
return nil, err
}
item.CreatedAt = createTime
return []*types.FetchedItem{item}, nil
case "file":
item, err := fetchDriveFile(ctx, client, node, resourceID, editTime, baseMeta, region)
if err != nil {
return nil, err
}
item.CreatedAt = createTime
return []*types.FetchedItem{item}, nil
default:
return nil, nil
}
}
// fetchViaExport exports a doc/sheet/bitable node via the async export API and
// returns a single FetchedItem containing the exported binary.
func fetchViaExport(ctx context.Context, client *core.Client, node core.WikiNode, resourceID string, editTime time.Time, baseMeta map[string]string, region core.Region) (*types.FetchedItem, error) {
// Export as a file via the async export API
data, fileName, err := client.ExportAndDownload(ctx, node.ObjToken, node.ObjType)
if err != nil {
return nil, fmt.Errorf("export %s (%s): %w", node.Title, node.ObjType, err)
}
// Ensure a reasonable file name with correct extension
ext := core.ExportFileExtToSuffix[core.ObjTypeToExportFileExtension[node.ObjType]]
if fileName == "" {
fileName = core.SanitizeFileName(node.Title) + ext
} else if !strings.HasSuffix(strings.ToLower(fileName), ext) {
// Feishu often returns the doc title without extension - append it
fileName = core.SanitizeFileName(fileName) + ext
}
return &types.FetchedItem{
ExternalID: node.NodeToken,
Title: node.Title,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: region.WikiURL(node.NodeToken),
UpdatedAt: editTime,
SourceResourceID: resourceID,
Metadata: baseMeta,
}, nil
}
// fetchDriveFile downloads an original uploaded file from Drive and returns a
// single FetchedItem containing the raw bytes.
func fetchDriveFile(ctx context.Context, client *core.Client, node core.WikiNode, resourceID string, editTime time.Time, baseMeta map[string]string, region core.Region) (*types.FetchedItem, error) {
// Download the original uploaded file from Drive
data, err := client.DownloadDriveFile(ctx, node.ObjToken)
if err != nil {
return nil, fmt.Errorf("download file %s (%s): %w", node.Title, node.ObjToken, err)
}
// Use the node title as file name; it usually preserves the original extension
fileName := core.SanitizeFileName(node.Title)
if fileName == "" {
fileName = node.ObjToken
}
return &types.FetchedItem{
ExternalID: node.NodeToken,
Title: node.Title,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: region.WikiURL(node.NodeToken),
UpdatedAt: editTime,
SourceResourceID: resourceID,
Metadata: baseMeta,
}, nil
}
// contentEditTime is the document's last content edit time (obj_edit_time),
// falling back to the node attribute edit time when Feishu omits it. It is
// what ingestion persists as source_updated_at; NodeEditTime alone would move
// on a rename or a move in the tree without any content change.
func contentEditTime(node core.WikiNode) time.Time {
if t := core.ParseFeishuTimestamp(node.ObjEditTime); !t.IsZero() {
return t
}
return core.ParseFeishuTimestamp(node.NodeEditTime)
}
// contentCreateTime is the document creation time (obj_create_time), falling
// back to the node creation time. Persisted as source_created_at.
func contentCreateTime(node core.WikiNode) time.Time {
if t := core.ParseFeishuTimestamp(node.ObjCreateTime); !t.IsZero() {
return t
}
return core.ParseFeishuTimestamp(node.NodeCreateTime)
}
// --- Helper functions ---
func makeWikiNodeResourceID(spaceID, nodeToken string) string {
return spaceID + core.FeishuWikiNodeResourceSeparator + nodeToken
}
func parseWikiResourceID(resourceID string) (spaceID string, nodeToken string) {
spaceID, nodeToken, _ = strings.Cut(resourceID, core.FeishuWikiNodeResourceSeparator)
return spaceID, nodeToken
}
func (c *Connector) wikiNodeToResource(spaceID string, node core.WikiNode) types.Resource {
parentID := spaceID
if node.ParentNodeID != "" {
parentID = makeWikiNodeResourceID(spaceID, node.ParentNodeID)
}
name := node.Title
if name == "" {
name = node.NodeToken
}
modifiedAt := core.ParseFeishuTimestamp(node.ObjEditTime)
if modifiedAt.IsZero() {
modifiedAt = core.ParseFeishuTimestamp(node.NodeEditTime)
}
return types.Resource{
ExternalID: makeWikiNodeResourceID(spaceID, node.NodeToken),
Name: name,
Type: "wiki_node",
URL: c.region.WikiURL(node.NodeToken),
ParentID: parentID,
HasChildren: node.HasChild,
ModifiedAt: modifiedAt,
Metadata: map[string]interface{}{
"space_id": spaceID,
"node_token": node.NodeToken,
"obj_token": node.ObjToken,
"obj_type": node.ObjType,
},
}
}
@@ -0,0 +1,267 @@
package wiki
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
)
// statefulFeishu is a fake Feishu server whose per-node export outcome can be
// changed between sync passes. A node whose obj_token is in failTokens has its
// export status poll return a failed job, so fetchNodeContent errors for it —
// modelling a transient rate-limit / export failure that later recovers.
type statefulFeishu struct {
mu sync.Mutex
failTokens map[string]bool
}
func (s *statefulFeishu) setFail(tokens ...string) {
s.mu.Lock()
defer s.mu.Unlock()
s.failTokens = map[string]bool{}
for _, t := range tokens {
s.failTokens[t] = true
}
}
func (s *statefulFeishu) shouldFail(token string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.failTokens[token]
}
func newStatefulFeishu(nodes []core.WikiNode) (*httptest.Server, *core.Config, *statefulFeishu) {
s := &statefulFeishu{failTokens: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiNodeListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeListData{Items: nodes},
})
})
// Export create: ticket == obj_token so the poll below can key on it.
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) {
var body struct {
Token string `json:"token"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
writeJSON(w, core.ExportTaskCreateResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskCreateData{Ticket: body.Token},
})
})
// Export status poll: /open-apis/drive/v1/export_tasks/<ticket>?token=<objToken>
mux.HandleFunc("/open-apis/drive/v1/export_tasks/", func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/file/") && strings.HasSuffix(r.URL.Path, "/download") {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("fake-docx-content"))
return
}
token := r.URL.Query().Get("token")
status := 0
if s.shouldFail(token) {
status = 3 // failed job
}
resp := core.ExportTaskStatusResponse{ApiResponse: core.ApiResponse{Code: 0}}
resp.Data.Result.FileToken = "file-" + token
resp.Data.Result.FileName = "exported.docx"
resp.Data.Result.JobStatus = status
resp.Data.Result.JobErrorMsg = "rate limited"
writeJSON(w, resp)
})
ts := httptest.NewServer(mux)
return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}, s
}
// convergenceHandler models the service side across a resumable sync:
// - Emit ingests content items (mirroring the service's ctx check + apply),
// records failure items separately, and can simulate a mid-tree task timeout
// by canceling the run's context after cancelAfterCalls Emit calls.
// - Checkpoint snapshots the connector cursor (the DB round-trip).
type convergenceHandler struct {
ingested []string // ExternalIDs of successfully ingested content items
failed []string // ExternalIDs surfaced as failures (Metadata["error"])
exportedTokens map[string]int
checkpoints []core.FeishuCursor
calls int
cancelAfterCall int // >0: cancel ctx and abort on the Nth Emit call
cancel context.CancelFunc
}
func (h *convergenceHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if err := ctx.Err(); err != nil { // mirror service Emit
return err
}
h.calls++
if h.cancelAfterCall > 0 && h.calls >= h.cancelAfterCall {
if h.cancel != nil {
h.cancel()
}
return context.Canceled // service returns ctx err → connector aborts
}
if item.Metadata["error"] != "" {
h.failed = append(h.failed, item.ExternalID)
return nil
}
h.ingested = append(h.ingested, item.ExternalID)
return nil
}
func (h *convergenceHandler) Checkpoint(ctx context.Context, cursor *types.SyncCursor) error {
var fc core.FeishuCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
h.checkpoints = append(h.checkpoints, fc)
return nil
}
func lastCheckpointCursor(h *convergenceHandler, t *testing.T) *types.SyncCursor {
t.Helper()
if len(h.checkpoints) == 0 {
return nil
}
last := h.checkpoints[len(h.checkpoints)-1]
b, _ := json.Marshal(last)
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
t.Fatalf("rebuild persisted cursor: %v", err)
}
return &types.SyncCursor{ConnectorCursor: m}
}
// TestFetchStream_ResumeConvergesAfterTimeoutAndTransientFailure is the
// end-to-end proof for Tencent/WeKnora#2136: a large-ish wiki that (a) hits a
// transient per-node export failure and (b) is killed by the 2h task timeout
// mid-traversal must, on the asynq retry, resume from the last Checkpoint,
// re-core.Fetch only what is outstanding, retry the transiently-failed node, and end
// with EVERY document synced exactly once — no permanent core.Skip, no full restart,
// no redundant re-export of already-done nodes.
func TestFetchStream_ResumeConvergesAfterTimeoutAndTransientFailure(t *testing.T) {
// Checkpoint on every processed node so the persisted cursor is precise.
prevN := core.FeishuStreamCheckpointInterval
core.FeishuStreamCheckpointInterval = 1
defer func() { core.FeishuStreamCheckpointInterval = prevN }()
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc1", ObjEditTime: "100"},
{NodeToken: "nt2", ObjToken: "obj2", ObjType: "docx", Title: "Doc2", ObjEditTime: "200"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
{NodeToken: "nt4", ObjToken: "obj4", ObjType: "docx", Title: "Doc4", ObjEditTime: "400"},
{NodeToken: "nt5", ObjToken: "obj5", ObjType: "docx", Title: "Doc5", ObjEditTime: "500"},
}
ts, cfg, srv := newStatefulFeishu(nodes)
defer ts.Close()
cfgDS := makeConfig(cfg, []string{"space1"})
c := NewConnector(core.RegionFeishu)
// ---- Pass 1: obj2 export fails transiently; task "times out" on the 3rd
// Emit call (nt1 success, nt2 failure-item, then cancel as nt3 is emitted).
srv.setFail("obj2")
ctx1, cancel1 := context.WithCancel(context.Background())
h1 := &convergenceHandler{cancelAfterCall: 3, cancel: cancel1}
_, err1 := c.FetchStream(ctx1, cfgDS, nil, h1)
cancel1()
if err1 == nil {
t.Fatalf("pass 1 expected a timeout/abort error, got nil")
}
// Pass 1 ingested only nt1; nt2 surfaced as a failure; nt3+ never reached.
if got := strings.Join(h1.ingested, ","); got != "nt1" {
t.Fatalf("pass 1 ingested = %q, want just nt1", got)
}
// The persisted cursor (last Checkpoint) must contain nt1 but NOT the
// aborted nt3, nor the transiently-failed nt2 — otherwise resume would core.Skip
// them forever.
persisted := lastCheckpointCursor(h1, t)
if persisted == nil {
t.Fatalf("pass 1 wrote no Checkpoint — resume would restart from scratch")
}
var pc core.FeishuCursor
pb, _ := json.Marshal(persisted.ConnectorCursor)
_ = json.Unmarshal(pb, &pc)
p := pc.SpaceNodeTimes["space1"]
if _, ok := p["nt1"]; !ok {
t.Errorf("persisted cursor missing nt1 (done work lost on resume)")
}
if _, ok := p["nt2"]; ok {
t.Errorf("persisted cursor recorded transiently-failed nt2 — it would be core.Skipped forever")
}
if _, ok := p["nt3"]; ok {
t.Errorf("persisted cursor recorded aborted nt3 — it would be core.Skipped forever")
}
// ---- Pass 2: asynq retry. obj2 has recovered; run to completion resuming
// from the persisted cursor.
srv.setFail() // clear all failures
h2 := &convergenceHandler{}
next2, err2 := c.FetchStream(context.Background(), cfgDS, persisted, h2)
if err2 != nil {
t.Fatalf("pass 2 error: %v", err2)
}
// nt1 was already done → must be core.Skipped (not re-exported, not re-ingested).
for _, id := range h2.ingested {
if id == "nt1" {
t.Errorf("pass 2 re-ingested nt1 — redundant re-export of completed work")
}
}
// Everything still outstanding (nt2 transiently-failed, nt3 aborted, nt4, nt5)
// must be ingested in pass 2.
want := map[string]bool{"nt2": true, "nt3": true, "nt4": true, "nt5": true}
got2 := map[string]bool{}
for _, id := range h2.ingested {
got2[id] = true
}
for id := range want {
if !got2[id] {
t.Errorf("pass 2 did not ingest %s (want all outstanding nodes)", id)
}
}
// ---- Convergence: union across both passes covers ALL five nodes exactly.
union := map[string]bool{}
for _, id := range h1.ingested {
union[id] = true
}
for _, id := range h2.ingested {
union[id] = true
}
for _, n := range nodes {
if !union[n.NodeToken] {
t.Errorf("node %s was NEVER synced across both passes — data loss (#2136)", n.NodeToken)
}
}
if len(union) != len(nodes) {
t.Errorf("synced %d distinct nodes, want %d", len(union), len(nodes))
}
// Final cursor is a complete snapshot of every node (next incremental sync
// starts clean).
var fc core.FeishuCursor
nb, _ := json.Marshal(next2.ConnectorCursor)
_ = json.Unmarshal(nb, &fc)
for _, n := range nodes {
if _, ok := fc.SpaceNodeTimes["space1"][n.NodeToken]; !ok {
t.Errorf("final cursor missing %s — incremental sync would re-core.Fetch it", n.NodeToken)
}
}
}
@@ -0,0 +1,294 @@
package wiki
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
)
// ──────────────────────────────────────────────────────────────────────
// Golden end-to-end test: a single rich docx node exercising EVERY new
// capability at once, driven through the real Connector.FetchAll → real
// core.Client → Feishu-shaped fake endpoints (blocks / sheets-v2 / bitable-v1 /
// medias). This is the glue test the per-function unit tests can't be:
// it proves the whole pipeline produces correct, ordered Markdown plus the
// correctly filtered attachment sub-items.
// ──────────────────────────────────────────────────────────────────────
// blk constructors kept local to this file to keep the fixture readable.
func sheetBlk(id, token string) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeSheet, Sheet: &core.BlockTokenRef{Token: token}}
}
func bitableBlk(id, token string) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeBitable, Bitable: &core.BlockTokenRef{Token: token}}
}
func imageBlk(id, token string) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeImage, Image: &core.BlockTokenRef{Token: token}}
}
func fileBlk(id, token, name string) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeFile, File: &core.BlockFileRef{Token: token, Name: name}}
}
// cellBlk builds a table_cell container. A real Feishu table_cell holds no
// inline text of its own — its text lives in a child block, so the cell only
// references the child id (see cellTextBlk).
func cellBlk(id string) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeTableCell, Children: []string{id + "_txt"}}
}
// cellTextBlk builds the child text block a table cell points at.
func cellTextBlk(id, text string) core.DocxBlock {
return core.DocxBlock{BlockID: id + "_txt", BlockType: core.BlockTypeText, Text: txt(text)}
}
func tableBlk(id string, cols int, cellIDs ...string) core.DocxBlock {
b := core.DocxBlock{BlockID: id, BlockType: core.BlockTypeTable}
b.Table = &core.BlockTable{Cells: cellIDs}
b.Table.Property = &core.BlockTableProperty{ColumnSize: cols}
return b
}
// fakeFeishuGolden serves the full API surface a rich docx node needs.
func fakeFeishuGolden(nodes []core.WikiNode, docToken string, blocks []core.DocxBlock,
mediaByToken map[string][]byte,
) (*httptest.Server, *core.Config) {
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{ApiResponse: core.ApiResponse{Code: 0}, Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}}})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiNodeListResponse{ApiResponse: core.ApiResponse{Code: 0}, Data: core.WikiNodeListData{Items: nodes}})
})
// docx blocks — paginated across two pages to exercise the paging glue.
mux.HandleFunc("/open-apis/docx/v1/documents/"+docToken+"/blocks", func(w http.ResponseWriter, r *http.Request) {
half := len(blocks) / 2
page := blocks[:half]
hasMore := true
if r.URL.Query().Get("page_token") == "p2" {
page = blocks[half:]
hasMore = false
}
nextTok := "p2"
if !hasMore {
nextTok = ""
}
writeJSON(w, core.DocxBlocksResponse{ApiResponse: core.ApiResponse{Code: 0}, Data: core.DocxBlocksData{Items: page, HasMore: hasMore, PageToken: nextTok}})
})
// sheets-v2 values: sht_spread_0 → spreadsheet "sht_spread", sheet "0".
// Raw JSON keeps the fake honest to the real wire shape without wrestling
// nested anonymous-struct literals.
mux.HandleFunc("/open-apis/sheets/v2/spreadsheets/sht_spread/values/0", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"code":0,"msg":"","data":{"valueRange":{"values":[["名称","数量"],["苹果",3]]}}}`))
})
// bitable-v1 fields + records: bascApp_tblMain → app "bascApp", table "tblMain".
mux.HandleFunc("/open-apis/bitable/v1/apps/bascApp/tables/tblMain/fields", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"code":0,"msg":"","data":{"items":[{"field_name":"任务"},{"field_name":"状态"}]}}`))
})
mux.HandleFunc("/open-apis/bitable/v1/apps/bascApp/tables/tblMain/records/search", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"code":0,"msg":"","data":{"has_more":false,"page_token":"","items":[{"fields":{"任务":"写码","状态":"完成"}}]}}`))
})
// medias download, routed by token embedded in the path.
mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/download") {
http.NotFound(w, r)
return
}
// path: /open-apis/drive/v1/medias/<token>/download
p := strings.TrimPrefix(r.URL.Path, "/open-apis/drive/v1/medias/")
tok := strings.TrimSuffix(p, "/download")
data, ok := mediaByToken[tok]
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Write(data)
})
// ParseMode is set explicitly even though blocks is now the default, so the
// golden baseline stays valid if the default ever flips again (the env var
// FEISHU_DOCX_PARSE_MODE was retired in favor of per-data-source Settings).
ts := httptest.NewServer(mux)
return ts, &core.Config{
AppID: "test-app-id", AppSecret: "test-app-secret",
BaseURL: ts.URL, ParseMode: core.ParseModeBlocks,
}
}
func TestGolden_RichDocxAllCapabilities(t *testing.T) {
const docToken = "obj-golden"
bigPDF := bytes.Repeat([]byte("A"), core.MinAttachmentBytes+512) // kept
tinyPDF := bytes.Repeat([]byte("B"), 100) // whitelisted but too small → dropped
// Valid PNG for the embedded image block (image items are unconditional in
// the P3 marker pipeline; the media token stays out of the Markdown).
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
blocks := []core.DocxBlock{
{BlockID: "root", BlockType: core.BlockTypePage},
{BlockID: "h1", BlockType: core.BlockTypeHeading1, Heading1: txt("季度报告")},
{BlockID: "p1", BlockType: core.BlockTypeText, Text: txt("本季度概览。")},
{BlockID: "h2", BlockType: core.BlockTypeHeading1 + 1, Heading2: txt("关键指标")},
{BlockID: "b1", BlockType: core.BlockTypeBullet, Bullet: txt("收入增长")},
{BlockID: "o1", BlockType: core.BlockTypeOrdered, Ordered: txt("第一步立项")},
{BlockID: "code1", BlockType: core.BlockTypeCode, Code: txt("SELECT 1")},
{BlockID: "q1", BlockType: core.BlockTypeQuote, Quote: txt("重要提示")},
{BlockID: "todo1", BlockType: core.BlockTypeTodo, Todo: txt("完成复盘")},
{BlockID: "call1", BlockType: core.BlockTypeCallout, Callout: txt("注意风险")},
{BlockID: "div1", BlockType: core.BlockTypeDivider},
tableBlk("tbl1", 2, "c1", "c2", "c3", "c4"),
sheetBlk("sh1", "sht_spread_0"),
bitableBlk("bt1", "bascApp_tblMain"),
imageBlk("im1", "img-tok-SECRET"),
fileBlk("fbig", "tok-big", "手册.pdf"),
fileBlk("flogo", "tok-logo", "logo.png"), // non-whitelisted ext → no sub-item
fileBlk("fsmall", "tok-small", "small.pdf"), // whitelisted but too small → no sub-item
// table cells (containers) + their child text blocks — both are core.Skipped by
// the main loop and read by the table renderer via the cells' Children.
cellBlk("c1"), cellBlk("c2"), cellBlk("c3"), cellBlk("c4"),
cellTextBlk("c1", "列A"), cellTextBlk("c2", "列B"),
cellTextBlk("c3", "1"), cellTextBlk("c4", "2"),
}
nodes := []core.WikiNode{{
NodeToken: "nt-golden", ObjToken: docToken, ObjType: "docx",
Title: "季度报告文档", NodeEditTime: "1711468800",
}}
media := map[string][]byte{"tok-big": bigPDF, "tok-small": tinyPDF, "img-tok-SECRET": png}
ts, cfg := fakeFeishuGolden(nodes, docToken, blocks, media)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
items, err := c.FetchAll(context.Background(), makeConfig(cfg, []string{"space1"}), []string{"space1"})
if err != nil {
t.Fatalf("FetchAll error: %v", err)
}
// ── sub-items first (attachment), then the main markdown item ──
// Orthodox image flow (2026-09-20): images ride inline in the parent
// markdown as base64 data URIs — no image sub-items at all.
if len(items) != 2 {
t.Fatalf("want 2 items (1 kept attachment + main), got %d:\n%+v", len(items), items)
}
var main, att *types.FetchedItem
for i := range items {
switch items[i].ExternalID {
case "nt-golden":
main = &items[i]
case "nt-golden#file#tok-big":
att = &items[i]
}
}
if main == nil {
t.Fatal("main markdown item missing")
}
// P3 contract: sub-items precede the parent document.
if items[len(items)-1].ExternalID != "nt-golden" {
order := []string{items[0].ExternalID, items[1].ExternalID, items[2].ExternalID}
t.Errorf("main item must be emitted last, got order: %v", order)
}
if main.ContentType != "text/markdown" {
t.Errorf("main ContentType = %q, want text/markdown", main.ContentType)
}
if !main.ReplacesSubtree {
t.Error("main item must set ReplacesSubtree for orphan sweeping")
}
if !strings.HasSuffix(main.FileName, ".md") {
t.Errorf("main FileName = %q, want .md", main.FileName)
}
md := string(main.Content)
// ── every text construct rendered correctly ──
// Baseline re-recorded (2026-09-20, orthodox image flow): image blocks
// render inline base64 data URIs (stored to provider:// URLs by the
// doc-process image resolver), and file blocks render as
// `- 文件名` list entries (whitelisted) or `> [附件: …](链接)` references
// (non-whitelisted), replacing the old `📎 附件:…` placeholder.
fragments := []string{
"# 季度报告",
"本季度概览。",
"## 关键指标",
"- 收入增长",
"1. 第一步立项",
"```\nSELECT 1\n```",
"> 重要提示",
"- [ ] 完成复盘",
"> 注意风险",
"---",
"| 列A | 列B |", // native docx table header
"| 1 | 2 |", // native docx table row
"| 名称 | 数量 |", // embedded sheet header
"| 苹果 | 3 |", // embedded sheet row
"| 任务 | 状态 |", // embedded bitable header
"| 写码 | 完成 |", // embedded bitable row
"![图片](data:image/png;base64,", // image inlined as base64 data URI
"- 手册.pdf",
"> [附件: logo.png](",
"- small.pdf",
}
for _, f := range fragments {
if !strings.Contains(md, f) {
t.Errorf("markdown missing fragment %q\n--- full markdown ---\n%s", f, md)
}
}
// ── document order preserved (heading before table before attachments) ──
order := []string{"# 季度报告", "## 关键指标", "| 列A | 列B |", "| 名称 | 数量 |", "| 任务 | 状态 |", "- 手册.pdf"}
last := -1
for _, f := range order {
idx := strings.Index(md, f)
if idx <= last {
t.Errorf("fragment %q out of order (idx=%d, prev=%d)\n%s", f, idx, last, md)
}
last = idx
}
// ── the internal image media token must NEVER leak into embeddings ──
if strings.Contains(md, "img-tok-SECRET") {
t.Errorf("internal image token leaked into markdown:\n%s", md)
}
// The internal image media token must map to nothing: markers are gone.
if main.Metadata["image_map"] != "" {
t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
}
if !strings.Contains(main.Metadata["attachment_ids"], "nt-golden#file#tok-big") {
t.Errorf("main.Metadata[attachment_ids] = %q, want it to contain tok-big", main.Metadata["attachment_ids"])
}
// ── attachment filtering: only the big whitelisted PDF becomes a sub-item ──
if att == nil {
t.Fatal("kept attachment sub-item missing")
}
if att.ExternalID != "nt-golden#file#tok-big" {
t.Errorf("attachment ExternalID = %q, want nt-golden#file#tok-big", att.ExternalID)
}
if att.Title != "手册.pdf" {
t.Errorf("attachment Title = %q", att.Title)
}
if !bytes.Equal(att.Content, bigPDF) {
t.Errorf("attachment content mismatch: got %d bytes want %d", len(att.Content), len(bigPDF))
}
if att.Metadata["attachment"] != "true" || att.Metadata["parent_node_token"] != "nt-golden" {
t.Errorf("attachment metadata wrong: %+v", att.Metadata)
}
}
@@ -0,0 +1,234 @@
//go:build feishu_integration
// Real-API integration test for FetchStream against a live Feishu tenant.
//
// It is OPT-IN and never runs in the normal suite or CI: it is guarded by the
// `feishu_integration` build tag AND skips unless the required env vars are set.
//
// Run it with:
//
// export CPLUS_INCLUDE_PATH="$(xcrun --show-sdk-path)/usr/include/c++/v1"
// FEISHU_APP_ID=... FEISHU_APP_SECRET=... FEISHU_TEST_SPACE_ID=... \
// go test -tags feishu_integration -run TestRealAPI -v \
// ./internal/datasource/connector/feishu/
//
// The test is strictly READ-ONLY: it lists and exports documents from the given
// wiki space but never creates, edits or deletes anything. It whitelists
// *.feishu.cn / *.larksuite.com for SSRF in-process so it works from a dev
// machine behind a fake-ip proxy without any production code change.
package wiki
import (
"context"
"encoding/json"
"os"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// collectHandler records everything a real FetchStream emits so the test can
// assert coverage and resume behaviour. cancelAfter>0 simulates a task timeout
// by cancelling the run after that many successful content emits.
type collectHandler struct {
ingested []string
failed []string
checkpoints []*types.SyncCursor
calls int
cancelAfter int
cancel context.CancelFunc
}
func (h *collectHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if err := ctx.Err(); err != nil {
return err
}
if item.Metadata["error"] != "" {
h.failed = append(h.failed, item.ExternalID)
return nil
}
h.calls++
if h.cancelAfter > 0 && h.calls > h.cancelAfter {
if h.cancel != nil {
h.cancel()
}
return context.Canceled
}
h.ingested = append(h.ingested, item.ExternalID)
return nil
}
func (h *collectHandler) Checkpoint(_ context.Context, cursor *types.SyncCursor) error {
// Snapshot the cursor JSON (mirrors the service serialising synchronously).
b, _ := json.Marshal(cursor.ConnectorCursor)
var m map[string]interface{}
_ = json.Unmarshal(b, &m)
h.checkpoints = append(h.checkpoints, &types.SyncCursor{ConnectorCursor: m})
return nil
}
func nodeTimes(t *testing.T, cur *types.SyncCursor) map[string]map[string]string {
t.Helper()
if cur == nil {
return nil
}
var fc core.FeishuCursor
b, _ := json.Marshal(cur.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
return fc.SpaceNodeTimes
}
func countNodes(m map[string]map[string]string) int {
n := 0
for _, v := range m {
n += len(v)
}
return n
}
// TestRealAPI_ListSpaces discovers which wiki spaces the app can access, so the
// space ID for the other tests can be found without guessing. Read-only.
func TestRealAPI_ListSpaces(t *testing.T) {
appID := os.Getenv("FEISHU_APP_ID")
appSecret := os.Getenv("FEISHU_APP_SECRET")
if appID == "" || appSecret == "" {
t.Skip("set FEISHU_APP_ID, FEISHU_APP_SECRET to run")
}
utils.SetSSRFWhitelistFromRaw("*.feishu.cn,*.larksuite.com")
client := core.NewClient(&core.Config{AppID: appID, AppSecret: appSecret, BaseURL: os.Getenv("FEISHU_BASE_URL")})
spaces, err := client.ListWikiSpaces(context.Background())
if err != nil {
t.Fatalf("ListWikiSpaces: %v", err)
}
if len(spaces) == 0 {
t.Fatalf("app can access 0 wiki spaces — add the app as a member of a knowledge base")
}
for _, s := range spaces {
t.Logf("SPACE space_id=%s name=%q", s.SpaceID, s.Name)
}
}
func TestRealAPI_FetchStreamResumeConverges(t *testing.T) {
appID := os.Getenv("FEISHU_APP_ID")
appSecret := os.Getenv("FEISHU_APP_SECRET")
spaceID := os.Getenv("FEISHU_TEST_SPACE_ID")
if appID == "" || appSecret == "" || spaceID == "" {
t.Skip("set FEISHU_APP_ID, FEISHU_APP_SECRET, FEISHU_TEST_SPACE_ID to run")
}
// Whitelist the Feishu/Lark hosts for SSRF so the dev-machine fake-ip proxy
// (198.18.x) is allowed. No production code change; scoped to these hosts.
utils.SetSSRFWhitelistFromRaw("*.feishu.cn,*.larksuite.com")
baseURL := os.Getenv("FEISHU_BASE_URL") // optional; defaults to region base
cfg := &types.DataSourceConfig{
Type: types.ConnectorTypeFeishu,
Credentials: map[string]interface{}{
"app_id": appID,
"app_secret": appSecret,
"base_url": baseURL,
},
ResourceIDs: []string{spaceID},
}
c := NewConnector(core.RegionFeishu)
// ---- Pass 1: full sync against the real space.
h1 := &collectHandler{}
cur1, err := c.FetchStream(context.Background(), cfg, nil, h1)
if err != nil {
t.Fatalf("pass 1 (full) FetchStream error: %v", err)
}
n := len(h1.ingested)
t.Logf("pass 1: ingested=%d failed=%d cursor_nodes=%d", n, len(h1.failed), countNodes(nodeTimes(t, cur1)))
if n == 0 {
t.Fatalf("pass 1 ingested 0 documents — create a few docs in the space, or check app scopes (wiki/docx/drive read)")
}
// Every ingested *node* must be recorded in the cursor. A multi-item node (a
// docx that fans out into a main document plus attachment/image sub-items)
// also ingests child items whose external_id is "<node>#file#..." or
// "<node>#image#...". Those are not wiki nodes: they ride their parent node's
// edit-time and intentionally carry no independent cursor entry (the parent's
// edit-time gates re-core.Fetch of the whole subtree). Only node-level ids are
// required to be present.
nt1 := nodeTimes(t, cur1)[spaceID]
for _, id := range h1.ingested {
if strings.Contains(id, "#") {
continue // attachment/image sub-item, not a top-level cursor node
}
if _, ok := nt1[id]; !ok {
t.Errorf("pass 1 cursor missing edit time for ingested node %s", id)
}
}
// ---- Pass 2: incremental with pass-1 cursor. Against the REAL API this is
// the load-bearing check a fake can't make: real obj_edit_time must be
// stable for unchanged docs, so NOTHING is re-ingested.
h2 := &collectHandler{}
cur2, err := c.FetchStream(context.Background(), cfg, cur1, h2)
if err != nil {
t.Fatalf("pass 2 (incremental) FetchStream error: %v", err)
}
t.Logf("pass 2: re-ingested=%d (want 0)", len(h2.ingested))
if len(h2.ingested) != 0 {
t.Errorf("pass 2 re-ingested %v — real edit-time is unstable or core.Skip logic is broken", h2.ingested)
}
if got := countNodes(nodeTimes(t, cur2)); got != countNodes(nt1AsMap(nt1)) {
t.Logf("note: cursor node count changed between passes (%d→%d) — space may have been edited concurrently", countNodes(nt1AsMap(nt1)), got)
}
// ---- Pass 3: interrupt mid-sync then resume, against the real API.
// Only meaningful with at least 2 documents.
if n < 2 {
t.Logf("only %d doc(s); skipping interrupt/resume convergence sub-test (needs >=2)", n)
return
}
prevN := core.FeishuStreamCheckpointInterval
core.FeishuStreamCheckpointInterval = 1 // Checkpoint every node so resume is precise
defer func() { core.FeishuStreamCheckpointInterval = prevN }()
ctx3, cancel3 := context.WithCancel(context.Background())
h3 := &collectHandler{cancelAfter: 1, cancel: cancel3} // abort after 1 success
_, err = c.FetchStream(ctx3, cfg, nil, h3)
cancel3()
if err == nil {
t.Fatalf("pass 3 expected an abort error from the simulated timeout")
}
if len(h3.checkpoints) == 0 {
t.Fatalf("pass 3 wrote no Checkpoint — resume would restart from scratch")
}
persisted := h3.checkpoints[len(h3.checkpoints)-1]
t.Logf("pass 3: ingested=%d before abort, persisted cursor nodes=%d", len(h3.ingested), countNodes(nodeTimes(t, persisted)))
// Resume from the persisted Checkpoint; must converge to full coverage.
h4 := &collectHandler{}
_, err = c.FetchStream(context.Background(), cfg, persisted, h4)
if err != nil {
t.Fatalf("pass 4 (resume) FetchStream error: %v", err)
}
union := map[string]bool{}
for _, id := range h3.ingested {
union[id] = true
}
for _, id := range h4.ingested {
union[id] = true
}
t.Logf("pass 3+4 union ingested=%d, pass-1 full=%d", len(union), n)
if len(union) < n {
t.Errorf("resume converged to %d docs but full sync had %d — a document was lost across interrupt+resume", len(union), n)
}
// Resume must not redo already-checkpointed work.
done := nodeTimes(t, persisted)[spaceID]
for _, id := range h4.ingested {
if _, ok := done[id]; ok {
t.Errorf("pass 4 re-ingested already-checkpointed node %s (redundant re-export)", id)
}
}
}
func nt1AsMap(m map[string]string) map[string]map[string]string {
return map[string]map[string]string{"_": m}
}
@@ -0,0 +1,152 @@
//go:build feishu_integration
// Seeder for the real-API integration test. OPT-IN (feishu_integration tag +
// env vars) so it never runs in the normal suite or CI.
//
// It WRITES to your Feishu tenant: it creates a handful of docx documents under
// the given wiki space, each titled "WeKnora sync test doc N" so you can find
// and delete them afterwards. Requires app write scopes:
// - wiki:wiki (create wiki nodes)
// - docx:document (write docx content)
//
// plus the app being a member of the space.
//
// Run:
//
// export CPLUS_INCLUDE_PATH="$(xcrun --show-sdk-path)/usr/include/c++/v1"
// FEISHU_APP_ID=... FEISHU_APP_SECRET=... FEISHU_TEST_SPACE_ID=... FEISHU_SEED_COUNT=3 \
// go test -tags feishu_integration -run TestRealAPI_SeedDocs -v \
// ./internal/datasource/connector/feishu/
package wiki
import (
"context"
"fmt"
"os"
"strconv"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/utils"
)
// wikiNodeCreateResp is the subset of POST /wiki/v2/spaces/:id/nodes we need.
type wikiNodeCreateResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Node struct {
NodeToken string `json:"node_token"`
ObjToken string `json:"obj_token"`
ObjType string `json:"obj_type"`
Title string `json:"title"`
} `json:"node"`
} `json:"data"`
}
// TestRealAPI_CreateSpace creates a fresh knowledge base owned by the app, so
// the app can seed and read it without a human adding it to an existing space.
// It prints the new space_id for use as FEISHU_TEST_SPACE_ID.
func TestRealAPI_CreateSpace(t *testing.T) {
appID := os.Getenv("FEISHU_APP_ID")
appSecret := os.Getenv("FEISHU_APP_SECRET")
if appID == "" || appSecret == "" {
t.Skip("set FEISHU_APP_ID, FEISHU_APP_SECRET to run")
}
utils.SetSSRFWhitelistFromRaw("*.feishu.cn,*.larksuite.com")
client := core.NewClient(&core.Config{AppID: appID, AppSecret: appSecret, BaseURL: os.Getenv("FEISHU_BASE_URL")})
var resp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Space struct {
SpaceID string `json:"space_id"`
Name string `json:"name"`
} `json:"space"`
} `json:"data"`
}
err := client.DoRequest(context.Background(), "POST", "/open-apis/wiki/v2/spaces",
map[string]interface{}{
"name": "WeKnora Resilience Test KB",
"description": "Auto-created for connector resilience testing (#2136). Safe to delete.",
}, &resp)
if err != nil {
t.Fatalf("create space: %v", err)
}
if resp.Code != 0 {
t.Fatalf("create space: code=%d msg=%s (needs wiki:wiki write scope)", resp.Code, resp.Msg)
}
t.Logf("CREATED_SPACE space_id=%s name=%q", resp.Data.Space.SpaceID, resp.Data.Space.Name)
}
func TestRealAPI_SeedDocs(t *testing.T) {
appID := os.Getenv("FEISHU_APP_ID")
appSecret := os.Getenv("FEISHU_APP_SECRET")
spaceID := os.Getenv("FEISHU_TEST_SPACE_ID")
if appID == "" || appSecret == "" || spaceID == "" {
t.Skip("set FEISHU_APP_ID, FEISHU_APP_SECRET, FEISHU_TEST_SPACE_ID to run")
}
count := 3
if v := os.Getenv("FEISHU_SEED_COUNT"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
count = n
}
}
utils.SetSSRFWhitelistFromRaw("*.feishu.cn,*.larksuite.com")
baseURL := os.Getenv("FEISHU_BASE_URL")
client := core.NewClient(&core.Config{AppID: appID, AppSecret: appSecret, BaseURL: baseURL})
ctx := context.Background()
for i := 1; i <= count; i++ {
title := fmt.Sprintf("WeKnora sync test doc %d", i)
// 1) Create a docx wiki node.
var created wikiNodeCreateResp
err := client.DoRequest(ctx, "POST",
fmt.Sprintf("/open-apis/wiki/v2/spaces/%s/nodes", spaceID),
map[string]interface{}{
"obj_type": "docx",
"node_type": "origin",
"title": title,
}, &created)
if err != nil {
t.Fatalf("create wiki node %d: %v", i, err)
}
if created.Code != 0 {
t.Fatalf("create wiki node %d: code=%d msg=%s (check wiki:wiki write scope + space membership)", i, created.Code, created.Msg)
}
docID := created.Data.Node.ObjToken // for docx, obj_token == document_id
// 2) Add a text block so the export is non-empty.
var blockResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
berr := client.DoRequest(ctx, "POST",
fmt.Sprintf("/open-apis/docx/v1/documents/%s/blocks/%s/children", docID, docID),
map[string]interface{}{
"index": 0,
"children": []map[string]interface{}{{
"block_type": 2, // text
"text": map[string]interface{}{
"elements": []map[string]interface{}{{
"text_run": map[string]interface{}{
"content": fmt.Sprintf("This is WeKnora sync test document number %d. It exists to validate connector resilience (issue #2136).", i),
},
}},
},
}},
}, &blockResp)
if berr != nil {
t.Logf("warn: add content to doc %d failed (%v) — doc still created, export may be empty", i, berr)
} else if blockResp.Code != 0 {
t.Logf("warn: add content to doc %d: code=%d msg=%s (needs docx:document write scope) — doc still created", i, blockResp.Code, blockResp.Msg)
}
t.Logf("created doc %d: title=%q node_token=%s obj_token=%s", i, title, created.Data.Node.NodeToken, docID)
}
t.Logf("seeded %d docs under space %s. Now run TestRealAPI_FetchStreamResumeConverges.", count, spaceID)
}
@@ -0,0 +1,493 @@
package wiki
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
)
// fakeFeishuFailingExport serves the auth/spaces/nodes endpoints normally but
// fails every document export (code != 0), so fetchNodeContent returns an error
// for each supported node — modelling a rate-limited / broken export.
func fakeFeishuFailingExport(nodes []core.WikiNode) (*httptest.Server, *core.Config) {
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiNodeListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeListData{Items: nodes},
})
})
// Export creation fails for every document.
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.ApiResponse{Code: 1, Msg: "export unavailable"})
})
ts := httptest.NewServer(mux)
return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
}
// A node whose core.Fetch fails must NOT have its new edit time recorded in the
// returned cursor: recording it would make the next sync's unchanged fast-path
// core.Skip it forever, silently dropping a document on a transient export failure
// (Tencent/WeKnora#2136). With a prior edit time known, the prior value is
// retained so prev != current next run and the node is retried.
func TestFetchStream_FailedFetchRetainsPriorCursor(t *testing.T) {
nodes := []core.WikiNode{{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"}}
ts, cfg := fakeFeishuFailingExport(nodes)
defer ts.Close()
cursor := makeStreamCursor(t, map[string]map[string]string{"space1": {"nt1": "50"}}) // prior, older
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
next, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), cursor, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
// A failure item must be surfaced, not silently dropped.
if len(h.emitted) != 1 || h.emitted[0].Metadata["error"] == "" {
t.Fatalf("expected 1 emitted failure item with error metadata, got %+v", h.emitted)
}
var fc core.FeishuCursor
b, _ := json.Marshal(next.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
got := fc.SpaceNodeTimes["space1"]["nt1"]
if got == "100" {
t.Fatalf("failed node advanced to current edit time %q — it will be core.Skipped forever", got)
}
if got != "50" {
t.Errorf("failed node cursor = %q, want prior value \"50\" (retry next run)", got)
}
}
// With no prior cursor entry, a failed core.Fetch must leave the node out of the
// returned cursor entirely, so the next run treats it as new and retries it.
func TestFetchStream_FailedFetchNoPriorOmitsFromCursor(t *testing.T) {
nodes := []core.WikiNode{{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"}}
ts, cfg := fakeFeishuFailingExport(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
next, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
var fc core.FeishuCursor
b, _ := json.Marshal(next.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
if v, ok := fc.SpaceNodeTimes["space1"]["nt1"]; ok {
t.Errorf("failed node recorded in cursor as %q; want absent so it is retried next run", v)
}
}
// recordingHandler captures the items and checkpoints a streaming core.Fetch emits.
// Checkpoints are snapshotted (JSON-encoded) at call time — mirroring the
// service, which serializes the cursor synchronously inside Checkpoint — so the
// test observes the cursor state as it was when Checkpoint was called, not the
// connector's later-mutated map.
type recordingHandler struct {
emitted []types.FetchedItem
checkpoints []core.FeishuCursor
emitErr func(item types.FetchedItem) error
}
func (h *recordingHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if h.emitErr != nil {
if err := h.emitErr(item); err != nil {
return err
}
}
h.emitted = append(h.emitted, item)
return nil
}
func (h *recordingHandler) Checkpoint(ctx context.Context, cursor *types.SyncCursor) error {
var fc core.FeishuCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
h.checkpoints = append(h.checkpoints, fc)
return nil
}
func makeStreamCursor(t *testing.T, spaceNodeTimes map[string]map[string]string) *types.SyncCursor {
t.Helper()
prev := core.FeishuCursor{SpaceNodeTimes: spaceNodeTimes}
b, _ := json.Marshal(prev)
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
t.Fatalf("build cursor: %v", err)
}
return &types.SyncCursor{ConnectorCursor: m}
}
// A nil-cursor stream emits every supported node once and skips unsupported
// types, and the returned cursor records the edit time of every discovered node
// (so the next incremental run can detect changes).
func TestFetchStream_EmitsSupportedSkipsUnsupported(t *testing.T) {
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt2", ObjToken: "obj2", ObjType: "mindnote", Title: "Brain", ObjEditTime: "200"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
next, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 2 {
t.Fatalf("emitted %d items, want 2 (nt1, nt3)", len(h.emitted))
}
if h.emitted[0].ExternalID != "nt1" || h.emitted[1].ExternalID != "nt3" {
t.Errorf("emitted ids = %q,%q; want nt1,nt3", h.emitted[0].ExternalID, h.emitted[1].ExternalID)
}
var fc core.FeishuCursor
b, _ := json.Marshal(next.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
times := fc.SpaceNodeTimes["space1"]
for _, tok := range []string{"nt1", "nt2", "nt3"} {
if _, ok := times[tok]; !ok {
t.Errorf("returned cursor missing edit time for %s", tok)
}
}
}
// When a cursor already records a node at its current edit time, that node is
// unchanged and must not be re-emitted; only new/changed nodes stream through.
// This is the resume/incremental-core.Skip behavior that lets a timed-out sync
// converge across retries instead of re-exporting everything.
func TestFetchStream_SkipsUnchangedNodesFromCursor(t *testing.T) {
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
_, firstCursor, err := c.FetchIncremental(context.Background(), makeConfig(cfg, []string{"space1"}), nil)
if err != nil {
t.Fatalf("first sync: %v", err)
}
first := (&wikiOps{}).DecodeCursorTimes(firstCursor.ConnectorCursor)
delete(first["space1"], "nt3") // nt1 unchanged; nt3 unknown → new
cursor := makeStreamCursor(t, first)
h := &recordingHandler{}
if _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), cursor, h); err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 1 {
t.Fatalf("emitted %d items, want 1 (only changed nt3)", len(h.emitted))
}
if h.emitted[0].ExternalID != "nt3" {
t.Errorf("emitted id = %q, want nt3", h.emitted[0].ExternalID)
}
}
// Checkpoints must persist progress at page boundaries so a crash mid-sync
// resumes from the last Checkpoint. With the interval set to 1, each emitted
// item triggers a Checkpoint, and the first Checkpoint must already contain the
// first node's edit time.
func TestFetchStream_CheckpointsProgress(t *testing.T) {
prev := core.FeishuStreamCheckpointInterval
core.FeishuStreamCheckpointInterval = 1
defer func() { core.FeishuStreamCheckpointInterval = prev }()
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
if _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h); err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.checkpoints) == 0 {
t.Fatalf("expected at least one Checkpoint")
}
first := h.checkpoints[0]
if _, ok := first.SpaceNodeTimes["space1"]["nt1"]; !ok {
t.Errorf("first Checkpoint missing nt1 progress: %+v", first.SpaceNodeTimes)
}
}
// Checkpoints must ALSO fire on elapsed time, not only every N nodes.
// Otherwise a sync with fewer than the node interval of slow (rate-limited)
// exports reaches the 2h task timeout having never checkpointed, and resumes
// from scratch forever — exactly the #2136 "never fully syncs" case. With the
// node interval effectively disabled and the time interval at 0, every
// processed node must still produce a Checkpoint.
func TestFetchStream_CheckpointsOnElapsedTime(t *testing.T) {
prevN := core.FeishuStreamCheckpointInterval
prevT := core.FeishuStreamCheckpointMaxInterval
core.FeishuStreamCheckpointInterval = 1 << 30 // never fires by count
core.FeishuStreamCheckpointMaxInterval = 0 // fires by elapsed time every node
defer func() {
core.FeishuStreamCheckpointInterval = prevN
core.FeishuStreamCheckpointMaxInterval = prevT
}()
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
if _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h); err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.checkpoints) == 0 {
t.Fatalf("expected time-based checkpoints even though node interval never fires")
}
}
// An Emit error aborts the stream immediately — the connector must return the
// error and stop fetching further nodes (the sync is failing; do not burn API
// budget on the rest of the tree).
func TestFetchStream_EmitErrorAborts(t *testing.T) {
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
boom := errors.New("ingest failed")
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{emitErr: func(item types.FetchedItem) error { return boom }}
_, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h)
if !errors.Is(err, boom) {
t.Fatalf("FetchStream() error = %v, want %v", err, boom)
}
if len(h.emitted) != 0 {
t.Errorf("emitted %d items, want 0 (aborted on first Emit)", len(h.emitted))
}
}
// ──────────────────────────────────────────────────────────────────────
// Stream integration: docx blocks fan-out (multi-item) through FetchStream
// ──────────────────────────────────────────────────────────────────────
// TestFetchStream_DocxMultiItem is a stream-level integration test proving that a
// docx node fans out to a main Markdown item + an attachment item through the real
// FetchStream → fetchNodeContent → core.FetchDocxWithBlocks path. The fake server
// serves the blocks API (one text block + one file block) and the drive download;
// no export endpoint is registered, so any accidental fall-through to the export
// path would 404 and surface as a core.Fetch error.
func TestFetchStream_DocxMultiItem(t *testing.T) {
const (
nodeToken = "nt-blocks"
objToken = "obj-blocks"
attToken = "ft-stream-att"
attName = "slides.pdf"
)
// Attachment content must exceed core.MinAttachmentBytes (2 KiB).
attContent := bytes.Repeat([]byte("a"), core.MinAttachmentBytes+1)
nodes := []core.WikiNode{{
NodeToken: nodeToken,
ObjToken: objToken,
ObjType: "docx",
Title: "Stream Blocks Doc",
ObjEditTime: "500",
}}
ts, cfg := fakeFeishuWithBlocks(nodes, objToken, attToken, attName, attContent)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 2 {
t.Fatalf("expected 2 emitted items (attachment + main doc), got %d: %+v", len(h.emitted), h.emitted)
}
// P3 contract: sub-items are emitted BEFORE the parent document.
att := h.emitted[0]
wantAttID := nodeToken + "#file#" + attToken
if att.ExternalID != wantAttID {
t.Errorf("items[0].ExternalID = %q, want %q", att.ExternalID, wantAttID)
}
if att.Metadata["attachment"] != "true" {
t.Errorf("items[0].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
}
main := h.emitted[1]
if main.ExternalID != nodeToken {
t.Errorf("items[1].ExternalID = %q, want %q", main.ExternalID, nodeToken)
}
if main.ContentType != "text/markdown" {
t.Errorf("items[1].ContentType = %q, want text/markdown", main.ContentType)
}
if !main.ReplacesSubtree {
t.Errorf("items[1].ReplacesSubtree = false, want true")
}
}
// fakeFeishuWithBlocksFallback returns a server where the blocks API returns HTTP 500
// (simulating a permission/scope error) and the export task path returns success.
// This wires the fallback path: core.FetchDocxWithBlocks → blocks error → fetchViaExport.
func fakeFeishuWithBlocksFallback(nodes []core.WikiNode, docToken string) (*httptest.Server, *core.Config) {
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.TokenResponse{
ApiResponse: core.ApiResponse{Code: 0},
TenantAccessToken: "fake-token",
Expire: 7200,
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiNodeListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeListData{Items: nodes},
})
})
// Blocks API — always returns HTTP 500 (missing scope / permission denied).
blocksPath := "/open-apis/docx/v1/documents/" + docToken + "/blocks"
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"code":99991400,"msg":"insufficient scope"}`))
})
// Export task creation → returns ticket.
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
writeJSON(w, core.ExportTaskCreateResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskCreateData{Ticket: "ticket-fb"},
})
return
}
http.NotFound(w, r)
})
// Export task status polling.
mux.HandleFunc("/open-apis/drive/v1/export_tasks/ticket-fb", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.ExportTaskStatusResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskStatusData{
Result: core.ExportTaskResult{
FileToken: "ft-export-fallback",
FileSize: 512,
JobStatus: 0, // done
FileName: "fallback.docx",
},
},
})
})
// Export file download.
mux.HandleFunc("/open-apis/drive/v1/export_tasks/file/ft-export-fallback/download", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("fake-exported-fallback-binary"))
})
// Drive file download endpoint (not expected to be called in the fallback path,
// but registered to avoid 404 panic if the mux catches a stray request).
mux.HandleFunc("/open-apis/drive/v1/files/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/download") {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("should-not-be-called"))
return
}
http.NotFound(w, r)
})
ts := httptest.NewServer(mux)
return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
}
// TestFetchStream_DocxBlocksFallback proves that when the blocks API returns HTTP 500
// (e.g. missing docx:document:readonly scope), the connector automatically falls back
// to the export-API path and emits exactly one item with ContentType
// "application/octet-stream", not "text/markdown". No hard failure occurs —
// the sync completes successfully with the exported binary.
func TestFetchStream_DocxBlocksFallback(t *testing.T) {
const (
nodeToken = "nt-fallback"
objToken = "obj-fallback"
)
nodes := []core.WikiNode{{
NodeToken: nodeToken,
ObjToken: objToken,
ObjType: "docx",
Title: "Fallback Doc",
ObjEditTime: "600",
}}
ts, cfg := fakeFeishuWithBlocksFallback(nodes, objToken)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
// The fallback path must Emit exactly one item (exported binary, not multi-item).
if len(h.emitted) != 1 {
t.Fatalf("expected 1 emitted item (export fallback), got %d: %+v", len(h.emitted), h.emitted)
}
item := h.emitted[0]
if item.ExternalID != nodeToken {
t.Errorf("item.ExternalID = %q, want %q", item.ExternalID, nodeToken)
}
if item.ContentType == "text/markdown" {
t.Errorf("item.ContentType = %q; want application/octet-stream (export fallback, not blocks path)", item.ContentType)
}
if item.ContentType != "application/octet-stream" {
t.Errorf("item.ContentType = %q, want application/octet-stream", item.ContentType)
}
if item.Metadata["error"] != "" {
t.Errorf("fallback item should have no error metadata, got %q", item.Metadata["error"])
}
// The export fallback cannot re-enumerate the doc's attachments, so it must
// NOT set ReplacesSubtree — otherwise a transient blocks-API failure would
// sweep and permanently delete the good attachment children from the prior
// blocks-path sync with nothing to replace them.
if item.ReplacesSubtree {
t.Error("export-fallback item must not set ReplacesSubtree (would delete good prior attachments on a transient failure)")
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
package wiki
import "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
func txt(s string) *core.BlockText {
return &core.BlockText{Elements: []core.TextElement{{TextRun: &core.TextRun{Content: s}}}}
}
@@ -0,0 +1,86 @@
package wiki
import (
"context"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
)
// A Lark connector must surface wiki links on the Lark host. Before Lark became
// its own connector type, every resource URL was hardcoded to feishu.cn, so Lark
// users got links into a cloud their content does not live on.
//
// The fake server stands in for the Open Platform (base_url points at it), but
// the resource URL is built from the region's web host, so this exercises the
// real ListResources → wikiNodeToResource → region.WikiURL path.
func TestListResources_ResourceURLFollowsRegion(t *testing.T) {
cases := []struct {
region core.Region
wantURL string
forbiddenIn string
}{
{core.RegionFeishu, "https://feishu.cn/wiki/space1", "larksuite"},
{core.RegionLark, "https://larksuite.com/wiki/space1", "feishu"},
}
for _, c := range cases {
t.Run(c.region.Label, func(t *testing.T) {
ts, cfg := fakeFeishu(nil)
defer ts.Close()
conn := NewConnector(c.region)
resources, err := conn.ListResources(context.Background(), makeConfig(cfg, nil), "")
if err != nil {
t.Fatalf("ListResources: %v", err)
}
if len(resources) != 1 {
t.Fatalf("got %d resources, want 1", len(resources))
}
if got := resources[0].URL; got != c.wantURL {
t.Errorf("resource URL = %q, want %q", got, c.wantURL)
}
if strings.Contains(resources[0].URL, c.forbiddenIn) {
t.Errorf("%s resource URL leaks the other cloud's host: %q", c.region.Label, resources[0].URL)
}
})
}
}
// A Lark connector with no base_url override must reach open.larksuite.com,
// never open.feishu.cn — the SDK-less client has no default of its own, so the
// region is the only thing standing between a Lark app and the wrong cloud.
func TestClient_ResolvesRegionHostWithoutOverride(t *testing.T) {
cases := []struct {
region core.Region
want string
}{
{core.RegionFeishu, "https://open.feishu.cn"},
{core.RegionLark, "https://open.larksuite.com"},
}
for _, c := range cases {
t.Run(c.region.Label, func(t *testing.T) {
cfg, err := core.ParseFeishuConfig(makeConfigNoBaseURL(), c.region)
if err != nil {
t.Fatalf("ParseFeishuConfig: %v", err)
}
if cfg.GetBaseURL() != c.want {
t.Errorf("baseURL = %q, want %q", cfg.GetBaseURL(), c.want)
}
})
}
}
// makeConfigNoBaseURL builds credentials without base_url, so the region default
// is what resolves.
func makeConfigNoBaseURL() *types.DataSourceConfig {
return &types.DataSourceConfig{
Credentials: map[string]interface{}{
"app_id": "cli_x",
"app_secret": "s",
},
}
}
@@ -0,0 +1,43 @@
package wiki
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
)
func TestParseModeChangeRefetchesExistingDocument(t *testing.T) {
nodes := []core.WikiNode{{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"}}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
conf := makeConfig(cfg, []string{"space1"})
conf.Settings = map[string]interface{}{"parse_mode": "export"}
c := NewConnector(core.RegionFeishu)
items, cursor, err := c.FetchIncremental(context.Background(), conf, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("first sync items=%d", len(items))
}
t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
for _, mode := range []string{"blocks", "", "blocks", "export"} {
conf.Settings["parse_mode"] = mode
items, cursor, err = c.FetchIncremental(context.Background(), conf, cursor)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("parse_mode change must refetch the document: got %d items", len(items))
}
items, _, err = c.FetchIncremental(context.Background(), conf, cursor)
if err != nil {
t.Fatal(err)
}
if len(items) != 0 {
t.Fatalf("unchanged effective mode must skip document: got %d items", len(items))
}
}
}
@@ -0,0 +1,142 @@
package wiki
import (
"strings"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
)
// This file implements the P1 directory mapping: FetchedItem.FileName becomes
// "<空间名>/<目录A>/<目录B>/<文档名>.md" rooted at the synced space's own name
// (the space = a top-level KB folder) so ingestion's
// types.SplitKnowledgeRelativePath derives the KB folder_path (GitLab-style).
// The path table is built per sync run from the recursive node listing — zero
// engine changes. external_id stays the node token, so a move/rename lands in
// the new folder through the existing update=delete+recreate path.
// filterShortcutSubtrees drops only shortcuts whose original subtree is also
// in this complete listing. Never follow origins outside the selected scope:
// the shortcut can be the only accessible copy of a document.
func filterShortcutSubtrees(nodes []core.WikiNode) []core.WikiNode {
byToken := make(map[string]core.WikiNode, len(nodes))
for _, n := range nodes {
byToken[n.NodeToken] = n
}
redundant := make(map[string]bool)
for _, n := range nodes {
origin, ok := byToken[n.OriginNodeID]
if n.NodeType != "shortcut" || !ok || origin.NodeType == "shortcut" {
continue
}
if n.OriginSpaceID != "" && origin.SpaceID != "" && n.OriginSpaceID != origin.SpaceID {
continue
}
// An origin reached only through a shortcut is not an independently
// enumerated copy. In particular, do not discard mutually linked trees.
if !underShortcut(origin, byToken) {
redundant[n.NodeToken] = true
}
}
kept := make([]core.WikiNode, 0, len(nodes))
for _, n := range nodes {
if underFilteredNode(n, byToken, redundant) {
continue
}
kept = append(kept, n)
}
return kept
}
func underFilteredNode(n core.WikiNode, byToken map[string]core.WikiNode, filtered map[string]bool) bool {
visited := make(map[string]bool)
for token := n.NodeToken; token != "" && !visited[token]; token = byToken[token].ParentNodeID {
if filtered[token] {
return true
}
visited[token] = true
}
return false
}
// underShortcut reports whether n is itself a shortcut or has one on its
// ancestor chain within the listed set. An ancestor missing from the listing
// (subtree root's parent, or a partial listing) ends the walk as "no shortcut".
func underShortcut(n core.WikiNode, byToken map[string]core.WikiNode) bool {
if n.NodeType == "shortcut" {
return true
}
visited := make(map[string]bool)
for p := n.ParentNodeID; p != "" && !visited[p]; p = byToken[p].ParentNodeID {
visited[p] = true
parent, ok := byToken[p]
if !ok {
return false
}
if parent.NodeType == "shortcut" {
return true
}
}
return false
}
// buildWikiDirPaths maps each node token to its cleaned directory prefix,
// rooted at spacePrefix (the synced space's sanitized name): a top-level node
// maps to spacePrefix (its document lands in the space's own KB folder) and
// deeper nodes to "<space>/<父目录标题...>". Ancestors are resolved bottom-up
// through ParentNodeID within the listing; for a sub-tree selection the
// ancestors above the sub-tree root are unknown, so its documents land
// directly in the space folder. A docx node that also has children is both a
// document and a directory — its own item sits beside the child folder it
// forms. An empty spacePrefix (space name unresolved) falls back to paths
// relative to the listing root.
func buildWikiDirPaths(nodes []core.WikiNode, spacePrefix string) map[string]string {
byToken := make(map[string]core.WikiNode, len(nodes))
for _, n := range nodes {
byToken[n.NodeToken] = n
}
paths := make(map[string]string, len(nodes))
for _, n := range nodes {
// Walk up collecting ancestor titles, then reverse so the topmost
// directory leads; the space name itself leads the chain.
var ancestors []string
visited := make(map[string]bool)
for p := n.ParentNodeID; p != "" && !visited[p]; p = byToken[p].ParentNodeID {
visited[p] = true
parent, ok := byToken[p]
if !ok {
break
}
ancestors = append(ancestors, core.SanitizeFileName(parent.Title))
}
for i, j := 0, len(ancestors)-1; i < j; i, j = i+1, j-1 {
ancestors[i], ancestors[j] = ancestors[j], ancestors[i]
}
if spacePrefix != "" {
ancestors = append([]string{spacePrefix}, ancestors...)
}
paths[n.NodeToken] = strings.Join(ancestors, "/")
}
return paths
}
// prepareDirPaths rebuilds the per-resource directory table. Called from List
// after removing redundant shortcut subtrees.
func (o *wikiOps) prepareDirPaths(nodes []core.WikiNode, spacePrefix string) {
o.dirPaths = buildWikiDirPaths(nodes, spacePrefix)
}
// qualifyItemFileNames prefixes every fetched item's FileName with dir so
// ingestion derives the KB folder path. The prefix applies to the main item
// and to attachment/image sub-items alike — they all live in the same folder.
// An empty dir (node not in the current listing) or FileName is untouched.
func qualifyItemFileNames(items []*types.FetchedItem, dir string) {
if dir == "" {
return
}
for _, it := range items {
if it != nil && it.FileName != "" {
it.FileName = dir + "/" + it.FileName
}
}
}
@@ -0,0 +1,147 @@
package wiki
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func TestWikiShortcutOutsideSelectionRemainsSyncable(t *testing.T) {
for _, resource := range []string{"space1", "space1:shortcut"} {
t.Run(resource, func(t *testing.T) {
shortcut := fileNode("shortcut", "reference.pdf", func(n *core.WikiNode) {
n.NodeType = "shortcut"
n.OriginNodeID = "outside"
n.OriginSpaceID = "space2"
n.HasChild = true
})
f := newFakeWikiTree(t, []core.WikiNode{shortcut}, map[string][]core.WikiNode{
"shortcut": {fileNode("child", "child.pdf")},
})
conn := NewConnector(core.RegionFeishu)
cfg := makeConfig(f.cfg, []string{resource})
items, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
require.NoError(t, err)
require.Len(t, items, 2)
require.Equal(t, "shortcut", items[0].ExternalID)
require.Equal(t, "Test Space/reference.pdf/child.pdf", items[1].FileName)
items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
require.NoError(t, err)
require.Empty(t, items, "unchanged shortcuts must not be deleted or fetched again")
})
}
}
func TestWikiShortcutDedupRequiresIndependentOrigin(t *testing.T) {
cases := []struct {
name string
nodes []core.WikiNode
want []string
}{
{"original in same listing", []core.WikiNode{
{NodeToken: "original", NodeType: "origin"},
{NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original"},
{NodeToken: "child", ParentNodeID: "shortcut"},
}, []string{"original"}},
{"original outside selected subtree", []core.WikiNode{
{NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "outside"},
{NodeToken: "child", ParentNodeID: "shortcut"},
}, []string{"shortcut", "child"}},
{"origin exists only below shortcut", []core.WikiNode{
{NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original"},
{NodeToken: "original", ParentNodeID: "shortcut", NodeType: "origin"},
}, []string{"shortcut", "original"}},
{"mismatched origin space", []core.WikiNode{
{NodeToken: "original", NodeType: "origin", SpaceID: "space1"},
{NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original", OriginSpaceID: "space2"},
}, []string{"original", "shortcut"}},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
var ids []string
for _, n := range filterShortcutSubtrees(tt.nodes) {
ids = append(ids, n.NodeToken)
}
require.Equal(t, tt.want, ids)
})
}
}
func TestWikiAncestorChangesRefreshDescendants(t *testing.T) {
for _, change := range []string{"rename", "move"} {
t.Run(change, func(t *testing.T) {
parent := fileNode("parent", "Old", func(n *core.WikiNode) { n.HasChild = true })
f := newFakeWikiTree(t, []core.WikiNode{parent}, map[string][]core.WikiNode{
"parent": {fileNode("child", "child.pdf")},
})
conn := NewConnector(core.RegionFeishu)
cfg := makeConfig(f.cfg, []string{"space1"})
_, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
require.NoError(t, err)
want := "Test Space/New/child.pdf"
if change == "rename" {
f.top[0].Title = "New"
f.top[0].NodeEditTime = "200"
} else {
parent.NodeEditTime = "200"
f.top = []core.WikiNode{fileNode("new-parent", "New", func(n *core.WikiNode) { n.HasChild = true })}
f.children["new-parent"] = []core.WikiNode{parent}
want = "Test Space/New/Old/child.pdf"
}
items, next, err := conn.FetchIncremental(context.Background(), cfg, cursor)
require.NoError(t, err)
var child *types.FetchedItem
for i := range items {
if items[i].ExternalID == "child" {
child = &items[i]
}
}
require.NotNil(t, child, "unchanged child must follow its ancestor's path")
require.Equal(t, want, child.FileName)
require.EqualValues(t, 100, child.UpdatedAt.Unix(), "source timestamp must remain the document's own")
items, _, err = conn.FetchIncremental(context.Background(), cfg, next)
require.NoError(t, err)
require.Empty(t, items)
})
}
}
func TestWikiLegacyTimestampCursorRefreshesOnce(t *testing.T) {
f := newFakeWikiTree(t, []core.WikiNode{fileNode("doc", "doc.pdf")}, nil)
conn := NewConnector(core.RegionFeishu)
cfg := makeConfig(f.cfg, []string{"space1"})
legacy := makeStreamCursor(t, map[string]map[string]string{"space1": {"doc": "100"}})
items, cursor, err := conn.FetchIncremental(context.Background(), cfg, legacy)
require.NoError(t, err)
require.Len(t, items, 1)
items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
require.NoError(t, err)
require.Empty(t, items)
}
func TestWikiPartialListingKeepsAccessibleShortcut(t *testing.T) {
origin := fileNode("origin", "origin.pdf", func(n *core.WikiNode) { n.HasChild = true })
shortcut := fileNode("shortcut", "reference.pdf", func(n *core.WikiNode) {
n.NodeType = "shortcut"
n.OriginNodeID = "origin"
n.HasChild = true
})
server, cfg := fakeFeishuHierarchy([]core.WikiNode{origin, shortcut}, map[string][]core.WikiNode{
"shortcut": {fileNode("child", "child.pdf")},
}, "origin")
defer server.Close()
conn := NewConnector(core.RegionFeishu)
items, _, err := conn.FetchIncremental(context.Background(), makeConfig(cfg, []string{"space1"}), nil)
require.NoError(t, err)
var fetched []string
for _, item := range items {
if item.Metadata["error"] == "" {
fetched = append(fetched, item.ExternalID)
}
}
require.Contains(t, fetched, "shortcut")
require.Contains(t, fetched, "child", "a failed origin subtree must not suppress the accessible copy")
}
@@ -0,0 +1,282 @@
package wiki
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
"github.com/Tencent/WeKnora/internal/types"
)
// ──────────────────────────────────────────────────────────────────────
// P1 directory mapping tests: path-qualified FileName, shortcut subtree
// dedup, move/rename following, anchored against the fake wiki tree below.
// ──────────────────────────────────────────────────────────────────────
// fakeWikiTree serves a mutable wiki hierarchy: the test can rewrite the tree
// between sync runs to model moves/renames. All nodes are "file" obj_type so
// fetchDriveFile uses the node title verbatim as the base file name — the
// assertions then exercise only the path prefix logic under test.
type fakeWikiTree struct {
top []core.WikiNode
children map[string][]core.WikiNode
ts *httptest.Server
cfg *core.Config
}
func newFakeWikiTree(t *testing.T, top []core.WikiNode, children map[string][]core.WikiNode) *fakeWikiTree {
t.Helper()
f := &fakeWikiTree{top: top, children: children}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.TokenResponse{
ApiResponse: core.ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
parentToken := r.URL.Query().Get("parent_node_token")
nodes := f.top
if parentToken != "" {
nodes = f.children[parentToken]
for i := range nodes {
if nodes[i].ParentNodeID == "" {
nodes[i].ParentNodeID = parentToken
}
if nodes[i].SpaceID == "" {
nodes[i].SpaceID = "space1"
}
}
}
writeJSON(w, core.WikiNodeListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeListData{Items: nodes},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/get_node", func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
for _, n := range f.top {
if n.NodeToken == token {
writeJSON(w, core.WikiNodeInfoResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeInfoData{Node: n},
})
return
}
}
for _, group := range f.children {
for _, n := range group {
if n.NodeToken == token {
writeJSON(w, core.WikiNodeInfoResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeInfoData{Node: n},
})
return
}
}
}
writeJSON(w, core.WikiNodeInfoResponse{ApiResponse: core.ApiResponse{Code: 1663, Msg: "node not found"}})
})
// Drive download for "file" type nodes.
mux.HandleFunc("/open-apis/drive/v1/files/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/download") {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("fake-file-content"))
return
}
http.NotFound(w, r)
})
f.ts = httptest.NewServer(mux)
t.Cleanup(f.ts.Close)
f.cfg = &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: f.ts.URL}
return f
}
func fileNode(token, title string, opts ...func(*core.WikiNode)) core.WikiNode {
n := core.WikiNode{
NodeToken: token,
ObjToken: "obj-" + token,
ObjType: "file",
NodeType: "origin",
Title: title,
NodeEditTime: "100",
}
for _, opt := range opts {
opt(&n)
}
return n
}
// TestWikiFetchAll_PathQualifiedMultiLevel anchors the multi-level directory
// mapping: the synced space mirrors as a top-level KB folder named after it,
// so paths are <空间名>/<目录A>/<目录B>/<文档名>, Chinese directory names kept
// as-is and "/" inside a directory name sanitised to "_" so it cannot fake an
// extra nesting level.
func TestWikiFetchAll_PathQualifiedMultiLevel(t *testing.T) {
f := newFakeWikiTree(t,
[]core.WikiNode{
fileNode("nt-dirA", "产品文档", func(n *core.WikiNode) { n.HasChild = true }),
fileNode("nt-top", "顶层.pdf"),
},
map[string][]core.WikiNode{
"nt-dirA": {
fileNode("nt-dirB", "子/目录", func(n *core.WikiNode) { n.HasChild = true }),
},
"nt-dirB": {
fileNode("nt-leaf", "规格说明.pdf"),
},
},
)
c := NewConnector(core.RegionFeishu)
items, err := c.FetchAll(context.Background(), makeConfig(f.cfg, []string{"space1"}), []string{"space1"})
if err != nil {
t.Fatalf("FetchAll() error: %v", err)
}
want := map[string]string{
// The synced space mirrors as a top-level KB folder ("Test Space" in
// the fake tree): every item's prefix starts with the space name,
// deeper items then carry the directory path. Base names are
// sanitised like directory segments: a "/" in a title must not fake
// an extra folder level (nt-dirB), while the directory path prefix
// is built from the sanitised folder name (nt-leaf).
"nt-dirA": "Test Space/产品文档",
"nt-top": "Test Space/顶层.pdf",
"nt-dirB": "Test Space/产品文档/子_目录",
"nt-leaf": "Test Space/产品文档/子_目录/规格说明.pdf",
}
got := make(map[string]string, len(items))
for _, item := range items {
got[item.ExternalID] = item.FileName
}
if len(got) != len(want) {
t.Fatalf("got %d items (%v), want %d", len(got), got, len(want))
}
for id, wantPath := range want {
if got[id] != wantPath {
t.Errorf("FileName for %s = %q, want %q", id, got[id], wantPath)
}
}
}
// TestWikiFetchAll_ShortcutSubtreeDeduped anchors the shortcut dedup: a
// shortcut node and its whole subtree are skipped — the origin entity is
// enumerated at its real location, so the shortcut would duplicate it.
func TestWikiFetchAll_ShortcutSubtreeDeduped(t *testing.T) {
origin := fileNode("nt-origin", "origin.pdf")
shortcut := fileNode("nt-shortcut", "origin.pdf", func(n *core.WikiNode) {
n.NodeType = "shortcut"
n.OriginNodeID = "nt-origin"
n.HasChild = true
})
f := newFakeWikiTree(t,
[]core.WikiNode{origin, shortcut},
map[string][]core.WikiNode{
// The client's recursive walk descends into the shortcut (HasChild),
// so the listing contains the origin's subtree a second time.
"nt-shortcut": {fileNode("nt-under-shortcut", "duplicate.pdf")},
},
)
c := NewConnector(core.RegionFeishu)
items, cursor, err := c.FetchIncremental(context.Background(), makeConfig(f.cfg, []string{"space1"}), nil)
if err != nil {
t.Fatalf("FetchIncremental() error: %v", err)
}
if len(items) != 1 {
t.Fatalf("expected exactly 1 item (the origin), got %d: %+v", len(items), items)
}
if items[0].ExternalID != "nt-origin" {
t.Errorf("item ExternalID = %q, want nt-origin", items[0].ExternalID)
}
// The cursor must only record the kept node, so the filtered shortcut and
// its subtree do not linger as ghosts.
var fc core.FeishuCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
times := fc.SpaceNodeTimes["space1"]
if _, ok := times["nt-shortcut"]; ok {
t.Error("cursor records the skipped shortcut node")
}
if _, ok := times["nt-under-shortcut"]; ok {
t.Error("cursor records a node under the skipped shortcut subtree")
}
if _, ok := times["nt-origin"]; !ok {
t.Error("cursor missing the origin node")
}
}
// TestWikiFetchIncremental_MoveFollowsNewPath anchors the move/rename story:
// the external_id is unchanged, and once the node's edit time moves the next
// sync re-fetches it under the NEW directory path. Ingestion's
// update=delete+recreate then lands the knowledge row in the new folder_path.
func TestWikiFetchIncremental_MoveFollowsNewPath(t *testing.T) {
doc := fileNode("nt-doc", "文档.pdf", func(n *core.WikiNode) { n.NodeEditTime = "100" })
f := newFakeWikiTree(t,
[]core.WikiNode{
fileNode("nt-dirA", "目录A", func(n *core.WikiNode) { n.HasChild = true }),
},
map[string][]core.WikiNode{"nt-dirA": {doc}},
)
c := NewConnector(core.RegionFeishu)
cfg := makeConfig(f.cfg, []string{"space1"})
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first sync error: %v", err)
}
if len(items1) != 2 {
t.Fatalf("first sync: expected 2 items (dir + doc), got %d: %+v", len(items1), items1)
}
var docItem *types.FetchedItem
for i := range items1 {
if items1[i].ExternalID == "nt-doc" {
docItem = &items1[i]
}
}
if docItem == nil || docItem.FileName != "Test Space/目录A/文档.pdf" {
t.Fatalf("first sync: doc item missing or wrong path: %+v", items1)
}
// Move the doc from 目录A to a new top-level 目录B; the edit time moves so
// the incremental fast-path does not skip it.
f.top = append(f.top, fileNode("nt-dirB", "目录B", func(n *core.WikiNode) { n.HasChild = true }))
f.children = map[string][]core.WikiNode{
"nt-dirB": {fileNode("nt-doc", "文档.pdf", func(n *core.WikiNode) { n.NodeEditTime = "200" })},
}
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second sync error: %v", err)
}
var moved *types.FetchedItem
for i := range items2 {
if items2[i].ExternalID == "nt-doc" && !items2[i].IsDeleted {
moved = &items2[i]
}
}
if moved == nil {
t.Fatalf("moved doc not re-fetched on second sync: %+v", items2)
}
if moved.FileName != "Test Space/目录B/文档.pdf" {
t.Errorf("moved doc FileName = %q, want %q (same external_id, new folder)",
moved.FileName, "Test Space/目录B/文档.pdf")
}
}
@@ -0,0 +1,382 @@
package gitlab
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/logger"
)
const (
// maxJSONResponseBytes bounds project, user, commit and paginated tree JSON.
// Those listings are small; a larger body means a broken or hostile server.
maxJSONResponseBytes int64 = 16 << 20
// maxCompareResponseBytes bounds GET /repository/compare. That body carries
// the full commit list and patch text. A straight compare across a long
// unsynced range or a force-push routinely exceeds the metadata cap, and
// failing it aborts the project sync before the cursor advances. Sync only
// keeps paths and compare_timeout, but the response still has to be buffered.
maxCompareResponseBytes int64 = 128 << 20
// maxRawFileBytes bounds a single repository blob. GitLab's tree and
// compare endpoints do not report blob sizes, so the download itself is the
// only place a limit can be enforced. 512 MiB matches the Feishu connector,
// the other connector that pulls arbitrary binary files.
maxRawFileBytes int64 = 512 << 20
)
// base64FileBytes is the JSON cap for the file-detail fallback, whose body
// carries the raw blob base64-encoded (4/3 of its size) plus an envelope.
func base64FileBytes(rawLimit int64) int64 {
return rawLimit/3*4 + (1 << 20)
}
// maxPaginationHops bounds a single paginated walk. GitLab reports the next
// page through the X-Next-Page header, so a broken instance or reverse proxy
// could keep advertising pages indefinitely.
const maxPaginationHops = 10000
type client struct {
baseURL, token string
http *http.Client
// jsonLimit, compareLimit and rawLimit are fields rather than direct uses of
// the constants above so tests can lower them without materialising hundreds
// of megabytes. newClient always sets the production values.
jsonLimit int64
compareLimit int64
rawLimit int64
}
// readCapped reads a response body, refusing anything larger than limit instead
// of buffering it. Oversized payloads are reported as an error: a truncated
// body would be indexed as if it were the whole document.
func readCapped(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("response exceeds maximum size (%d bytes)", limit)
}
return data, nil
}
type apiError struct {
endpoint string
status int
}
func (e *apiError) Error() string {
return fmt.Sprintf("gitlab API %s: status %d", e.endpoint, e.status)
}
type project struct {
ID int64 `json:"id"`
PathWithNamespace string `json:"path_with_namespace"`
Name string `json:"name"`
WebURL string `json:"web_url"`
DefaultBranch string `json:"default_branch"`
Namespace struct {
ID int64 `json:"id"`
} `json:"namespace"`
}
type treeEntry struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Path string `json:"path"`
}
type comparison struct {
Diffs []struct {
OldPath string `json:"old_path"`
NewPath string `json:"new_path"`
NewFile bool `json:"new_file"`
DeletedFile bool `json:"deleted_file"`
RenamedFile bool `json:"renamed_file"`
} `json:"diffs"`
CompareTimeout bool `json:"compare_timeout"`
CompareSameRef bool `json:"compare_same_ref"`
}
func newClient(baseURL, token string) (*client, error) {
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
if baseURL == "" || strings.TrimSpace(token) == "" {
return nil, fmt.Errorf("GitLab platform configuration is missing")
}
if err := datasource.ValidateConnectorBaseURL(baseURL); err != nil {
return nil, err
}
if !strings.Contains(baseURL, "://") {
baseURL = "https://" + baseURL
}
if !strings.HasSuffix(baseURL, "/api/v4") {
baseURL += "/api/v4"
}
return &client{
baseURL: baseURL,
token: token,
http: datasource.NewConnectorHTTPClient(30 * time.Second),
jsonLimit: maxJSONResponseBytes,
compareLimit: maxCompareResponseBytes,
rawLimit: maxRawFileBytes,
}, nil
}
func (c *client) get(ctx context.Context, endpoint string, out interface{}) error {
return c.getCapped(ctx, endpoint, out, c.jsonLimit)
}
// getCapped is get with an explicit response cap. Compare and the base64 file
// fallback pass their own limits because those bodies are larger than metadata.
func (c *client) getCapped(ctx context.Context, endpoint string, out interface{}, limit int64) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+endpoint, nil)
if err != nil {
return err
}
req.Header.Set("PRIVATE-TOKEN", c.token)
resp, err := c.http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return &apiError{endpoint: endpoint, status: resp.StatusCode}
}
body, err := readCapped(resp.Body, limit)
if err != nil {
return fmt.Errorf("gitlab API %s: %w", endpoint, err)
}
return json.Unmarshal(body, out)
}
func (c *client) getRaw(ctx context.Context, endpoint string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("PRIVATE-TOKEN", c.token)
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, &apiError{endpoint: endpoint, status: resp.StatusCode}
}
body, err := readCapped(resp.Body, c.rawLimit)
if err != nil {
return nil, fmt.Errorf("gitlab raw file %s: %w", endpoint, err)
}
return body, nil
}
// projectPath encodes a GitLab project identifier for URL path segments.
// Numeric IDs are used verbatim. Namespace paths accept either "group/project"
// or a once-encoded "group%2Fproject" without double-encoding percent signs.
func projectPath(id string) string {
id = strings.TrimSpace(id)
if id == "" {
return ""
}
if _, err := strconv.ParseInt(id, 10, 64); err == nil {
return id
}
decoded := id
if strings.Contains(id, "%") {
if unescaped, err := url.PathUnescape(id); err == nil {
decoded = unescaped
}
}
if strings.Contains(decoded, "/") {
parts := strings.Split(decoded, "/")
for i, part := range parts {
parts[i] = url.PathEscape(part)
}
return strings.Join(parts, "%2F")
}
return url.PathEscape(decoded)
}
func (c *client) project(ctx context.Context, id string) (*project, error) {
var p project
err := c.get(ctx, "/projects/"+projectPath(id), &p)
return &p, err
}
// trackPage records the page a paginated walk is about to request. A page that
// was already requested means X-Next-Page is not advancing, so the walk stops
// with an error instead of re-reading the same page; the hop cap bounds a
// server that keeps advertising fresh page numbers.
func trackPage(ctx context.Context, scope string, seen map[string]struct{}, page string) error {
if _, dup := seen[page]; dup {
return fmt.Errorf("gitlab %s pagination repeated page %q", scope, page)
}
if len(seen) >= maxPaginationHops {
logger.Warnf(ctx, "[GitLab] %s pagination exceeded %d pages; aborting", scope, maxPaginationHops)
return fmt.Errorf("gitlab %s pagination exceeded %d pages", scope, maxPaginationHops)
}
seen[page] = struct{}{}
return nil
}
func (c *client) projects(ctx context.Context) ([]project, error) {
q := url.Values{
"membership": {"true"}, "per_page": {"100"}, "page": {"1"},
"order_by": {"path_with_namespace"}, "sort": {"asc"},
}
var all []project
seen := make(map[string]struct{})
for {
if err := trackPage(ctx, "project", seen, q.Get("page")); err != nil {
return nil, err
}
var page []project
nextPage, err := c.getPage(ctx, "/projects", q, &page)
if err != nil {
return nil, err
}
all = append(all, page...)
if nextPage == "" {
return all, nil
}
q.Set("page", nextPage)
}
}
// ping verifies that the supplied private token is accepted by this GitLab
// instance. It avoids project-list ordering parameters that older GitLab
// deployments may reject even when the token is valid.
func (c *client) ping(ctx context.Context) error {
var user struct {
ID int64 `json:"id"`
}
return c.get(ctx, "/user", &user)
}
func (c *client) commitSHA(ctx context.Context, id, ref string) (string, error) {
var v struct {
ID string `json:"id"`
}
err := c.get(ctx, "/projects/"+projectPath(id)+"/repository/commits/"+url.PathEscape(ref), &v)
return v.ID, err
}
func (c *client) tree(ctx context.Context, id, ref, dir string) ([]treeEntry, error) {
q := url.Values{"ref": {ref}, "per_page": {"100"}, "page": {"1"}}
if dir != "" {
q.Set("path", dir)
}
endpoint := "/projects/" + projectPath(id) + "/repository/tree"
var all []treeEntry
seen := make(map[string]struct{})
for {
if err := trackPage(ctx, "tree", seen, q.Get("page")); err != nil {
return nil, err
}
var page []treeEntry
nextPage, err := c.getPage(ctx, endpoint, q, &page)
if err != nil {
return nil, err
}
all = append(all, page...)
if nextPage == "" {
return all, nil
}
q.Set("page", nextPage)
}
}
func (c *client) getPage(ctx context.Context, endpoint string, query url.Values, out interface{}) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+endpoint+"?"+query.Encode(), nil)
if err != nil {
return "", err
}
req.Header.Set("PRIVATE-TOKEN", c.token)
resp, err := c.http.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", &apiError{endpoint: endpoint, status: resp.StatusCode}
}
body, err := readCapped(resp.Body, c.jsonLimit)
if err != nil {
return "", fmt.Errorf("gitlab API %s: %w", endpoint, err)
}
if err := json.Unmarshal(body, out); err != nil {
return "", err
}
return resp.Header.Get("X-Next-Page"), nil
}
func (c *client) raw(ctx context.Context, id, ref, file string) ([]byte, error) {
q := url.Values{"ref": {ref}}
encodedFile := gitlabFilePathEscape(file)
rawEndpoint := "/projects/" + projectPath(id) + "/repository/files/" + encodedFile + "/raw?" + q.Encode()
content, err := c.getRaw(ctx, rawEndpoint)
if err == nil {
return content, nil
}
var apiErr *apiError
if !errors.As(err, &apiErr) || apiErr.status != http.StatusNotFound {
return nil, fmt.Errorf("gitlab file %s: %w", file, err)
}
// Some GitLab deployments expose the file detail endpoint but return 404
// for the otherwise standard /raw route. The detail response contains the
// same content as base64 and provides a compatible fallback.
var detail struct {
Encoding string `json:"encoding"`
Content string `json:"content"`
}
detailEndpoint := "/projects/" + projectPath(id) + "/repository/files/" + encodedFile + "?" + q.Encode()
if err := c.getCapped(ctx, detailEndpoint, &detail, base64FileBytes(c.rawLimit)); err != nil {
return nil, fmt.Errorf("gitlab file %s: %w", file, err)
}
if detail.Encoding != "base64" {
return nil, fmt.Errorf("gitlab file %s: unsupported encoding %q", file, detail.Encoding)
}
content, err = base64.StdEncoding.DecodeString(detail.Content)
if err != nil {
return nil, fmt.Errorf("gitlab file %s: decode base64: %w", file, err)
}
return content, nil
}
// gitlabFilePathEscape mirrors the company GitLab raw-file route: only ASCII
// letters, digits, hyphen and underscore remain literal. In particular dots,
// path separators and UTF-8 bytes must be percent-encoded.
func gitlabFilePathEscape(file string) string {
const hex = "0123456789ABCDEF"
var b strings.Builder
b.Grow(len(file) * 3)
for _, c := range []byte(file) {
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
b.WriteByte(c)
continue
}
b.WriteByte('%')
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&0x0f])
}
return b.String()
}
func (c *client) compare(ctx context.Context, id, from, to string) (*comparison, error) {
// Sync compares snapshots, not changes since their merge base. The default
// comparison misses reverted files when a branch is reset or force-pushed.
q := url.Values{"from": {from}, "to": {to}, "straight": {"true"}}
var v comparison
err := c.getCapped(ctx, "/projects/"+projectPath(id)+"/repository/compare?"+q.Encode(), &v, c.compareLimit)
return &v, err
}
@@ -0,0 +1,693 @@
package gitlab
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
func allowLocalGitLabServer(t *testing.T) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1,::1,localhost")
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
}
func TestConnectorValidateUsesDataSourceCredentials(t *testing.T) {
allowLocalGitLabServer(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v4/user" {
http.NotFound(w, r)
return
}
if got := r.Header.Get("PRIVATE-TOKEN"); got != "per-source-token" {
t.Fatalf("PRIVATE-TOKEN = %q", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id": 42}`))
}))
defer server.Close()
ds := &types.DataSourceConfig{
Credentials: map[string]interface{}{
"base_url": server.URL,
"access_token": "per-source-token",
},
}
if err := NewConnector().Validate(context.Background(), ds); err != nil {
t.Fatalf("Validate() error = %v", err)
}
}
func TestConnectorValidateReturnsGitLabAPIError(t *testing.T) {
allowLocalGitLabServer(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v4/user" {
http.NotFound(w, r)
return
}
http.Error(w, "invalid token", http.StatusUnauthorized)
}))
defer server.Close()
err := NewConnector().Validate(context.Background(), &types.DataSourceConfig{
Credentials: map[string]interface{}{
"base_url": server.URL,
"access_token": "invalid-token",
},
})
var apiErr *apiError
if !errors.As(err, &apiErr) {
t.Fatalf("Validate() error = %v, want GitLab API error", err)
}
if apiErr.endpoint != "/user" || apiErr.status != http.StatusUnauthorized {
t.Fatalf("apiError = %#v", apiErr)
}
}
func TestConnectorValidateRejectsMissingCredentials(t *testing.T) {
err := NewConnector().Validate(context.Background(), &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": "https://gitlab.example.com"},
})
if err == nil || err.Error() != "GitLab platform configuration is missing" {
t.Fatalf("Validate() error = %v", err)
}
}
func TestConnectorValidateRejectsMissingProjectsOnSave(t *testing.T) {
allowLocalGitLabServer(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v4/user" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id": 42}`))
}))
defer server.Close()
err := NewConnector().Validate(context.Background(), &types.DataSourceConfig{
Credentials: map[string]interface{}{
"base_url": server.URL,
"access_token": "token",
},
Settings: map[string]interface{}{
"projects": []interface{}{},
},
})
if err == nil {
t.Fatal("expected missing projects validation error")
}
}
func TestConnectorConfiguredDoesNotReuseRegistryClient(t *testing.T) {
allowLocalGitLabServer(t)
var requestedTokens []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v4/user" {
http.NotFound(w, r)
return
}
requestedTokens = append(requestedTokens, r.Header.Get("PRIVATE-TOKEN"))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id": 42}`))
}))
defer server.Close()
connector := NewConnector()
first := &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token-a"},
}
second := &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token-b"},
}
if err := connector.Validate(context.Background(), first); err != nil {
t.Fatalf("first validate: %v", err)
}
if err := connector.Validate(context.Background(), second); err != nil {
t.Fatalf("second validate: %v", err)
}
if len(requestedTokens) != 2 || requestedTokens[0] != "token-a" || requestedTokens[1] != "token-b" {
t.Fatalf("requested tokens = %#v", requestedTokens)
}
}
func TestNewClientNormalizesAPIBaseURL(t *testing.T) {
allowLocalGitLabServer(t)
server := httptest.NewServer(http.NotFoundHandler())
defer server.Close()
c, err := newClient(server.URL+"/", "token")
if err != nil {
t.Fatal(err)
}
if got, want := c.baseURL, server.URL+"/api/v4"; got != want {
t.Fatalf("baseURL = %q, want %q", got, want)
}
}
func TestFetchIncrementalSyncsMultipleProjects(t *testing.T) {
allowLocalGitLabServer(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 "/api/v4/projects/1":
_, _ = w.Write([]byte(`{"id":1,"name":"project-one","path_with_namespace":"group/project-one","web_url":"https://gitlab.test/group/project-one","default_branch":"master"}`))
case "/api/v4/projects/2":
_, _ = w.Write([]byte(`{"id":2,"name":"project-two","path_with_namespace":"group/project-two","web_url":"https://gitlab.test/group/project-two","default_branch":"master"}`))
case "/api/v4/projects/1/repository/commits/master":
_, _ = w.Write([]byte(`{"id":"commit-1"}`))
case "/api/v4/projects/2/repository/commits/master":
_, _ = w.Write([]byte(`{"id":"commit-2"}`))
case "/api/v4/projects/1/repository/tree":
_, _ = w.Write([]byte(`[{"name":"one.md","type":"blob","path":"one.md"}]`))
case "/api/v4/projects/2/repository/tree":
_, _ = w.Write([]byte(`[{"name":"two.md","type":"blob","path":"two.md"}]`))
default:
if strings.HasPrefix(r.URL.EscapedPath(), "/api/v4/projects/1/repository/files/one%2Emd/raw") {
_, _ = w.Write([]byte("one"))
return
}
if strings.HasPrefix(r.URL.EscapedPath(), "/api/v4/projects/2/repository/files/two%2Emd/raw") {
_, _ = w.Write([]byte("two"))
return
}
http.NotFound(w, r)
}
}))
defer server.Close()
connector := NewConnector()
config := &types.DataSourceConfig{
Credentials: map[string]interface{}{
"base_url": server.URL,
"access_token": "token",
},
Settings: map[string]interface{}{
"projects": []interface{}{
map[string]interface{}{"project_id": "1", "ref": "master", "paths": []interface{}{}},
map[string]interface{}{"project_id": "2", "ref": "master", "paths": []interface{}{}},
},
},
}
items, cursor, err := connector.FetchIncremental(context.Background(), config, nil)
if err != nil {
t.Fatalf("first sync: %v", err)
}
if len(items) != 2 {
t.Fatalf("first sync items = %d, want 2", len(items))
}
if cursor == nil || fmt.Sprint(cursor.ConnectorCursor["projects"]) == "" {
t.Fatal("first sync did not return per-project cursor state")
}
items, _, err = connector.FetchIncremental(context.Background(), config, cursor)
if err != nil {
t.Fatalf("second sync: %v", err)
}
if len(items) != 0 {
t.Fatalf("second sync items = %d, want 0", len(items))
}
}
type gitLabStreamRecorder struct {
items []types.FetchedItem
checkpoints []*types.SyncCursor
}
func (h *gitLabStreamRecorder) Emit(_ context.Context, item types.FetchedItem) error {
h.items = append(h.items, item)
return nil
}
func (h *gitLabStreamRecorder) Checkpoint(_ context.Context, cursor *types.SyncCursor) error {
h.checkpoints = append(h.checkpoints, cursor)
return nil
}
func TestFetchStreamFiltersUnsupportedFilesAndCheckpointsProjects(t *testing.T) {
allowLocalGitLabServer(t)
var rawRequests []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v4/projects/1":
_, _ = w.Write([]byte(`{"id":1,"name":"docs","path_with_namespace":"group/docs","web_url":"https://gitlab.test/group/docs","default_branch":"main"}`))
case "/api/v4/projects/1/repository/commits/main":
_, _ = w.Write([]byte(`{"id":"commit-1"}`))
case "/api/v4/projects/1/repository/tree":
_, _ = w.Write([]byte(`[
{"name":"README.md","type":"blob","path":"README.md"},
{"name":"server.go","type":"blob","path":"server.go"},
{"name":"payload.exe","type":"blob","path":"payload.exe"}
]`))
default:
if strings.Contains(r.URL.EscapedPath(), "/repository/files/") {
rawRequests = append(rawRequests, r.URL.EscapedPath())
_, _ = w.Write([]byte("# readme"))
return
}
http.NotFound(w, r)
}
}))
defer server.Close()
connector := NewConnector()
config := &types.DataSourceConfig{
Credentials: map[string]interface{}{
"base_url": server.URL,
"access_token": "token",
},
Settings: map[string]interface{}{
"projects": []interface{}{map[string]interface{}{"project_id": "1", "paths": []interface{}{}}},
},
}
handler := &gitLabStreamRecorder{}
next, err := connector.FetchStream(context.Background(), config, nil, handler)
if err != nil {
t.Fatalf("FetchStream() error = %v", err)
}
if len(handler.items) != 1 || handler.items[0].FileName != "docs-main/README.md" {
t.Fatalf("emitted items = %#v", handler.items)
}
if len(rawRequests) != 1 || !strings.Contains(rawRequests[0], "README%2Emd") {
t.Fatalf("raw requests = %v, want only README.md", rawRequests)
}
if len(handler.checkpoints) != 1 || next == nil {
t.Fatalf("checkpoints = %d, next = %#v", len(handler.checkpoints), next)
}
projects, _ := next.ConnectorCursor["projects"].(map[string]string)
if projects["1"] != "commit-1" {
t.Fatalf("cursor projects = %#v", next.ConnectorCursor["projects"])
}
}
func TestIsSupportedFile(t *testing.T) {
for _, tc := range []struct {
file string
want bool
}{
{file: "docs/guide.MD", want: true},
{file: "docs/guide.mdx", want: true},
{file: "report.pdf", want: true},
{file: "src/main.go", want: false},
{file: "archive.tar.gz", want: false},
{file: "LICENSE", want: false},
} {
if got := isSupportedFile(tc.file); got != tc.want {
t.Errorf("isSupportedFile(%q) = %v, want %v", tc.file, got, tc.want)
}
}
}
func TestTreeFollowsGitLabPagination(t *testing.T) {
allowLocalGitLabServer(t)
var requestedPages []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v4/projects/1/repository/tree" {
http.NotFound(w, r)
return
}
requestedPages = append(requestedPages, r.URL.Query().Get("page"))
w.Header().Set("Content-Type", "application/json")
switch r.URL.Query().Get("page") {
case "1":
w.Header().Set("X-Next-Page", "2")
_, _ = w.Write([]byte(`[{"name":"one.md","type":"blob","path":"one.md"}]`))
case "2":
_, _ = w.Write([]byte(`[{"name":"two.md","type":"blob","path":"two.md"}]`))
default:
http.Error(w, "unexpected page", http.StatusBadRequest)
}
}))
defer server.Close()
c, err := newClient(server.URL, "token")
if err != nil {
t.Fatal(err)
}
entries, err := c.tree(context.Background(), "1", "main", "")
if err != nil {
t.Fatalf("tree() error = %v", err)
}
if len(entries) != 2 || entries[1].Path != "two.md" {
t.Fatalf("entries = %#v", entries)
}
if got, want := strings.Join(requestedPages, ","), "1,2"; got != want {
t.Fatalf("requested pages = %q, want %q", got, want)
}
}
func TestProjectPathEncodesNamespaceWithoutDoubleEscaping(t *testing.T) {
for _, tc := range []struct {
in, want string
}{
{in: "12345", want: "12345"},
{in: "group/project", want: "group%2Fproject"},
{in: "group%2Fproject", want: "group%2Fproject"},
{in: "my group/my project", want: "my%20group%2Fmy%20project"},
} {
if got := projectPath(tc.in); got != tc.want {
t.Errorf("projectPath(%q) = %q, want %q", tc.in, got, tc.want)
}
}
}
func TestRawFallsBackToBase64FileDetail(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1,::1,localhost")
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.EscapedPath() {
case "/api/v4/projects/18724/repository/files/docs%2Finternal%2Freadme%2Emd/raw":
http.NotFound(w, r)
case "/api/v4/projects/18724/repository/files/docs%2Finternal%2Freadme%2Emd":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"encoding":"base64","content":"SGVsbG8sIEdpdExhYiE="}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
c, err := newClient(server.URL, "token")
if err != nil {
t.Fatal(err)
}
content, err := c.raw(context.Background(), "18724", "master", "docs/internal/readme.md")
if err != nil {
t.Fatal(err)
}
if string(content) != "Hello, GitLab!" {
t.Fatalf("content = %q", content)
}
}
func TestGitlabFilePathEscape(t *testing.T) {
got := gitlabFilePathEscape("docs/internal/中文-file.md")
want := "docs%2Finternal%2F%E4%B8%AD%E6%96%87-file%2Emd"
if got != want {
t.Fatalf("gitlabFilePathEscape() = %q, want %q", got, want)
}
}
// newCappedTestClient builds a client whose JSON and raw-file caps are small
// enough to exercise them without materialising the production limits.
// compareLimit stays at the production value unless the test assigns it.
func newCappedTestClient(t *testing.T, serverURL string, jsonLimit, rawLimit int64) *client {
t.Helper()
c, err := newClient(serverURL, "token")
if err != nil {
t.Fatal(err)
}
c.jsonLimit = jsonLimit
c.rawLimit = rawLimit
return c
}
func TestGetRawRejectsBlobLargerThanCap(t *testing.T) {
allowLocalGitLabServer(t)
const rawLimit = 1 << 20
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit+1))
}))
defer server.Close()
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
content, err := c.getRaw(context.Background(), "/projects/1/repository/files/big.bin/raw")
if err == nil {
t.Fatalf("getRaw() accepted a %d-byte blob under a %d-byte cap", len(content), rawLimit)
}
if content != nil {
t.Fatalf("getRaw() returned %d bytes alongside the error, want no partial body", len(content))
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
if !strings.Contains(err.Error(), fmt.Sprint(rawLimit)) {
t.Fatalf("error = %v, want it to name the %d-byte limit", err, rawLimit)
}
}
func TestGetRawAcceptsBlobAtCap(t *testing.T) {
allowLocalGitLabServer(t)
const rawLimit = 1 << 20
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit))
}))
defer server.Close()
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
content, err := c.getRaw(context.Background(), "/projects/1/repository/files/fit.bin/raw")
if err != nil {
t.Fatalf("getRaw() rejected a blob exactly at the cap: %v", err)
}
if len(content) != rawLimit {
t.Fatalf("content = %d bytes, want the full %d", len(content), rawLimit)
}
}
// TestRawSurfacesOversizedBlobInsteadOfFallingBack checks that hitting the size
// cap fails the fetch rather than being mistaken for a missing /raw route and
// retried through the base64 detail endpoint.
func TestRawSurfacesOversizedBlobInsteadOfFallingBack(t *testing.T) {
allowLocalGitLabServer(t)
const rawLimit = 1 << 20
detailHits := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.EscapedPath(), "/raw") {
_, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit+1))
return
}
detailHits++
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"encoding":"base64","content":"SGk="}`))
}))
defer server.Close()
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
const file = "docs/guide.mp3"
content, err := c.raw(context.Background(), "1", "main", file)
if err == nil {
t.Fatalf("raw() accepted a %d-byte blob under a %d-byte cap", len(content), rawLimit)
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
if !strings.Contains(err.Error(), file) {
t.Fatalf("error = %v, want the repository path %s", err, file)
}
if detailHits != 0 {
t.Fatalf("base64 detail endpoint hit %d times, want 0", detailHits)
}
}
func TestBase64FallbackRejectsOversizedDetail(t *testing.T) {
allowLocalGitLabServer(t)
const rawLimit = 3 << 20
limit := base64FileBytes(rawLimit)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.EscapedPath(), "/raw") {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(bytes.Repeat([]byte("a"), int(limit)+1))
}))
defer server.Close()
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
const file = "docs/guide.mp3"
if _, err := c.raw(context.Background(), "1", "main", file); err == nil {
t.Fatal("raw() accepted an oversized base64 detail response")
} else if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
} else if !strings.Contains(err.Error(), file) {
t.Fatalf("error = %v, want the repository path %s", err, file)
}
}
func TestGetRejectsOversizedJSONResponse(t *testing.T) {
allowLocalGitLabServer(t)
const jsonLimit = 512 << 10
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
}))
defer server.Close()
c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
var out struct{}
err := c.get(context.Background(), "/projects/1", &out)
if err == nil {
t.Fatal("get() accepted an oversized JSON response")
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
}
func TestGetPageRejectsOversizedJSONResponse(t *testing.T) {
allowLocalGitLabServer(t)
const jsonLimit = 512 << 10
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
}))
defer server.Close()
c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
if _, err := c.tree(context.Background(), "1", "main", ""); err == nil {
t.Fatal("tree() accepted an oversized JSON response")
} else if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
}
// TestOversizedErrorBodyKeepsStatusError pins that an oversized body on a
// non-2xx response is still reported as the HTTP status, so a large error page
// cannot mask the real failure.
func TestOversizedErrorBodyKeepsStatusError(t *testing.T) {
allowLocalGitLabServer(t)
const jsonLimit = 512 << 10
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
}))
defer server.Close()
for name, call := range map[string]func(*client) error{
"get": func(c *client) error {
var out struct{}
return c.get(context.Background(), "/projects/1", &out)
},
"getPage": func(c *client) error {
_, err := c.tree(context.Background(), "1", "main", "")
return err
},
} {
c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
err := call(c)
var apiErr *apiError
if !errors.As(err, &apiErr) {
t.Fatalf("%s: error = %v, want an *apiError", name, err)
}
if apiErr.status != http.StatusInternalServerError {
t.Fatalf("%s: status = %d, want %d", name, apiErr.status, http.StatusInternalServerError)
}
}
}
func TestNewClientSetsResponseCaps(t *testing.T) {
allowLocalGitLabServer(t)
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer server.Close()
c, err := newClient(server.URL, "token")
if err != nil {
t.Fatal(err)
}
if c.jsonLimit != maxJSONResponseBytes ||
c.compareLimit != maxCompareResponseBytes ||
c.rawLimit != maxRawFileBytes {
t.Fatalf("caps = json %d compare %d raw %d", c.jsonLimit, c.compareLimit, c.rawLimit)
}
if c.compareLimit <= c.jsonLimit {
t.Fatalf("compare cap %d must sit above the metadata cap %d", c.compareLimit, c.jsonLimit)
}
}
// TestCompareAllowsPayloadAboveMetadataCap pins that a straight compare larger
// than the metadata JSON cap still succeeds. That body carries commits and
// patches the sync does not store; rejecting it would stall the project cursor.
func TestCompareAllowsPayloadAboveMetadataCap(t *testing.T) {
allowLocalGitLabServer(t)
const (
jsonLimit = 512
compareLimit = 8 << 10
)
padding := strings.Repeat("p", jsonLimit)
payload := `{"diffs":[{"old_path":"docs/old.md","new_path":"docs/new.md","renamed_file":true}],` +
`"compare_timeout":false,"padding":"` + padding + `"}`
body := []byte(payload)
if int64(len(body)) <= jsonLimit || int64(len(body)) > compareLimit {
t.Fatalf("fixture is %d bytes, want it between %d and %d", len(body), jsonLimit, compareLimit)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(body)
}))
defer server.Close()
c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
c.compareLimit = compareLimit
var project struct{}
if err := c.get(context.Background(), "/projects/1", &project); err == nil {
t.Fatal("get() accepted a body above the metadata cap")
} else if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("get() error = %v, want an explicit over-limit error", err)
}
diff, err := c.compare(context.Background(), "1", "abc", "def")
if err != nil {
t.Fatalf("compare() rejected a body above the metadata cap and under the compare cap: %v", err)
}
if diff.CompareTimeout {
t.Fatal("compare_timeout = true, want false")
}
if len(diff.Diffs) != 1 ||
diff.Diffs[0].OldPath != "docs/old.md" ||
diff.Diffs[0].NewPath != "docs/new.md" ||
!diff.Diffs[0].RenamedFile {
t.Fatalf("diffs = %+v", diff.Diffs)
}
}
func TestCompareRejectsPayloadAboveCompareCap(t *testing.T) {
allowLocalGitLabServer(t)
const compareLimit = 1024
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(bytes.Repeat([]byte("a"), compareLimit+1))
}))
defer server.Close()
c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, maxRawFileBytes)
c.compareLimit = compareLimit
_, err := c.compare(context.Background(), "1", "abc", "def")
if err == nil {
t.Fatal("compare() accepted a body above the compare cap")
}
if !strings.Contains(err.Error(), "exceeds maximum size") ||
!strings.Contains(err.Error(), fmt.Sprint(compareLimit)) {
t.Fatalf("error = %v, want an explicit over-limit error naming %d", err, compareLimit)
}
}
@@ -0,0 +1,83 @@
package gitlab
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConnectorRollbackEmitsSnapshotChanges(t *testing.T) {
for _, mode := range []string{"incremental", "stream"} {
t.Run(mode, func(t *testing.T) {
allowLocalGitLabServer(t)
server := rollbackGitLabServer(t)
cfg := &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
Settings: map[string]interface{}{"projects": []interface{}{
map[string]interface{}{"project_id": "1", "ref": "main"},
}},
}
old := gitLabCursor(cursor{Projects: map[string]string{"1": "descendant"}})
connector := NewConnector()
var items []types.FetchedItem
var next *types.SyncCursor
var err error
if mode == "incremental" {
items, next, err = connector.FetchIncremental(context.Background(), cfg, old)
} else {
handler := &gitLabStreamRecorder{}
next, err = connector.FetchStream(context.Background(), cfg, old, handler)
items = handler.items
require.Len(t, handler.checkpoints, 1)
}
require.NoError(t, err)
require.Len(t, items, 2, "rollback must restore changed files and delete files absent from the target")
require.Equal(t, []byte("# original README"), items[0].Content)
require.Equal(t, "README.md", items[0].Metadata["gitlab_path"])
require.True(t, items[1].IsDeleted)
require.Equal(t, "added.md", items[1].Metadata["gitlab_path"])
require.Equal(t, server.URL+"/api/v4:1:main:added.md", strings.TrimPrefix(items[1].ExternalID, "gitlab:"))
require.Equal(t, "ancestor", next.ConnectorCursor["projects"].(map[string]string)["1"])
})
}
}
func rollbackGitLabServer(t *testing.T) *httptest.Server {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v4/projects/1":
_, _ = fmt.Fprint(w, `{"id":1,"name":"docs","default_branch":"main"}`)
case "/api/v4/projects/1/repository/commits/main":
_, _ = fmt.Fprint(w, `{"id":"ancestor"}`)
case "/api/v4/projects/1/repository/compare":
assert.Equal(t, "descendant", r.URL.Query().Get("from"))
assert.Equal(t, "ancestor", r.URL.Query().Get("to"))
// GitLab's default merge-base comparison returns no diffs when to
// is an ancestor of from. Direct comparison returns the rollback.
if r.URL.Query().Get("straight") != "true" {
_, _ = fmt.Fprint(w, `{"diffs":[]}`)
return
}
_, _ = fmt.Fprint(w, `{"diffs":[
{"old_path":"README.md","new_path":"README.md"},
{"old_path":"added.md","new_path":"added.md","deleted_file":true}
]}`)
case "/api/v4/projects/1/repository/files/README.md/raw":
assert.Equal(t, "main", r.URL.Query().Get("ref"))
_, _ = fmt.Fprint(w, "# original README")
default:
http.NotFound(w, r)
}
}))
t.Cleanup(server.Close)
return server
}
@@ -0,0 +1,469 @@
package gitlab
import (
"context"
"encoding/json"
"fmt"
"path"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
var _ datasource.StreamingConnector = (*Connector)(nil)
type Connector struct {
client *client
canonicalBase string
}
// NewConnector creates a stateless connector. Each data source provides its
// own GitLab URL and access token in its encrypted credentials.
func NewConnector() *Connector { return &Connector{} }
func (c *Connector) Type() string { return types.ConnectorTypeGitLab }
func (c *Connector) configured(ds *types.DataSourceConfig) (*Connector, error) {
if ds == nil {
return nil, datasource.ErrInvalidConfig
}
baseURL, _ := ds.Credentials["base_url"].(string)
token, _ := ds.Credentials["access_token"].(string)
client, err := newClient(baseURL, token)
if err != nil {
return nil, err
}
return &Connector{client: client, canonicalBase: client.baseURL}, nil
}
func (c *Connector) Validate(ctx context.Context, ds *types.DataSourceConfig) error {
configured, err := c.configured(ds)
if err != nil {
return err
}
if err := configured.client.ping(ctx); err != nil {
return err
}
if ds != nil {
if _, ok := ds.Settings["projects"]; ok {
if _, err := parseConfig(ds); err != nil {
return err
}
}
}
return nil
}
func (c *Connector) ListResources(ctx context.Context, ds *types.DataSourceConfig, parent string) ([]types.Resource, error) {
var err error
if c, err = c.configured(ds); err != nil {
return nil, err
}
if _, err := parseConfig(ds); err != nil {
return nil, err
}
if parent == "" {
ps, err := c.client.projects(ctx)
if err != nil {
return nil, err
}
out := make([]types.Resource, 0, len(ps))
for _, p := range ps {
out = append(out, types.Resource{ExternalID: fmt.Sprint(p.ID), Name: p.PathWithNamespace, Type: "project", URL: p.WebURL, HasChildren: true})
}
return out, nil
}
id, dir := splitResourceID(parent)
p, err := c.client.project(ctx, id)
if err != nil {
return nil, err
}
ref := p.DefaultBranch
entries, err := c.client.tree(ctx, id, ref, dir)
if err != nil {
return nil, err
}
out := make([]types.Resource, 0, len(entries))
for _, e := range entries {
if e.Type == "tree" {
out = append(out, types.Resource{ExternalID: id + ":" + e.Path, Name: e.Name, Type: "directory", ParentID: parent, HasChildren: true})
}
}
return out, nil
}
func (c *Connector) ResolveResourceAncestors(context.Context, *types.DataSourceConfig, []string) ([]string, error) {
return []string{}, nil
}
func (c *Connector) FetchAll(ctx context.Context, ds *types.DataSourceConfig, _ []string) ([]types.FetchedItem, error) {
var err error
if c, err = c.configured(ds); err != nil {
return nil, err
}
cfg, err := parseConfig(ds)
if err != nil {
return nil, err
}
var out []types.FetchedItem
for _, s := range cfg.Projects {
p, err := c.client.project(ctx, s.ProjectID)
if err != nil {
return nil, err
}
ref := s.Ref
if ref == "" {
ref = p.DefaultBranch
}
files, err := c.files(ctx, s.ProjectID, ref, s.Paths)
if err != nil {
return nil, err
}
for _, file := range files {
item, err := c.item(ctx, p, ref, file)
if err != nil {
return nil, err
}
out = append(out, item)
}
}
return out, nil
}
type cursor struct {
Projects map[string]string `json:"projects"`
}
func (c *Connector) FetchIncremental(ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor) ([]types.FetchedItem, *types.SyncCursor, error) {
var err error
if c, err = c.configured(ds); err != nil {
return nil, nil, err
}
cfg, err := parseConfig(ds)
if err != nil {
return nil, nil, err
}
prev := cursor{Projects: map[string]string{}}
if old != nil {
b, _ := json.Marshal(old.ConnectorCursor)
_ = json.Unmarshal(b, &prev)
if prev.Projects == nil {
prev.Projects = map[string]string{}
}
}
var out []types.FetchedItem
next := cursor{Projects: map[string]string{}}
for _, s := range cfg.Projects {
p, err := c.client.project(ctx, s.ProjectID)
if err != nil {
return nil, nil, err
}
ref := s.Ref
if ref == "" {
ref = p.DefaultBranch
}
head, err := c.client.commitSHA(ctx, s.ProjectID, ref)
if err != nil {
return nil, nil, err
}
previous := prev.Projects[s.ProjectID]
if previous == "" {
files, err := c.files(ctx, s.ProjectID, ref, s.Paths)
if err != nil {
return nil, nil, err
}
for _, f := range files {
item, err := c.item(ctx, p, ref, f)
if err != nil {
return nil, nil, err
}
out = append(out, item)
}
} else if previous != head {
diff, err := c.compareChanges(ctx, s.ProjectID, previous, head)
if err != nil {
return nil, nil, err
}
for _, d := range diff.Diffs {
if d.DeletedFile {
if c.inScope(d.OldPath, s.Paths) && isSupportedFile(d.OldPath) {
out = append(out, c.deleted(p, ref, d.OldPath))
}
continue
}
if d.RenamedFile && c.inScope(d.OldPath, s.Paths) && isSupportedFile(d.OldPath) {
out = append(out, c.deleted(p, ref, d.OldPath))
}
if c.inScope(d.NewPath, s.Paths) && isSupportedFile(d.NewPath) {
item, err := c.item(ctx, p, ref, d.NewPath)
if err != nil {
return nil, nil, err
}
out = append(out, item)
}
}
}
next.Projects[s.ProjectID] = head
}
raw, _ := json.Marshal(next)
return out, &types.SyncCursor{LastSyncTime: time.Now().UTC(), ConnectorCursor: map[string]interface{}{"projects": next.Projects, "raw": string(raw)}}, nil
}
// FetchStream is the production sync path. It emits each supported repository
// file as soon as it is read, so large GitLab projects do not accumulate their
// contents in memory. The service prefers this method for StreamingConnector
// implementations; FetchAll and FetchIncremental remain compatibility methods
// required by the base Connector interface.
func (c *Connector) FetchStream(
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
var err error
if c, err = c.configured(ds); err != nil {
return nil, err
}
cfg, err := parseConfig(ds)
if err != nil {
return nil, err
}
prev := cursor{Projects: map[string]string{}}
if old != nil {
b, _ := json.Marshal(old.ConnectorCursor)
_ = json.Unmarshal(b, &prev)
if prev.Projects == nil {
prev.Projects = map[string]string{}
}
}
next := cursor{Projects: make(map[string]string, len(cfg.Projects))}
for projectID, commit := range prev.Projects {
next.Projects[projectID] = commit
}
for _, selection := range cfg.Projects {
project, err := c.client.project(ctx, selection.ProjectID)
if err != nil {
return nil, err
}
ref := selection.Ref
if ref == "" {
ref = project.DefaultBranch
}
head, err := c.client.commitSHA(ctx, selection.ProjectID, ref)
if err != nil {
return nil, err
}
previous := prev.Projects[selection.ProjectID]
switch {
case previous == "":
err = c.streamFiles(ctx, project, ref, selection.Paths, h)
case previous != head:
err = c.streamChanges(ctx, project, ref, previous, head, selection.Paths, h)
}
if err != nil {
return nil, err
}
next.Projects[selection.ProjectID] = head
checkpoint := gitLabCursor(next)
if err := h.Checkpoint(ctx, checkpoint); err != nil {
return nil, err
}
}
return gitLabCursor(next), nil
}
func gitLabCursor(value cursor) *types.SyncCursor {
raw, _ := json.Marshal(value)
return &types.SyncCursor{
LastSyncTime: time.Now().UTC(),
ConnectorCursor: map[string]interface{}{"projects": value.Projects, "raw": string(raw)},
}
}
func (c *Connector) streamChanges(
ctx context.Context, project *project, ref, from, to string, roots []string, h datasource.StreamHandler,
) error {
diff, err := c.compareChanges(ctx, fmt.Sprint(project.ID), from, to)
if err != nil {
return err
}
for _, change := range diff.Diffs {
if change.DeletedFile {
if c.inScope(change.OldPath, roots) && isSupportedFile(change.OldPath) {
if err := h.Emit(ctx, c.deleted(project, ref, change.OldPath)); err != nil {
return err
}
}
continue
}
if change.RenamedFile && c.inScope(change.OldPath, roots) && isSupportedFile(change.OldPath) {
if err := h.Emit(ctx, c.deleted(project, ref, change.OldPath)); err != nil {
return err
}
}
if c.inScope(change.NewPath, roots) && isSupportedFile(change.NewPath) {
item, err := c.item(ctx, project, ref, change.NewPath)
if err != nil {
return err
}
if err := h.Emit(ctx, item); err != nil {
return err
}
}
}
return nil
}
func (c *Connector) compareChanges(ctx context.Context, projectID, from, to string) (*comparison, error) {
diff, err := c.client.compare(ctx, projectID, from, to)
if err != nil {
return nil, fmt.Errorf("gitlab compare project %s: %w", projectID, err)
}
if diff.CompareTimeout {
return nil, fmt.Errorf("gitlab compare project %s timed out", projectID)
}
return diff, nil
}
func (c *Connector) streamFiles(
ctx context.Context, project *project, ref string, roots []string, h datasource.StreamHandler,
) error {
return c.walkFiles(ctx, fmt.Sprint(project.ID), ref, roots, func(file string) error {
item, err := c.item(ctx, project, ref, file)
if err != nil {
return err
}
return h.Emit(ctx, item)
})
}
func (c *Connector) files(ctx context.Context, id, ref string, roots []string) ([]string, error) {
var out []string
err := c.walkFiles(ctx, id, ref, roots, func(file string) error {
out = append(out, file)
return nil
})
return out, err
}
// walkFiles visits supported blobs while traversing the selected directories.
// It deliberately does not collect paths, keeping streaming sync memory bounded
// by the traversal depth plus the current file body.
func (c *Connector) walkFiles(ctx context.Context, id, ref string, roots []string, visit func(string) error) error {
if len(roots) == 0 {
roots = []string{""}
}
var walk func(string) error
walk = func(dir string) error {
entries, err := c.client.tree(ctx, id, ref, dir)
if err != nil {
return err
}
for _, e := range entries {
if e.Type == "tree" {
if err := walk(e.Path); err != nil {
return err
}
} else if e.Type == "blob" && isSupportedFile(e.Path) {
if err := visit(e.Path); err != nil {
return err
}
}
}
return nil
}
for _, r := range roots {
if err := walk(r); err != nil {
return err
}
}
return nil
}
func isSupportedFile(file string) bool {
_, ok := gitLabSupportedFileExtensions[strings.ToLower(path.Ext(file))]
return ok
}
// gitLabSupportedFileExtensions limits repository sync to formats the current
// knowledge import pipeline can process. This is intentionally connector-local:
// GitLab exposes arbitrary repository blobs, unlike document-centric sources.
var gitLabSupportedFileExtensions = map[string]struct{}{
".pdf": {}, ".txt": {}, ".docx": {}, ".doc": {}, ".epub": {},
".html": {}, ".htm": {}, ".mhtml": {}, ".md": {}, ".markdown": {}, ".mdx": {},
".png": {}, ".jpg": {}, ".jpeg": {}, ".gif": {},
".csv": {}, ".xlsx": {}, ".xls": {}, ".pptx": {}, ".ppt": {}, ".json": {},
".mp3": {}, ".wav": {}, ".m4a": {}, ".flac": {}, ".ogg": {},
}
func (c *Connector) item(ctx context.Context, p *project, ref, file string) (types.FetchedItem, error) {
body, err := c.client.raw(ctx, fmt.Sprint(p.ID), ref, file)
if err != nil {
return types.FetchedItem{}, err
}
id := fmt.Sprintf("gitlab:%s:%d:%s:%s", c.canonicalBase, p.ID, ref, file)
title := p.PathWithNamespace + "/" + file
// A file emptied by a commit still exists at this path, and ingestion reads
// an item with no content and no URL as "nothing to sync" (see
// datasource_service applyFetchedItem): the sync is acknowledged as
// successful while the body indexed from an earlier commit stays fully
// searchable. Nothing revisits it afterwards either — a full sync sees the
// file present in the tree, and an incremental sync only walks the diffs of
// commits newer than the recorded head, which the emptying commit already
// moved past.
//
// Emitting the file's path as its content replaces the stale body instead,
// which is what the Notion (b9be7d0d), Confluence and IMA (b71b31c8)
// connectors already do for the same case. The check is on length alone, not
// on TrimSpace: a blob that holds only whitespace still carries content the
// repository has, and only a zero-byte blob has none.
if len(body) == 0 {
logger.Infof(ctx, "[GitLab] %s is empty, syncing its path only", title)
body = []byte("# " + title + "\n")
}
// UpdatedAt is intentionally left unset: the file's last commit time is not
// fetched here, and a fetch timestamp would be a fabricated source time.
return types.FetchedItem{
ExternalID: id,
Title: title,
FileName: knowledgeRelativePath(p.Name, ref, file),
Content: body,
ContentType: "text/plain",
SourceResourceID: fmt.Sprint(p.ID),
Metadata: map[string]string{
"channel": types.ConnectorTypeGitLab,
"source_type": "gitlab",
"gitlab_project_id": fmt.Sprint(p.ID),
"gitlab_ref": ref,
"gitlab_path": file,
"gitlab_url": p.WebURL + "/-/blob/" + ref + "/" + file,
},
}, nil
}
// knowledgeRelativePath maps a repository file to the KB folder convention:
// <GitLab project name>-<branch>/<repository-relative file path>.
func knowledgeRelativePath(projectName, ref, file string) string {
root := strings.TrimSpace(projectName) + "-" + strings.ReplaceAll(strings.TrimSpace(ref), "/", "-")
return path.Join(root, file)
}
func (c *Connector) deleted(p *project, ref, file string) types.FetchedItem {
return types.FetchedItem{ExternalID: fmt.Sprintf("gitlab:%s:%d:%s:%s", c.canonicalBase, p.ID, ref, file), IsDeleted: true, Metadata: map[string]string{"channel": types.ConnectorTypeGitLab, "gitlab_path": file}}
}
func (c *Connector) inScope(file string, roots []string) bool {
if len(roots) == 0 {
return true
}
for _, r := range roots {
if file == r || strings.HasPrefix(file, r+"/") {
return true
}
}
return false
}
func splitResourceID(value string) (string, string) {
parts := strings.SplitN(value, ":", 2)
if len(parts) == 1 {
return value, ""
}
return parts[0], parts[1]
}
@@ -0,0 +1,255 @@
package gitlab
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path"
"slices"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
// Exercise the real tree and raw-file APIs, including a subdirectory returned
// on the second page. Browsing remains shallow; fetching must visit every level.
func TestConnectorFetchesNestedDirectories(t *testing.T) {
for _, mode := range []string{
"all", "incremental", "stream",
} {
t.Run(mode, func(t *testing.T) {
allowLocalGitLabServer(t)
dirs := []string{"docs", "docs/a", "docs/a/b", "docs/a/b/c", "docs/a/b/c/d"}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v4/projects/1":
_, _ = w.Write([]byte(`{
"id":1,"name":"docs","path_with_namespace":"group/docs","default_branch":"main"
}`))
case "/api/v4/projects/1/repository/commits/main":
_, _ = w.Write([]byte(`{"id":"head"}`))
case "/api/v4/projects/1/repository/compare":
_, _ = w.Write([]byte(`{"compare_timeout":true}`))
case "/api/v4/projects/1/repository/tree":
dir := r.URL.Query().Get("path")
index := slices.Index(dirs, dir)
if index < 0 || r.URL.Query().Get("ref") != "main" {
http.Error(w, "unexpected tree scope", http.StatusBadRequest)
return
}
var entries []treeEntry
switch r.URL.Query().Get("page") {
case "1":
entries = append(entries, treeEntry{Name: "README.md", Path: dir + "/README.md", Type: "blob"})
if index < len(dirs)-1 {
w.Header().Set("X-Next-Page", "2")
}
case "2":
if index < len(dirs)-1 {
child := dirs[index+1]
entries = append(entries, treeEntry{Name: path.Base(child), Path: child, Type: "tree"})
}
default:
http.Error(w, "unexpected page", http.StatusBadRequest)
return
}
_ = json.NewEncoder(w).Encode(entries)
default:
if strings.HasPrefix(r.URL.Path, "/api/v4/projects/1/repository/files/docs/") &&
strings.HasSuffix(r.URL.Path, "/raw") {
_, _ = fmt.Fprint(w, "# same content")
return
}
http.NotFound(w, r)
}
}))
defer server.Close()
cfg := &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
Settings: map[string]interface{}{"projects": []interface{}{
map[string]interface{}{"project_id": "1", "paths": []interface{}{"docs", "docs/a"}},
}},
}
connector := NewConnector()
var old *types.SyncCursor
if strings.Contains(mode, "fallback") {
old = gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}})
}
var items []types.FetchedItem
var err error
switch {
case mode == "all":
items, err = connector.FetchAll(context.Background(), cfg, nil)
case strings.HasPrefix(mode, "incremental"):
items, _, err = connector.FetchIncremental(context.Background(), cfg, old)
default:
handler := &gitLabStreamRecorder{}
_, err = connector.FetchStream(context.Background(), cfg, old, handler)
items = handler.items
require.Len(t, handler.checkpoints, 1)
}
require.NoError(t, err)
require.Len(t, items, len(dirs), "overlapping selected roots must not duplicate files")
for i, dir := range dirs {
require.Equal(t, "docs-main/"+dir+"/README.md", items[i].FileName)
require.Equal(t, dir+"/README.md", items[i].Metadata["gitlab_path"])
}
resources, err := connector.ListResources(context.Background(), cfg, "1:docs")
require.NoError(t, err)
require.Len(t, resources, 1)
require.Equal(t, "1:docs/a", resources[0].ExternalID)
})
}
}
func TestConnectorCompareFailuresDoNotFallBackToFullSync(t *testing.T) {
for _, failure := range []struct {
name string
statusCode int
body string
}{
{name: "timeout response", statusCode: http.StatusOK, body: `{"compare_timeout":true}`},
{name: "API error", statusCode: http.StatusInternalServerError, body: `{"message":"compare failed"}`},
} {
for _, mode := range []string{"incremental", "stream"} {
t.Run(failure.name+" "+mode, func(t *testing.T) {
allowLocalGitLabServer(t)
downstreamRequests := 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 "/api/v4/projects/1":
_, _ = w.Write([]byte(`{
"id":1,"name":"docs","path_with_namespace":"group/docs","default_branch":"main"
}`))
case "/api/v4/projects/1/repository/commits/main":
_, _ = w.Write([]byte(`{"id":"head"}`))
case "/api/v4/projects/1/repository/compare":
w.WriteHeader(failure.statusCode)
_, _ = w.Write([]byte(failure.body))
case "/api/v4/projects/1/repository/tree":
downstreamRequests++
_, _ = w.Write([]byte(`[{"name":"README.md","path":"README.md","type":"blob"}]`))
default:
if strings.Contains(r.URL.EscapedPath(), "/repository/files/") {
downstreamRequests++
_, _ = w.Write([]byte("# unchanged"))
return
}
http.NotFound(w, r)
}
}))
defer server.Close()
cfg := &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
Settings: map[string]interface{}{"projects": []interface{}{
map[string]interface{}{"project_id": "1", "paths": []interface{}{}},
}},
}
old := gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}})
connector := NewConnector()
switch mode {
case "incremental":
items, next, err := connector.FetchIncremental(context.Background(), cfg, old)
require.ErrorContains(t, err, "gitlab compare project 1")
require.Empty(t, items)
require.Nil(t, next)
case "stream":
handler := &gitLabStreamRecorder{}
next, err := connector.FetchStream(context.Background(), cfg, old, handler)
require.ErrorContains(t, err, "gitlab compare project 1")
require.Nil(t, next)
require.Empty(t, handler.items)
require.Empty(t, handler.checkpoints)
}
require.Zero(t, downstreamRequests, "compare failures must not trigger a full repository walk")
})
}
}
}
func TestConnectorSuccessfulCompareStillEmitsOnlyChangedFiles(t *testing.T) {
for _, mode := range []string{"incremental", "stream"} {
t.Run(mode, func(t *testing.T) {
allowLocalGitLabServer(t)
var compareQuery string
treeRequests := 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 "/api/v4/projects/1":
_, _ = w.Write([]byte(`{
"id":1,"name":"docs","path_with_namespace":"group/docs",
"web_url":"https://gitlab.test/group/docs","default_branch":"main"
}`))
case "/api/v4/projects/1/repository/commits/main":
_, _ = w.Write([]byte(`{"id":"head"}`))
case "/api/v4/projects/1/repository/compare":
compareQuery = r.URL.RawQuery
_, _ = w.Write([]byte(`{"diffs":[
{"old_path":"removed.md","new_path":"removed.md","deleted_file":true},
{"old_path":"old.md","new_path":"renamed.md","renamed_file":true},
{"old_path":"guide.md","new_path":"guide.md"},
{"old_path":"server.go","new_path":"server.go"}
]}`))
case "/api/v4/projects/1/repository/tree":
treeRequests++
http.Error(w, "unexpected full repository walk", http.StatusInternalServerError)
default:
if strings.Contains(r.URL.EscapedPath(), "/repository/files/") {
_, _ = w.Write([]byte("# changed"))
return
}
http.NotFound(w, r)
}
}))
defer server.Close()
cfg := &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
Settings: map[string]interface{}{"projects": []interface{}{
map[string]interface{}{"project_id": "1", "paths": []interface{}{}},
}},
}
old := gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}})
connector := NewConnector()
var items []types.FetchedItem
var next *types.SyncCursor
switch mode {
case "incremental":
var err error
items, next, err = connector.FetchIncremental(context.Background(), cfg, old)
require.NoError(t, err)
case "stream":
handler := &gitLabStreamRecorder{}
var err error
next, err = connector.FetchStream(context.Background(), cfg, old, handler)
require.NoError(t, err)
items = handler.items
require.Len(t, handler.checkpoints, 1)
}
require.Equal(t, "from=previous&straight=true&to=head", compareQuery)
require.Zero(t, treeRequests)
require.Len(t, items, 4)
require.True(t, items[0].IsDeleted)
require.Equal(t, "removed.md", items[0].Metadata["gitlab_path"])
require.True(t, items[1].IsDeleted)
require.Equal(t, "old.md", items[1].Metadata["gitlab_path"])
require.False(t, items[2].IsDeleted)
require.Equal(t, "renamed.md", items[2].Metadata["gitlab_path"])
require.False(t, items[3].IsDeleted)
require.Equal(t, "guide.md", items[3].Metadata["gitlab_path"])
require.Equal(t, "head", next.ConnectorCursor["projects"].(map[string]string)["1"])
})
}
}
@@ -0,0 +1,116 @@
package gitlab
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
// An emptied file is still a file. Ingestion treats an item with neither content
// nor URL as nothing to ingest and acknowledges the sync, so emitting the
// emptied blob verbatim leaves the body indexed from an earlier commit
// searchable forever — and no later sync revisits it, because a full sync still
// sees the path in the tree and an incremental sync has already moved its head
// past the commit that emptied it.
//
// The Notion (b9be7d0d), Confluence and IMA (b71b31c8) connectors emit the
// document's title in this case so ingestion replaces the stale body. GitLab
// does the same with the file's path, on both sync paths that can observe the
// change.
//
// Only a zero-byte blob is rewritten. A blob holding whitespace carries content
// the repository still has, so its bytes must reach ingestion untouched.
func TestConnectorEmitsPathWhenAFileIsEmptied(t *testing.T) {
for _, mode := range []string{"full", "incremental", "stream"} {
t.Run(mode, func(t *testing.T) {
allowLocalGitLabServer(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 "/api/v4/projects/1":
_, _ = w.Write([]byte(`{
"id":1,"name":"docs","path_with_namespace":"group/docs",
"web_url":"https://gitlab.test/group/docs","default_branch":"main"
}`))
case "/api/v4/projects/1/repository/commits/main":
_, _ = w.Write([]byte(`{"id":"head"}`))
case "/api/v4/projects/1/repository/compare":
_, _ = w.Write([]byte(`{"diffs":[
{"old_path":"runbook.md","new_path":"runbook.md"},
{"old_path":"indented.md","new_path":"indented.md"},
{"old_path":"kept.md","new_path":"kept.md"}
]}`))
case "/api/v4/projects/1/repository/tree":
_, _ = w.Write([]byte(`[
{"name":"runbook.md","path":"runbook.md","type":"blob"},
{"name":"indented.md","path":"indented.md","type":"blob"},
{"name":"kept.md","path":"kept.md","type":"blob"}
]`))
default:
if strings.Contains(r.URL.Path, "/repository/files/") {
switch {
case strings.Contains(r.URL.Path, "runbook.md"):
// 200 with no bytes at all: the emptied commit.
case strings.Contains(r.URL.Path, "indented.md"):
_, _ = w.Write([]byte(" \n\t\n"))
default:
_, _ = w.Write([]byte("# still here"))
}
return
}
http.NotFound(w, r)
}
}))
defer server.Close()
cfg := &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token"},
Settings: map[string]interface{}{"projects": []interface{}{
map[string]interface{}{"project_id": "1", "paths": []interface{}{}},
}},
}
connector := NewConnector()
var items []types.FetchedItem
var err error
switch mode {
case "full":
items, err = connector.FetchAll(context.Background(), cfg, nil)
case "incremental":
items, _, err = connector.FetchIncremental(
context.Background(), cfg, gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}}))
default:
handler := &gitLabStreamRecorder{}
_, err = connector.FetchStream(
context.Background(), cfg,
gitLabCursor(cursor{Projects: map[string]string{"1": "previous"}}), handler)
items = handler.items
}
require.NoError(t, err)
require.Len(t, items, 3)
byPath := make(map[string]types.FetchedItem, len(items))
for _, item := range items {
byPath[item.Metadata["gitlab_path"]] = item
}
emptied := byPath["runbook.md"]
require.False(t, emptied.IsDeleted)
require.Equal(t,
"# group/docs/runbook.md\n",
string(emptied.Content),
"an emptied file must still reach ingestion, or its stale body stays searchable")
require.Equal(t, "group/docs/runbook.md", emptied.Title)
// Whitespace is content: it must not be mistaken for an emptied file.
require.Equal(t, " \n\t\n", string(byPath["indented.md"].Content))
require.Equal(t, "# still here", string(byPath["kept.md"].Content))
})
}
}
@@ -0,0 +1,146 @@
package gitlab
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/stretchr/testify/require"
)
// guardTestTimeout bounds every walk here so that a missing guard fails the
// test instead of hanging it.
const guardTestTimeout = 5 * time.Second
// repeatedPageServer always advertises the same X-Next-Page value and refuses
// to serve more than three requests: a walk without a repeated-page guard then
// fails quickly with an unexpected error instead of spinning until the context
// deadline.
func repeatedPageServer(t *testing.T) (*httptest.Server, *int64) {
t.Helper()
allowLocalGitLabServer(t)
var requests int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if atomic.AddInt64(&requests, 1) > 3 {
http.Error(w, "pagination guard missing: too many requests", http.StatusTooManyRequests)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Next-Page", "2")
if strings.HasSuffix(r.URL.Path, "/repository/tree") {
_, _ = w.Write([]byte(`[{"name":"one.md","type":"blob","path":"one.md"}]`))
return
}
_, _ = w.Write([]byte(`[{"id":1,"path_with_namespace":"group/project-001"}]`))
}))
t.Cleanup(server.Close)
return server, &requests
}
func TestProjectsStopsOnRepeatedNextPage(t *testing.T) {
server, requests := repeatedPageServer(t)
c, err := newClient(server.URL, "test-token")
require.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), guardTestTimeout)
defer cancel()
projects, err := c.projects(ctx)
require.Error(t, err, "a repeated X-Next-Page must not be treated as the end of the list")
require.Nil(t, projects)
require.Contains(t, err.Error(), `gitlab project pagination repeated page "2"`)
require.LessOrEqual(t, atomic.LoadInt64(requests), int64(3), "must stop before re-reading the repeated page")
}
func TestTreeStopsOnRepeatedNextPage(t *testing.T) {
server, requests := repeatedPageServer(t)
c, err := newClient(server.URL, "test-token")
require.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), guardTestTimeout)
defer cancel()
entries, err := c.tree(ctx, "1", "main", "")
require.Error(t, err, "a repeated X-Next-Page must not be treated as the end of the list")
require.Nil(t, entries)
require.Contains(t, err.Error(), `gitlab tree pagination repeated page "2"`)
require.LessOrEqual(t, atomic.LoadInt64(requests), int64(3), "must stop before re-reading the repeated page")
}
// TestPaginationHopCapStopsWalk drives each walk with a server that always
// advertises a fresh page number, so only the hop cap can end it.
func TestPaginationHopCapStopsWalk(t *testing.T) {
for _, tc := range []struct {
name string
want string
walk func(context.Context, *client) error
}{
{
name: "projects",
want: "gitlab project pagination exceeded 10000 pages",
walk: func(ctx context.Context, c *client) error {
_, err := c.projects(ctx)
return err
},
},
{
name: "tree",
want: "gitlab tree pagination exceeded 10000 pages",
walk: func(ctx context.Context, c *client) error {
_, err := c.tree(ctx, "1", "main", "")
return err
},
},
} {
t.Run(tc.name, func(t *testing.T) {
allowLocalGitLabServer(t)
var requests int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := atomic.AddInt64(&requests, 1)
if n > maxPaginationHops+10 {
http.Error(w, "hop cap missing: too many requests", http.StatusTooManyRequests)
return
}
page, convErr := strconv.Atoi(r.URL.Query().Get("page"))
if convErr != nil {
http.Error(w, "unexpected page", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Next-Page", strconv.Itoa(page+1))
_, _ = w.Write([]byte(`[]`))
}))
t.Cleanup(server.Close)
c, err := newClient(server.URL, "test-token")
require.NoError(t, err)
var logs bytes.Buffer
logger.SetOutput(&logs)
t.Cleanup(logger.ConfigureFromEnv)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err = tc.walk(ctx, c)
require.EqualError(t, err, tc.want)
require.Equal(t, int64(maxPaginationHops), atomic.LoadInt64(&requests))
require.Contains(t, logs.String(), "pagination exceeded 10000 pages",
"hitting the cap must leave a warning in the log")
})
}
}
func TestTrackPageAllowsForwardPages(t *testing.T) {
seen := make(map[string]struct{})
for _, page := range []string{"1", "2", "3"} {
require.NoError(t, trackPage(context.Background(), "project", seen, page))
}
require.Error(t, trackPage(context.Background(), "project", seen, "2"))
}
@@ -0,0 +1,148 @@
package gitlab
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func TestListResourcesIncludesProjectsAfterFirstPage(t *testing.T) {
const pageSize = 100
const projectCount = 2*pageSize + 1
server, requests := projectListServer(t, map[string]projectListPage{
"1": {body: projectListJSON(t, 1, pageSize), next: "2"},
"2": {body: projectListJSON(t, pageSize+1, pageSize), next: "3"},
"3": {body: projectListJSON(t, projectCount, 1)},
})
ds := &types.DataSourceConfig{
Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "test-token"},
Settings: map[string]interface{}{"projects": []interface{}{
map[string]interface{}{"project_id": "1"},
}},
}
resources, err := NewConnector().ListResources(context.Background(), ds, "")
require.NoError(t, err)
require.Equal(t, projectCount, len(resources), "every GitLab project must be available for selection")
for i, resource := range resources {
require.Equal(t, fmt.Sprint(i+1), resource.ExternalID)
require.Equal(t, fmt.Sprintf("group/project-%03d", i+1), resource.Name)
require.Equal(t, fmt.Sprintf("https://gitlab.example.com/group/project-%03d", i+1), resource.URL)
require.Equal(t, "project", resource.Type)
require.True(t, resource.HasChildren)
}
require.Equal(t, []string{"1", "2", "3"}, recordedProjectPages(requests))
}
func TestProjectsStopsAtFinalPage(t *testing.T) {
const pageSize = 100
for _, count := range []int{0, pageSize} {
t.Run(fmt.Sprintf("%d projects", count), func(t *testing.T) {
server, requests := projectListServer(t, map[string]projectListPage{
"1": {body: projectListJSON(t, 1, count)},
})
c, err := newClient(server.URL, "test-token")
require.NoError(t, err)
projects, err := c.projects(context.Background())
require.NoError(t, err)
require.Len(t, projects, count)
require.Equal(t, []string{"1"}, recordedProjectPages(requests))
})
}
}
func TestProjectsRejectsIncompleteList(t *testing.T) {
for _, tc := range []struct {
name string
page projectListPage
}{
{name: "HTTP error", page: projectListPage{status: http.StatusServiceUnavailable}},
{name: "malformed JSON", page: projectListPage{body: "not JSON"}},
} {
t.Run(tc.name, func(t *testing.T) {
server, requests := projectListServer(t, map[string]projectListPage{
"1": {body: projectListJSON(t, 1, 1), next: "2"},
"2": tc.page,
})
c, err := newClient(server.URL, "test-token")
require.NoError(t, err)
projects, err := c.projects(context.Background())
require.Error(t, err)
require.Nil(t, projects, "do not return a partial list as a successful result")
require.Equal(t, []string{"1", "2"}, recordedProjectPages(requests))
})
}
}
type projectListPage struct {
body string
next string
status int
}
func projectListServer(t *testing.T, pages map[string]projectListPage) (*httptest.Server, <-chan string) {
t.Helper()
allowLocalGitLabServer(t)
requests := make(chan string, len(pages)+1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
if r.Method != http.MethodGet || r.URL.Path != "/api/v4/projects" ||
r.Header.Get("PRIVATE-TOKEN") != "test-token" || query.Get("membership") != "true" ||
query.Get("per_page") != "100" || query.Get("order_by") != "path_with_namespace" ||
query.Get("sort") != "asc" {
http.Error(w, "unexpected project-list request", http.StatusBadRequest)
return
}
page := query.Get("page")
if page == "" {
page = "1" // GitLab defaults to its first page when the parameter is omitted.
}
response, ok := pages[page]
if !ok {
http.Error(w, "unexpected page", http.StatusBadRequest)
return
}
select {
case requests <- page:
default:
http.Error(w, "too many page requests", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Next-Page", response.next)
if response.status != 0 {
w.WriteHeader(response.status)
}
_, _ = fmt.Fprint(w, response.body)
}))
t.Cleanup(server.Close)
return server, requests
}
func projectListJSON(t *testing.T, start, count int) string {
t.Helper()
projects := make([]project, 0, count)
for id := start; id < start+count; id++ {
projects = append(projects, project{
ID: int64(id), PathWithNamespace: fmt.Sprintf("group/project-%03d", id),
WebURL: fmt.Sprintf("https://gitlab.example.com/group/project-%03d", id),
})
}
data, err := json.Marshal(projects)
require.NoError(t, err)
return string(data)
}
func recordedProjectPages(requests <-chan string) []string {
var pages []string
for len(requests) > 0 {
pages = append(pages, <-requests)
}
return pages
}
@@ -0,0 +1,108 @@
package gitlab
import (
"fmt"
"path"
"sort"
"strings"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/types"
)
type projectSelection struct {
ProjectID string `json:"project_id"`
Ref string `json:"ref"`
Paths []string `json:"paths"`
}
type config struct {
Projects []projectSelection `json:"projects"`
}
func parseConfig(ds *types.DataSourceConfig) (*config, error) {
if ds == nil {
return nil, datasource.ErrInvalidConfig
}
raw, ok := ds.Settings["projects"]
if !ok {
return nil, fmt.Errorf("%w: settings.projects is required", datasource.ErrInvalidConfig)
}
items, ok := raw.([]interface{})
if !ok {
return nil, fmt.Errorf("%w: settings.projects must be an array", datasource.ErrInvalidConfig)
}
out := &config{Projects: make([]projectSelection, 0, len(items))}
seen := map[string]bool{}
for _, rawProject := range items {
m, ok := rawProject.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("%w: invalid project selection", datasource.ErrInvalidConfig)
}
id, _ := m["project_id"].(string)
id = strings.TrimSpace(id)
if id == "" || seen[id] {
return nil, fmt.Errorf("%w: project_id must be unique and non-empty", datasource.ErrInvalidConfig)
}
seen[id] = true
ref, _ := m["ref"].(string)
p := projectSelection{ProjectID: id, Ref: strings.TrimSpace(ref)}
if rawPaths, exists := m["paths"]; exists {
values, ok := rawPaths.([]interface{})
if !ok {
return nil, fmt.Errorf("%w: paths must be an array", datasource.ErrInvalidConfig)
}
for _, value := range values {
s, ok := value.(string)
if !ok {
return nil, fmt.Errorf("%w: path must be a string", datasource.ErrInvalidConfig)
}
normalized, err := normalizePath(s)
if err != nil {
return nil, err
}
p.Paths = append(p.Paths, normalized)
}
}
p.Paths = collapsePaths(p.Paths)
out.Projects = append(out.Projects, p)
}
if len(out.Projects) == 0 {
return nil, fmt.Errorf("%w: at least one project is required", datasource.ErrInvalidConfig)
}
return out, nil
}
func normalizePath(value string) (string, error) {
v := strings.Trim(strings.TrimSpace(value), "/")
if v == "" {
return "", nil
}
if strings.Contains(v, "\\") {
return "", fmt.Errorf("%w: path must use forward slashes", datasource.ErrInvalidConfig)
}
if path.Clean(v) != v || v == "." || strings.HasPrefix(v, "../") || strings.Contains(v, "/../") {
return "", fmt.Errorf("%w: invalid repository path", datasource.ErrInvalidConfig)
}
return v, nil
}
func collapsePaths(paths []string) []string {
if len(paths) == 0 {
return nil
}
sort.Strings(paths)
for _, p := range paths {
if p == "" {
return nil
}
}
out := make([]string, 0, len(paths))
for _, p := range paths {
if len(out) > 0 && (p == out[len(out)-1] || strings.HasPrefix(p, out[len(out)-1]+"/")) {
continue
}
out = append(out, p)
}
return out
}
@@ -0,0 +1,47 @@
package gitlab
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestParseConfigCollapsesDirectories(t *testing.T) {
cfg, err := parseConfig(&types.DataSourceConfig{Settings: map[string]interface{}{
"projects": []interface{}{map[string]interface{}{
"project_id": "team/docs", "ref": "main",
"paths": []interface{}{"docs/guide", "docs", "docs"},
}},
}})
if err != nil {
t.Fatal(err)
}
if len(cfg.Projects) != 1 || len(cfg.Projects[0].Paths) != 1 || cfg.Projects[0].Paths[0] != "docs" {
t.Fatalf("unexpected config: %#v", cfg)
}
}
func TestParseConfigRootMeansWholeProject(t *testing.T) {
cfg, err := parseConfig(&types.DataSourceConfig{Settings: map[string]interface{}{
"projects": []interface{}{map[string]interface{}{"project_id": "42", "paths": []interface{}{"/"}}},
}})
if err != nil {
t.Fatal(err)
}
if len(cfg.Projects[0].Paths) != 0 {
t.Fatalf("root path must collapse to whole project: %#v", cfg.Projects[0].Paths)
}
}
func TestNormalizePathRejectsTraversal(t *testing.T) {
if _, err := normalizePath("docs/../secrets"); err == nil {
t.Fatal("expected traversal rejection")
}
}
func TestKnowledgeRelativePathPreservesRepositoryTreeBelowProjectAndBranch(t *testing.T) {
got := knowledgeRelativePath("knowledge", "feature/login", "docs/guide/install.md")
if got != "knowledge-feature-login/docs/guide/install.md" {
t.Fatalf("knowledge relative path = %q", got)
}
}
+442
View File
@@ -0,0 +1,442 @@
// Package ima implements the WeKnora data source connector for Tencent IMA
// (ima.qq.com), syncing documents and files out of IMA knowledge bases via the
// /openapi/wiki/v1 OpenAPI.
package ima
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sync"
"time"
"unicode/utf8"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/utils"
)
const (
defaultTimeout = 60 * time.Second
defaultPageSize = 50
userAgent = "WeKnora-IMA-Connector/1.0"
// IMA hard limit: get_knowledge_list max limit=50; search_knowledge_base max=20.
searchPageSize = 20
// Default per-item download timeout — IMA COS URLs can be slow for large PDFs.
downloadTimeout = 120 * time.Second
// Max body we accept from get_media_info-URLs. 200MB matches IMA's largest
maxDownloadBytes = 200 * 1024 * 1024
// maxJSONResponseBytes bounds every API response body. Listings and document
// payloads are small; a larger body means a broken or hostile server.
maxJSONResponseBytes = 16 << 20
)
// client wraps the IMA OpenAPI. It is safe for concurrent use.
type client struct {
baseURL string
clientID string
apiKey string
httpClient *http.Client
// jsonLimit caps each API response body; a field so tests can lower it
// without materialising the production limit.
jsonLimit int64
// downloadClient is a separate client with a longer timeout for pulling
// media bodies from COS/CDN URLs returned by get_media_info.
downloadClient *http.Client
logCredentialOnce sync.Once
}
// newClient constructs a client with a normalized base URL.
func newClient(cfg *Config) *client {
return &client{
baseURL: cfg.GetBaseURL(),
clientID: cfg.ClientID,
apiKey: cfg.APIKey,
httpClient: datasource.NewConnectorHTTPClient(defaultTimeout),
downloadClient: datasource.NewConnectorHTTPClient(downloadTimeout),
jsonLimit: maxJSONResponseBytes,
}
}
// errResponseTooLarge marks a body over the cap. It is deterministic: the same
// request returns the same oversized body, so callers must not retry it.
var errResponseTooLarge = errors.New("response exceeds maximum size")
// readCapped reads a response body, refusing anything larger than limit instead
// of buffering it. Oversized payloads are reported as an error: a truncated
// body would be indexed as if it were the whole document. A non-positive limit
// (e.g. a zero-value client built in tests) falls back to maxJSONResponseBytes.
func readCapped(body io.Reader, limit int64) ([]byte, error) {
if limit <= 0 {
limit = maxJSONResponseBytes
}
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 (%d bytes)", errResponseTooLarge, limit)
}
return data, nil
}
// callAPI executes an authenticated POST to /openapi/wiki/v1/<action>.
func (c *client) callAPI(ctx context.Context, action string, req interface{}, result interface{}) error {
return c.callAPIAt(ctx, apiBasePath, action, req, result)
}
// callAPIAt executes an authenticated POST to <basePath>/<action>. It parses
// the standard {code, msg, data} envelope and unmarshals `data` into `result`.
// A non-zero business code is returned as a plain error so the caller can
// surface `msg` to the user.
//
// basePath is a parameter because notes live under a second namespace
// (/openapi/note/v1) that shares this authentication and envelope.
func (c *client) callAPIAt(
ctx context.Context, basePath, action string, req interface{}, result interface{},
) error {
const (
maxRetries = 3
max5xxRetries = 1
retry5xxDelay = 2 * time.Second
)
backoff := []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second}
c.logCredentialOnce.Do(func() {
logger.Infof(ctx, "[IMA] client configured client_id=%s api_key=%s base=%s",
redact(c.clientID), redact(c.apiKey), c.baseURL)
})
var body []byte
if req != nil {
b, err := json.Marshal(req)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
body = b
} else {
body = []byte("{}")
}
url := c.baseURL + basePath + "/" + action
// Both namespaces expose distinct actions, but log the full path so the two
// are never ambiguous.
label := basePath + "/" + action
var lastErr error
for attempt := 0; attempt <= maxRetries; attempt++ {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("ima-openapi-clientid", c.clientID)
httpReq.Header.Set("ima-openapi-apikey", c.apiKey)
httpReq.Header.Set("Content-Type", "application/json; charset=utf-8")
httpReq.Header.Set("User-Agent", userAgent)
if attempt == 0 {
logger.Infof(ctx, "[IMA] POST %s", label)
} else {
logger.Infof(ctx, "[IMA] POST %s (retry %d/%d)", label, attempt, maxRetries)
}
resp, err := c.httpClient.Do(httpReq)
if err != nil {
lastErr = fmt.Errorf("execute request: %w", err)
if attempt < maxRetries {
if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {
return sErr
}
continue
}
return lastErr
}
respBody, readErr := readCapped(resp.Body, c.jsonLimit)
_ = resp.Body.Close()
if readErr != nil {
lastErr = fmt.Errorf("read response: %w", readErr)
if attempt < maxRetries && !errors.Is(readErr, errResponseTooLarge) {
if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {
return sErr
}
continue
}
return lastErr
}
// The body is only ever logged on an error path: successful responses
// (get_media_info in particular) carry pre-signed storage URLs and
// per-request auth headers that must not land in the server log.
bodyPreview := truncate(string(respBody), 500)
logger.Infof(ctx, "[IMA] POST %s → status=%d bodyLen=%d", label, resp.StatusCode, len(respBody))
// HTTP-level auth failures: surface as ErrInvalidCredentials.
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
return fmt.Errorf("%w: status=%d body=%s",
datasource.ErrInvalidCredentials, resp.StatusCode, bodyPreview)
}
if resp.StatusCode == http.StatusTooManyRequests {
wait := backoff[minInt(attempt, len(backoff)-1)]
lastErr = fmt.Errorf("ima rate limited: status=429 body=%s", bodyPreview)
if attempt < maxRetries {
if sErr := sleepCtx(ctx, wait); sErr != nil {
return sErr
}
continue
}
return lastErr
}
if resp.StatusCode >= 500 && resp.StatusCode < 600 {
lastErr = fmt.Errorf("ima server error: status=%d body=%s", resp.StatusCode, bodyPreview)
if attempt < max5xxRetries {
if sErr := sleepCtx(ctx, retry5xxDelay); sErr != nil {
return sErr
}
continue
}
return lastErr
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("ima api http error: status=%d body=%s", resp.StatusCode, bodyPreview)
}
var env apiEnvelope
if err := json.Unmarshal(respBody, &env); err != nil {
return fmt.Errorf("decode envelope: %w", err)
}
// Business-level errors.
// 110030 (无权限) is mapped to ErrInvalidCredentials so the service marks
// the source in `error` state and stops scheduling until re-authenticated.
// 110021 (限频) is retried. Everything else — including 110001 (参数非法),
// which is a bug on our side rather than a credential problem — surfaces
// verbatim so the user sees IMA's own message.
if code := env.statusCode(); code != 0 {
if code == 110030 {
return fmt.Errorf("%w: ima code=%d msg=%s",
datasource.ErrInvalidCredentials, code, env.message())
}
if code == 110021 && attempt < maxRetries {
lastErr = fmt.Errorf("ima rate limited: code=%d msg=%s", code, env.message())
if sErr := sleepCtx(ctx, backoff[minInt(attempt, len(backoff)-1)]); sErr != nil {
return sErr
}
continue
}
return fmt.Errorf("ima api error: code=%d msg=%s", code, env.message())
}
if result != nil && len(env.Data) > 0 && string(env.Data) != "null" {
if err := json.Unmarshal(env.Data, result); err != nil {
return fmt.Errorf("decode data: %w", err)
}
}
return nil
}
return lastErr
}
// SearchKnowledgeBase — POST /search_knowledge_base. Empty query returns the
// list of every knowledge base visible to the current token (see api.md §7).
func (c *client) SearchKnowledgeBase(
ctx context.Context, query, cursor string, limit int,
) (*searchKnowledgeBaseResp, error) {
if limit <= 0 || limit > searchPageSize {
limit = searchPageSize
}
req := map[string]interface{}{
"query": query,
"cursor": cursor,
"limit": uint64(limit),
}
var resp searchKnowledgeBaseResp
if err := c.callAPI(ctx, "search_knowledge_base", req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// GetKnowledgeBase — POST /get_knowledge_base for a batch of ids (1-20).
func (c *client) GetKnowledgeBase(ctx context.Context, ids []string) (map[string]knowledgeBaseInfo, error) {
if len(ids) == 0 {
return map[string]knowledgeBaseInfo{}, nil
}
req := map[string]interface{}{"ids": ids}
var resp getKnowledgeBaseResp
if err := c.callAPI(ctx, "get_knowledge_base", req, &resp); err != nil {
return nil, err
}
if resp.Infos == nil {
resp.Infos = map[string]knowledgeBaseInfo{}
}
return resp.Infos, nil
}
// GetAddableKnowledgeBaseList — POST /get_addable_knowledge_base_list.
// Lists knowledge bases the current token has permission to add content to.
// This is the authoritative "what KBs can this credential see?" endpoint
// (see api.md §7). Used as the primary enumeration source in ListResources —
// search_knowledge_base with empty query has been observed to return an empty
// list even when the token owns KBs, so we prefer this endpoint.
func (c *client) GetAddableKnowledgeBaseList(
ctx context.Context, cursor string, limit int,
) (*getAddableKnowledgeBaseListResp, error) {
if limit <= 0 || limit > defaultPageSize {
limit = defaultPageSize
}
req := map[string]interface{}{
"cursor": cursor,
"limit": uint64(limit),
}
var resp getAddableKnowledgeBaseListResp
if err := c.callAPI(ctx, "get_addable_knowledge_base_list", req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// GetKnowledgeList — POST /get_knowledge_list. folderID may be empty for root.
func (c *client) GetKnowledgeList(
ctx context.Context, kbID, folderID, cursor string, limit int,
) (*getKnowledgeListResp, error) {
if limit <= 0 || limit > defaultPageSize {
limit = defaultPageSize
}
req := map[string]interface{}{
"cursor": cursor,
"limit": uint64(limit),
"knowledge_base_id": kbID,
}
if folderID != "" {
req["folder_id"] = folderID
}
var resp getKnowledgeListResp
if err := c.callAPI(ctx, "get_knowledge_list", req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// GetMediaInfo — POST /get_media_info. Returns URL access info and (for notes)
// the notebook_id under notebook_ext_info.
func (c *client) GetMediaInfo(ctx context.Context, mediaID string) (*getMediaInfoResp, error) {
req := map[string]interface{}{"media_id": mediaID}
var resp getMediaInfoResp
if err := c.callAPI(ctx, "get_media_info", req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// GetNoteContent — POST /openapi/note/v1/get_doc_content. Returns an IMA note's
// body as plain text (target_content_format=0).
//
// noteID is the notebook_id that get_media_info reports for a note: the wiki
// namespace never exposes note bodies, it only points at them.
func (c *client) GetNoteContent(ctx context.Context, noteID string) (string, error) {
req := map[string]interface{}{
"note_id": noteID,
"target_content_format": 0,
}
var resp getDocContentResp
if err := c.callAPIAt(ctx, noteBasePath, "get_doc_content", req, &resp); err != nil {
return "", err
}
return resp.Content, nil
}
// DownloadURL fetches a URL returned by GetMediaInfo, respecting the auth
// headers IMA may return alongside it. Enforces maxDownloadBytes to avoid a
// runaway body blowing up sync memory.
func (c *client) DownloadURL(ctx context.Context, u urlInfo) ([]byte, string, error) {
if u.URL == "" {
return nil, "", fmt.Errorf("empty url")
}
// The URL comes from an API response, so it is attacker-influenced as far
// as this process is concerned. downloadClient already guards the dial and
// every redirect hop; this rejects an unsafe target before the first
// connection is even attempted.
if err := utils.ValidateURLForSSRF(u.URL); err != nil {
return nil, "", fmt.Errorf("media URL rejected: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.URL, nil)
if err != nil {
return nil, "", fmt.Errorf("create download request: %w", err)
}
for k, v := range u.Headers {
req.Header.Set(k, v)
}
req.Header.Set("User-Agent", userAgent)
resp, err := c.downloadClient.Do(req)
if err != nil {
return nil, "", fmt.Errorf("download: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, "", fmt.Errorf("download http error: status=%d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxDownloadBytes+1))
if err != nil {
return nil, "", fmt.Errorf("read download body: %w", err)
}
if int64(len(body)) > maxDownloadBytes {
return nil, "", fmt.Errorf("download body exceeds %d bytes", maxDownloadBytes)
}
return body, resp.Header.Get("Content-Type"), nil
}
// sleepCtx pauses for d, returning early if ctx is cancelled.
func sleepCtx(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func truncate(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
// Back off to a rune boundary: a partial multi-byte rune is invalid UTF-8,
// and this preview reaches sync_logs / data_sources through the sync error
// message, which PostgreSQL rejects. Same rule as #4555.
cut := maxLen
for cut > 0 && !utf8.RuneStart(s[cut]) {
cut--
}
return s[:cut] + "..."
}
// redact returns a masked form of a credential for logging (never log full).
func redact(t string) string {
if len(t) < 12 {
return "***"
}
return t[:6] + "..." + t[len(t)-4:]
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
@@ -0,0 +1,33 @@
package ima
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
func TestCallAPI_RejectsOversizedResponse(t *testing.T) {
var hits atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
hits.Add(1)
_, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))
}))
defer server.Close()
c := newClient(&Config{ClientID: "cid", APIKey: "cak", BaseURL: server.URL})
c.jsonLimit = 1 << 20
err := c.callAPI(context.Background(), "get_knowledge_list", map[string]any{}, &map[string]any{})
if err == nil {
t.Fatal("callAPI accepted a response larger than the cap, want error")
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
if got := hits.Load(); got != 1 {
t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)
}
}
@@ -0,0 +1,617 @@
package ima
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// Compile-time proof that *Connector satisfies the datasource.Connector interface.
var _ datasource.Connector = (*Connector)(nil)
// Connector implements datasource.Connector for Tencent IMA (ima.qq.com).
type Connector struct{}
// NewConnector creates a new IMA connector.
func NewConnector() *Connector { return &Connector{} }
// Type returns the connector type identifier.
func (c *Connector) Type() string { return types.ConnectorTypeIMA }
// Validate verifies the credentials by calling get_addable_knowledge_base_list
// — the endpoint most likely to succeed even when the token has zero KBs, and
// the same one ListResources uses. It returns 110030 (无权限) when the token
// itself is invalid, which client.callAPI already maps to ErrInvalidCredentials.
func (c *Connector) Validate(ctx context.Context, config *types.DataSourceConfig) error {
cfg, err := parseIMAConfig(config)
if err != nil {
return err
}
cli := newClient(cfg)
if _, err := cli.GetAddableKnowledgeBaseList(ctx, "", defaultPageSize); err != nil {
return fmt.Errorf("ima connection failed: %w", err)
}
return nil
}
// ResolveResourceAncestors returns nothing: IMA knowledge bases are exposed as
// a flat list of top-level resources, so a lazy-loaded picker has no ancestors
// to reveal.
func (c *Connector) ResolveResourceAncestors(
_ context.Context, _ *types.DataSourceConfig, _ []string,
) ([]string, error) {
return []string{}, nil
}
// maxPaginationHops bounds every cursor-paginated loop in this file. A vendor
// that keeps handing back a fresh cursor would otherwise keep the connector
// (and the sync task holding it) spinning until the task deadline; the value
// mirrors the guard Confluence and DingTalk already carry.
const maxPaginationHops = 10000
// nextPageCursor validates the progress of a cursor-paginated loop after page
// `page` (1-based) has been fetched: a cursor handed back twice means the
// vendor is repeating a page, and page >= maxPaginationHops means the listing
// is unbounded. Both are reported instead of being retried forever, and the
// hop cap is also logged because it is the one failure that looks like a
// healthy, still-running sync from the outside.
func nextPageCursor(
ctx context.Context, seen map[string]struct{}, cursor string, page int,
) (string, error) {
if page >= maxPaginationHops {
logger.Warnf(ctx, "[IMA] pagination exceeded %d pages; aborting", maxPaginationHops)
return "", fmt.Errorf("pagination exceeded %d pages", maxPaginationHops)
}
if _, exists := seen[cursor]; exists {
return "", fmt.Errorf("pagination repeated next_cursor %q", cursor)
}
seen[cursor] = struct{}{}
return cursor, nil
}
// ListResources returns the flat list of knowledge bases the token can read.
// parentID is honoured only for the "no children" contract — see the note on
// Connector.ListResources in internal/datasource/connector.go.
//
// Primary source is get_addable_knowledge_base_list, which returns the KBs the
// current OpenAPI credential has permission to operate on. When that endpoint
// returns an empty list (e.g. a legacy tenant only exposes read scopes) we
// fall back to search_knowledge_base with an empty query so users still see
// something to pick.
func (c *Connector) ListResources(
ctx context.Context, config *types.DataSourceConfig, parentID string,
) ([]types.Resource, error) {
if parentID != "" {
return []types.Resource{}, nil
}
cfg, err := parseIMAConfig(config)
if err != nil {
return nil, err
}
cli := newClient(cfg)
type kbLite struct {
ID string
Name string
CoverURL string
}
var bases []kbLite
cursor := ""
seenCursors := make(map[string]struct{})
for page := 1; ; page++ {
resp, err := cli.GetAddableKnowledgeBaseList(ctx, cursor, defaultPageSize)
if err != nil {
return nil, fmt.Errorf("get_addable_knowledge_base_list: %w", err)
}
for _, b := range resp.AddableKnowledgeBaseList {
bases = append(bases, kbLite{ID: b.ID, Name: b.Name})
}
if resp.IsEnd || resp.NextCursor == "" {
break
}
next, err := nextPageCursor(ctx, seenCursors, resp.NextCursor, page)
if err != nil {
return nil, fmt.Errorf("get_addable_knowledge_base_list: %w", err)
}
cursor = next
}
logger.Infof(ctx, "[IMA] get_addable_knowledge_base_list returned %d knowledge bases", len(bases))
if len(bases) == 0 {
cursor = ""
seenCursors = make(map[string]struct{})
for page := 1; ; page++ {
resp, err := cli.SearchKnowledgeBase(ctx, "", cursor, searchPageSize)
if err != nil {
return nil, fmt.Errorf("search_knowledge_base fallback: %w", err)
}
for _, b := range resp.InfoList {
bases = append(bases, kbLite(b))
}
if resp.IsEnd || resp.NextCursor == "" {
break
}
next, err := nextPageCursor(ctx, seenCursors, resp.NextCursor, page)
if err != nil {
return nil, fmt.Errorf("search_knowledge_base fallback: %w", err)
}
cursor = next
}
logger.Infof(ctx, "[IMA] search_knowledge_base fallback returned %d knowledge bases", len(bases))
}
ids := make([]string, 0, len(bases))
for _, b := range bases {
ids = append(ids, b.ID)
}
details := map[string]knowledgeBaseInfo{}
for i := 0; i < len(ids); i += 20 {
end := i + 20
if end > len(ids) {
end = len(ids)
}
batch, err := cli.GetKnowledgeBase(ctx, ids[i:end])
if err != nil {
logger.Warnf(ctx, "[IMA] get_knowledge_base batch failed (skipping enrichment): %v", err)
continue
}
for k, v := range batch {
details[k] = v
}
}
out := make([]types.Resource, 0, len(bases))
for _, b := range bases {
desc := ""
coverURL := b.CoverURL
if d, ok := details[b.ID]; ok {
desc = d.Description
if coverURL == "" {
coverURL = d.CoverURL
}
}
out = append(out, types.Resource{
ExternalID: b.ID,
Name: b.Name,
Type: "knowledge_base",
Description: desc,
URL: cfg.GetBaseURL(),
Metadata: map[string]interface{}{
"cover_url": coverURL,
},
})
}
sort.Slice(out, func(i, j int) bool { return out[i].ExternalID < out[j].ExternalID })
logger.Infof(ctx, "[IMA] ListResources returning %d knowledge bases to UI", len(out))
return out, nil
}
// FetchAll performs a full sync of every knowledge base in resourceIDs.
func (c *Connector) FetchAll(
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
) ([]types.FetchedItem, error) {
items, _, err := c.walk(ctx, config, resourceIDs, nil, false)
return items, err
}
// FetchIncremental syncs new / replaced / removed items against the cursor.
//
// Each IMA item is identified by a stable logical_key (see logicalKey), NOT by
// media_id — because IMA reassigns media_id whenever a same-named file is
// replaced in place, and we want that replacement to surface as an UPDATE to
// the same knowledge item rather than a delete-plus-insert pair.
//
// Emitted this cycle:
//
// - logical_key new since last sync → add (new content)
// - logical_key present, media_id changed → update (re-fetched content;
// ingest layer's existing
// external_id match triggers
// delete-and-recreate)
// - logical_key unchanged, media_id unchanged → skip
// - logical_key present last sync, absent this sync → IsDeleted tombstone
//
// LIMITATION: IMA still exposes no per-item updated_at, so an in-place edit
// that keeps the SAME media_id (same file bytes replaced under the hood by
// IMA, if that ever happens) is invisible to us. Users needing a full content
// refresh should periodically run a Full sync.
func (c *Connector) FetchIncremental(
ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor,
) ([]types.FetchedItem, *types.SyncCursor, error) {
resourceIDs := config.ResourceIDs
if len(resourceIDs) == 0 {
return nil, nil, fmt.Errorf("no resource IDs (knowledge base IDs) configured")
}
var prev *imaCursor
if cursor != nil && cursor.ConnectorCursor != nil {
var p imaCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &p)
prev = &p
}
items, newCursor, err := c.walk(ctx, config, resourceIDs, prev, true)
if err != nil {
return nil, nil, err
}
cursorMap := make(map[string]interface{})
b, _ := json.Marshal(newCursor)
_ = json.Unmarshal(b, &cursorMap)
return items, &types.SyncCursor{
LastSyncTime: newCursor.LastSyncTime,
ConnectorCursor: cursorMap,
}, nil
}
// walk is the shared implementation for FetchAll / FetchIncremental.
// When incremental is false, prev is ignored and returned cursor is nil.
func (c *Connector) walk(
ctx context.Context,
config *types.DataSourceConfig,
resourceIDs []string,
prev *imaCursor,
incremental bool,
) ([]types.FetchedItem, *imaCursor, error) {
cfg, err := parseIMAConfig(config)
if err != nil {
return nil, nil, err
}
cli := newClient(cfg)
newCursor := &imaCursor{
LastSyncTime: time.Now(),
KBLogical: make(map[string]map[string]string),
}
var out []types.FetchedItem
for _, kbID := range resourceIDs {
files, folderPath, err := listAllKBFiles(ctx, cli, kbID)
if err != nil {
return nil, nil, fmt.Errorf("list KB %s: %w", kbID, err)
}
// present holds every logical_key IMA listed this cycle; it drives
// delete detection. syncedLogical holds only the keys we actually
// resolved this cycle and is what gets persisted as the cursor, so a
// transient failure is retried next run rather than being remembered
// as "unchanged" forever.
present := make(map[string]struct{}, len(files))
syncedLogical := make(map[string]string, len(files))
keys := make([]string, len(files))
for i, f := range files {
key := logicalKey(kbID, f.ParentFolderID, f.Title)
keys[i] = key
present[key] = struct{}{}
}
newCursor.KBLogical[kbID] = syncedLogical
var replaced, failed int
for i, f := range files {
key := keys[i]
// Incremental skip / replacement detection.
if incremental && prev != nil && prev.KBLogical != nil {
if prevSet, ok := prev.KBLogical[kbID]; ok {
if prevMediaID, seen := prevSet[key]; seen {
if prevMediaID == f.MediaID {
// Unchanged: carry the entry forward so it is not
// re-fetched next cycle either.
syncedLogical[key] = f.MediaID
continue
}
replaced++ // media_id changed → replacement, fall through to re-fetch
}
}
}
item, outcome := fetchOneMedia(ctx, cli, kbID, key, f, folderPath)
switch outcome {
case fetchOK:
syncedLogical[key] = f.MediaID
out = append(out, item)
case fetchSkipped:
// Deterministic skip (unsupported media type, no URL): record it
// so we do not pay for get_media_info on every future sync.
syncedLogical[key] = f.MediaID
case fetchFailed:
// Transient: leave the key out of the cursor so the next run
// retries. `present` still contains it, so it is not mistaken
// for a deletion.
failed++
}
}
// Deletion detection (incremental only) — based on logical_key vanishing
// from the listing, so neither a same-name replacement (media_id churns
// but logical_key stays) nor a failed download fires a spurious delete.
deleted := 0
if incremental && prev != nil && prev.KBLogical != nil {
if prevSet, ok := prev.KBLogical[kbID]; ok {
for prevKey := range prevSet {
if _, still := present[prevKey]; !still {
out = append(out, types.FetchedItem{
ExternalID: prevKey,
IsDeleted: true,
SourceResourceID: kbID,
})
deleted++
}
}
}
}
logger.Infof(ctx, "[IMA] KB %s: total=%d replaced=%d failed=%d deleted=%d",
kbID, len(files), replaced, failed, deleted)
}
if !incremental {
return out, nil, nil
}
return out, newCursor, nil
}
// walkedFile is an internal representation of a knowledge item after we've
// resolved its folder location within the KB tree.
type walkedFile struct {
knowledgeInfo
// FolderPath is the "/A/B" style path (folder names, no leading slash)
// of the containing folder — empty for root-level items.
FolderPath string
}
// listAllKBFiles recursively enumerates a knowledge base into a flat list of
// files, resolving each item's folder path from the on-the-fly folder tree.
// folderPath maps folder_id → readable path (for metadata).
func listAllKBFiles(
ctx context.Context, cli *client, kbID string,
) ([]walkedFile, map[string]string, error) {
folderPath := map[string]string{}
var out []walkedFile
// BFS/DFS over folders. Start from root (empty folder_id).
type todo struct {
folderID string
path string
}
stack := []todo{{folderID: "", path: ""}}
for len(stack) > 0 {
cur := stack[len(stack)-1]
stack = stack[:len(stack)-1]
cursor := ""
seenCursors := make(map[string]struct{})
for page := 1; ; page++ {
resp, err := cli.GetKnowledgeList(ctx, kbID, cur.folderID, cursor, defaultPageSize)
if err != nil {
return nil, nil, err
}
for _, raw := range resp.KnowledgeList {
var ki knowledgeInfo
if err := json.Unmarshal(raw, &ki); err != nil || ki.MediaID == "" {
continue // unrecognized shape, skip defensively
}
if ki.MediaType == mediaTypeFolder {
// List entries identify folders by media_type. Their full
// media_id (including the folder_ prefix) is the recursion key.
child := cur.path
if child == "" {
child = ki.Title
} else {
child = cur.path + "/" + ki.Title
}
folderPath[ki.MediaID] = child
stack = append(stack, todo{folderID: ki.MediaID, path: child})
continue
}
out = append(out, walkedFile{
knowledgeInfo: ki,
FolderPath: cur.path,
})
}
if resp.IsEnd || resp.NextCursor == "" {
break
}
next, err := nextPageCursor(ctx, seenCursors, resp.NextCursor, page)
if err != nil {
return nil, nil, fmt.Errorf("get_knowledge_list: %w", err)
}
cursor = next
}
}
return out, folderPath, nil
}
// fetchNote resolves an IMA note (media_type=11). Notes carry no downloadable
// body: get_media_info only reports the notebook_id, and the text has to be
// read from the separate note namespace.
//
// The body arrives as plain text but is ingested as Markdown, because IMA notes
// are authored as rich text and the export keeps its heading and list markers —
// parsing it as Markdown preserves that structure for chunking, and text with
// no markers is unaffected.
func fetchNote(
ctx context.Context, cli *client,
kbID string, externalID string, f walkedFile, folderPath map[string]string,
info *getMediaInfoResp,
) (types.FetchedItem, fetchOutcome) {
noteID := info.NotebookExtInfo.NotebookID
if noteID == "" {
logger.Warnf(ctx, "[IMA] note %s (title=%q) has no notebook_id, skipping", f.MediaID, f.Title)
return types.FetchedItem{}, fetchSkipped
}
content, err := cli.GetNoteContent(ctx, noteID)
if err != nil {
logger.Warnf(ctx, "[IMA] get_doc_content(note %s, title=%q) failed, will retry next sync: %v",
noteID, f.Title, err)
return types.FetchedItem{}, fetchFailed
}
if strings.TrimSpace(content) == "" {
// A cleared note still exists. Keep its title as content so ingestion
// replaces the stale body instead of silently acknowledging the edit:
// skipping here would leave the old text indexed forever.
logger.Infof(ctx, "[IMA] note %s (title=%q) is empty, syncing its title only", noteID, f.Title)
content = "# " + f.Title + "\n"
}
fileName := datasource.SanitizeFileName(f.Title)
if !strings.HasSuffix(strings.ToLower(fileName), ".md") {
fileName += ".md"
}
return types.FetchedItem{
ExternalID: externalID,
Title: f.Title,
Content: []byte(content),
ContentType: "text/markdown",
FileName: fileName,
SourceResourceID: kbID,
UpdatedAt: time.Now(),
Metadata: baseMetadata(externalID, f, folderPath, info, kbID),
}, fetchOK
}
// fetchOutcome distinguishes the three ways fetchOneMedia can end, because the
// caller has to treat them differently when building the sync cursor: only a
// transient failure must stay out of the cursor so it is retried next run.
type fetchOutcome int
const (
// fetchOK: the item was resolved and should be ingested.
fetchOK fetchOutcome = iota
// fetchSkipped: IMA cannot give us this item's content and never will
// (unsupported media type, no URL). Deterministic, so it is safe to
// remember in the cursor and stop re-probing it.
fetchSkipped
// fetchFailed: a transient error (API call or download). Must be retried.
fetchFailed
)
// fetchOneMedia calls get_media_info for a single item and, when possible,
// downloads its body.
//
// externalID is the stable logical_key computed by the caller — same value
// across syncs even after an IMA same-name replacement mints a new media_id.
// The raw media_id is still preserved in metadata for observability.
func fetchOneMedia(
ctx context.Context, cli *client,
kbID string, externalID string, f walkedFile, folderPath map[string]string,
) (types.FetchedItem, fetchOutcome) {
info, err := cli.GetMediaInfo(ctx, f.MediaID)
if err != nil {
logger.Warnf(ctx, "[IMA] get_media_info(%s) failed, will retry next sync: %v", f.MediaID, err)
return types.FetchedItem{}, fetchFailed
}
if info.MediaType == mediaTypeNote {
return fetchNote(ctx, cli, kbID, externalID, f, folderPath, info)
}
if isSkippableMediaType(info.MediaType) {
logger.Infof(ctx, "[IMA] skip media %s (title=%q media_type=%d): unsupported by the IMA OpenAPI",
f.MediaID, f.Title, info.MediaType)
return types.FetchedItem{}, fetchSkipped
}
if info.URLInfo.URL == "" {
logger.Warnf(ctx, "[IMA] media %s (title=%q) has no url_info.url, skipping", f.MediaID, f.Title)
return types.FetchedItem{}, fetchSkipped
}
ext := extensionForMediaType(info.MediaType)
// A media type with no fixed extension (web page, WeChat article, ...) is
// normally handed to the ingest layer as a bare URL so WeKnora fetches it
// itself. That only works for publicly reachable links: when IMA attaches
// auth headers the URL points at IMA-hosted storage and WeKnora's own
// fetch — which cannot carry those headers — would be rejected. In that
// case download here, where the headers are available, and infer the
// extension from the response instead.
if ext == "" {
if len(info.URLInfo.Headers) == 0 {
return types.FetchedItem{
ExternalID: externalID,
Title: f.Title,
URL: info.URLInfo.URL,
SourceResourceID: kbID,
UpdatedAt: time.Now(),
Metadata: baseMetadata(externalID, f, folderPath, info, kbID),
}, fetchOK
}
ext = "html"
}
body, ct, err := cli.DownloadURL(ctx, info.URLInfo)
if err != nil {
logger.Warnf(ctx, "[IMA] download media %s (title=%q) failed, will retry next sync: %v",
f.MediaID, f.Title, err)
return types.FetchedItem{}, fetchFailed
}
// IMA labels every image media_type=9, so trust the response's own
// Content-Type over the media_type default when it names a real format.
if detected := extensionForContentType(ct); detected != "" {
ext = detected
}
if ct == "" || strings.HasPrefix(ct, "application/octet-stream") {
ct = mimeForExtension(ext)
}
fileName := datasource.SanitizeFileName(f.Title)
if !strings.HasSuffix(strings.ToLower(fileName), "."+ext) {
fileName = fileName + "." + ext
}
return types.FetchedItem{
ExternalID: externalID,
Title: f.Title,
Content: body,
ContentType: ct,
FileName: fileName,
URL: info.URLInfo.URL,
UpdatedAt: time.Now(),
SourceResourceID: kbID,
Metadata: baseMetadata(externalID, f, folderPath, info, kbID),
}, fetchOK
}
// baseMetadata builds the metadata map preserved on every ingested item.
// externalID (the caller's logical_key) is stored so operators can join the
// stable identity back to the raw media_id — useful when debugging why a
// same-name replacement showed up as an update instead of an add.
func baseMetadata(
externalID string, f walkedFile, folderPath map[string]string,
info *getMediaInfoResp, kbID string,
) map[string]string {
m := map[string]string{
"channel": types.ChannelIMA,
"media_id": f.MediaID,
"ima_logical_key": externalID,
"knowledge_base_id": kbID,
"folder_path": f.FolderPath,
"media_type": fmt.Sprintf("%d", info.MediaType),
}
if f.ParentFolderID != "" {
m["parent_folder_id"] = f.ParentFolderID
}
if fp, ok := folderPath[f.ParentFolderID]; ok && fp != "" {
m["folder_path"] = fp
}
if info.NotebookExtInfo.NotebookID != "" {
m["notebook_id"] = info.NotebookExtInfo.NotebookID
}
return m
}
@@ -0,0 +1,672 @@
package ima
import (
"context"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/types"
)
func TestConnector_Type(t *testing.T) {
if got := NewConnector().Type(); got != types.ConnectorTypeIMA {
t.Errorf("Type() = %q, want %q", got, types.ConnectorTypeIMA)
}
}
// TestFetchIncremental_TransientFailureIsRetried is the regression test for the
// cursor bug: the cursor used to be built from the raw listing before any
// content was fetched, so an item whose download failed was recorded as
// "seen with this media_id" and every later incremental sync skipped it as
// unchanged. The document was then silently missing from the KB forever.
func TestFetchIncremental_TransientFailureIsRetried(t *testing.T) {
f := newFakeIMA(t)
good := fakeFile{MediaID: "m-good", Title: "Good", MediaType: mediaTypeMarkdown, Body: "# ok"}
flaky := fakeFile{
MediaID: "m-flaky", Title: "Flaky", MediaType: mediaTypeMarkdown,
Body: "# later", DownloadFails: true,
}
f.setKB("kb1", []fakeFile{good, flaky})
c := NewConnector()
cfg := f.config("kb1")
goodKey := logicalKey("kb1", "", "Good")
flakyKey := logicalKey("kb1", "", "Flaky")
items, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first FetchIncremental: %v", err)
}
if _, ok := findItem(items, flakyKey); ok {
t.Fatalf("failed download must not be emitted, got %s", describeItems(items))
}
mustFindItem(t, items, goodKey)
state := decodeCursor(t, cursor)
if _, recorded := state.KBLogical["kb1"][flakyKey]; recorded {
t.Fatal("a failed item must not be recorded in the cursor, otherwise it is never retried")
}
if state.KBLogical["kb1"][goodKey] != "m-good" {
t.Fatalf("successful item missing from cursor: %#v", state.KBLogical["kb1"])
}
// Second pass: the download now succeeds and the item must be re-attempted.
flaky.DownloadFails = false
f.setKB("kb1", []fakeFile{good, flaky})
items2, cursor2, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second FetchIncremental: %v", err)
}
retried := mustFindItem(t, items2, flakyKey)
if string(retried.Content) != "# later" {
t.Errorf("retried content = %q, want %q", retried.Content, "# later")
}
if _, ok := findItem(items2, goodKey); ok {
t.Errorf("unchanged item must be skipped on the second pass, got %s", describeItems(items2))
}
if decodeCursor(t, cursor2).KBLogical["kb1"][flakyKey] != "m-flaky" {
t.Error("the retried item should now be recorded in the cursor")
}
}
// TestFetchIncremental_FailureIsNotADeletion guards the other half of the fix:
// keeping a failed item out of the cursor must not make the next sync mistake
// it for a document that vanished from IMA.
func TestFetchIncremental_FailureIsNotADeletion(t *testing.T) {
f := newFakeIMA(t)
good := fakeFile{MediaID: "m-good", Title: "Good", MediaType: mediaTypeMarkdown, Body: "# ok"}
flaky := fakeFile{MediaID: "m-flaky", Title: "Flaky", MediaType: mediaTypeMarkdown, DownloadFails: true}
f.setKB("kb1", []fakeFile{good, flaky})
c := NewConnector()
cfg := f.config("kb1")
flakyKey := logicalKey("kb1", "", "Flaky")
_, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first FetchIncremental: %v", err)
}
// Still failing, still listed by IMA: no tombstone may be emitted.
items, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second FetchIncremental: %v", err)
}
for _, it := range items {
if it.IsDeleted && it.ExternalID == flakyKey {
t.Fatalf("a still-listed item that merely failed to download must not be tombstoned: %s",
describeItems(items))
}
}
}
func TestFetchIncremental_RemovedItemIsTombstoned(t *testing.T) {
f := newFakeIMA(t)
keep := fakeFile{MediaID: "m-keep", Title: "Keep", MediaType: mediaTypeMarkdown, Body: "# keep"}
drop := fakeFile{MediaID: "m-drop", Title: "Drop", MediaType: mediaTypeMarkdown, Body: "# drop"}
f.setKB("kb1", []fakeFile{keep, drop})
c := NewConnector()
cfg := f.config("kb1")
dropKey := logicalKey("kb1", "", "Drop")
_, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first FetchIncremental: %v", err)
}
f.setKB("kb1", []fakeFile{keep})
items, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second FetchIncremental: %v", err)
}
tombstone, ok := findItem(items, dropKey)
if !ok || !tombstone.IsDeleted {
t.Fatalf("removed item must be tombstoned, got %s", describeItems(items))
}
if tombstone.SourceResourceID != "kb1" {
t.Errorf("tombstone SourceResourceID = %q, want kb1", tombstone.SourceResourceID)
}
}
// TestFetchIncremental_SameNameReplacementKeepsExternalID covers IMA minting a
// new media_id when a file is replaced in place: the item must come back as an
// update under the same external id rather than a delete plus an insert.
func TestFetchIncremental_SameNameReplacementKeepsExternalID(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{MediaID: "m-v1", Title: "Doc", MediaType: mediaTypeMarkdown, Body: "v1"}})
c := NewConnector()
cfg := f.config("kb1")
key := logicalKey("kb1", "", "Doc")
_, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first FetchIncremental: %v", err)
}
f.setKB("kb1", []fakeFile{{MediaID: "m-v2", Title: "Doc", MediaType: mediaTypeMarkdown, Body: "v2"}})
items, cursor2, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second FetchIncremental: %v", err)
}
updated := mustFindItem(t, items, key)
if updated.IsDeleted {
t.Fatal("a same-name replacement must be an update, not a delete")
}
if string(updated.Content) != "v2" {
t.Errorf("content = %q, want v2", updated.Content)
}
if updated.Metadata["media_id"] != "m-v2" {
t.Errorf("metadata media_id = %q, want m-v2", updated.Metadata["media_id"])
}
for _, it := range items {
if it.IsDeleted {
t.Errorf("no tombstone expected, got %s", describeItems(items))
}
}
if decodeCursor(t, cursor2).KBLogical["kb1"][key] != "m-v2" {
t.Error("cursor should track the new media_id")
}
}
// TestFetchIncremental_UnsupportedTypeIsProbedOnce checks that a deterministic
// skip is remembered, so an IMA knowledge base full of notes does not re-pay
// for get_media_info on every scheduled sync.
func TestFetchIncremental_UnsupportedTypeIsProbedOnce(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{MediaID: "m-note", Title: "Note", MediaType: mediaTypeNote}})
c := NewConnector()
cfg := f.config("kb1")
items, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first FetchIncremental: %v", err)
}
if len(items) != 0 {
t.Fatalf("note must be skipped, got %s", describeItems(items))
}
if f.callCount("get_media_info:m-note") != 1 {
t.Fatalf("get_media_info calls = %d, want 1", f.callCount("get_media_info:m-note"))
}
if _, _, err := c.FetchIncremental(context.Background(), cfg, cursor); err != nil {
t.Fatalf("second FetchIncremental: %v", err)
}
if got := f.callCount("get_media_info:m-note"); got != 1 {
t.Errorf("get_media_info calls after second sync = %d, want 1 (skip should be cached)", got)
}
}
// TestFetchAll_NoteBodyIsReadFromNoteNamespace covers IMA notes. They expose no
// url_info at all: get_media_info only reports a notebook_id, and the body has
// to be read from /openapi/note/v1/get_doc_content.
func TestFetchAll_NoteBodyIsReadFromNoteNamespace(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{
MediaID: "note_1",
Title: "Meeting notes",
MediaType: mediaTypeNote,
NotebookID: "987654321",
NoteBody: "# Standup\n- shipped the connector",
}})
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatalf("FetchAll: %v", err)
}
note := mustFindItem(t, items, logicalKey("kb1", "", "Meeting notes"))
if string(note.Content) != "# Standup\n- shipped the connector" {
t.Errorf("content = %q, want the note body", note.Content)
}
if !strings.HasSuffix(note.FileName, ".md") {
t.Errorf("FileName = %q, want an .md suffix", note.FileName)
}
if note.ContentType != "text/markdown" {
t.Errorf("ContentType = %q, want text/markdown", note.ContentType)
}
if note.Metadata["notebook_id"] != "987654321" {
t.Errorf("metadata notebook_id = %q, want 987654321", note.Metadata["notebook_id"])
}
if f.callCount("get_doc_content:987654321") != 1 {
t.Errorf("get_doc_content calls = %d, want 1", f.callCount("get_doc_content:987654321"))
}
}
// TestFetchIncremental_NoteReadFailureIsRetried checks that a note whose body
// could not be read follows the same retry path as a failed download rather
// than being remembered as synced.
func TestFetchIncremental_NoteReadFailureIsRetried(t *testing.T) {
f := newFakeIMA(t)
note := fakeFile{
MediaID: "note_1", Title: "Broken", MediaType: mediaTypeNote,
NotebookID: "111", NoteBody: "recovered", NoteFails: true,
}
f.setKB("kb1", []fakeFile{note})
c := NewConnector()
cfg := f.config("kb1")
key := logicalKey("kb1", "", "Broken")
items, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first FetchIncremental: %v", err)
}
if len(items) != 0 {
t.Fatalf("a note that could not be read must not be emitted, got %s", describeItems(items))
}
if _, recorded := decodeCursor(t, cursor).KBLogical["kb1"][key]; recorded {
t.Fatal("a failed note read must not be recorded in the cursor")
}
note.NoteFails = false
f.setKB("kb1", []fakeFile{note})
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second FetchIncremental: %v", err)
}
if got := mustFindItem(t, items2, key); string(got.Content) != "recovered" {
t.Errorf("content = %q, want recovered", got.Content)
}
}
// TestFetchAll_EmptyNoteSyncsTitleOnly covers a note whose body was cleared in
// IMA. The note still exists, so it must be emitted with its title as content:
// skipping it would leave whatever was indexed before the edit in place.
func TestFetchAll_EmptyNoteSyncsTitleOnly(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{
MediaID: "note_1", Title: "Blank", MediaType: mediaTypeNote,
NotebookID: "222", NoteBody: " \n ",
}})
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatalf("FetchAll: %v", err)
}
note := mustFindItem(t, items, logicalKey("kb1", "", "Blank"))
if string(note.Content) != "# Blank\n" {
t.Errorf("content = %q, want the title as markdown", note.Content)
}
if note.ContentType != "text/markdown" {
t.Errorf("ContentType = %q, want text/markdown", note.ContentType)
}
if !strings.HasSuffix(note.FileName, ".md") {
t.Errorf("FileName = %q, want an .md suffix", note.FileName)
}
}
// TestFetchAll_ClearedNoteReplacesStaleContent is the regression test for stale
// note bodies: after a note that was already ingested is cleared in IMA, the
// next sync that re-reads it must emit an item with the same external id so
// ingestion overwrites the old text instead of keeping it indexed forever.
func TestFetchAll_ClearedNoteReplacesStaleContent(t *testing.T) {
f := newFakeIMA(t)
note := fakeFile{
MediaID: "note_1", Title: "Runbook", MediaType: mediaTypeNote,
NotebookID: "777", NoteBody: "# Runbook\nold body",
}
f.setKB("kb1", []fakeFile{note})
c := NewConnector()
cfg := f.config("kb1")
key := logicalKey("kb1", "", "Runbook")
items, err := c.FetchAll(context.Background(), cfg, []string{"kb1"})
if err != nil {
t.Fatalf("first FetchAll: %v", err)
}
first := mustFindItem(t, items, key)
if string(first.Content) != "# Runbook\nold body" {
t.Fatalf("first content = %q, want the note body", first.Content)
}
// The user clears the note body. The note itself still exists and keeps the
// same media_id, so only a sync that re-reads it can notice.
note.NoteBody = ""
f.setKB("kb1", []fakeFile{note})
items2, err := c.FetchAll(context.Background(), cfg, []string{"kb1"})
if err != nil {
t.Fatalf("second FetchAll: %v", err)
}
replacement := mustFindItem(t, items2, key)
if replacement.ExternalID != first.ExternalID {
t.Errorf("external id = %q, want the original %q so ingestion updates in place",
replacement.ExternalID, first.ExternalID)
}
if string(replacement.Content) != "# Runbook\n" {
t.Errorf("content after clearing = %q, want the title only", replacement.Content)
}
}
// TestFetchAll_AISessionIsStillSkipped pins the types IMA genuinely cannot
// export, so widening note support does not quietly widen these too.
func TestFetchAll_AISessionIsStillSkipped(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{
{MediaID: "m-ai", Title: "Chat", MediaType: mediaTypeAISession},
{MediaID: "m-video", Title: "Clip", MediaType: mediaTypeVideo},
})
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatalf("FetchAll: %v", err)
}
if len(items) != 0 {
t.Fatalf("AI sessions and video parses must be skipped, got %s", describeItems(items))
}
}
// TestFetchAll_AuthenticatedURLIsDownloaded covers media types with no fixed
// extension. When IMA attaches auth headers the URL is IMA-hosted and WeKnora's
// own fetch could not authenticate, so the connector must download it here and
// forward the headers.
func TestFetchAll_AuthenticatedURLIsDownloaded(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{
MediaID: "m-web",
Title: "Article",
MediaType: mediaTypeWeb,
Body: "<html>body</html>",
ContentType: "text/html",
URLHeaders: map[string]string{"X-Ima-Token": "secret"},
}})
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatalf("FetchAll: %v", err)
}
item := mustFindItem(t, items, logicalKey("kb1", "", "Article"))
if string(item.Content) != "<html>body</html>" {
t.Errorf("content = %q, want the downloaded body", item.Content)
}
if !strings.HasSuffix(item.FileName, ".html") {
t.Errorf("FileName = %q, want an .html suffix", item.FileName)
}
if got := f.downloadHeaders["m-web"].Get("X-Ima-Token"); got != "secret" {
t.Errorf("auth header forwarded = %q, want %q", got, "secret")
}
}
// TestFetchAll_PublicURLStaysURLOnly is the counterpart: without auth headers
// the link is publicly reachable, so it is handed to the ingest layer as a URL
// and WeKnora renders the live page instead of a snapshot.
func TestFetchAll_PublicURLStaysURLOnly(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{MediaID: "m-web", Title: "Article", MediaType: mediaTypeWeb, Body: "ignored"}})
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatalf("FetchAll: %v", err)
}
item := mustFindItem(t, items, logicalKey("kb1", "", "Article"))
if len(item.Content) != 0 {
t.Errorf("public URL must not be downloaded, got %d bytes", len(item.Content))
}
if item.URL == "" {
t.Error("URL-only item must carry a URL")
}
if f.callCount("download:m-web") != 0 {
t.Error("no download should have been attempted")
}
}
// TestFetchAll_ImageExtensionFollowsContentType guards against naming a JPEG
// ".png": IMA reports every image as media_type=9, so only the download's
// Content-Type reveals the real format, and the extension drives the ingest
// pipeline's file-type checks.
func TestFetchAll_ImageExtensionFollowsContentType(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{
MediaID: "m-img",
Title: "Photo",
MediaType: mediaTypeImage,
Body: "\xff\xd8\xff\xe0jpeg",
ContentType: "image/jpeg",
}})
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatalf("FetchAll: %v", err)
}
item := mustFindItem(t, items, logicalKey("kb1", "", "Photo"))
if !strings.HasSuffix(item.FileName, ".jpg") {
t.Errorf("FileName = %q, want a .jpg suffix for an image/jpeg body", item.FileName)
}
}
func TestFetchAll_SkipsItemWithoutURL(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{MediaID: "m-empty", Title: "Empty", MediaType: mediaTypePDF, NoURL: true}})
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatalf("FetchAll: %v", err)
}
if len(items) != 0 {
t.Fatalf("item without a URL must be skipped, got %s", describeItems(items))
}
}
// TestFetchAll_ResolvesFolderPath checks the mixed file/folder listing walk.
func TestFetchAll_ResolvesFolderPath(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1",
[]fakeFile{
{MediaID: "m-root", Title: "Root", MediaType: mediaTypeMarkdown, Body: "root"},
{MediaID: "m-deep", Title: "Deep", ParentFolderID: "folder_f2", MediaType: mediaTypeMarkdown, Body: "deep"},
},
fakeFolder{FolderID: "folder_f1", Name: "Outer"},
fakeFolder{FolderID: "folder_f2", Name: "Inner", ParentFolderID: "folder_f1"},
fakeFolder{FolderID: "folder_empty", Name: "Empty"},
)
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatalf("FetchAll: %v", err)
}
if len(items) != 2 {
t.Fatalf("expected only the root and nested files, got %s", describeItems(items))
}
deep := mustFindItem(t, items, logicalKey("kb1", "folder_f2", "Deep"))
if string(deep.Content) != "deep" {
t.Errorf("nested content = %q, want deep", deep.Content)
}
if deep.Metadata["folder_path"] != "Outer/Inner" {
t.Errorf("folder_path = %q, want Outer/Inner", deep.Metadata["folder_path"])
}
root := mustFindItem(t, items, logicalKey("kb1", "", "Root"))
if root.Metadata["folder_path"] != "" {
t.Errorf("root folder_path = %q, want empty", root.Metadata["folder_path"])
}
for _, id := range []string{"folder_f1", "folder_f2", "folder_empty"} {
if got := f.callCount("get_knowledge_list:" + id); got != 1 {
t.Errorf("list folder %q calls = %d, want 1 (with the folder_ prefix preserved)", id, got)
}
if got := f.callCount("get_media_info:" + id); got != 0 {
t.Errorf("folder %q was fetched as a file %d times", id, got)
}
}
}
func TestFetchIncremental_NestedFolders(t *testing.T) {
f := newFakeIMA(t)
folders := []fakeFolder{
{FolderID: "folder_outer", Name: "Outer"},
{FolderID: "folder_inner", Name: "Inner", ParentFolderID: "folder_outer"},
}
file := fakeFile{
MediaID: "m-deep", Title: "Deep", ParentFolderID: "folder_inner",
MediaType: mediaTypeMarkdown, Body: "deep",
}
f.setKB("kb1", []fakeFile{file}, folders...)
c := NewConnector()
cfg := f.config("kb1")
key := logicalKey("kb1", "folder_inner", "Deep")
items, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first FetchIncremental: %v", err)
}
deep := mustFindItem(t, items, key)
if deep.Metadata["folder_path"] != "Outer/Inner" {
t.Errorf("folder_path = %q, want Outer/Inner", deep.Metadata["folder_path"])
}
state := decodeCursor(t, cursor).KBLogical["kb1"]
if len(state) != 1 || state[key] != file.MediaID {
t.Fatalf("cursor should contain only the nested file, got %#v", state)
}
items, cursor, err = c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("unchanged FetchIncremental: %v", err)
}
if len(items) != 0 {
t.Fatalf("unchanged nested file must not be emitted or tombstoned, got %s", describeItems(items))
}
if got := f.callCount("get_media_info:" + file.MediaID); got != 1 {
t.Errorf("nested file fetched %d times, want 1", got)
}
if decodeCursor(t, cursor).KBLogical["kb1"][key] != file.MediaID {
t.Fatal("unchanged nested file must remain in the cursor")
}
f.setKB("kb1", nil, folders...)
items, cursor, err = c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("deleted FetchIncremental: %v", err)
}
if len(items) != 1 || !mustFindItem(t, items, key).IsDeleted {
t.Fatalf("removed nested file must be tombstoned, got %s", describeItems(items))
}
if state := decodeCursor(t, cursor).KBLogical["kb1"]; len(state) != 0 {
t.Errorf("empty folders must not be recorded as files, got %#v", state)
}
for _, folder := range folders {
if got := f.callCount("get_media_info:" + folder.FolderID); got != 0 {
t.Errorf("folder %q was fetched as a file %d times", folder.FolderID, got)
}
}
}
func TestListResources_ReturnsAddableBases(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb-b", nil)
f.setKB("kb-a", nil)
resources, err := NewConnector().ListResources(context.Background(), f.config(), "")
if err != nil {
t.Fatalf("ListResources: %v", err)
}
if len(resources) != 2 {
t.Fatalf("got %d resources, want 2", len(resources))
}
if resources[0].ExternalID != "kb-a" || resources[1].ExternalID != "kb-b" {
t.Errorf("resources are not sorted by id: %+v", resources)
}
if resources[0].Description != "desc kb-a" {
t.Errorf("description not enriched from get_knowledge_base: %q", resources[0].Description)
}
}
// TestListResources_FallsBackToSearch covers tenants whose credential exposes
// read-only scopes, where get_addable_knowledge_base_list comes back empty.
func TestListResources_FallsBackToSearch(t *testing.T) {
f := newFakeIMA(t)
f.searchBases = []searchedKnowledgeBaseInfo{{ID: "kb-x", Name: "X", CoverURL: "https://cover"}}
resources, err := NewConnector().ListResources(context.Background(), f.config(), "")
if err != nil {
t.Fatalf("ListResources: %v", err)
}
if len(resources) != 1 || resources[0].ExternalID != "kb-x" {
t.Fatalf("expected the search fallback to surface kb-x, got %+v", resources)
}
if resources[0].Metadata["cover_url"] != "https://cover" {
t.Errorf("cover_url = %v, want https://cover", resources[0].Metadata["cover_url"])
}
}
func TestListResources_ChildrenAreEmpty(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", nil)
resources, err := NewConnector().ListResources(context.Background(), f.config(), "kb1")
if err != nil {
t.Fatalf("ListResources: %v", err)
}
if len(resources) != 0 {
t.Errorf("knowledge bases have no children, got %+v", resources)
}
}
func TestValidate_InvalidCredentials(t *testing.T) {
f := newFakeIMA(t)
cfg := f.config()
cfg.Credentials["client_id"] = ""
err := NewConnector().Validate(context.Background(), cfg)
if err == nil {
t.Fatal("expected an error for a missing client_id")
}
if !strings.Contains(err.Error(), "client_id") {
t.Errorf("error = %v, want it to name the missing field", err)
}
}
func TestFetchIncremental_RequiresResourceIDs(t *testing.T) {
f := newFakeIMA(t)
if _, _, err := NewConnector().FetchIncremental(context.Background(), f.config(), nil); err == nil {
t.Fatal("expected an error when no knowledge base is selected")
}
}
func TestConnectorIsRegisteredInMetadata(t *testing.T) {
meta, ok := datasource.ConnectorMetadataRegistry[types.ConnectorTypeIMA]
if !ok {
t.Fatal("IMA connector missing from the metadata registry")
}
if meta.Type != types.ConnectorTypeIMA {
t.Errorf("metadata type = %q, want %q", meta.Type, types.ConnectorTypeIMA)
}
}
func TestFetchAll_FileNamePolicy(t *testing.T) {
for _, media := range []struct {
name string
kind int32
}{{"media", mediaTypeMarkdown}, {"note", mediaTypeNote}} {
for _, tt := range []struct{ name, title, want string }{
{"punctuation", "A/B:C", "A_B_C.md"},
{"existing extension and whitespace", " \tA/B.MD", " \tA_B.MD"},
{"long title", strings.Repeat("测", 100) + ".MD", strings.Repeat("测", 66) + ".md"},
} {
t.Run(media.name+"/"+tt.name, func(t *testing.T) {
f := newFakeIMA(t)
f.setKB("kb1", []fakeFile{{
MediaID: "file", Title: tt.title, MediaType: media.kind,
Body: "# content", NotebookID: "123", NoteBody: "# content",
}})
items, err := NewConnector().FetchAll(context.Background(), f.config("kb1"), []string{"kb1"})
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("got %d items, want 1", len(items))
}
if items[0].Title != tt.title || items[0].FileName != tt.want {
t.Fatalf("title = %q, filename = %q; want %q, %q",
items[0].Title, items[0].FileName, tt.title, tt.want)
}
})
}
}
}
@@ -0,0 +1,439 @@
package ima
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// TestMain whitelists loopback for SSRF so the httptest servers (127.0.0.1)
// are reachable, and the default base host so parseIMAConfig does not resolve
// ima.qq.com over live DNS during a unit test. Production keeps the default
// strict SSRF policy.
func TestMain(m *testing.M) {
_ = os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost,ima.qq.com")
secutils.ResetSSRFWhitelistForTest()
os.Exit(m.Run())
}
// fakeFile is one entry in a fake knowledge base listing.
type fakeFile struct {
MediaID string
Title string
ParentFolderID string
// MediaType is reported by both get_knowledge_list and get_media_info.
MediaType int32
// Body is what the download URL serves.
Body string
// ContentType is the download response's Content-Type ("" omits the header).
ContentType string
// URLHeaders are the auth headers IMA attaches to url_info.
URLHeaders map[string]string
// NoURL makes get_media_info return an empty url_info.url.
NoURL bool
// InfoFails makes get_media_info return a 500 for this media_id.
InfoFails bool
// DownloadFails makes the download URL return a 500.
DownloadFails bool
// NotebookID is reported under notebook_ext_info for notes.
NotebookID string
// NoteBody is what get_doc_content serves for NotebookID.
NoteBody string
// NoteFails makes get_doc_content return a business error.
NoteFails bool
}
// fakeFolder is a folder entry in a fake knowledge base listing.
type fakeFolder struct {
FolderID string
Name string
ParentFolderID string
}
// fakeIMA is an in-process stand-in for the IMA OpenAPI. Only the endpoints
// the connector calls are implemented.
type fakeIMA struct {
server *httptest.Server
mu sync.Mutex
// files and folders are keyed by knowledge base id, then by parent folder
// id ("" for the KB root).
files map[string]map[string][]fakeFile
folders map[string]map[string][]fakeFolder
// bases is what get_addable_knowledge_base_list returns.
bases []addableKnowledgeBaseInfo
// searchBases is what search_knowledge_base returns.
searchBases []searchedKnowledgeBaseInfo
// calls counts requests per action, plus "download:<media_id>".
calls map[string]int
// paging overrides an action's paging envelope; see fakePaging.
paging map[string]fakePaging
// downloadHeaders records the headers seen by the last download of a media.
downloadHeaders map[string]http.Header
}
// fakePaging forces the paging envelope of one action so a test can reproduce
// a vendor that never stops paging. maxRequests bounds the fake: once the
// action has been called more times than that it answers 400, so a run without
// the connector's guard fails instead of spinning forever.
type fakePaging struct {
// nextCursor is answered as next_cursor; with advanceCursor the request
// number is appended so every page hands back a cursor never seen before.
nextCursor string
advanceCursor bool
isEnd bool
// stopAfter ends the listing (is_end=true, empty cursor) once the action
// has been called this many times, so a test can model a finite listing.
stopAfter int
// filesByCall replaces get_knowledge_list's payload for one request
// number (1-based), so a test can prove several pages are merged.
filesByCall map[int][]fakeFile
// maxRequests answers 400 once the action has been called more than this.
maxRequests int
}
func newFakeIMA(t *testing.T) *fakeIMA {
t.Helper()
f := &fakeIMA{
files: map[string]map[string][]fakeFile{},
folders: map[string]map[string][]fakeFolder{},
calls: map[string]int{},
paging: map[string]fakePaging{},
downloadHeaders: map[string]http.Header{},
}
mux := http.NewServeMux()
mux.HandleFunc(apiBasePath+"/", f.handleAPI)
mux.HandleFunc(noteBasePath+"/", f.handleNoteAPI)
mux.HandleFunc("/dl/", f.handleDownload)
f.server = httptest.NewServer(mux)
t.Cleanup(f.server.Close)
return f
}
// setKB replaces the listing of a knowledge base and registers it as addable.
func (f *fakeIMA) setKB(kbID string, files []fakeFile, folders ...fakeFolder) {
f.mu.Lock()
defer f.mu.Unlock()
byParent := map[string][]fakeFile{}
for _, file := range files {
byParent[file.ParentFolderID] = append(byParent[file.ParentFolderID], file)
}
f.files[kbID] = byParent
foldersByParent := map[string][]fakeFolder{}
for _, folder := range folders {
foldersByParent[folder.ParentFolderID] = append(foldersByParent[folder.ParentFolderID], folder)
}
f.folders[kbID] = foldersByParent
for _, b := range f.bases {
if b.ID == kbID {
return
}
}
f.bases = append(f.bases, addableKnowledgeBaseInfo{ID: kbID, Name: "KB " + kbID})
}
func (f *fakeIMA) callCount(key string) int {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls[key]
}
func (f *fakeIMA) record(key string) {
f.mu.Lock()
defer f.mu.Unlock()
f.calls[key]++
}
// pagingFields answers the is_end/next_cursor pair for an action, applying the
// test's paging override when one is installed.
func (f *fakeIMA) pagingFields(action string) (isEnd bool, nextCursor string) {
f.mu.Lock()
defer f.mu.Unlock()
override, ok := f.paging[action]
if !ok {
return true, ""
}
if override.stopAfter > 0 && f.calls[action] >= override.stopAfter {
return true, ""
}
if override.advanceCursor {
return override.isEnd, fmt.Sprintf("%s-%d", override.nextCursor, f.calls[action])
}
return override.isEnd, override.nextCursor
}
// pagingFiles answers the file payload for one get_knowledge_list request,
// falling back to the knowledge base's own listing.
func (f *fakeIMA) pagingFiles(kbID, folderID string, call int) []fakeFile {
f.mu.Lock()
defer f.mu.Unlock()
if override, ok := f.paging["get_knowledge_list"]; ok {
if files, ok := override.filesByCall[call]; ok {
return files
}
}
return f.files[kbID][folderID]
}
// requestBudgetExceeded reports whether the action has used up the request
// budget a test installed, so the fake can answer 400 instead of letting an
// unguarded connector spin.
func (f *fakeIMA) requestBudgetExceeded(action string) bool {
f.mu.Lock()
defer f.mu.Unlock()
limit := f.paging[action].maxRequests
return limit > 0 && f.calls[action] > limit
}
// findFile locates a file by media_id across every knowledge base.
func (f *fakeIMA) findFile(mediaID string) (fakeFile, bool) {
f.mu.Lock()
defer f.mu.Unlock()
for _, byParent := range f.files {
for _, files := range byParent {
for _, file := range files {
if file.MediaID == mediaID {
return file, true
}
}
}
}
return fakeFile{}, false
}
func (f *fakeIMA) handleAPI(w http.ResponseWriter, r *http.Request) {
action := strings.TrimPrefix(r.URL.Path, apiBasePath+"/")
f.record(action)
if f.requestBudgetExceeded(action) {
w.WriteHeader(http.StatusBadRequest)
return
}
var req map[string]interface{}
_ = json.NewDecoder(r.Body).Decode(&req)
str := func(k string) string {
if v, ok := req[k].(string); ok {
return v
}
return ""
}
switch action {
case "get_addable_knowledge_base_list":
isEnd, nextCursor := f.pagingFields(action)
f.mu.Lock()
resp := getAddableKnowledgeBaseListResp{
AddableKnowledgeBaseList: f.bases,
IsEnd: isEnd,
NextCursor: nextCursor,
}
f.mu.Unlock()
writeEnvelope(w, 0, "", resp)
case "search_knowledge_base":
isEnd, nextCursor := f.pagingFields(action)
f.mu.Lock()
resp := searchKnowledgeBaseResp{InfoList: f.searchBases, IsEnd: isEnd, NextCursor: nextCursor}
f.mu.Unlock()
writeEnvelope(w, 0, "", resp)
case "get_knowledge_base":
infos := map[string]knowledgeBaseInfo{}
if ids, ok := req["ids"].([]interface{}); ok {
for _, raw := range ids {
id, _ := raw.(string)
infos[id] = knowledgeBaseInfo{ID: id, Name: "KB " + id, Description: "desc " + id}
}
}
writeEnvelope(w, 0, "", getKnowledgeBaseResp{Infos: infos})
case "get_knowledge_list":
kbID, folderID := str("knowledge_base_id"), str("folder_id")
f.record("get_knowledge_list:" + folderID)
isEnd, nextCursor := f.pagingFields("get_knowledge_list")
files := f.pagingFiles(kbID, folderID, f.callCount("get_knowledge_list"))
f.mu.Lock()
folders := f.folders[kbID][folderID]
f.mu.Unlock()
var list []json.RawMessage
for _, folder := range folders {
// Folder entries use the same fields as files in list responses.
b, _ := json.Marshal(map[string]interface{}{
"media_id": folder.FolderID,
"title": folder.Name,
"parent_folder_id": folder.ParentFolderID,
"media_type": 99,
})
list = append(list, b)
}
for _, file := range files {
b, _ := json.Marshal(map[string]interface{}{
"media_id": file.MediaID,
"title": file.Title,
"parent_folder_id": file.ParentFolderID,
"media_type": file.MediaType,
})
list = append(list, b)
}
writeEnvelope(w, 0, "", getKnowledgeListResp{KnowledgeList: list, IsEnd: isEnd, NextCursor: nextCursor})
case "get_media_info":
mediaID := str("media_id")
f.record("get_media_info:" + mediaID)
file, ok := f.findFile(mediaID)
if !ok {
writeEnvelope(w, 110001, "unknown media", nil)
return
}
if file.InfoFails {
w.WriteHeader(http.StatusInternalServerError)
return
}
resp := getMediaInfoResp{MediaType: file.MediaType}
resp.NotebookExtInfo = notebookExtInfo{NotebookID: file.NotebookID}
// Notes carry no url_info; the body lives in the note namespace.
if !file.NoURL && file.MediaType != mediaTypeNote {
resp.URLInfo = urlInfo{
URL: f.server.URL + "/dl/" + mediaID,
Headers: file.URLHeaders,
}
}
writeEnvelope(w, 0, "", resp)
default:
writeEnvelope(w, 110001, "unsupported action "+action, nil)
}
}
// handleNoteAPI serves the /openapi/note/v1 namespace.
func (f *fakeIMA) handleNoteAPI(w http.ResponseWriter, r *http.Request) {
action := strings.TrimPrefix(r.URL.Path, noteBasePath+"/")
f.record("note/" + action)
var req map[string]interface{}
_ = json.NewDecoder(r.Body).Decode(&req)
if action != "get_doc_content" {
writeEnvelope(w, 110012, "unsupported note action "+action, nil)
return
}
noteID, _ := req["note_id"].(string)
f.record("get_doc_content:" + noteID)
f.mu.Lock()
defer f.mu.Unlock()
for _, byParent := range f.files {
for _, files := range byParent {
for _, file := range files {
if file.NotebookID != noteID || noteID == "" {
continue
}
if file.NoteFails {
writeEnvelope(w, 110011, "note read failed", nil)
return
}
writeEnvelope(w, 0, "", getDocContentResp{Content: file.NoteBody})
return
}
}
}
writeEnvelope(w, 110001, "unknown note", nil)
}
func (f *fakeIMA) handleDownload(w http.ResponseWriter, r *http.Request) {
mediaID := strings.TrimPrefix(r.URL.Path, "/dl/")
f.record("download:" + mediaID)
f.mu.Lock()
f.downloadHeaders[mediaID] = r.Header.Clone()
f.mu.Unlock()
file, ok := f.findFile(mediaID)
if !ok || file.DownloadFails {
w.WriteHeader(http.StatusInternalServerError)
return
}
if file.ContentType != "" {
w.Header().Set("Content-Type", file.ContentType)
}
_, _ = w.Write([]byte(file.Body))
}
func writeEnvelope(w http.ResponseWriter, code int, msg string, data interface{}) {
raw, _ := json.Marshal(data)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(apiEnvelope{Code: code, Msg: msg, Data: raw})
}
func (f *fakeIMA) config(resourceIDs ...string) *types.DataSourceConfig {
return &types.DataSourceConfig{
Type: types.ConnectorTypeIMA,
Credentials: map[string]interface{}{
"client_id": "cid",
"api_key": "key",
"base_url": f.server.URL,
},
ResourceIDs: resourceIDs,
}
}
// decodeCursor converts the connector cursor back into its typed form.
func decodeCursor(t *testing.T, cur *types.SyncCursor) *imaCursor {
t.Helper()
if cur == nil {
t.Fatal("cursor is nil")
}
b, err := json.Marshal(cur.ConnectorCursor)
if err != nil {
t.Fatalf("marshal cursor: %v", err)
}
var out imaCursor
if err := json.Unmarshal(b, &out); err != nil {
t.Fatalf("unmarshal cursor: %v", err)
}
return &out
}
// findItem returns the fetched item with the given external id.
func findItem(items []types.FetchedItem, externalID string) (types.FetchedItem, bool) {
for _, it := range items {
if it.ExternalID == externalID {
return it, true
}
}
return types.FetchedItem{}, false
}
func mustFindItem(t *testing.T, items []types.FetchedItem, externalID string) types.FetchedItem {
t.Helper()
it, ok := findItem(items, externalID)
if !ok {
t.Fatalf("item %s not found in %s", externalID, describeItems(items))
}
return it
}
func describeItems(items []types.FetchedItem) string {
var parts []string
for _, it := range items {
parts = append(parts, fmt.Sprintf("{id=%s title=%q deleted=%t}", it.ExternalID, it.Title, it.IsDeleted))
}
return "[" + strings.Join(parts, " ") + "]"
}
@@ -0,0 +1,137 @@
package ima
import (
"bytes"
"context"
"os"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/logger"
)
// paginationHopCap mirrors maxPaginationHops in connector.go. It is spelled as
// a literal so this file also compiles — and then fails on behaviour — against
// a tree that has no guard at all.
const paginationHopCap = 10000
// fakeLoopBudget bounds an unguarded run a little above the guard's own cap:
// the fake answers 400 once the budget is gone, so a regression fails with the
// wrong error instead of spinning forever.
const fakeLoopBudget = paginationHopCap + 5
func imaTestClient(t *testing.T, fake *fakeIMA) *client {
t.Helper()
cfg, err := parseIMAConfig(fake.config("kb-1"))
require.NoError(t, err)
return newClient(cfg)
}
// A vendor that keeps answering is_end=false with the same next_cursor used to
// make all three loops request the same page until the task deadline. Each
// loop must now stop as soon as a cursor repeats.
func TestListResourcesRejectsRepeatedCursor(t *testing.T) {
fake := newFakeIMA(t)
fake.setKB("kb-1", nil)
fake.paging["get_addable_knowledge_base_list"] = fakePaging{
nextCursor: "same-cursor",
maxRequests: fakeLoopBudget,
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := NewConnector().ListResources(ctx, fake.config("kb-1"), "")
require.Error(t, err)
require.Equal(t, 2, fake.callCount("get_addable_knowledge_base_list"),
"the guard must reject the repeated cursor on the second page; err=%v", err)
require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
}
func TestListResourcesSearchFallbackRejectsRepeatedCursor(t *testing.T) {
fake := newFakeIMA(t)
// No addable knowledge bases: ListResources falls back to search.
fake.paging["search_knowledge_base"] = fakePaging{
nextCursor: "same-cursor",
maxRequests: fakeLoopBudget,
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := NewConnector().ListResources(ctx, fake.config(), "")
require.Error(t, err)
require.Contains(t, err.Error(), "search_knowledge_base fallback")
require.Equal(t, 2, fake.callCount("search_knowledge_base"),
"the guard must reject the repeated cursor on the second page; err=%v", err)
require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
}
func TestListAllKBFilesRejectsRepeatedCursor(t *testing.T) {
fake := newFakeIMA(t)
fake.paging["get_knowledge_list"] = fakePaging{
nextCursor: "same-cursor",
maxRequests: fakeLoopBudget,
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, _, err := listAllKBFiles(ctx, imaTestClient(t, fake), "kb-1")
require.Error(t, err)
require.Equal(t, 2, fake.callCount("get_knowledge_list"),
"the guard must reject the repeated cursor on the second page; err=%v", err)
require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
}
// A vendor that hands back a brand new cursor on every page never repeats one,
// so the repeat guard cannot stop it: the hop cap must, and it must say so in
// the log instead of vanishing into a task deadline.
func TestListResourcesSearchFallbackStopsAtPaginationCap(t *testing.T) {
fake := newFakeIMA(t)
fake.paging["search_knowledge_base"] = fakePaging{
nextCursor: "cursor",
advanceCursor: true,
maxRequests: fakeLoopBudget,
}
var logs bytes.Buffer
logger.SetOutput(&logs)
defer logger.SetOutput(os.Stdout)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
_, err := NewConnector().ListResources(ctx, fake.config(), "")
require.Error(t, err)
require.Contains(t, err.Error(), "pagination exceeded 10000 pages")
require.Equal(t, paginationHopCap, fake.callCount("search_knowledge_base"))
require.Contains(t, logs.String(), "pagination exceeded 10000 pages",
"hitting the hop cap must be visible in the log")
}
// The guard must not truncate a listing that genuinely spans several pages.
func TestListAllKBFilesMergesRealPages(t *testing.T) {
fake := newFakeIMA(t)
fake.paging["get_knowledge_list"] = fakePaging{
nextCursor: "page",
advanceCursor: true,
stopAfter: 2, // page 2 ends the listing
filesByCall: map[int][]fakeFile{
1: {{MediaID: "media-1", Title: "a.txt", MediaType: mediaTypeMarkdown}},
2: {{MediaID: "media-2", Title: "b.txt", MediaType: mediaTypeMarkdown}},
},
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
files, _, err := listAllKBFiles(ctx, imaTestClient(t, fake), "kb-1")
require.NoError(t, err)
require.Len(t, files, 2)
require.Equal(t, 2, fake.callCount("get_knowledge_list"))
require.True(t, strings.HasSuffix(files[0].Title, "a.txt") || strings.HasSuffix(files[1].Title, "a.txt"))
}
@@ -0,0 +1,39 @@
package ima
import (
"strings"
"testing"
"unicode/utf8"
)
// truncate caps a connector error preview with a plain byte slice. Connector error
// text is often Chinese, so the cut can land inside a multi-byte rune; these
// previews reach sync_logs and data_sources through the sync error message, and
// PostgreSQL rejects the invalid UTF-8 that a partial rune produces.
func TestTruncateKeepsValidUTF8AcrossCaps(t *testing.T) {
body := strings.Repeat("错", 400)
for _, maxLen := range []int{499, 500, 501, 1000, 1} {
got := truncate(body, maxLen)
if !utf8.ValidString(got) {
t.Fatalf("%s(%d): preview is not valid UTF-8", "truncate", maxLen)
}
if len(got) > maxLen+len("...") {
t.Fatalf("%s(%d): preview is %d bytes", "truncate", maxLen, len(got))
}
if !strings.HasPrefix(body, strings.TrimSuffix(got, "...")) {
t.Fatalf("%s(%d): preview is not a prefix of the input", "truncate", maxLen)
}
}
}
func TestTruncateLeavesShortAndASCIIInputAlone(t *testing.T) {
for _, s := range []string{"", "ok", "服务返回 500", "短"} {
if got := truncate(s, 500); got != s {
t.Fatalf("%s(%q, 500) = %q, want the input unchanged", "truncate", s, got)
}
}
if got := truncate("abcdef", 3); got != "abc..." {
t.Fatalf("truncate keeps the ASCII cut: %q", got)
}
}
+432
View File
@@ -0,0 +1,432 @@
package ima
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/types"
)
// DefaultBaseURL is the IMA OpenAPI base URL. The Path prefix is baked into
// the client (see client.go); users only configure the host.
const DefaultBaseURL = "https://ima.qq.com"
// Base path for knowledge-base OpenAPI requests.
const apiBasePath = "/openapi/wiki/v1"
// Base path for the note OpenAPI. Notes live in their own namespace: the wiki
// endpoints only ever hand back a notebook_id for them, and the body has to be
// read from here.
const noteBasePath = "/openapi/note/v1"
// Config holds IMA-specific configuration decoded from
// DataSourceConfig.Credentials. Both credentials are opaque strings and
// stored encrypted at rest by DataSourceConfig.ToJSON (see internal/types/datasource.go).
type Config struct {
// ClientID: value of the `ima-openapi-clientid` request header,
// obtained from https://ima.qq.com/agent-interface.
ClientID string `json:"client_id"`
// APIKey: value of the `ima-openapi-apikey` request header.
APIKey string `json:"api_key"`
// BaseURL lets users point at an on-prem / test IMA endpoint.
// Defaults to https://ima.qq.com when empty.
BaseURL string `json:"base_url,omitempty"`
}
// GetBaseURL returns the normalized base URL (empty → default, no trailing slash).
func (c *Config) GetBaseURL() string {
url := strings.TrimSpace(c.BaseURL)
if url == "" {
return DefaultBaseURL
}
if !strings.Contains(url, "://") {
url = "https://" + url
}
return strings.TrimRight(url, "/")
}
// parseIMAConfig extracts and validates IMA-specific configuration.
// Uses JSON marshal/unmarshal roundtrip so extra fields are ignored gracefully.
func parseIMAConfig(config *types.DataSourceConfig) (*Config, error) {
if config == nil {
return nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig)
}
credBytes, err := json.Marshal(config.Credentials)
if err != nil {
return nil, fmt.Errorf("marshal credentials: %w", err)
}
var cfg Config
if err := json.Unmarshal(credBytes, &cfg); err != nil {
return nil, fmt.Errorf("parse ima credentials: %w", err)
}
if strings.TrimSpace(cfg.ClientID) == "" {
return nil, fmt.Errorf("%w: client_id is required", datasource.ErrInvalidCredentials)
}
if strings.TrimSpace(cfg.APIKey) == "" {
return nil, fmt.Errorf("%w: api_key is required", datasource.ErrInvalidCredentials)
}
if err := datasource.ValidateConnectorBaseURL(cfg.GetBaseURL()); err != nil {
return nil, err
}
return &cfg, nil
}
// apiEnvelope is the uniform IMA response wrapper: `{ code, msg, data }`.
// A non-zero code is a business-level error and MUST be surfaced to the user.
//
// Some published IMA references spell the same envelope `{ retcode, errmsg }`.
// Accepting both costs nothing and avoids the failure mode where a mismatch
// leaves Code at its zero value and every API error is silently read as
// success.
type apiEnvelope struct {
Code int `json:"code"`
Msg string `json:"msg"`
RetErr *int `json:"retcode"`
ErrMsg string `json:"errmsg"`
Data json.RawMessage `json:"data"`
}
// statusCode returns the business status code under either spelling.
func (e apiEnvelope) statusCode() int {
if e.Code != 0 {
return e.Code
}
if e.RetErr != nil {
return *e.RetErr
}
return 0
}
// message returns the human-readable error under either spelling.
func (e apiEnvelope) message() string {
if e.Msg != "" {
return e.Msg
}
return e.ErrMsg
}
// KnowledgeBaseInfo mirrors IMA's KnowledgeBaseInfo (get_knowledge_base).
type knowledgeBaseInfo struct {
ID string `json:"id"`
Name string `json:"name"`
CoverURL string `json:"cover_url"`
Description string `json:"description"`
RecommendedQuestions []string `json:"recommended_questions"`
}
// searchedKnowledgeBaseInfo — search_knowledge_base returns fewer fields.
type searchedKnowledgeBaseInfo struct {
ID string `json:"id"`
Name string `json:"name"`
CoverURL string `json:"cover_url"`
}
// searchKnowledgeBaseResp — search_knowledge_base response.
type searchKnowledgeBaseResp struct {
InfoList []searchedKnowledgeBaseInfo `json:"info_list"`
IsEnd bool `json:"is_end"`
NextCursor string `json:"next_cursor"`
}
// addableKnowledgeBaseInfo — get_addable_knowledge_base_list item.
// Contains only id + name (no cover_url), see api.md §7.
type addableKnowledgeBaseInfo struct {
ID string `json:"id"`
Name string `json:"name"`
}
// getAddableKnowledgeBaseListResp — get_addable_knowledge_base_list response.
// NOTE: the JSON field is `addable_knowledge_base_list`, not `info_list`.
type getAddableKnowledgeBaseListResp struct {
AddableKnowledgeBaseList []addableKnowledgeBaseInfo `json:"addable_knowledge_base_list"`
IsEnd bool `json:"is_end"`
NextCursor string `json:"next_cursor"`
}
// getKnowledgeBaseResp — get_knowledge_base response (map keyed by id).
type getKnowledgeBaseResp struct {
Infos map[string]knowledgeBaseInfo `json:"infos"`
}
// knowledgeInfo mirrors entries in IMA's knowledge_list (files, notes, folders).
// Folders have media_type=99 and use media_id as the folder ID for child listings.
// File download details are resolved separately through get_media_info.
type knowledgeInfo struct {
MediaID string `json:"media_id"`
Title string `json:"title"`
ParentFolderID string `json:"parent_folder_id"`
MediaType int32 `json:"media_type,omitempty"`
}
// folderInfo mirrors IMA's FolderInfo in current_path, not knowledge_list.
type folderInfo struct {
FolderID string `json:"folder_id"`
Name string `json:"name"`
FileNumber json.Number `json:"file_number"`
FolderNumber json.Number `json:"folder_number"`
ParentFolderID string `json:"parent_folder_id"`
IsTop bool `json:"is_top"`
}
// FileCount safely converts FileNumber to int64 (0 on empty/invalid).
func (f folderInfo) FileCount() int64 {
if f.FileNumber == "" {
return 0
}
n, err := f.FileNumber.Int64()
if err != nil {
return 0
}
return n
}
// FolderCount safely converts FolderNumber to int64 (0 on empty/invalid).
func (f folderInfo) FolderCount() int64 {
if f.FolderNumber == "" {
return 0
}
n, err := f.FolderNumber.Int64()
if err != nil {
return 0
}
return n
}
// getKnowledgeListResp — get_knowledge_list response.
// The response returns files and folders together in knowledge_list;
// media_type distinguishes folders from knowledge items.
type getKnowledgeListResp struct {
// KnowledgeList is a loose slice of raw JSON objects because IMA returns
// files and folders in the same array. We iterate and inspect fields.
KnowledgeList []json.RawMessage `json:"knowledge_list"`
IsEnd bool `json:"is_end"`
NextCursor string `json:"next_cursor"`
CurrentPath []folderInfo `json:"current_path"`
}
// urlInfo mirrors IMA's URLInfo (present on get_media_info for URL-backed media).
type urlInfo struct {
URL string `json:"url"`
Headers map[string]string `json:"headers"`
}
// notebookExtInfo — set on notes (media_type=11).
type notebookExtInfo struct {
NotebookID string `json:"notebook_id"`
}
// getMediaInfoResp — get_media_info response.
type getMediaInfoResp struct {
MediaType int32 `json:"media_type"`
URLInfo urlInfo `json:"url_info"`
NotebookExtInfo notebookExtInfo `json:"notebook_ext_info"`
}
// getDocContentResp — note/v1 get_doc_content response. Content is the note
// body; with target_content_format=0 it is plain text.
type getDocContentResp struct {
Content string `json:"content"`
}
// imaCursor tracks per-knowledge-base state seen during the last sync.
//
// KBLogical: { logical_key: media_id } — the authoritative source for both
// delete detection AND "replacement" detection. IMA reassigns media_id
// whenever a same-named file is replaced in place, so a logical key (see
// logicalKey) is what we treat as a document's stable identity.
// A logical_key present last sync but absent this sync ⇒ delete.
// A logical_key whose media_id changed ⇒ replacement (re-fetch content; the
// emitted FetchedItem carries the same ExternalID so the ingest layer's
// "existing external_id → delete-and-recreate" path (see
// datasource_service.go applyFetchedItem) treats it as an update.
//
// Only items that were successfully synced (or deterministically skipped)
// this cycle are recorded, so a transient download failure leaves the key
// absent and the next run retries it instead of treating it as unchanged.
//
// KBMedia is a legacy field retained only so cursors persisted by earlier
// builds still deserialize; it is never written or consulted.
type imaCursor struct {
LastSyncTime time.Time `json:"last_sync_time"`
KBLogical map[string]map[string]string `json:"kb_logical,omitempty"`
KBMedia map[string]map[string]string `json:"kb_media,omitempty"`
}
// logicalKey derives a stable identity for an IMA item that survives
// same-name replacement (which mints a new media_id server-side).
//
// The key is a short SHA-256 hex over (kb_id, parent_folder_id, title).
// Rationale:
//
// - kb_id keeps identities isolated across knowledge bases (same file
// copied into two KBs is two distinct docs from WeKnora's perspective).
// - parent_folder_id + title anchor the doc to its folder location and
// display name — the tuple IMA's own check_repeated_names uses to gate
// uploads (see api.md), so IMA's own uniqueness constraint enforces
// this key's uniqueness inside a KB.
//
// media_type is deliberately NOT part of the key: get_knowledge_list omits it
// (it only arrives later from get_media_info), so folding it in would mean
// every external_id shifts the day IMA starts populating the field in list
// responses — which reads as "every document deleted and re-added".
//
// Emitted as "ima_" + first 32 hex chars (128 bits) — small enough to fit
// well within Postgres varchar(64) external_id columns, still >> collision
// resistant for any realistic KB size.
func logicalKey(kbID, parentFolderID, title string) string {
h := sha256.New()
// Delimiter can't appear in any component because it's neither a valid
// IMA id character nor allowed in titles once we've folded to bytes.
_, _ = fmt.Fprintf(h, "%s\x1f%s\x1f%s", kbID, parentFolderID, title)
return "ima_" + hex.EncodeToString(h.Sum(nil))[:32]
}
// IMA MediaType enum (see api.md §MediaType).
const (
mediaTypePDF int32 = 1
mediaTypeWeb int32 = 2
mediaTypeWord int32 = 3
mediaTypePPT int32 = 4
mediaTypeExcel int32 = 5
mediaTypeMPArticle int32 = 6
mediaTypeMarkdown int32 = 7
mediaTypeImage int32 = 9
mediaTypeNote int32 = 11
mediaTypeAISession int32 = 12
mediaTypeTXT int32 = 13
mediaTypeXmind int32 = 14
mediaTypeAudio int32 = 15
mediaTypeVideo int32 = 16
mediaTypeHTML int32 = 20
mediaTypeEPUB int32 = 21
mediaTypeFolder int32 = 99
)
// extensionForMediaType maps IMA media types to a file extension.
// Returns "" when the media type has no downloadable body (web page, note, AI
// session, video-parse) — callers should skip those or treat them as URL-only.
func extensionForMediaType(t int32) string {
switch t {
case mediaTypePDF:
return "pdf"
case mediaTypeWord:
return "docx"
case mediaTypePPT:
return "pptx"
case mediaTypeExcel:
return "xlsx"
case mediaTypeMarkdown:
return "md"
case mediaTypeImage:
return "png"
case mediaTypeTXT:
return "txt"
case mediaTypeXmind:
return "xmind"
case mediaTypeAudio:
return "mp3"
case mediaTypeHTML:
return "html"
case mediaTypeEPUB:
return "epub"
default:
return ""
}
}
// extensionForContentType maps a response Content-Type back to a file
// extension, ignoring any "; charset=..." suffix. Returns "" for types we
// have no better guess for than the media_type-derived default.
//
// IMA reports every image as media_type=9 regardless of the real encoding, so
// the download's Content-Type is the only signal that distinguishes a JPEG
// from a PNG. Naming a JPEG ".png" breaks the extension-based file-type checks
// downstream in the ingest pipeline.
func extensionForContentType(contentType string) string {
mediaType := strings.ToLower(strings.TrimSpace(contentType))
if i := strings.Index(mediaType, ";"); i >= 0 {
mediaType = strings.TrimSpace(mediaType[:i])
}
switch mediaType {
case "image/png":
return "png"
case "image/jpeg", "image/jpg":
return "jpg"
case "image/gif":
return "gif"
case "image/webp":
return "webp"
case "image/bmp":
return "bmp"
default:
return ""
}
}
// mimeForExtension maps a file extension to a canonical MIME type.
// Used when the downloaded URL response omits (or misreports) Content-Type.
func mimeForExtension(ext string) string {
switch strings.ToLower(strings.TrimPrefix(ext, ".")) {
case "pdf":
return "application/pdf"
case "doc":
return "application/msword"
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
case "ppt":
return "application/vnd.ms-powerpoint"
case "pptx":
return "application/vnd.openxmlformats-officedocument.presentationml.presentation"
case "xls":
return "application/vnd.ms-excel"
case "xlsx":
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
case "md":
return "text/markdown"
case "txt":
return "text/plain"
case "html", "htm":
return "text/html"
case "png":
return "image/png"
case "jpg", "jpeg":
return "image/jpeg"
case "webp":
return "image/webp"
case "gif":
return "image/gif"
case "bmp":
return "image/bmp"
case "epub":
return "application/epub+zip"
case "xmind":
return "application/x-xmind"
case "mp3":
return "audio/mpeg"
case "m4a":
return "audio/x-m4a"
case "wav":
return "audio/wav"
case "aac":
return "audio/aac"
default:
return "application/octet-stream"
}
}
// isSkippableMediaType reports whether IMA offers no way to read this type's
// content. AI sessions are only ever referenced by session_id with no read
// endpoint, and video parses cannot even be added outside the IMA desktop app.
// Notes are NOT listed here: they are read through the note namespace, see
// fetchNote.
func isSkippableMediaType(t int32) bool {
return t == mediaTypeAISession || t == mediaTypeVideo
}
Loaded 100 of 5769 files, more files were not shown because too many files have changed in this diff. Show more