RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
Feat: connector go webdav (#18379)
mkaaad94a93748dbee
diff --git a/internal/syncer/connector/builtin.go b/internal/syncer/connector/builtin.goindex cd2ef1b1fa..ba0bd67e07 100644--- a/internal/syncer/connector/builtin.go+++ b/internal/syncer/connector/builtin.go@@ -37,6 +37,7 @@ func RegisterBuiltIns(registry *Registry) {registerBuiltIn(registry, "mysql", NewMySQLConnector)registerBuiltIn(registry, "postgresql", NewPostgreSQLConnector)registerBuiltIn(registry, "discord", NewDiscordConnector)+ registerBuiltIn(registry, "webdav", NewWebDAVConnector)}func registerBuiltIn[T Connector](registry *Registry, source string, factory func(map[string]any) (T, error)) {diff --git a/internal/syncer/connector/webdav.go b/internal/syncer/connector/webdav.gonew file mode 100644index 0000000000..a797bd3dd8--- /dev/null+++ b/internal/syncer/connector/webdav.go@@ -0,0 +1,607 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package connector++import (+ "bytes"+ "context"+ "encoding/xml"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "os"+ "path"+ "sort"+ "strconv"+ "strings"+ "time"+)++const (+ defaultWebDAVBatchSize = 2+ defaultWebDAVSizeThreshold = 20 * 1024 * 1024+ webdavRequestTimeout = 60 * time.Second+ maxWebDAVResponseSize = 32 * 1024 * 1024+ webdavPropfindBody = `<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><allprop/></propfind>`+)++var (+ webdavTextExtensions = map[string]struct{}{+ ".txt": {}, ".md": {}, ".mdx": {}, ".conf": {}, ".log": {}, ".json": {},+ ".csv": {}, ".tsv": {}, ".xml": {}, ".yml": {}, ".yaml": {}, ".sql": {},+ }+ webdavDocumentExtensions = map[string]struct{}{+ ".pdf": {}, ".docx": {}, ".pptx": {}, ".xlsx": {}, ".eml": {}, ".epub": {}, ".html": {},+ }+ webdavImageExtensions = map[string]struct{}{+ ".jpg": {}, ".jpeg": {}, ".png": {}, ".gif": {}, ".bmp": {}, ".tiff": {}, ".webp": {},+ }+)++// WebDAVConnector reads files from a WebDAV server.+type WebDAVConnector struct {+ baseURL string+ remotePath string+ batchSize int+ allowImages bool+ username string+ password string+ sizeThreshold int64+ client *webdavClient+ listFiles func(ctx context.Context, target string) ([]webdavFile, error)+ downloadFile func(ctx context.Context, fileURL string) ([]byte, error)+}++// NewWebDAVConnector creates a WebDAV connector from stored connector config.+func NewWebDAVConnector(config map[string]any) (*WebDAVConnector, error) {+ credentials, _ := config["credentials"].(map[string]any)+ baseURL := strings.TrimRight(strings.TrimSpace(stringConfig(config["base_url"])), "/")+ remotePath := normalizeWebDAVPath(stringConfig(config["remote_path"]))+ username := strings.TrimSpace(stringConfig(credentials["username"]))+ password := stringConfig(credentials["password"])+ connector := &WebDAVConnector{+ baseURL: baseURL,+ remotePath: remotePath,+ batchSize: configInt(config["batch_size"], defaultWebDAVBatchSize),+ allowImages: configBoolDefault(config["allow_images"], false),+ username: username,+ password: password,+ sizeThreshold: webDAVSizeThreshold(),+ client: &webdavClient{+ baseURL: baseURL,+ httpClient: &http.Client{+ Timeout: webdavRequestTimeout,+ },+ },+ }+ connector.client.username = username+ connector.client.password = password+ connector.listFiles = connector.client.listRecursive+ connector.downloadFile = connector.client.download+ return connector, nil+}++// Validate validates WebDAV settings and credentials by probing the remote path.+func (c *WebDAVConnector) Validate(ctx context.Context) error {+ if c == nil {+ return fmt.Errorf("webdav connector is nil")+ }+ if c.baseURL == "" {+ return fmt.Errorf("WebDAV base URL is required")+ }+ if c.username == "" || c.password == "" {+ return fmt.Errorf("WebDAV requires username and password credentials")+ }+ if c.batchSize <= 0 {+ return fmt.Errorf("batch_size must be a positive integer")+ }++ testPath := c.remotePath+ if testPath != "/" {+ testPath = strings.TrimRight(testPath, "/") + "/"+ }+ _, err := c.client.propfind(ctx, testPath)+ if err == nil {+ return nil+ }+ var statusErr *webdavStatusError+ if errors.As(err, &statusErr) {+ switch statusErr.status {+ case http.StatusUnauthorized:+ return fmt.Errorf("WebDAV credentials appear invalid or expired")+ case http.StatusForbidden:+ return fmt.Errorf("insufficient permissions to access path '%s' on WebDAV server", c.remotePath)+ case http.StatusNotFound:+ return fmt.Errorf("remote path '%s' does not exist on WebDAV server", c.remotePath)+ }+ }+ return fmt.Errorf("WebDAV validation failed for path '%s': %v", testPath, err)+}++// OpenSync opens one WebDAV sync session.+func (c *WebDAVConnector) OpenSync(ctx context.Context, request SyncRequest) (SyncSession, error) {+ files, err := c.listFiles(ctx, c.remotePath)+ if err != nil {+ return nil, err+ }+ start := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)+ if request.WindowStart != nil {+ start = *request.WindowStart+ }+ end := request.WindowEnd+ if end.IsZero() {+ end = time.Now().UTC()+ }++ nameCounts := webdavBasenameCounts(files)+ documents := make([]SourceDocument, 0, len(files))+ for _, file := range files {+ if !file.hasModified {+ file.modified = end+ }+ if !start.Before(file.modified) || file.modified.After(end) {+ continue+ }+ if !c.isAcceptedExtension(file) || !file.hasSize || file.size > c.sizeThreshold {+ continue+ }+ blob, err := c.downloadFile(ctx, file.url)+ if err != nil || len(blob) == 0 {+ continue+ }+ documents = append(documents, c.buildDocument(file, blob, nameCounts))+ }+ sort.Slice(documents, func(i, j int) bool { return documents[i].SourceID < documents[j].SourceID })++ session := &webdavSyncSession{documents: documents, batchSize: c.batchSize}+ session.applyResume(request.Resume)+ return session, nil+}++// OpenPrune opens one complete WebDAV prune snapshot session.+func (c *WebDAVConnector) OpenPrune(ctx context.Context, request PruneRequest) (PruneSession, error) {+ files, err := c.listFiles(ctx, c.remotePath)+ if err != nil {+ return nil, err+ }+ documents := make([]SlimDocument, 0, len(files))+ for _, file := range files {+ if !c.isAcceptedExtension(file) || !file.hasSize || file.size > c.sizeThreshold {+ continue+ }+ documents = append(documents, SlimDocument{SourceID: c.sourceID(file.url)})+ }+ sort.Slice(documents, func(i, j int) bool { return documents[i].SourceID < documents[j].SourceID })+ return &webdavPruneSession{documents: documents, batchSize: c.batchSize}, nil+}++func (c *WebDAVConnector) buildDocument(file webdavFile, blob []byte, nameCounts map[string]int) SourceDocument {+ return SourceDocument{+ SourceID: c.sourceID(file.url),+ SemanticIdentifier: webdavSemanticIdentifier(file, c.remotePath, nameCounts),+ Extension: webdavExtension(file.url),+ Blob: blob,+ UpdatedAt: file.modified,+ SizeBytes: file.size,+ Fingerprint: contentFingerprint(blob),+ }+}++func (c *WebDAVConnector) sourceID(fileURL string) string {+ return "webdav:" + c.baseURL + ":" + fileURL+}++func (c *WebDAVConnector) isAcceptedExtension(file webdavFile) bool {+ ext := webdavExtension(file.url)+ if _, ok := webdavTextExtensions[ext]; ok {+ return true+ }+ if _, ok := webdavDocumentExtensions[ext]; ok {+ return true+ }+ if c.allowImages {+ if _, ok := webdavImageExtensions[ext]; ok {+ return true+ }+ }+ return false+}++type webdavSyncSession struct {+ documents []SourceDocument+ batchSize int+ index int+}++// NextBatch returns the next WebDAV document batch.+func (s *webdavSyncSession) NextBatch(ctx context.Context) (SyncBatch, error) {+ if s.index >= len(s.documents) {+ return SyncBatch{}, io.EOF+ }+ end := s.index + s.batchSize+ if end > len(s.documents) {+ end = len(s.documents)+ }+ batchDocuments := s.documents[s.index:end]+ batch := SyncBatch{Documents: batchDocuments, Checkpoint: webdavSyncCheckpoint(batchDocuments[len(batchDocuments)-1])}+ s.index = end+ return batch, nil+}++// Close closes the WebDAV sync session.+func (s *webdavSyncSession) Close() error {+ return nil+}++// applyResume advances past the last committed WebDAV document when retrying a task.+func (s *webdavSyncSession) applyResume(checkpoint *SyncCheckpoint) {+ if checkpoint == nil {+ return+ }+ sourceID := firstNonEmpty(checkpoint.SourceID, checkpoint.Cursor)+ if sourceID == "" {+ return+ }+ for index, doc := range s.documents {+ if doc.SourceID == sourceID {+ s.index = index + 1+ return+ }+ }+}++// webdavSyncCheckpoint returns a resume point after a committed WebDAV document.+func webdavSyncCheckpoint(doc SourceDocument) *SyncCheckpoint {+ updatedAt := doc.UpdatedAt+ return &SyncCheckpoint{+ Cursor: doc.SourceID,+ SourceID: doc.SourceID,+ UpdatedAt: &updatedAt,+ }+}++type webdavPruneSession struct {+ documents []SlimDocument+ batchSize int+ index int+}++// NextBatch returns the next WebDAV prune snapshot batch.+func (s *webdavPruneSession) NextBatch(ctx context.Context) (PruneBatch, error) {+ if s.index >= len(s.documents) {+ return PruneBatch{}, io.EOF+ }+ end := s.index + s.batchSize+ if end > len(s.documents) {+ end = len(s.documents)+ }+ batch := PruneBatch{Documents: s.documents[s.index:end]}+ s.index = end+ return batch, nil+}++// Close closes the WebDAV prune session.+func (s *webdavPruneSession) Close() error {+ return nil+}++type webdavFile struct {+ url string+ isDir bool+ size int64+ hasSize bool+ modified time.Time+ hasModified bool+}++type webdavClient struct {+ baseURL string+ username string+ password string+ httpClient *http.Client+}++// listRecursive lists every file under target using Depth-1 PROPFIND walks.+func (c *webdavClient) listRecursive(ctx context.Context, target string) ([]webdavFile, error) {+ var files []webdavFile+ visited := map[string]struct{}{}+ var walk func(current string) error+ walk = func(current string) error {+ key := webDAVPathKey(current)+ if _, ok := visited[key]; ok {+ return nil+ }+ visited[key] = struct{}{}++ items, err := c.propfind(ctx, current)+ if err != nil {+ return err+ }+ for _, item := range items {+ if webDAVPathKey(item.url) == key {+ continue // the collection itself+ }+ if item.isDir {+ if err := walk(item.url); err != nil {+ return err+ }+ continue+ }+ files = append(files, item)+ }+ return nil+ }+ if err := walk(target); err != nil {+ return nil, err+ }+ return files, nil+}++// propfind issues a Depth-1 PROPFIND and parses the multistatus response.+func (c *webdavClient) propfind(ctx context.Context, target string) ([]webdavFile, error) {+ resolved, err := c.resolve(target)+ if err != nil {+ return nil, err+ }+ req, err := http.NewRequestWithContext(ctx, "PROPFIND", resolved, bytes.NewReader([]byte(webdavPropfindBody)))+ if err != nil {+ return nil, err+ }+ req.Header.Set("Depth", "1")+ req.Header.Set("Content-Type", "application/xml")+ if c.username != "" {+ req.SetBasicAuth(c.username, c.password)+ }+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusMultiStatus {+ return nil, &webdavStatusError{status: resp.StatusCode, url: resolved}+ }+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxWebDAVResponseSize))+ if err != nil {+ return nil, err+ }+ return parseWebDAVMultistatus(data, c.baseURL)+}++// download fetches a file body over GET.+func (c *webdavClient) download(ctx context.Context, fileURL string) ([]byte, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, fileURL, nil)+ if err != nil {+ return nil, err+ }+ if c.username != "" {+ req.SetBasicAuth(c.username, c.password)+ }+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ return nil, &webdavStatusError{status: resp.StatusCode, url: fileURL}+ }+ blob, err := io.ReadAll(io.LimitReader(resp.Body, maxWebDAVResponseSize+1))+ if err != nil {+ return nil, err+ }+ if len(blob) > maxWebDAVResponseSize {+ return nil, fmt.Errorf("webdav response exceeds maximum size of %d bytes", maxWebDAVResponseSize)+ }+ return blob, nil+}++// resolve joins a server-relative path or href onto the configured base URL.+func (c *webdavClient) resolve(target string) (string, error) {+ base, err := url.Parse(c.baseURL)+ if err != nil || base.Scheme == "" || base.Host == "" {+ return "", fmt.Errorf("invalid WebDAV base URL")+ }+ return resolveWebDAVURL(c.baseURL, target)+}++// resolveWebDAVURL joins a target onto a WebDAV base URL without letting a+// leading slash discard a non-root mount path.+func resolveWebDAVURL(baseURL, target string) (string, error) {+ base, err := url.Parse(baseURL)+ if err != nil {+ return "", err+ }+ ref, err := url.Parse(target)+ if err != nil {+ return "", err+ }+ if ref.IsAbs() || ref.Host != "" {+ if ref.Scheme == "" {+ ref.Scheme = base.Scheme+ }+ if ref.Scheme != base.Scheme || ref.Host != base.Host {+ return "", fmt.Errorf("webdav href resolves to a different origin than base URL: %s", ref.String())+ }+ return ref.String(), nil+ }+ resolved := *base+ switch {+ case base.Path == "" || base.Path == "/":+ resolved.Path = ref.Path+ case ref.Path == base.Path || strings.HasPrefix(ref.Path, base.Path+"/"):+ resolved.Path = ref.Path+ default:+ resolved.Path = strings.TrimRight(base.Path, "/") + "/" + strings.TrimLeft(ref.Path, "/")+ }+ resolved.RawPath = ""+ resolved.RawQuery = ref.RawQuery+ resolved.Fragment = ref.Fragment+ return resolved.String(), nil+}++type webdavStatusError struct {+ status int+ url string+}++func (e *webdavStatusError) Error() string {+ return fmt.Sprintf("webdav request failed with status %d for %s", e.status, e.url)+}++type webdavMultistatus struct {+ Responses []webdavResponse `xml:"response"`+}++type webdavResponse struct {+ Href string `xml:"href"`+ Propstat webdavPropstat `xml:"propstat"`+}++type webdavPropstat struct {+ Prop webdavProp `xml:"prop"`+}++type webdavProp struct {+ ResourceType webdavResourceType `xml:"resourcetype"`+ ContentLength string `xml:"getcontentlength"`+ GetLastModified string `xml:"getlastmodified"`+}++type webdavResourceType struct {+ Collection *string `xml:"collection"`+}++// parseWebDAVMultistatus converts a PROPFIND multistatus document into files.+func parseWebDAVMultistatus(data []byte, baseURL string) ([]webdavFile, error) {+ var status webdavMultistatus+ if err := xml.Unmarshal(data, &status); err != nil {+ return nil, fmt.Errorf("failed to parse WebDAV PROPFIND response: %w", err)+ }+ if _, err := url.Parse(baseURL); err != nil {+ return nil, fmt.Errorf("invalid WebDAV base URL")+ }+ files := make([]webdavFile, 0, len(status.Responses))+ for _, response := range status.Responses {+ href := strings.TrimSpace(response.Href)+ if href == "" {+ continue+ }+ fileURL, err := resolveWebDAVURL(baseURL, href)+ if err != nil {+ continue+ }+ file := webdavFile{+ url: fileURL,+ isDir: response.Propstat.Prop.ResourceType.Collection != nil,+ }+ if raw := strings.TrimSpace(response.Propstat.Prop.ContentLength); raw != "" {+ if size, err := strconv.ParseInt(raw, 10, 64); err == nil && size >= 0 {+ file.size = size+ file.hasSize = true+ }+ }+ if modified := parseFeedTime(response.Propstat.Prop.GetLastModified); !modified.IsZero() {+ file.modified = modified+ file.hasModified = true+ }+ files = append(files, file)+ }+ return files, nil+}++// webdavBasenameCounts counts basename occurrences across a listing.+func webdavBasenameCounts(files []webdavFile) map[string]int {+ counts := map[string]int{}+ for _, file := range files {+ counts[webdavBasename(file.url)]+++ }+ return counts+}++// webdavSemanticIdentifier prefers the file name, or the relative path when+// the name is not unique within one listing.+func webdavSemanticIdentifier(file webdavFile, remotePath string, nameCounts map[string]int) string {+ fileName := webdavBasename(file.url)+ if nameCounts[fileName] <= 1 {+ return fileName+ }+ parsed, err := url.Parse(file.url)+ if err != nil {+ return fileName+ }+ relative := strings.TrimPrefix(parsed.Path, remotePath)+ relative = strings.TrimPrefix(relative, "/")+ if relative == "" {+ return fileName+ }+ return strings.ReplaceAll(relative, "/", " / ")+}++func webdavBasename(fileURL string) string {+ parsed, err := url.Parse(fileURL)+ if err != nil {+ return ""+ }+ return path.Base(parsed.Path)+}++// webDAVPathKey normalizes a URL or server path to a comparable path key.+func webDAVPathKey(value string) string {+ parsed, err := url.Parse(value)+ if err != nil {+ return value+ }+ key := strings.TrimRight(parsed.Path, "/")+ if key == "" {+ return "/"+ }+ return key+}++func webdavExtension(fileURL string) string {+ parsed, err := url.Parse(fileURL)+ if err != nil {+ return ""+ }+ return strings.ToLower(path.Ext(parsed.Path))+}++// normalizeWebDAVPath normalizes a remote path the same way as the connector config.+func normalizeWebDAVPath(remotePath string) string {+ remotePath = strings.TrimSpace(remotePath)+ if remotePath == "" {+ return "/"+ }+ if !strings.HasPrefix(remotePath, "/") {+ remotePath = "/" + remotePath+ }+ if strings.HasSuffix(remotePath, "/") && remotePath != "/" {+ remotePath = strings.TrimRight(remotePath, "/")+ }+ return remotePath+}++// webDAVSizeThreshold returns the configured blob size threshold.+func webDAVSizeThreshold() int64 {+ if raw := strings.TrimSpace(os.Getenv("BLOB_STORAGE_SIZE_THRESHOLD")); raw != "" {+ if parsed, err := strconv.ParseInt(raw, 10, 64); err == nil && parsed > 0 {+ return parsed+ }+ }+ return defaultWebDAVSizeThreshold+}diff --git a/internal/syncer/connector/webdav_test.go b/internal/syncer/connector/webdav_test.gonew file mode 100644index 0000000000..2043398f51--- /dev/null+++ b/internal/syncer/connector/webdav_test.go@@ -0,0 +1,629 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package connector++import (+ "bytes"+ "context"+ "encoding/base64"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++type webdavTestFile struct {+ content string+ size int64+ hasSize bool+ modified string+ isDir bool+}++// newWebDAVTestServer serves a small static WebDAV tree.+func newWebDAVTestServer(t *testing.T, files map[string]webdavTestFile) (*httptest.Server, *[]string, *[]string) {+ t.Helper()+ return newWebDAVTestServerAtMount(t, "", files)+}++// newWebDAVMountedTestServer serves a small static WebDAV tree under a non-root endpoint path.+func newWebDAVMountedTestServer(t *testing.T, mountPath string, files map[string]webdavTestFile) (*httptest.Server, *[]string, *[]string) {+ t.Helper()+ return newWebDAVTestServerAtMount(t, mountPath, files)+}++func newWebDAVTestServerAtMount(t *testing.T, mountPath string, files map[string]webdavTestFile) (*httptest.Server, *[]string, *[]string) {+ t.Helper()+ var authHeaders []string+ var getRequests []string+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ username, password, ok := r.BasicAuth()+ if !ok || username != "user" || password != "pass" {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ authHeaders = append(authHeaders, r.Header.Get("Authorization"))+ if mountPath != "" && !strings.HasPrefix(r.URL.Path, mountPath) {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ apiPath := strings.TrimPrefix(r.URL.Path, mountPath)+ if apiPath == "" {+ apiPath = "/"+ }++ switch r.Method {+ case "PROPFIND":+ if _, ok := files[apiPath]; !ok {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ var body bytes.Buffer+ body.WriteString(`<?xml version="1.0" encoding="utf-8"?>` + "\n")+ body.WriteString(`<D:multistatus xmlns:D="DAV:">` + "\n")+ writeWebDAVTestResponse(&body, r.URL.Path, files[apiPath])+ for itemPath, item := range files {+ if itemPath != apiPath && webDAVTestParent(itemPath) == apiPath {+ href := itemPath+ if mountPath != "" {+ href = mountPath + itemPath+ }+ writeWebDAVTestResponse(&body, href, item)+ }+ }+ body.WriteString(`</D:multistatus>`)+ w.Header().Set("Content-Type", "application/xml")+ w.WriteHeader(http.StatusMultiStatus)+ _, _ = io.WriteString(w, body.String())+ case "GET":+ entry, ok := files[apiPath]+ if !ok || entry.isDir {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ getRequests = append(getRequests, r.URL.Path)+ _, _ = io.WriteString(w, entry.content)+ default:+ w.WriteHeader(http.StatusMethodNotAllowed)+ }+ })+ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)+ return server, &authHeaders, &getRequests+}++func writeWebDAVTestResponse(body *bytes.Buffer, href string, file webdavTestFile) {+ body.WriteString(`<D:response><D:href>` + href + `</D:href><D:propstat><D:prop>`)+ if file.isDir {+ body.WriteString(`<D:resourcetype><D:collection/></D:resourcetype>`)+ }+ if file.hasSize {+ fmt.Fprintf(body, `<D:getcontentlength>%d</D:getcontentlength>`, file.size)+ }+ if file.modified != "" {+ body.WriteString(`<D:getlastmodified>` + file.modified + `</D:getlastmodified>`)+ }+ body.WriteString(`</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>`)+}++func webDAVTestParent(itemPath string) string {+ trimmed := strings.TrimRight(itemPath, "/")+ if trimmed == "" {+ return "/"+ }+ index := strings.LastIndex(trimmed, "/")+ if index < 0 {+ return "/"+ }+ return trimmed[:index+1]+}++func webDAVTestTree() map[string]webdavTestFile {+ return map[string]webdavTestFile{+ "/": {isDir: true},+ "/notes/": {isDir: true},+ "/notes/alpha.txt": {content: "hello alpha", size: 11, hasSize: true, modified: "Fri, 02 Jan 2026 00:00:00 GMT"},+ "/notes/beta.md": {content: "hello beta", size: 10, hasSize: true, modified: "Sat, 03 Jan 2026 00:00:00 GMT"},+ "/notes/big.bin": {content: "bin", size: 3, hasSize: true, modified: "Thu, 01 Jan 2026 00:00:00 GMT"},+ "/notes/skip.png": {content: "png", size: 3, hasSize: true, modified: "Thu, 01 Jan 2026 00:00:00 GMT"},+ "/notes/nosize.txt": {content: "x", hasSize: false, modified: "Thu, 01 Jan 2026 00:00:00 GMT"},+ "/notes/huge.txt": {content: "huge", size: 21, hasSize: true, modified: "Thu, 01 Jan 2026 00:00:00 GMT"},+ "/docs/": {isDir: true},+ "/docs/alpha.txt": {content: "hello alpha docs", size: 15, hasSize: true, modified: "Fri, 02 Jan 2026 00:00:00 GMT"},+ "/docs/gamma.pdf": {content: "hello gamma", size: 11, hasSize: true, modified: "Tue, 06 Jan 2026 00:00:00 GMT"},+ }+}++func webDAVTestConnector(t *testing.T, serverURL string, allowImages bool, batchSize int) *WebDAVConnector {+ t.Helper()+ config := map[string]any{+ "base_url": serverURL,+ "remote_path": "/",+ "batch_size": batchSize,+ "allow_images": allowImages,+ "credentials": map[string]any{+ "username": "user",+ "password": "pass",+ },+ }+ connector, err := NewWebDAVConnector(config)+ if err != nil {+ t.Fatalf("NewWebDAVConnector failed: %v", err)+ }+ return connector+}++func TestWebDAVConnectorValidate(t *testing.T) {+ server, _, _ := newWebDAVTestServer(t, webDAVTestTree())++ connector := webDAVTestConnector(t, server.URL, false, 2)+ if err := connector.Validate(context.Background()); err != nil {+ t.Fatalf("Validate failed: %v", err)+ }++ missingCredentials, err := NewWebDAVConnector(map[string]any{+ "base_url": server.URL,+ "credentials": map[string]any{},+ })+ if err != nil {+ t.Fatalf("NewWebDAVConnector failed: %v", err)+ }+ if err := missingCredentials.Validate(context.Background()); err == nil || !strings.Contains(err.Error(), "username and password") {+ t.Fatalf("missing credentials error = %v", err)+ }++ badPassword, err := NewWebDAVConnector(map[string]any{+ "base_url": server.URL,+ "credentials": map[string]any{+ "username": "user",+ "password": "wrong",+ },+ })+ if err != nil {+ t.Fatalf("NewWebDAVConnector failed: %v", err)+ }+ if err := badPassword.Validate(context.Background()); err == nil || !strings.Contains(err.Error(), "credentials appear invalid") {+ t.Fatalf("bad password error = %v", err)+ }++ missingPath, err := NewWebDAVConnector(map[string]any{+ "base_url": server.URL,+ "remote_path": "/missing",+ "credentials": map[string]any{+ "username": "user",+ "password": "pass",+ },+ })+ if err != nil {+ t.Fatalf("NewWebDAVConnector failed: %v", err)+ }+ if err := missingPath.Validate(context.Background()); err == nil || !strings.Contains(err.Error(), "does not exist") {+ t.Fatalf("missing path error = %v", err)+ }+}++func TestWebDAVConnectorOpenSyncFull(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", "20")+ server, authHeaders, _ := newWebDAVTestServer(t, webDAVTestTree())+ connector := webDAVTestConnector(t, server.URL, false, 2)++ session, err := connector.OpenSync(context.Background(), SyncRequest{+ FromBeginning: true,+ WindowEnd: mustTime(t, "2026-01-07T00:00:00Z"),+ })+ if err != nil {+ t.Fatalf("OpenSync failed: %v", err)+ }+ defer session.Close()++ first, err := session.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch first failed: %v", err)+ }+ if len(first.Documents) != 2 {+ t.Fatalf("first batch len = %d, want 2: %+v", len(first.Documents), first.Documents)+ }+ alphaDocs := first.Documents[0]+ if alphaDocs.SourceID != "webdav:"+server.URL+":"+server.URL+"/docs/alpha.txt" {+ t.Fatalf("docs alpha source id = %s", alphaDocs.SourceID)+ }+ if alphaDocs.SemanticIdentifier != "docs / alpha.txt" {+ t.Fatalf("docs alpha semantic identifier = %q", alphaDocs.SemanticIdentifier)+ }+ if alphaDocs.Extension != ".txt" {+ t.Fatalf("docs alpha extension = %q", alphaDocs.Extension)+ }+ if string(alphaDocs.Blob) != "hello alpha docs" || alphaDocs.SizeBytes != 15 {+ t.Fatalf("docs alpha blob/size = %q/%d", alphaDocs.Blob, alphaDocs.SizeBytes)+ }+ if !alphaDocs.UpdatedAt.Equal(mustTime(t, "2026-01-02T00:00:00Z")) {+ t.Fatalf("docs alpha updated at = %v", alphaDocs.UpdatedAt)+ }+ if alphaDocs.Fingerprint == "" {+ t.Fatalf("docs alpha fingerprint is empty")+ }+ if first.Checkpoint == nil || first.Checkpoint.SourceID != "webdav:"+server.URL+":"+server.URL+"/docs/gamma.pdf" {+ t.Fatalf("first checkpoint = %+v", first.Checkpoint)+ }++ second, err := session.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch second failed: %v", err)+ }+ if len(second.Documents) != 2 {+ t.Fatalf("second batch len = %d, want 2", len(second.Documents))+ }+ notesAlpha := second.Documents[0]+ if notesAlpha.SourceID != "webdav:"+server.URL+":"+server.URL+"/notes/alpha.txt" {+ t.Fatalf("notes alpha source id = %s", notesAlpha.SourceID)+ }+ if notesAlpha.SemanticIdentifier != "notes / alpha.txt" {+ t.Fatalf("notes alpha semantic identifier = %q", notesAlpha.SemanticIdentifier)+ }+ if string(second.Documents[1].Blob) != "hello beta" {+ t.Fatalf("beta blob = %q", second.Documents[1].Blob)+ }++ if _, err := session.NextBatch(context.Background()); !errors.Is(err, io.EOF) {+ t.Fatalf("NextBatch EOF = %v", err)+ }++ expectedAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("user:pass"))+ if len(*authHeaders) == 0 || (*authHeaders)[0] != expectedAuth {+ t.Fatalf("auth headers = %v, want %s", *authHeaders, expectedAuth)+ }+}++func TestWebDAVConnectorOpenSyncIncremental(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", "20")+ server, _, _ := newWebDAVTestServer(t, webDAVTestTree())+ connector := webDAVTestConnector(t, server.URL, false, 2)++ start := mustTime(t, "2026-01-02T00:00:00Z")+ session, err := connector.OpenSync(context.Background(), SyncRequest{+ WindowStart: &start,+ WindowEnd: mustTime(t, "2026-01-04T00:00:00Z"),+ })+ if err != nil {+ t.Fatalf("OpenSync failed: %v", err)+ }+ defer session.Close()++ batch, err := session.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch failed: %v", err)+ }+ if len(batch.Documents) != 1 {+ t.Fatalf("incremental batch len = %d, want 1: %+v", len(batch.Documents), batch.Documents)+ }+ if batch.Documents[0].SemanticIdentifier != "beta.md" {+ t.Fatalf("incremental document = %q", batch.Documents[0].SemanticIdentifier)+ }+}++func TestWebDAVConnectorMountedUnderNonRootPath(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", "20")+ server, _, getRequests := newWebDAVMountedTestServer(t, "/webdav", webDAVTestTree())+ connector := webDAVTestConnector(t, server.URL+"/webdav", false, 10)++ resolved, err := connector.client.resolve("/notes")+ if err != nil {+ t.Fatalf("resolve failed: %v", err)+ }+ if resolved != server.URL+"/webdav/notes" {+ t.Fatalf("resolved URL = %q, want %q", resolved, server.URL+"/webdav/notes")+ }++ if err := connector.Validate(context.Background()); err != nil {+ t.Fatalf("Validate failed: %v", err)+ }++ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true, WindowEnd: mustTime(t, "2026-01-07T00:00:00Z")})+ if err != nil {+ t.Fatalf("OpenSync failed: %v", err)+ }+ defer session.Close()+ batch, err := session.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch failed: %v", err)+ }+ if len(batch.Documents) != 4 {+ t.Fatalf("batch len = %d, want 4: %+v", len(batch.Documents), batch.Documents)+ }+ mountedSourceID := "webdav:" + server.URL + "/webdav:" + server.URL + "/webdav/notes/alpha.txt"+ foundMountedSourceID := false+ for _, doc := range batch.Documents {+ if doc.SourceID == mountedSourceID {+ foundMountedSourceID = true+ }+ if !strings.HasPrefix(doc.SourceID, "webdav:"+server.URL+"/webdav:") {+ t.Fatalf("source id escaped mount path: %q", doc.SourceID)+ }+ }+ if !foundMountedSourceID {+ t.Fatalf("missing mounted source id %q in %+v", mountedSourceID, batch.Documents)+ }+ if len(*getRequests) != 4 {+ t.Fatalf("download requests = %d, want 4: %v", len(*getRequests), *getRequests)+ }+ for _, requestPath := range *getRequests {+ if !strings.HasPrefix(requestPath, "/webdav/") {+ t.Fatalf("download request escaped mount path: %q", requestPath)+ }+ }+ if _, err := session.NextBatch(context.Background()); !errors.Is(err, io.EOF) {+ t.Fatalf("NextBatch EOF = %v", err)+ }+}++func TestWebDAVConnectorOpenSyncIncludesSizedFileWithoutLastModified(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", "20")+ server, _, _ := newWebDAVTestServer(t, map[string]webdavTestFile{+ "/": {isDir: true},+ "/notes/": {isDir: true},+ "/notes/nomod.txt": {content: "no modified", size: 12, hasSize: true},+ })+ connector := webDAVTestConnector(t, server.URL, false, 10)++ windowEnd := mustTime(t, "2026-01-02T00:00:00Z")+ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true, WindowEnd: windowEnd})+ if err != nil {+ t.Fatalf("OpenSync failed: %v", err)+ }+ defer session.Close()+ batch, err := session.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch failed: %v", err)+ }+ if len(batch.Documents) != 1 {+ t.Fatalf("batch len = %d, want 1: %+v", len(batch.Documents), batch.Documents)+ }+ if !batch.Documents[0].UpdatedAt.Equal(windowEnd) {+ t.Fatalf("updated at = %v, want %v", batch.Documents[0].UpdatedAt, windowEnd)+ }++ unsetSession, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true})+ if err != nil {+ t.Fatalf("OpenSync with unset WindowEnd failed: %v", err)+ }+ defer unsetSession.Close()+ unsetBatch, err := unsetSession.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch with unset WindowEnd failed: %v", err)+ }+ if len(unsetBatch.Documents) != 1 {+ t.Fatalf("unset window batch len = %d, want 1: %+v", len(unsetBatch.Documents), unsetBatch.Documents)+ }+ if batch.Documents[0].SourceID != unsetBatch.Documents[0].SourceID {+ t.Fatalf("unset window source id = %q", unsetBatch.Documents[0].SourceID)+ }+ if string(unsetBatch.Documents[0].Blob) != "no modified" {+ t.Fatalf("unset window blob = %q", unsetBatch.Documents[0].Blob)+ }+ if unsetBatch.Documents[0].UpdatedAt.IsZero() {+ t.Fatalf("unset window updated at is zero")+ }+}++func TestWebDAVConnectorOpenSyncRejectsOversizedResponse(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", fmt.Sprintf("%d", maxWebDAVResponseSize+1))+ content := strings.Repeat("x", maxWebDAVResponseSize+1)+ server, _, getRequests := newWebDAVTestServer(t, map[string]webdavTestFile{+ "/": {isDir: true},+ "/notes/": {isDir: true},+ "/notes/large.txt": {content: content, size: int64(len(content)), hasSize: true, modified: "Fri, 02 Jan 2026 00:00:00 GMT"},+ })+ connector := webDAVTestConnector(t, server.URL, false, 10)++ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true, WindowEnd: mustTime(t, "2026-01-07T00:00:00Z")})+ if err != nil {+ t.Fatalf("OpenSync failed: %v", err)+ }+ defer session.Close()+ if _, err := session.NextBatch(context.Background()); !errors.Is(err, io.EOF) {+ t.Fatalf("NextBatch = %v, want EOF", err)+ }+ if len(*getRequests) != 1 {+ t.Fatalf("download requests = %d, want 1", len(*getRequests))+ }+}++func TestWebDAVConnectorOpenSyncResumesAfterCheckpoint(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", "20")+ server, _, _ := newWebDAVTestServer(t, webDAVTestTree())+ connector := webDAVTestConnector(t, server.URL, false, 2)++ windowEnd := mustTime(t, "2026-01-07T00:00:00Z")+ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true, WindowEnd: windowEnd})+ if err != nil {+ t.Fatalf("OpenSync failed: %v", err)+ }+ first, err := session.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch first failed: %v", err)+ }+ if first.Checkpoint == nil {+ t.Fatalf("first checkpoint is nil")+ }+ session.Close()++ resumed, err := connector.OpenSync(context.Background(), SyncRequest{+ FromBeginning: true,+ WindowEnd: windowEnd,+ Resume: first.Checkpoint,+ })+ if err != nil {+ t.Fatalf("resume OpenSync failed: %v", err)+ }+ defer resumed.Close()+ second, err := resumed.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("resume NextBatch failed: %v", err)+ }+ if len(second.Documents) != 2 || second.Documents[0].SemanticIdentifier != "notes / alpha.txt" {+ t.Fatalf("resume documents = %+v", second.Documents)+ }+ if second.Checkpoint == nil || second.Checkpoint.SourceID != "webdav:"+server.URL+":"+server.URL+"/notes/beta.md" {+ t.Fatalf("resume checkpoint = %+v", second.Checkpoint)+ }+ if _, err := resumed.NextBatch(context.Background()); !errors.Is(err, io.EOF) {+ t.Fatalf("resume EOF = %v", err)+ }+}++func TestWebDAVConnectorOpenPrune(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", "20")+ server, _, getRequests := newWebDAVTestServer(t, webDAVTestTree())+ connector := webDAVTestConnector(t, server.URL, false, 10)++ session, err := connector.OpenPrune(context.Background(), PruneRequest{})+ if err != nil {+ t.Fatalf("OpenPrune failed: %v", err)+ }+ defer session.Close()+ batch, err := session.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch failed: %v", err)+ }+ if len(batch.Documents) != 4 {+ t.Fatalf("prune batch len = %d, want 4: %+v", len(batch.Documents), batch.Documents)+ }+ if batch.Documents[0].SourceID != "webdav:"+server.URL+":"+server.URL+"/docs/alpha.txt" ||+ batch.Documents[3].SourceID != "webdav:"+server.URL+":"+server.URL+"/notes/beta.md" {+ t.Fatalf("unexpected prune ids: %+v", batch.Documents)+ }+ if len(*getRequests) != 0 {+ t.Fatalf("prune must not download files, got GETs: %v", *getRequests)+ }+ if _, err := session.NextBatch(context.Background()); !errors.Is(err, io.EOF) {+ t.Fatalf("prune EOF = %v", err)+ }+}++func TestWebDAVConnectorFiltersAndImages(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", "20")+ server, _, _ := newWebDAVTestServer(t, webDAVTestTree())++ withoutImages := webDAVTestConnector(t, server.URL, false, 10)+ session, err := withoutImages.OpenSync(context.Background(), SyncRequest{FromBeginning: true, WindowEnd: mustTime(t, "2026-01-07T00:00:00Z")})+ if err != nil {+ t.Fatalf("OpenSync failed: %v", err)+ }+ defer session.Close()+ batch, err := session.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch failed: %v", err)+ }+ for _, doc := range batch.Documents {+ if strings.Contains(doc.SourceID, "skip.png") || strings.Contains(doc.SourceID, "huge.txt") ||+ strings.Contains(doc.SourceID, "nosize.txt") || strings.Contains(doc.SourceID, "big.bin") {+ t.Fatalf("filtered document leaked into batch: %s", doc.SourceID)+ }+ }++ withImages := webDAVTestConnector(t, server.URL, true, 10)+ imageSession, err := withImages.OpenSync(context.Background(), SyncRequest{FromBeginning: true, WindowEnd: mustTime(t, "2026-01-07T00:00:00Z")})+ if err != nil {+ t.Fatalf("OpenSync with images failed: %v", err)+ }+ defer imageSession.Close()+ imageBatch, err := imageSession.NextBatch(context.Background())+ if err != nil {+ t.Fatalf("NextBatch with images failed: %v", err)+ }+ if len(imageBatch.Documents) != 5 {+ t.Fatalf("with images batch len = %d, want 5", len(imageBatch.Documents))+ }+}++// TestWebDAVConnectorOpenSyncRejectsExternalHref verifies that PROPFIND responses+// containing absolute or protocol-relative hrefs to a different origin are rejected+// at URL resolution time, preventing any GET to the external host.+func TestWebDAVConnectorOpenSyncRejectsExternalHref(t *testing.T) {+ t.Setenv("BLOB_STORAGE_SIZE_THRESHOLD", "20")++ var externalRequests int+ externalServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ externalRequests+++ w.WriteHeader(http.StatusNotFound)+ }))+ t.Cleanup(externalServer.Close)+ externalHost := strings.TrimPrefix(externalServer.URL, "http://")++ var getPaths []string+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == "GET" {+ getPaths = append(getPaths, r.URL.Path)+ }+ if r.Method != "PROPFIND" {+ w.WriteHeader(http.StatusMethodNotAllowed)+ return+ }+ w.Header().Set("Content-Type", "application/xml")+ w.WriteHeader(http.StatusMultiStatus)+ _, _ = io.WriteString(w, fmt.Sprintf(`<?xml version="1.0" encoding="utf-8"?>+<D:multistatus xmlns:D="DAV:">+<D:response><D:href>/</D:href><D:propstat><D:prop><D:resourcetype><D:collection/></D:resourcetype></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>+<D:response><D:href>/notes/alpha.txt</D:href><D:propstat><D:prop><D:getcontentlength>11</D:getcontentlength><D:getlastmodified>Fri, 02 Jan 2026 00:00:00 GMT</D:getlastmodified></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>+<D:response><D:href>%s/secret.txt</D:href><D:propstat><D:prop><D:getcontentlength>5</D:getcontentlength><D:getlastmodified>Fri, 02 Jan 2026 00:00:00 GMT</D:getlastmodified></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>+<D:response><D:href>//%s/secret.txt</D:href><D:propstat><D:prop><D:getcontentlength>5</D:getcontentlength><D:getlastmodified>Fri, 02 Jan 2026 00:00:00 GMT</D:getlastmodified></D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>+</D:multistatus>`, externalServer.URL, externalHost))+ })+ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)++ // Build connector without auth so the test handler stays simple.+ connector, err := NewWebDAVConnector(map[string]any{+ "base_url": server.URL,+ "remote_path": "/",+ "batch_size": 10,+ })+ if err != nil {+ t.Fatalf("NewWebDAVConnector failed: %v", err)+ }++ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true, WindowEnd: mustTime(t, "2026-01-07T00:00:00Z")})+ if err != nil {+ t.Fatalf("OpenSync failed: %v", err)+ }+ defer session.Close()++ for {+ batch, batchErr := session.NextBatch(context.Background())+ if errors.Is(batchErr, io.EOF) {+ break+ }+ if batchErr != nil {+ t.Fatalf("NextBatch failed: %v", batchErr)+ }+ for _, doc := range batch.Documents {+ if strings.Contains(doc.SourceID, externalHost) {+ t.Fatalf("external href leaked into sync results: %s", doc.SourceID)+ }+ }+ }++ if externalRequests != 0 {+ t.Fatalf("external server received %d request(s), want 0", externalRequests)+ }+ if len(getPaths) == 0 {+ t.Fatalf("expected GET for the legitimate file")+ }+}