diff --git a/.env.example b/.env.example
index 7af81301..55b73804 100644
--- a/.env.example
+++ b/.env.example
@@ -148,6 +148,11 @@ APP_PORT=8080
# 远程部署如后端为 HTTPS,需设为 https
# APP_SCHEME=http
+# 应用外部访问地址(用于 IM 渠道中生成图片等文件的可访问链接)
+# 设置为 WeKnora 实例的外部可访问 URL,如 https://weknora.example.com
+# 不设置时,IM 渠道中本地存储的图片将无法正常显示(云存储不受影响)
+# APP_EXTERNAL_URL=
+
# 前端服务端口,默认为80
FRONTEND_PORT=80
diff --git a/internal/application/service/file/factory.go b/internal/application/service/file/factory.go
index 405400bd..a726b0f9 100644
--- a/internal/application/service/file/factory.go
+++ b/internal/application/service/file/factory.go
@@ -47,7 +47,8 @@ func NewFileServiceFromStorageConfig(
}
}
}
- return NewLocalFileService(baseDir), p, nil
+ externalURL := strings.TrimSpace(os.Getenv("APP_EXTERNAL_URL"))
+ return NewLocalFileService(baseDir, externalURL), p, nil
case "minio":
if sec == nil || sec.MinIO == nil {
diff --git a/internal/application/service/file/local.go b/internal/application/service/file/local.go
index f772dbff..3c03b9c8 100644
--- a/internal/application/service/file/local.go
+++ b/internal/application/service/file/local.go
@@ -17,7 +17,8 @@ import (
// localFileService implements the FileService interface for local file system storage
type localFileService struct {
- baseDir string // Base directory for file storage
+ baseDir string // Base directory for file storage
+ externalURL string // External URL base for presigned URL generation (empty = return local:// paths)
}
const localScheme = "local://"
@@ -34,10 +35,13 @@ func (s *localFileService) CheckConnectivity(ctx context.Context) error {
return nil
}
-// NewLocalFileService creates a new local file service instance
-func NewLocalFileService(baseDir string) interfaces.FileService {
+// NewLocalFileService creates a new local file service instance.
+// externalURL is the externally-reachable base URL (e.g. "https://weknora.example.com");
+// when set, GetFileURL returns presigned HTTP URLs instead of local:// paths.
+func NewLocalFileService(baseDir, externalURL string) interfaces.FileService {
return &localFileService{
- baseDir: baseDir,
+ baseDir: baseDir,
+ externalURL: strings.TrimRight(externalURL, "/"),
}
}
@@ -183,19 +187,33 @@ func (s *localFileService) SaveBytes(ctx context.Context, data []byte, tenantID
return localScheme + filepath.ToSlash(relPath), nil
}
-// GetFileURL returns a download URL for the file
-// For local storage, returns the local://... path
+// GetFileURL returns a download URL for the file.
+// When externalURL is configured, returns a presigned HTTP URL suitable for external access.
+// Otherwise returns the local://... path for backward compatibility.
func (s *localFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
- // If already in provider:// format, return as-is
- if strings.HasPrefix(filePath, localScheme) {
- return filePath, nil
+ // Normalize to provider:// format.
+ normalized := filePath
+ if !strings.HasPrefix(filePath, localScheme) {
+ relPath, err := filepath.Rel(s.baseDir, filePath)
+ if err != nil {
+ normalized = filePath
+ } else {
+ normalized = localScheme + filepath.ToSlash(relPath)
+ }
}
- // Convert absolute path to provider:// format
- relPath, err := filepath.Rel(s.baseDir, filePath)
- if err != nil {
- return filePath, nil
+
+ // If external URL is configured, generate a presigned HTTP URL.
+ if s.externalURL != "" {
+ tenantID := secutils.ParseTenantIDFromStoragePath(normalized)
+ presignedURL, err := secutils.SignFileURL(s.externalURL, normalized, tenantID, 0)
+ if err != nil {
+ logger.Warnf(ctx, "Failed to generate presigned URL for %s: %v, returning local:// path", normalized, err)
+ return normalized, nil
+ }
+ return presignedURL, nil
}
- return localScheme + filepath.ToSlash(relPath), nil
+
+ return normalized, nil
}
// normalizePathForBase keeps backward compatibility for legacy file paths:
diff --git a/internal/container/container.go b/internal/container/container.go
index 02a6098e..622d7b72 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -737,7 +737,8 @@ func initFileService(cfg *config.Config) (interfaces.FileService, error) {
if baseDir == "" {
baseDir = "/data/files"
}
- return file.NewLocalFileService(baseDir), nil
+ externalURL := strings.TrimSpace(os.Getenv("APP_EXTERNAL_URL"))
+ return file.NewLocalFileService(baseDir, externalURL), nil
case "dummy":
return file.NewDummyFileService(), nil
default:
diff --git a/internal/im/content_rewrite_test.go b/internal/im/content_rewrite_test.go
new file mode 100644
index 00000000..d7955e21
--- /dev/null
+++ b/internal/im/content_rewrite_test.go
@@ -0,0 +1,198 @@
+package im
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestStripIMCitationTags(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want string
+ }{
+ {"no tags", "hello world", "hello world"},
+ {"kb tag", `text more`, "text more"},
+ {"web tag", `see here`, "see here"},
+ {"multiple", `text`, "text"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.want, stripIMCitationTags(tt.in))
+ })
+ }
+}
+
+func TestStripImageXMLTags(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want string
+ }{
+ {
+ "with image_original",
+ `
+
+a cat
+`,
+ "",
+ },
+ {
+ "without image_original",
+ `
+a cat
+`,
+ "",
+ },
+ {
+ "no image tags",
+ "just plain text ",
+ "just plain text ",
+ },
+ {
+ "mixed content",
+ `before  after`,
+ "before  after",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.want, stripImageXMLTags(tt.in))
+ })
+ }
+}
+
+func TestFindIncompleteStorageURL(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want int // expected return; -1 means no match expected
+ }{
+ {
+ "complete URL terminated by )",
+ "",
+ // The URL `local://1/abc/img.png` ends with `)` which is a terminator,
+ // but the regex [^\s)\]>"]* matches up to `)` — the `)` is NOT included.
+ // So the URL portion is `local://1/abc/img.png` and `)` terminates it.
+ // The match does NOT reach end of string → should return -1.
+ -1,
+ },
+ {
+ "complete URL terminated by space",
+ "text local://1/abc/img.png more text",
+ -1,
+ },
+ {
+ "truncated URL at end",
+ "text  {
+ got := findIncompleteStorageURL(tt.in)
+ assert.Equal(t, tt.want, got, "findIncompleteStorageURL(%q)", tt.in)
+ })
+ }
+}
+
+func TestFindIncompleteXMLTag(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want int
+ }{
+ {
+ "complete tag",
+ `text more`,
+ -1,
+ },
+ {
+ "incomplete kb tag",
+ `text , the content is truncated
+ },
+ {
+ "incomplete opening image_original",
+ `text ... blocks produced by
+// EnrichContentWithImageInfo in the RAG context pipeline. These blocks contain
+// metadata for the LLM and must be stripped before sending to IM platforms.
+var imageXMLBlockRe = regexp.MustCompile(`(?s)]*>.*?`)
+
+// imageOriginalRe extracts the original markdown image syntax from tags.
+var imageOriginalRe = regexp.MustCompile(`(.*?)`)
+
+// stripImageXMLTags collapses blocks back to plain markdown.
+// Extracts the original  from when present,
+// otherwise drops the block entirely.
+func stripImageXMLTags(s string) string {
+ return imageXMLBlockRe.ReplaceAllStringFunc(s, func(block string) string {
+ if m := imageOriginalRe.FindStringSubmatch(block); len(m) > 1 {
+ return m[1]
+ }
+ return ""
+ })
+}
+
+// storageSchemeRe matches provider:// URLs used by file storage backends.
+var storageSchemeRe = regexp.MustCompile(`\b(local|minio|s3|cos|tos|oss)://[^\s)\]>"]+`)
+
+// rewriteStorageURLs replaces all provider:// URLs in content with HTTP URLs
+// obtained from fileService.GetFileURL. URLs that are already HTTP or cannot
+// be resolved are left unchanged.
+func rewriteStorageURLs(ctx context.Context, content string, fileSvc interfaces.FileService) string {
+ if fileSvc == nil {
+ return content
+ }
+ return storageSchemeRe.ReplaceAllStringFunc(content, func(match string) string {
+ httpURL, err := fileSvc.GetFileURL(ctx, match)
+ if err != nil || httpURL == match {
+ return match
+ }
+ return httpURL
+ })
+}
+
+// ── Streaming holdback helpers ──
+// During streaming, content is flushed in 300ms batches. A provider:// URL or
+// an XML tag may be split across two batches. These helpers detect incomplete
+// patterns at the end of a chunk so the caller can hold them back until the
+// next flush completes them.
+
+// incompleteURLSuffixRe matches a provider:// URL that reaches the end of the
+// string — it may continue in the next chunk.
+var incompleteURLSuffixRe = regexp.MustCompile(
+ `\b(?:local|minio|s3|cos|tos|oss)://[^\s)\]>"]*$`,
+)
+
+// findIncompleteStorageURL returns the byte offset of a potentially truncated
+// provider:// URL at the tail of s, or -1 if none.
+func findIncompleteStorageURL(s string) int {
+ loc := incompleteURLSuffixRe.FindStringIndex(s)
+ if loc == nil {
+ return -1
+ }
+ return loc[0]
+}
+
+// incompleteXMLTagRe matches the opening of an , , or tag
+// that reaches the end of the string without a closing '>'.
+var incompleteXMLTagRe = regexp.MustCompile(
+ `<(?:image|image_original|image_caption|image_ocr|kb|web)[^>]*$`,
+)
+
+// findIncompleteXMLTag returns the byte offset of a potentially truncated XML
+// tag at the tail of s, or -1 if none.
+func findIncompleteXMLTag(s string) int {
+ loc := incompleteXMLTagRe.FindStringIndex(s)
+ if loc == nil {
+ return -1
+ }
+ return loc[0]
+}
+
+// holdbackCutoff returns the earliest incomplete-pattern offset at the tail of
+// chunk, or len(chunk) if the chunk is safe to flush entirely.
+func holdbackCutoff(chunk string) int {
+ cutoff := len(chunk)
+ if idx := findIncompleteStorageURL(chunk); idx >= 0 && idx < cutoff {
+ cutoff = idx
+ }
+ if idx := findIncompleteXMLTag(chunk); idx >= 0 && idx < cutoff {
+ cutoff = idx
+ }
+ return cutoff
+}
+
+// cleanIMContent applies all IM-specific content transformations:
+// 1. Collapse XML blocks back to plain markdown
+// 2. Strip and citation tags
+// 3. Rewrite provider:// URLs to HTTP URLs (if fileSvc is available)
+func cleanIMContent(ctx context.Context, content string, fileSvc interfaces.FileService) string {
+ content = stripImageXMLTags(content)
+ content = stripIMCitationTags(content)
+ content = rewriteStorageURLs(ctx, content, fileSvc)
+ return content
+}
+
+// buildTenantFileService creates a FileService for the given tenant's storage config.
+// Returns nil if the tenant has no storage config or if creation fails.
+func buildTenantFileService(tenant *types.Tenant) interfaces.FileService {
+ if tenant == nil {
+ return nil
+ }
+ baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
+ if baseDir == "" {
+ baseDir = "/data/files"
+ }
+ fileSvc, _, err := filesvc.NewFileServiceFromStorageConfig("", tenant.StorageEngineConfig, baseDir)
+ if err != nil {
+ return nil
+ }
+ return fileSvc
+}
+
const (
// wsLeaderTTL is the TTL for the Redis key used for WebSocket leader election.
wsLeaderTTL = 15 * time.Second
@@ -962,6 +1082,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
adapter: adapter,
channel: channel,
channelID: channelID,
+ fileSvc: buildTenantFileService(tenant),
userKey: userKey,
}
@@ -1033,7 +1154,7 @@ func (s *Service) executeQARequest(req *qaRequest) {
// If the adapter supports streaming and output is not "full", use streaming.
if !streamDisabled {
if streamer, ok := req.adapter.(StreamSender); ok {
- if err := s.handleMessageStream(ctx, req.msg, req.session, req.agent, kbIDs, streamer, req.adapter, req.userKey); err != nil {
+ if err := s.handleMessageStream(ctx, req.msg, req.session, req.agent, kbIDs, streamer, req.adapter, req.userKey, req.fileSvc); err != nil {
span.SetStatus(codes.Error, err.Error())
logger.Errorf(ctx, "[IM] Stream QA failed: %v", err)
}
@@ -1050,7 +1171,7 @@ func (s *Service) executeQARequest(req *qaRequest) {
}
reply := &ReplyMessage{
- Content: answer,
+ Content: cleanIMContent(ctx, answer, req.fileSvc),
IsFinal: true,
}
if err := req.adapter.SendReply(ctx, req.msg, reply); err != nil {
@@ -1455,19 +1576,12 @@ func briefToolSummary(output string) string {
// handleMessageStream runs the QA pipeline and streams answer chunks to the IM platform
// in real-time via the StreamSender interface. Chunks are batched at streamFlushInterval
// to avoid API rate-limiting.
-func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage, session *types.Session, customAgent *types.CustomAgent, kbIDs []string, streamer StreamSender, adapter Adapter, userKey string) error {
- ctx, span := tracing.ContextWithSpan(ctx, "im.StreamQA")
- defer span.End()
- span.SetAttributes(
- attribute.String("im.user_id", msg.UserID),
- attribute.String("im.platform", string(msg.Platform)),
- )
-
+func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage, session *types.Session, customAgent *types.CustomAgent, kbIDs []string, streamer StreamSender, adapter Adapter, userKey string, fileSvc interfaces.FileService) error {
// Start the stream on the IM platform (e.g., create Feishu streaming card)
streamID, err := streamer.StartStream(ctx, msg)
if err != nil {
logger.Warnf(ctx, "[IM] StartStream failed, falling back to non-streaming: %v", err)
- return s.fallbackNonStream(ctx, msg, session, customAgent, kbIDs, adapter, userKey)
+ return s.fallbackNonStream(ctx, msg, session, customAgent, kbIDs, adapter, userKey, fileSvc)
}
// Prepare the QA pipeline
@@ -1684,18 +1798,35 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
}
}()
- // Flush loop: periodically send buffered content to the IM platform
+ // Flush loop: periodically send buffered content to the IM platform.
+ // A holdback mechanism prevents flushing incomplete provider:// URLs or
+ // XML tags that straddle a chunk boundary (see holdbackCutoff).
ticker := time.NewTicker(streamFlushInterval)
defer ticker.Stop()
- flush := func() {
+ var holdback string // text held back from the previous flush
+
+ flush := func(final bool) {
bufMu.Lock()
- chunk := buf.String()
+ chunk := holdback + buf.String()
buf.Reset()
bufMu.Unlock()
+ holdback = ""
+
+ if chunk == "" {
+ return
+ }
+
+ // On non-final flushes, check for incomplete patterns at the tail.
+ if !final {
+ if cut := holdbackCutoff(chunk); cut < len(chunk) {
+ holdback = chunk[cut:]
+ chunk = chunk[:cut]
+ }
+ }
if chunk != "" {
- if err := streamer.SendStreamChunk(ctx, msg, streamID, stripIMCitationTags(chunk)); err != nil {
+ if err := streamer.SendStreamChunk(ctx, msg, streamID, cleanIMContent(ctx, chunk, fileSvc)); err != nil {
logger.Warnf(ctx, "[IM] SendStreamChunk failed: %v", err)
}
}
@@ -1705,7 +1836,7 @@ loop:
for {
select {
case <-ticker.C:
- flush()
+ flush(false)
case <-done:
break loop
case <-qaCtx.Done():
@@ -1713,8 +1844,8 @@ loop:
}
}
- // Final flush of any remaining content
- flush()
+ // Final flush of any remaining content (including holdback).
+ flush(true)
// If no user-visible content was streamed (e.g., the entire response was
// in blocks, or the QA pipeline errored), send a fallback message
@@ -1758,14 +1889,14 @@ loop:
}
// fallbackNonStream is used when streaming initialization fails.
-func (s *Service) fallbackNonStream(ctx context.Context, msg *IncomingMessage, session *types.Session, customAgent *types.CustomAgent, kbIDs []string, adapter Adapter, userKey string) error {
+func (s *Service) fallbackNonStream(ctx context.Context, msg *IncomingMessage, session *types.Session, customAgent *types.CustomAgent, kbIDs []string, adapter Adapter, userKey string, fileSvc interfaces.FileService) error {
answer, err := s.runQA(ctx, session, msg.Content, customAgent, kbIDs, userKey, msg.Quote)
if err != nil {
logger.Errorf(ctx, "[IM] QA fallback failed: %v", err)
answer = "抱歉,处理您的问题时出现了异常,请稍后再试。"
}
- return adapter.SendReply(ctx, msg, &ReplyMessage{Content: answer, IsFinal: true})
+ return adapter.SendReply(ctx, msg, &ReplyMessage{Content: cleanIMContent(ctx, answer, fileSvc), IsFinal: true})
}
// runQA executes the WeKnora QA pipeline and returns the full answer text.
@@ -1911,9 +2042,8 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
logger.Warnf(ctx, "[IM] Failed to update assistant message: %v", err)
}
- // Strip citation tags before returning to the IM adapter — IM platforms cannot
- // render / and would display them as raw text.
- return stripIMCitationTags(answer), nil
+ // Return raw answer — callers apply cleanIMContent with the appropriate FileService.
+ return answer, nil
}
// ── CRUD operations for IM channels ──
diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go
index 15c7fcec..3e56233f 100644
--- a/internal/middleware/auth.go
+++ b/internal/middleware/auth.go
@@ -27,6 +27,7 @@ var noAuthAPI = map[string][]string{
"/api/v1/auth/oidc/url": {"GET"},
"/api/v1/auth/oidc/callback": {"GET"},
"/api/v1/auth/refresh": {"POST"},
+ "/api/v1/files/presigned": {"GET"},
}
// 检查请求是否在无需认证的API列表中
diff --git a/internal/router/router.go b/internal/router/router.go
index 4b25c8db..aa15a44c 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -6,6 +6,7 @@ import (
"net/http"
"os"
"path/filepath"
+ "strconv"
"strings"
"time"
@@ -24,6 +25,7 @@ import (
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
_ "github.com/Tencent/WeKnora/docs" // swagger docs
)
@@ -120,6 +122,9 @@ func NewRouter(params RouterParams) *gin.Engine {
// 文件服务:统一代理本地/MinIO/COS/TOS存储后端(需要认证)
serveFiles(r)
+ // Presigned file access: no auth required, signature-verified.
+ servePresignedFiles(r, params.TenantService)
+
// 添加OpenTelemetry追踪中间件
// r.Use(middleware.TracingMiddleware())
@@ -807,6 +812,97 @@ func serveFiles(r *gin.Engine) {
})
}
+// servePresignedFiles serves files via HMAC-signed URLs without requiring authentication.
+// This is used by IM channels to serve images that are embedded in bot replies.
+//
+// Route:
+// - /api/v1/files/presigned?file_path=&tenant_id=&expires=&sig=
+func servePresignedFiles(r *gin.Engine, tenantService interfaces.TenantService) {
+ baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
+ if baseDir == "" {
+ baseDir = "/data/files"
+ }
+ absDir, _ := filepath.Abs(baseDir)
+
+ r.GET("/api/v1/files/presigned", func(c *gin.Context) {
+ filePath := strings.TrimSpace(c.Query("file_path"))
+ tenantIDStr := strings.TrimSpace(c.Query("tenant_id"))
+ expiresStr := strings.TrimSpace(c.Query("expires"))
+ sig := strings.TrimSpace(c.Query("sig"))
+
+ if filePath == "" || tenantIDStr == "" || expiresStr == "" || sig == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "missing required parameters"})
+ return
+ }
+ if strings.Contains(filePath, "..") {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid file path"})
+ return
+ }
+
+ tenantID, err := strconv.ParseUint(tenantIDStr, 10, 64)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid tenant_id"})
+ return
+ }
+
+ // Verify HMAC signature and expiry.
+ if !secutils.VerifyFileURLSig(filePath, tenantID, expiresStr, sig) {
+ c.JSON(http.StatusForbidden, gin.H{"error": "invalid or expired signature"})
+ return
+ }
+
+ // Resolve the file service for this tenant.
+ provider := types.ParseProviderScheme(filePath)
+ tenant, err := tenantService.GetTenantByID(c.Request.Context(), tenantID)
+ if err != nil {
+ logger.Warnf(context.Background(), "[Router] /files/presigned tenant lookup failed: tenant_id=%d err=%v", tenantID, err)
+ c.Status(http.StatusNotFound)
+ return
+ }
+
+ fileSvc, resolvedProvider, err := filesvc.NewFileServiceFromStorageConfig(provider, tenant.StorageEngineConfig, absDir)
+ if err != nil {
+ logger.Warnf(context.Background(), "[Router] /files/presigned resolve file service failed: tenant_id=%d provider=%s err=%v", tenantID, provider, err)
+ c.Status(http.StatusBadRequest)
+ return
+ }
+
+ reader, err := fileSvc.GetFile(c.Request.Context(), filePath)
+ if err != nil {
+ logger.Warnf(context.Background(), "[Router] /files/presigned get file failed: tenant_id=%d provider=%s path=%q err=%v", tenantID, resolvedProvider, filePath, err)
+ c.Status(http.StatusNotFound)
+ return
+ }
+ defer reader.Close()
+
+ ext := filepath.Ext(filePath)
+ contentType := "application/octet-stream"
+ switch strings.ToLower(ext) {
+ case ".png":
+ contentType = "image/png"
+ case ".jpg", ".jpeg":
+ contentType = "image/jpeg"
+ case ".gif":
+ contentType = "image/gif"
+ case ".webp":
+ contentType = "image/webp"
+ case ".bmp":
+ contentType = "image/bmp"
+ case ".svg":
+ contentType = "image/svg+xml"
+ case ".pdf":
+ contentType = "application/pdf"
+ }
+
+ c.Header("Content-Type", contentType)
+ c.Header("Cache-Control", "public, max-age=86400")
+ c.Status(http.StatusOK)
+ if _, err := io.Copy(c.Writer, reader); err != nil {
+ logger.Warnf(context.Background(), "[Router] /files/presigned write response failed: %v", err)
+ }
+ })
+}
+
// RegisterDataSourceRoutes 注册数据源相关的路由
func RegisterDataSourceRoutes(r *gin.RouterGroup, handler *handler.DataSourceHandler) {
// Data source routes
diff --git a/internal/utils/presign.go b/internal/utils/presign.go
new file mode 100644
index 00000000..f9d18cac
--- /dev/null
+++ b/internal/utils/presign.go
@@ -0,0 +1,121 @@
+package utils
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+)
+
+const (
+ // presignPath is the URL path for presigned file access.
+ presignPath = "/api/v1/files/presigned"
+ // presignDefaultTTL is the default validity period for presigned URLs.
+ presignDefaultTTL = 24 * time.Hour
+)
+
+// getPresignKey returns the HMAC key derived from SYSTEM_AES_KEY.
+// Returns nil if the key is not configured or invalid.
+func getPresignKey() []byte {
+ key := os.Getenv("SYSTEM_AES_KEY")
+ if len(key) < 16 {
+ return nil
+ }
+ return []byte(key)
+}
+
+// signPayload computes HMAC-SHA256 over the canonical payload string.
+func signPayload(key []byte, filePath string, tenantID uint64, expires int64) string {
+ payload := fmt.Sprintf("file_path=%s&tenant_id=%d&expires=%d", filePath, tenantID, expires)
+ mac := hmac.New(sha256.New, key)
+ mac.Write([]byte(payload))
+ return hex.EncodeToString(mac.Sum(nil))
+}
+
+// SignFileURL generates a presigned HTTP URL for accessing a storage file.
+// baseURL is the external URL of the WeKnora instance (e.g. "https://weknora.example.com").
+// filePath is the provider:// storage path (e.g. "local://1/abc/img.png").
+// tenantID identifies the tenant that owns the file.
+// ttl is how long the URL remains valid (0 uses the default 24h).
+//
+// Returns ("", error) if the signing key is not configured.
+func SignFileURL(baseURL, filePath string, tenantID uint64, ttl time.Duration) (string, error) {
+ key := getPresignKey()
+ if key == nil {
+ return "", fmt.Errorf("presign: SYSTEM_AES_KEY not configured")
+ }
+ if ttl <= 0 {
+ ttl = presignDefaultTTL
+ }
+ expires := time.Now().Add(ttl).Unix()
+ sig := signPayload(key, filePath, tenantID, expires)
+
+ u, err := url.Parse(strings.TrimRight(baseURL, "/") + presignPath)
+ if err != nil {
+ return "", fmt.Errorf("presign: invalid base URL: %w", err)
+ }
+ q := u.Query()
+ q.Set("file_path", filePath)
+ q.Set("tenant_id", strconv.FormatUint(tenantID, 10))
+ q.Set("expires", strconv.FormatInt(expires, 10))
+ q.Set("sig", sig)
+ u.RawQuery = q.Encode()
+
+ return u.String(), nil
+}
+
+// VerifyFileURLSig checks the HMAC signature and expiry of a presigned URL.
+// Returns true only if the signature is valid and the URL has not expired.
+func VerifyFileURLSig(filePath string, tenantID uint64, expiresStr, sig string) bool {
+ key := getPresignKey()
+ if key == nil {
+ return false
+ }
+
+ expires, err := strconv.ParseInt(expiresStr, 10, 64)
+ if err != nil {
+ return false
+ }
+
+ // Check expiry.
+ if time.Now().Unix() > expires {
+ return false
+ }
+
+ // Verify signature.
+ expected := signPayload(key, filePath, tenantID, expires)
+ return hmac.Equal([]byte(expected), []byte(sig))
+}
+
+// ParseTenantIDFromStoragePath extracts the tenant ID from a provider:// storage path.
+// Storage paths follow the convention: {scheme}://{tenantID}/...
+// Returns 0 if the path does not contain a valid tenant ID.
+func ParseTenantIDFromStoragePath(filePath string) uint64 {
+ // Strip scheme: "local://1/abc/img.png" → "1/abc/img.png"
+ _, rest, ok := strings.Cut(filePath, "://")
+ if !ok {
+ return 0
+ }
+
+ // Storage path layouts vary by provider:
+ // local://TENANT_ID/...
+ // minio://bucket/TENANT_ID/...
+ // s3://bucket/prefix/TENANT_ID/...
+ // cos://bucket/region/prefix/TENANT_ID/...
+ // tos://bucket/TENANT_ID/...
+ // oss://bucket/prefix/TENANT_ID/...
+ // We try each slash-separated segment until we find a numeric tenant ID.
+ parts := strings.Split(rest, "/")
+ for _, part := range parts {
+ if id, err := strconv.ParseUint(part, 10, 64); err == nil {
+ return id
+ }
+ }
+
+ return 0
+}
diff --git a/internal/utils/presign_test.go b/internal/utils/presign_test.go
new file mode 100644
index 00000000..794623f3
--- /dev/null
+++ b/internal/utils/presign_test.go
@@ -0,0 +1,112 @@
+package utils
+
+import (
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSignFileURL_RoundTrip(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", "weknora-test-aes-key-32bytes!!!")
+
+ baseURL := "https://weknora.example.com"
+ filePath := "local://1/abc/img.png"
+ var tenantID uint64 = 1
+
+ signed, err := SignFileURL(baseURL, filePath, tenantID, 1*time.Hour)
+ require.NoError(t, err)
+ assert.Contains(t, signed, "https://weknora.example.com/api/v1/files/presigned")
+ assert.Contains(t, signed, "file_path=")
+ assert.Contains(t, signed, "tenant_id=1")
+ assert.Contains(t, signed, "sig=")
+}
+
+func TestSignFileURL_NoKey(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", "")
+
+ _, err := SignFileURL("https://example.com", "local://1/img.png", 1, 0)
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "SYSTEM_AES_KEY")
+}
+
+func TestVerifyFileURLSig_Valid(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", "weknora-test-aes-key-32bytes!!!")
+
+ filePath := "local://42/knowledge/img.jpg"
+ var tenantID uint64 = 42
+ key := getPresignKey()
+ require.NotNil(t, key)
+
+ expires := time.Now().Add(1 * time.Hour).Unix()
+ sig := signPayload(key, filePath, tenantID, expires)
+
+ assert.True(t, VerifyFileURLSig(filePath, tenantID, strconv.FormatInt(expires, 10), sig))
+}
+
+func TestVerifyFileURLSig_Expired(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", "weknora-test-aes-key-32bytes!!!")
+
+ filePath := "local://1/img.png"
+ var tenantID uint64 = 1
+ key := getPresignKey()
+ require.NotNil(t, key)
+
+ expires := time.Now().Add(-1 * time.Hour).Unix() // already expired
+ sig := signPayload(key, filePath, tenantID, expires)
+
+ assert.False(t, VerifyFileURLSig(filePath, tenantID, strconv.FormatInt(expires, 10), sig))
+}
+
+func TestVerifyFileURLSig_Tampered(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", "weknora-test-aes-key-32bytes!!!")
+
+ filePath := "local://1/img.png"
+ var tenantID uint64 = 1
+ key := getPresignKey()
+ require.NotNil(t, key)
+
+ expires := time.Now().Add(1 * time.Hour).Unix()
+ sig := signPayload(key, filePath, tenantID, expires)
+ expiresStr := strconv.FormatInt(expires, 10)
+
+ // Tamper with file path
+ assert.False(t, VerifyFileURLSig("local://1/other.png", tenantID, expiresStr, sig))
+ // Tamper with tenant ID
+ assert.False(t, VerifyFileURLSig(filePath, 999, expiresStr, sig))
+ // Tamper with signature
+ assert.False(t, VerifyFileURLSig(filePath, tenantID, expiresStr, "deadbeef"))
+}
+
+func TestVerifyFileURLSig_NoKey(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", "")
+
+ assert.False(t, VerifyFileURLSig("local://1/img.png", 1, "99999999999", "abc"))
+}
+
+func TestParseTenantIDFromStoragePath(t *testing.T) {
+ tests := []struct {
+ path string
+ want uint64
+ }{
+ {"local://1/abc/img.png", 1},
+ {"local://42/knowledge/file.pdf", 42},
+ {"minio://bucket/1/abc/img.png", 1},
+ {"s3://bucket/weknora/1/abc/img.png", 1},
+ {"cos://bucket/region/prefix/1/abc/img.png", 1},
+ {"tos://bucket/1/abc/img.png", 1},
+ {"oss://bucket/weknora/1/abc/img.png", 1},
+ {"https://example.com/img.png", 0},
+ {"invalid", 0},
+ {"local://exports/file.csv", 0},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path, func(t *testing.T) {
+ got := ParseTenantIDFromStoragePath(tt.path)
+ assert.Equal(t, tt.want, got, "ParseTenantIDFromStoragePath(%q)", tt.path)
+ })
+ }
+}