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
+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 ──