refactor: simplify image handling in _resolve_images function

- Removed the image storage handling from the `_resolve_images` function, which now only decodes images and returns them as inline bytes.
- Updated the function's docstring to clarify that image persistence is managed by the Go App, and the return value for `image_dir_path` is always empty.
- Adjusted related gRPC and protobuf files to remove the `ConvertToPDF` method and its associated types, streamlining the API.
- Enhanced security measures in the frontend by implementing a placeholder for provider images and ensuring proper hydration of protected file images.

These changes improve the clarity and efficiency of image processing and API interactions within the application.
This commit is contained in:
wizardchen
2026-03-03 21:30:27 +08:00
committed by lyingbug
parent 894d2c060a
commit 4192cfd072
26 changed files with 835 additions and 897 deletions
+28 -6
View File
@@ -26,8 +26,12 @@ type cosFileService struct {
cosPathPrefix string
tempClient *cos.Client
tempBucketURL string
bucketName string
region string
}
const cosScheme = "cos://"
// newCosClient creates a bare cosFileService with just the SDK client initialised.
// Shared by NewCosFileService* constructors and CheckCosConnectivity.
func newCosClient(bucketName, region, secretID, secretKey string) (*cosFileService, error) {
@@ -43,7 +47,7 @@ func newCosClient(bucketName, region, secretID, secretKey string) (*cosFileServi
SecretKey: secretKey,
},
})
return &cosFileService{client: client, bucketURL: bucketURL}, nil
return &cosFileService{client: client, bucketURL: bucketURL, bucketName: bucketName, region: region}, nil
}
// NewCosFileService creates a new COS file service instance
@@ -114,12 +118,12 @@ func (s *cosFileService) SaveFile(ctx context.Context,
if err != nil {
return "", fmt.Errorf("failed to upload file to COS: %w", err)
}
return fmt.Sprintf("%s%s", s.bucketURL, objectName), nil
return fmt.Sprintf("cos://%s/%s/%s", s.bucketName, s.region, objectName), nil
}
// GetFile retrieves a file from COS storage by its path URL
func (s *cosFileService) GetFile(ctx context.Context, filePathUrl string) (io.ReadCloser, error) {
objectName := strings.TrimPrefix(filePathUrl, s.bucketURL)
objectName := s.parseCosObjectName(filePathUrl)
if err := utils.SafeObjectKey(objectName); err != nil {
return nil, fmt.Errorf("invalid file path: %w", err)
}
@@ -132,7 +136,7 @@ func (s *cosFileService) GetFile(ctx context.Context, filePathUrl string) (io.Re
// DeleteFile removes a file from COS storage
func (s *cosFileService) DeleteFile(ctx context.Context, filePath string) error {
objectName := strings.TrimPrefix(filePath, s.bucketURL)
objectName := s.parseCosObjectName(filePath)
if err := utils.SafeObjectKey(objectName); err != nil {
return fmt.Errorf("invalid file path: %w", err)
}
@@ -143,6 +147,23 @@ func (s *cosFileService) DeleteFile(ctx context.Context, filePath string) error
return nil
}
// parseCosObjectName extracts the object name from:
// - provider scheme: cos://{bucket}/{region}/{objectKey}
// - legacy URL: https://bucket.cos.region.myqcloud.com/{objectKey}
func (s *cosFileService) parseCosObjectName(filePath string) string {
// Provider scheme format: cos://{bucket}/{region}/{objectKey}
if strings.HasPrefix(filePath, cosScheme) {
rest := strings.TrimPrefix(filePath, cosScheme)
parts := strings.SplitN(rest, "/", 3)
if len(parts) == 3 {
return parts[2]
}
return rest
}
// Legacy format: https://bucket.cos.region.myqcloud.com/{objectKey}
return strings.TrimPrefix(filePath, s.bucketURL)
}
// 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
@@ -161,6 +182,7 @@ func (s *cosFileService) SaveBytes(ctx context.Context, data []byte, tenantID ui
if err != nil {
return "", fmt.Errorf("failed to upload bytes to COS temp bucket: %w", err)
}
// Temp bucket still uses legacy URL format for backward compat (auto-expiring)
return fmt.Sprintf("%s%s", s.tempBucketURL, objectName), nil
}
@@ -171,7 +193,7 @@ func (s *cosFileService) SaveBytes(ctx context.Context, data []byte, tenantID ui
return "", fmt.Errorf("failed to upload bytes to COS: %w", err)
}
return fmt.Sprintf("%s%s", s.bucketURL, objectName), nil
return fmt.Sprintf("cos://%s/%s/%s", s.bucketName, s.region, objectName), nil
}
// GetFileURL returns a presigned download URL for the file
@@ -190,7 +212,7 @@ func (s *cosFileService) GetFileURL(ctx context.Context, filePath string) (strin
return presignedURL.String(), nil
}
objectName := strings.TrimPrefix(filePath, s.bucketURL)
objectName := s.parseCosObjectName(filePath)
if err := utils.SafeObjectKey(objectName); err != nil {
return "", fmt.Errorf("invalid file path: %w", err)
}
@@ -0,0 +1,97 @@
package file
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// NewFileServiceFromStorageConfig builds a provider-specific FileService from tenant storage config.
// provider can be empty; in that case it falls back to sec.DefaultProvider.
// Returns the resolved provider name together with the service.
func NewFileServiceFromStorageConfig(
provider string,
sec *types.StorageEngineConfig,
localBaseDir string,
) (interfaces.FileService, string, error) {
p := strings.ToLower(strings.TrimSpace(provider))
if p == "" && sec != nil {
p = strings.ToLower(strings.TrimSpace(sec.DefaultProvider))
}
if p == "" {
return nil, "", fmt.Errorf("empty provider")
}
if localBaseDir == "" {
localBaseDir = strings.TrimSpace(os.Getenv("LOCAL_STORAGE_BASE_DIR"))
}
if localBaseDir == "" {
localBaseDir = "/data/files"
}
switch p {
case "local":
baseDir := localBaseDir
if sec != nil && sec.Local != nil {
rawPrefix := strings.TrimSpace(sec.Local.PathPrefix)
prefix := strings.Trim(rawPrefix, "/\\")
if prefix != "" {
candidate := filepath.Join(baseDir, prefix)
if safeBaseDir, err := secutils.SafePathUnderBase(baseDir, candidate); err == nil {
baseDir = safeBaseDir
}
}
}
return NewLocalFileService(baseDir), p, nil
case "minio":
if sec == nil || sec.MinIO == nil {
return nil, p, fmt.Errorf("missing minio config")
}
var endpoint, accessKeyID, secretAccessKey string
if sec.MinIO.Mode == "remote" {
endpoint = strings.TrimSpace(sec.MinIO.Endpoint)
accessKeyID = strings.TrimSpace(sec.MinIO.AccessKeyID)
secretAccessKey = strings.TrimSpace(sec.MinIO.SecretAccessKey)
} else {
endpoint = strings.TrimSpace(os.Getenv("MINIO_ENDPOINT"))
accessKeyID = strings.TrimSpace(os.Getenv("MINIO_ACCESS_KEY_ID"))
secretAccessKey = strings.TrimSpace(os.Getenv("MINIO_SECRET_ACCESS_KEY"))
}
bucketName := strings.TrimSpace(sec.MinIO.BucketName)
if bucketName == "" {
bucketName = strings.TrimSpace(os.Getenv("MINIO_BUCKET_NAME"))
}
if endpoint == "" || accessKeyID == "" || secretAccessKey == "" || bucketName == "" {
return nil, p, fmt.Errorf("incomplete minio config")
}
svc, err := NewMinioFileService(endpoint, accessKeyID, secretAccessKey, bucketName, sec.MinIO.UseSSL)
return svc, p, err
case "cos":
if sec == nil || sec.COS == nil || sec.COS.SecretID == "" || sec.COS.SecretKey == "" || sec.COS.BucketName == "" || sec.COS.Region == "" {
return nil, p, fmt.Errorf("incomplete cos config")
}
pathPrefix := strings.TrimSpace(sec.COS.PathPrefix)
if pathPrefix == "" {
pathPrefix = "weknora"
}
svc, err := NewCosFileService(sec.COS.BucketName, sec.COS.Region, sec.COS.SecretID, sec.COS.SecretKey, pathPrefix)
return svc, p, err
case "tos":
if sec == nil || sec.TOS == nil || sec.TOS.Endpoint == "" || sec.TOS.Region == "" || sec.TOS.AccessKey == "" || sec.TOS.SecretKey == "" || sec.TOS.BucketName == "" {
return nil, p, fmt.Errorf("incomplete tos config")
}
svc, err := NewTosFileService(sec.TOS.Endpoint, sec.TOS.Region, sec.TOS.AccessKey, sec.TOS.SecretKey, sec.TOS.BucketName, sec.TOS.PathPrefix)
return svc, p, err
default:
return nil, p, fmt.Errorf("unsupported provider %q", p)
}
}
+26 -5
View File
@@ -20,6 +20,8 @@ type localFileService struct {
baseDir string // Base directory for file storage
}
const localScheme = "local://"
// CheckConnectivity verifies the local storage directory exists and is accessible.
func (s *localFileService) CheckConnectivity(ctx context.Context) error {
info, err := os.Stat(s.baseDir)
@@ -93,11 +95,14 @@ func (s *localFileService) SaveFile(ctx context.Context,
}
logger.Infof(ctx, "File saved successfully: %s", filePath)
return filePath, nil
// Return provider:// path format: local://{relative_path}
relPath, _ := filepath.Rel(s.baseDir, filePath)
return localScheme + filepath.ToSlash(relPath), nil
}
// GetFile retrieves a file from the local file system by its path
// Returns a ReadCloser for reading the file content
// Supports both provider scheme: local://{relative_path} and legacy absolute paths.
// 路径必须在 baseDir 下,防止路径遍历(如 ../../)
func (s *localFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
logger.Infof(ctx, "Getting file: %s", filePath)
@@ -174,21 +179,37 @@ func (s *localFileService) SaveBytes(ctx context.Context, data []byte, tenantID
}
logger.Infof(ctx, "Bytes data saved successfully: %s", filePath)
return filePath, nil
relPath, _ := filepath.Rel(s.baseDir, filePath)
return localScheme + filepath.ToSlash(relPath), nil
}
// GetFileURL returns a download URL for the file
// For local storage, returns the file path itself (no URL support)
// For local storage, returns the local://... path
func (s *localFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
// Local storage doesn't support URLs, return the path
return filePath, nil
// If already in provider:// format, return as-is
if strings.HasPrefix(filePath, localScheme) {
return filePath, nil
}
// Convert absolute path to provider:// format
relPath, err := filepath.Rel(s.baseDir, filePath)
if err != nil {
return filePath, nil
}
return localScheme + filepath.ToSlash(relPath), nil
}
// normalizePathForBase keeps backward compatibility for legacy file paths:
// - provider scheme: "local://tenant/.." → baseDir/tenant/..
// - absolute path: "/data/files/tenant/.."
// - path under base dir: "tenant/.."
// - legacy relative with base prefix: "data/files/tenant/.."
func (s *localFileService) normalizePathForBase(filePath string) string {
// Handle provider:// format: local://{relPath}
if strings.HasPrefix(filePath, localScheme) {
relPath := strings.TrimPrefix(filePath, localScheme)
return filepath.Join(s.baseDir, filepath.FromSlash(relPath))
}
clean := filepath.Clean(strings.TrimSpace(filePath))
if clean == "." || clean == "" {
return clean
+2 -3
View File
@@ -90,9 +90,9 @@ func CheckMinioConnectivity(ctx context.Context, endpoint, accessKeyID, secretAc
return svc.CheckConnectivity(ctx)
}
// parseMinioFilePath extracts the object name from a "minio://bucket/key" path,
// validates the bucket matches this service instance, and checks for path traversal.
// parseMinioFilePath extracts the object name from a provider scheme: minio://{bucket}/{objectKey}
func (s *minioFileService) parseMinioFilePath(filePath string) (string, error) {
// Provider scheme format: minio://{bucket}/{objectKey}
const prefix = "minio://"
if !strings.HasPrefix(filePath, prefix) {
return "", fmt.Errorf("invalid MinIO file path: %s", filePath)
@@ -134,7 +134,6 @@ func (s *minioFileService) SaveFile(ctx context.Context,
return "", fmt.Errorf("failed to upload file to MinIO: %w", err)
}
// Return the complete path to the object
return fmt.Sprintf("minio://%s/%s", s.bucketName, objectName), nil
}
+4 -3
View File
@@ -26,6 +26,8 @@ type tosFileService struct {
tempBucketName string
}
const tosScheme = "tos://"
// NewTosFileService creates a TOS file service.
func NewTosFileService(endpoint, region, accessKey, secretKey, bucketName, pathPrefix string) (interfaces.FileService, error) {
return NewTosFileServiceWithTempBucket(endpoint, region, accessKey, secretKey, bucketName, pathPrefix, "", "")
@@ -137,12 +139,11 @@ func joinTOSObjectKey(parts ...string) string {
}
func parseTOSFilePath(filePath string) (bucketName string, objectKey string, err error) {
const prefix = "tos://"
if !strings.HasPrefix(filePath, prefix) {
if !strings.HasPrefix(filePath, tosScheme) {
return "", "", fmt.Errorf("invalid TOS file path: %s", filePath)
}
rest := strings.TrimPrefix(filePath, prefix)
rest := strings.TrimPrefix(filePath, tosScheme)
parts := strings.SplitN(rest, "/", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return "", "", fmt.Errorf("invalid TOS file path: %s", filePath)