fix: deep-copy stored files and images when cloning a knowledge base

Cloning a knowledge base previously copied only the storage path strings
(knowledge.FilePath and chunk.ImageInfo.URL), so the source and the clone
shared the same physical objects in the storage backend. Once the original
file and extracted images are deleted on source removal, the clone is left
with dangling references and its document and images become unreadable —
data loss that occurs even for same-store clones.

Add a CopyFile primitive to the FileService interface and implement it in
every backend: server-side CopyObject on the object stores
(s3/obs/cos/oss/tos/ks3/minio), io.Copy on local, and a no-op on dummy.
Destinations use the knowledge-owned layout and reuse the existing
path/object-key guards; a sentinel ErrCrossBackendCopy is returned when the
source scheme does not match the backend.

Use CopyFile to deep-copy the document file in cloneKnowledge and the
extracted images in CloneChunk and cloneFAQKnowledgeBase via a shared
cloneChunkImageInfo helper that deduplicates identical image URLs per clone
and rewrites them to the new objects. Copied objects are cleaned up
best-effort if a clone fails partway through. A clone-time preflight rejects
cloning into a target bound to a different storage backend when the tenant
pins providers via StorageEngineConfig.

Adds unit tests for local CopyFile (independent copy survives source
deletion, traversal rejection, cross-backend rejection), cloneChunkImageInfo
(empty/multi/dedup/parse-failure/OriginalURL handling), and the storage
provider preflight.
This commit is contained in:
ochan.kwon
2026-06-02 20:25:38 +09:00
committed by lyingbug
parent f4af9cca97
commit e9980c6011
25 changed files with 918 additions and 12 deletions
+29
View File
@@ -175,6 +175,35 @@ func (s *cosFileService) parseCosObjectName(filePath string) (string, error) {
return strings.TrimPrefix(filePath, s.bucketURL), nil
}
// CopyFile copies an existing COS object to a new knowledge-owned object using a
// server-side Object.Copy (no data leaves COS). The destination uses the same
// layout as SaveFile. Returns ErrCrossBackendCopy when srcPath is not a cos:// path.
func (s *cosFileService) CopyFile(ctx context.Context,
srcPath string, tenantID uint64, knowledgeID string,
) (string, error) {
srcObjectKey, err := s.parseCosObjectName(srcPath)
if err != nil {
return "", fmt.Errorf("cos copy rejected source %q: %w", srcPath, ErrCrossBackendCopy)
}
if err := utils.SafeObjectKey(srcObjectKey); err != nil {
return "", fmt.Errorf("invalid source path: %w", err)
}
ext := filepath.Ext(srcPath)
destKey := fmt.Sprintf("%s/%d/%s/%s%s", s.cosPathPrefix, tenantID, knowledgeID, uuid.New().String(), ext)
// sourceURL is the host + object key WITHOUT a scheme, per the COS SDK contract.
sourceURL := fmt.Sprintf("%s.cos.%s.myqcloud.com/%s", s.bucketName, s.region, srcObjectKey)
_, _, err = s.client.Object.Copy(ctx, destKey, sourceURL, nil)
if err != nil {
return "", fmt.Errorf("failed to copy file in COS: %w", err)
}
newPath := fmt.Sprintf("cos://%s/%s/%s", s.bucketName, s.region, destKey)
logger.Infof(ctx, "Copied COS object %s to %s", srcPath, newPath)
return newPath, nil
}
// SaveBytes saves bytes data to COS
// If temp is true and temp bucket is configured, saves to temp bucket (with lifecycle auto-expiration)
// Otherwise saves to main bucket
@@ -6,6 +6,7 @@ import (
"io"
"mime/multipart"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
@@ -47,6 +48,13 @@ func (s *DummyFileService) SaveBytes(ctx context.Context, data []byte, tenantID
return uuid.New().String(), nil
}
// CopyFile is a no-op for the dummy service: it logs a warning and returns the
// source path unchanged (the shared reference is intentional in this stub).
func (s *DummyFileService) CopyFile(ctx context.Context, srcPath string, tenantID uint64, knowledgeID string) (string, error) {
logger.Warnf(ctx, "[dummy] CopyFile no-op: returning source path %q unchanged (no real copy performed)", srcPath)
return srcPath, nil
}
// GetFileURL returns the file path as URL (dummy implementation)
func (s *DummyFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
return filePath, nil
@@ -0,0 +1,9 @@
package file
import "errors"
// ErrCrossBackendCopy is returned by CopyFile implementations when the source
// path belongs to a different storage provider than the destination service.
// PR1 only supports same-backend (server-side) copies; cross-backend streaming
// copy is intentionally not implemented yet.
var ErrCrossBackendCopy = errors.New("file: cross-backend copy not supported")
+33
View File
@@ -10,6 +10,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
@@ -177,6 +178,38 @@ func (s *ks3FileService) SaveBytes(ctx context.Context, data []byte, tenantID ui
return fmt.Sprintf("%s%s/%s", ks3Scheme, s.bucketName, objectKey), nil
}
// CopyFile copies an existing KS3 object to a new knowledge-owned object using a
// server-side CopyObject (no data leaves KS3). The destination uses the same
// layout as SaveFile. Returns ErrCrossBackendCopy when srcPath is not a ks3:// path.
func (s *ks3FileService) CopyFile(ctx context.Context,
srcPath string, tenantID uint64, knowledgeID string,
) (string, error) {
srcBucket, srcKey, err := parseKS3FilePath(srcPath)
if err != nil {
return "", fmt.Errorf("ks3 copy rejected source %q: %w", srcPath, ErrCrossBackendCopy)
}
if err := utils.SafeObjectKey(srcKey); err != nil {
return "", fmt.Errorf("invalid source path: %w", err)
}
ext := filepath.Ext(srcPath)
destKey := joinKS3Key(s.pathPrefix, fmt.Sprintf("%d", tenantID), knowledgeID, uuid.New().String()+ext)
_, err = s.client.CopyObject(&ks3s3.CopyObjectInput{
Bucket: ks3aws.String(s.bucketName),
Key: ks3aws.String(destKey),
SourceBucket: ks3aws.String(srcBucket),
SourceKey: ks3aws.String(srcKey),
})
if err != nil {
return "", fmt.Errorf("failed to copy file in KS3: %w", err)
}
newPath := fmt.Sprintf("%s%s/%s", ks3Scheme, s.bucketName, destKey)
logger.Infof(ctx, "Copied KS3 object %s to %s", srcPath, newPath)
return newPath, nil
}
func (s *ks3FileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
_, objectKey, err := parseKS3FilePath(filePath)
if err != nil {
@@ -151,6 +151,64 @@ func (s *localFileService) DeleteFile(ctx context.Context, filePath string) erro
return nil
}
// CopyFile copies an existing local object to a new knowledge-owned object.
// The destination uses the same layout as SaveFile (baseDir/{tenantID}/{knowledgeID}/{unique}{ext}),
// and the copy is a real byte-for-byte copy (no hardlink) so deleting the source
// never affects it. Returns ErrCrossBackendCopy when srcPath is not a local path.
func (s *localFileService) CopyFile(ctx context.Context,
srcPath string, tenantID uint64, knowledgeID string,
) (string, error) {
// Only local paths are accepted. A provider scheme other than local://
// (e.g. s3://, minio://) means a cross-backend copy, which this service
// does not support. Legacy bare/absolute paths have no scheme and pass.
if i := strings.Index(srcPath, "://"); i >= 0 && srcPath[:i+3] != localScheme {
return "", fmt.Errorf("local file service cannot copy %q: %w", srcPath, ErrCrossBackendCopy)
}
// Validate and resolve the source path under baseDir (same guard as GetFile).
srcCandidate := s.normalizePathForBase(srcPath)
srcResolved, err := secutils.SafePathUnderBase(s.baseDir, srcCandidate)
if err != nil {
logger.Errorf(ctx, "Path traversal denied for CopyFile src: %v", err)
return "", fmt.Errorf("invalid source path: %w", err)
}
// Build destination path with the knowledge-owned layout.
dir := filepath.Join(s.baseDir, fmt.Sprintf("%d", tenantID), knowledgeID)
if _, err := secutils.SafePathUnderBase(s.baseDir, dir); err != nil {
logger.Errorf(ctx, "Path traversal denied for CopyFile dir: %v", err)
return "", fmt.Errorf("invalid path: %w", err)
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", fmt.Errorf("failed to create directory: %w", err)
}
ext := filepath.Ext(srcPath)
filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
dstPath := filepath.Join(dir, filename)
src, err := os.Open(srcResolved)
if err != nil {
return "", fmt.Errorf("failed to open source file: %w", err)
}
defer src.Close()
dst, err := os.Create(dstPath)
if err != nil {
return "", fmt.Errorf("failed to create destination file: %w", err)
}
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
return "", fmt.Errorf("failed to copy file content: %w", err)
}
relPath, _ := filepath.Rel(s.baseDir, dstPath)
newPath := localScheme + filepath.ToSlash(relPath)
logger.Infof(ctx, "Copied local file %s to %s", srcPath, newPath)
return newPath, nil
}
// SaveBytes saves bytes data to a file and returns the file path
// temp parameter is ignored for local storage (no auto-expiration support)
// fileName 仅允许安全文件名,禁止路径遍历(如 ../../)
@@ -0,0 +1,90 @@
package file
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// seedLocalObject writes a file under baseDir at the SaveBytes-style layout
// (tenant/exports) and returns its local:// path.
func seedLocalObject(t *testing.T, baseDir string, tenantID uint64, name string, data []byte) string {
t.Helper()
dir := filepath.Join(baseDir, "0", "src-knowledge")
require.NoError(t, os.MkdirAll(dir, 0o755))
full := filepath.Join(dir, name)
require.NoError(t, os.WriteFile(full, data, 0o644))
rel, err := filepath.Rel(baseDir, full)
require.NoError(t, err)
return localScheme + filepath.ToSlash(rel)
}
func readLocal(t *testing.T, svc interface {
GetFile(context.Context, string) (io.ReadCloser, error)
}, path string) []byte {
t.Helper()
rc, err := svc.GetFile(context.Background(), path)
require.NoError(t, err)
defer rc.Close()
b, err := io.ReadAll(rc)
require.NoError(t, err)
return b
}
// TestLocalCopyFile_IndependentCopy verifies that CopyFile creates a real,
// independent copy: it exists at a new knowledge-owned path AND survives
// deletion of the source object (the C1/C2 regression this PR fixes).
func TestLocalCopyFile_IndependentCopy(t *testing.T) {
base := t.TempDir()
svc := NewLocalFileService(base, "")
content := []byte("hello deep copy")
srcPath := seedLocalObject(t, base, 0, "doc.txt", content)
newPath, err := svc.CopyFile(context.Background(), srcPath, 42, "dst-knowledge")
require.NoError(t, err)
// New path must be knowledge-owned: local://42/dst-knowledge/<unique>.txt
require.True(t, strings.HasPrefix(newPath, localScheme+"42/dst-knowledge/"),
"unexpected dst path: %s", newPath)
assert.Equal(t, ".txt", filepath.Ext(newPath))
// Copy is readable and byte-identical.
assert.Equal(t, content, readLocal(t, svc, newPath))
// Delete the source — the copy must remain intact.
require.NoError(t, svc.DeleteFile(context.Background(), srcPath))
assert.Equal(t, content, readLocal(t, svc, newPath),
"copy should survive deletion of source")
}
// TestLocalCopyFile_CrossBackend verifies that handing a non-local provider
// scheme to the local service is rejected with ErrCrossBackendCopy.
func TestLocalCopyFile_CrossBackend(t *testing.T) {
base := t.TempDir()
svc := NewLocalFileService(base, "")
_, err := svc.CopyFile(context.Background(), "s3://bucket/10/exports/a.png", 7, "k")
require.Error(t, err)
assert.True(t, errors.Is(err, ErrCrossBackendCopy),
"expected ErrCrossBackendCopy, got %v", err)
}
// TestLocalCopyFile_TraversalRejected verifies that the same path guard used by
// GetFile/DeleteFile rejects a traversal source path.
func TestLocalCopyFile_TraversalRejected(t *testing.T) {
base := t.TempDir()
svc := NewLocalFileService(base, "")
_, err := svc.CopyFile(context.Background(), localScheme+"../../etc/passwd", 7, "k")
require.Error(t, err)
assert.False(t, errors.Is(err, ErrCrossBackendCopy),
"traversal should be a path error, not cross-backend")
}
@@ -10,6 +10,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
@@ -164,6 +165,33 @@ func (s *minioFileService) DeleteFile(ctx context.Context, filePath string) erro
return nil
}
// CopyFile copies an existing MinIO object to a new knowledge-owned object using a
// server-side CopyObject (no data leaves MinIO). The destination uses the same
// layout as SaveFile. Returns ErrCrossBackendCopy when srcPath is not a minio:// path.
func (s *minioFileService) CopyFile(ctx context.Context,
srcPath string, tenantID uint64, knowledgeID string,
) (string, error) {
srcKey, err := s.parseMinioFilePath(srcPath)
if err != nil {
return "", fmt.Errorf("minio copy rejected source %q: %w", srcPath, ErrCrossBackendCopy)
}
ext := filepath.Ext(srcPath)
destKey := fmt.Sprintf("%d/%s/%s%s", tenantID, knowledgeID, uuid.New().String(), ext)
_, err = s.client.CopyObject(ctx,
minio.CopyDestOptions{Bucket: s.bucketName, Object: destKey},
minio.CopySrcOptions{Bucket: s.bucketName, Object: srcKey},
)
if err != nil {
return "", fmt.Errorf("failed to copy file in MinIO: %w", err)
}
newPath := fmt.Sprintf("minio://%s/%s", s.bucketName, destKey)
logger.Infof(ctx, "Copied MinIO object %s to %s", srcPath, newPath)
return newPath, nil
}
// SaveBytes saves bytes data to MinIO and returns the file path
// temp parameter is ignored for MinIO (no auto-expiration support in this implementation)
func (s *minioFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
+49
View File
@@ -10,6 +10,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
@@ -229,6 +230,54 @@ func (s *obsFileService) GetFileURL(ctx context.Context, filePath string) (strin
return fmt.Sprintf("%s/%s/%s", s.endpoint, s.bucketName, strings.TrimPrefix(objectKey, "/")), nil
}
// CopyFile copies an existing OBS object to a new knowledge-owned object using a
// server-side CopyObject (OBS is S3-compatible). The destination uses the same
// layout as SaveFile. Returns ErrCrossBackendCopy when srcPath does not belong
// to this OBS service.
func (s *obsFileService) CopyFile(ctx context.Context,
srcPath string, tenantID uint64, knowledgeID string,
) (string, error) {
// Reject paths that do not use this service's prefix (proxy domain or obs://).
// parseObsFilePath falls back to returning the raw input for unknown prefixes,
// so guard explicitly here to detect cross-backend sources.
if !strings.HasPrefix(srcPath, s.getPrifix()) {
return "", fmt.Errorf("obs copy rejected source %q: %w", srcPath, ErrCrossBackendCopy)
}
srcKey, err := s.parseObsFilePath(srcPath)
if err != nil {
return "", fmt.Errorf("obs copy rejected source %q: %w", srcPath, ErrCrossBackendCopy)
}
ext := filepath.Ext(srcPath)
var destKey string
if s.pathPrefix != "" {
destKey = fmt.Sprintf("%s/%d/%s/%s%s", s.pathPrefix, tenantID, knowledgeID, uuid.New().String(), ext)
} else {
destKey = fmt.Sprintf("%d/%s/%s%s", tenantID, knowledgeID, uuid.New().String(), ext)
}
// CopySource is "bucket/key"; the '/' separators must NOT be percent-encoded
// (url.PathEscape would turn them into %2F and break the bucket/key split).
_, err = s.client.CopyObject(ctx, &s3.CopyObjectInput{
Bucket: aws.String(s.bucketName),
CopySource: aws.String(s.bucketName + "/" + srcKey),
Key: aws.String(destKey),
})
if err != nil {
return "", fmt.Errorf("failed to copy file in OBS: %w", err)
}
prefix := s.getPrifix()
var newPath string
if s.proxyDomain != "" {
newPath = fmt.Sprintf("%s%s", prefix, destKey)
} else {
newPath = fmt.Sprintf("%s%s/%s", prefix, s.bucketName, destKey)
}
logger.Infof(ctx, "Copied OBS object %s to %s", srcPath, newPath)
return newPath, nil
}
func (s *obsFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
ext := filepath.Ext(fileName)
+33
View File
@@ -12,6 +12,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
@@ -242,6 +243,38 @@ func (s *ossFileService) SaveBytes(ctx context.Context, data []byte, tenantID ui
return fmt.Sprintf("oss://%s/%s", targetBucket, objectName), nil
}
// CopyFile copies an existing OSS object to a new knowledge-owned object using a
// server-side CopyObject (no data leaves OSS). The destination uses the same
// layout as SaveFile. Returns ErrCrossBackendCopy when srcPath is not an oss:// path.
func (s *ossFileService) CopyFile(ctx context.Context,
srcPath string, tenantID uint64, knowledgeID string,
) (string, error) {
srcBucket, srcKey, err := parseOssFilePath(srcPath)
if err != nil {
return "", fmt.Errorf("oss copy rejected source %q: %w", srcPath, ErrCrossBackendCopy)
}
if err := utils.SafeObjectKey(srcKey); err != nil {
return "", fmt.Errorf("invalid source path: %w", err)
}
ext := filepath.Ext(srcPath)
destKey := fmt.Sprintf("%s%d/%s/%s%s", s.pathPrefix, tenantID, knowledgeID, uuid.New().String(), ext)
_, err = s.client.CopyObject(ctx, &oss.CopyObjectRequest{
Bucket: oss.Ptr(s.bucketName),
Key: oss.Ptr(destKey),
SourceBucket: oss.Ptr(srcBucket),
SourceKey: oss.Ptr(srcKey),
})
if err != nil {
return "", fmt.Errorf("failed to copy file in OSS: %w", err)
}
newPath := fmt.Sprintf("oss://%s/%s", s.bucketName, destKey)
logger.Infof(ctx, "Copied OSS object %s to %s", srcPath, newPath)
return newPath, nil
}
// GetFile retrieves a file from OSS by its path.
func (s *ossFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
bucketName, objectName, err := parseOssFilePath(filePath)
+32
View File
@@ -11,6 +11,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/aws/aws-sdk-go-v2/aws"
@@ -244,6 +245,37 @@ func (s *s3FileService) DeleteFile(ctx context.Context, filePath string) error {
return nil
}
// CopyFile copies an existing S3 object to a new knowledge-owned object using a
// server-side CopyObject (no data leaves S3). The destination uses the same
// layout as SaveFile. Returns ErrCrossBackendCopy when srcPath is not an s3:// path.
func (s *s3FileService) CopyFile(ctx context.Context,
srcPath string, tenantID uint64, knowledgeID string,
) (string, error) {
srcKey, err := s.parseS3FilePath(srcPath)
if err != nil {
return "", fmt.Errorf("s3 copy rejected source %q: %w", srcPath, ErrCrossBackendCopy)
}
ext := filepath.Ext(srcPath)
destKey := fmt.Sprintf("%s%d/%s/%s%s", s.pathPrefix, tenantID, knowledgeID, uuid.New().String(), ext)
// CopySource is "bucket/key"; the '/' separators must NOT be percent-encoded
// (url.PathEscape would turn them into %2F and break the bucket/key split).
// srcKey is already validated by parseS3FilePath -> SafeObjectKey.
_, err = s.client.CopyObject(ctx, &s3.CopyObjectInput{
Bucket: aws.String(s.bucketName),
CopySource: aws.String(s.bucketName + "/" + srcKey),
Key: aws.String(destKey),
})
if err != nil {
return "", fmt.Errorf("failed to copy file in S3: %w", err)
}
newPath := fmt.Sprintf("s3://%s/%s", s.bucketName, destKey)
logger.Infof(ctx, "Copied S3 object %s to %s", srcPath, newPath)
return newPath, nil
}
// SaveBytes saves bytes data to S3 and returns the file path
// temp parameter is ignored for S3 (no auto-expiration support in this implementation)
func (s *s3FileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
+38
View File
@@ -11,6 +11,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
@@ -225,6 +226,43 @@ func (s *tosFileService) SaveBytes(ctx context.Context, data []byte, tenantID ui
return fmt.Sprintf("tos://%s/%s", targetBucket, objectName), nil
}
// CopyFile copies an existing TOS object to a new knowledge-owned object using a
// server-side CopyObject (no data leaves TOS). The destination uses the same
// layout as SaveFile. Returns ErrCrossBackendCopy when srcPath is not a tos:// path.
func (s *tosFileService) CopyFile(ctx context.Context,
srcPath string, tenantID uint64, knowledgeID string,
) (string, error) {
srcBucket, srcKey, err := parseTOSFilePath(srcPath)
if err != nil {
return "", fmt.Errorf("tos copy rejected source %q: %w", srcPath, ErrCrossBackendCopy)
}
if err := utils.SafeObjectKey(srcKey); err != nil {
return "", fmt.Errorf("invalid source path: %w", err)
}
ext := filepath.Ext(srcPath)
destKey := joinTOSObjectKey(
s.pathPrefix,
fmt.Sprintf("%d", tenantID),
knowledgeID,
uuid.New().String()+ext,
)
_, err = s.client.CopyObject(ctx, &tos.CopyObjectInput{
Bucket: s.bucketName,
Key: destKey,
SrcBucket: srcBucket,
SrcKey: srcKey,
})
if err != nil {
return "", fmt.Errorf("failed to copy file in TOS: %w", err)
}
newPath := fmt.Sprintf("tos://%s/%s", s.bucketName, destKey)
logger.Infof(ctx, "Copied TOS object %s to %s", srcPath, newPath)
return newPath, nil
}
func (s *tosFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
bucketName, objectName, err := parseTOSFilePath(filePath)
if err != nil {