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
+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)
})
}
}