fix(im): rewrite private storage URLs to HTTP in IM channel replies

IM platforms (Feishu, Slack, Telegram, DingTalk, Mattermost, WeCom) cannot
render provider:// URLs (local://, minio://, s3://, etc.) that appear in
LLM answers containing knowledge base images. The web frontend handles
these via the authenticated /files endpoint, but IM clients need publicly
resolvable HTTP URLs.

Changes:
- Add HMAC-SHA256 presigned URL utility (internal/utils/presign.go) for
  generating time-limited, signature-verified file access URLs
- Add GET /api/v1/files/presigned endpoint that serves files without
  session auth, verified by HMAC signature and expiry
- Update localFileService.GetFileURL() to return presigned HTTP URLs
  when APP_EXTERNAL_URL is configured (cloud backends already return
  presigned URLs via their SDKs)
- Add IM content rewriting pipeline: strip <image> XML tags, strip
  citation tags, rewrite storage URLs to HTTP — applied at all IM
  output points (streaming flush, non-streaming reply, fallback)
- Add holdback buffer in streaming flush to prevent URL/tag splitting
  across chunk boundaries

Closes #1058
This commit is contained in:
wizardchen
2026-04-28 20:22:04 +08:00
committed by lyingbug
parent 8c62a066af
commit 7fd566bc15
11 changed files with 727 additions and 39 deletions
+5
View File
@@ -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
+2 -1
View File
@@ -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 {
+32 -14
View File
@@ -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:
+2 -1
View File
@@ -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:
+198
View File
@@ -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 <kb id="1" title="doc"/> more`, "text more"},
{"web tag", `see <web url="http://x.com"/> here`, "see here"},
{"multiple", `<kb id="1"/><web url="x"/>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",
`<image url="local://1/img.png">
<image_original>![alt](local://1/img.png)</image_original>
<image_caption>a cat</image_caption>
</image>`,
"![alt](local://1/img.png)",
},
{
"without image_original",
`<image url="local://1/img.png">
<image_caption>a cat</image_caption>
</image>`,
"",
},
{
"no image tags",
"just plain text ![img](http://example.com/img.png)",
"just plain text ![img](http://example.com/img.png)",
},
{
"mixed content",
`before <image url="x"><image_original>![a](b)</image_original></image> after`,
"before ![a](b) 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 )",
"![img](local://1/abc/img.png)",
// 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 ![img](local://1/abc/im",
12, // starts at `l` in `local://`
},
{
"just scheme at end",
"text minio://",
5,
},
{
"no storage URL",
"just plain text http://example.com",
-1,
},
{
"URL at very end",
"local://1/img.png",
0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
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 <kb id="1"/> more`,
-1,
},
{
"incomplete kb tag",
`text <kb id="1`,
5,
},
{
"incomplete image tag",
`text <image url="local://1/img`,
5,
},
{
"incomplete image_original",
`<image_original>![alt](local://1/`,
-1, // the tag itself is complete (has >), the content is truncated
},
{
"incomplete opening image_original",
`text <image_original`,
5,
},
{
"no XML",
"just plain text",
-1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := findIncompleteXMLTag(tt.in)
assert.Equal(t, tt.want, got, "findIncompleteXMLTag(%q)", tt.in)
})
}
}
func TestHoldbackCutoff(t *testing.T) {
tests := []struct {
name string
in string
want int // expected cutoff (len(in) means no holdback)
}{
{
"no holdback needed",
"plain text with complete ![img](local://1/img.png) content",
// URL is terminated by `)` then space → no holdback
-1, // placeholder, computed below
},
{
"truncated URL",
"text ![img](local://1/abc/im",
12,
},
{
"truncated XML",
"text <kb id=",
5,
},
{
"both truncated, URL earlier",
"<image url=\"local://1/im",
0, // <image at 0 is earlier than local:// at 12
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := holdbackCutoff(tt.in)
if tt.want == -1 {
assert.Equal(t, len(tt.in), got, "holdbackCutoff(%q) should be len(in)", tt.in)
} else {
assert.Equal(t, tt.want, got, "holdbackCutoff(%q)", tt.in)
}
})
}
}
+5
View File
@@ -9,6 +9,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/redis/go-redis/v9"
)
@@ -43,6 +44,10 @@ type qaRequest struct {
channel *IMChannel
channelID string
// fileSvc resolves storage URLs to HTTP URLs for the tenant's storage backend.
// May be nil if the tenant has no storage config.
fileSvc interfaces.FileService
// userKey is "channelID:userID:chatID", used for per-user limits and /stop.
userKey string
enqueuedAt time.Time
+153 -23
View File
@@ -8,11 +8,13 @@ import (
"io"
"mime/multipart"
"net/textproto"
"os"
"regexp"
"strings"
"sync"
"time"
filesvc "github.com/Tencent/WeKnora/internal/application/service/file"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
@@ -52,6 +54,124 @@ func stripIMCitationTags(s string) string {
return imCitationTagRe.ReplaceAllString(s, "")
}
// imageXMLBlockRe matches <image ...>...</image> 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)<image\b[^>]*>.*?</image>`)
// imageOriginalRe extracts the original markdown image syntax from <image_original> tags.
var imageOriginalRe = regexp.MustCompile(`<image_original>(.*?)</image_original>`)
// stripImageXMLTags collapses <image> blocks back to plain markdown.
// Extracts the original ![alt](url) from <image_original> 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 <image…>, <kb…>, or <web…> 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 <image> XML blocks back to plain markdown
// 2. Strip <kb/> and <web/> 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 <think> 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 <kb .../> / <web .../> 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 ──
+1
View File
@@ -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列表中
+96
View File
@@ -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=<provider://...>&tenant_id=<id>&expires=<unix>&sig=<hmac>
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
+121
View File
@@ -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
}
+112
View File
@@ -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)
})
}
}