diff --git a/.env.example b/.env.example index 776e1952..824d4eba 100644 --- a/.env.example +++ b/.env.example @@ -169,9 +169,16 @@ APP_PORT=8080 # 远程部署如后端为 HTTPS,需设为 https # APP_SCHEME=http -# 应用外部访问地址(用于 IM 渠道中生成图片等文件的可访问链接) -# 设置为 WeKnora 实例的外部可访问 URL,如 https://weknora.example.com -# 不设置时,IM 渠道中本地存储的图片将无法正常显示(云存储不受影响) +# 应用外部访问地址(仅影响 IM 渠道中 local 后端的图片/文件链接) +# 设置为 WeKnora 实例的「IM 平台 / 客户端公网可达」URL,如 https://weknora.example.com +# +# 作用范围: +# - local 后端:必须设置,否则 IM 收到的是 local://... 路径,无法渲染 +# - MinIO/COS/OSS/S3/TOS/OBS/KS3:不读取此变量;它们的链接由各自 SDK 生成, +# host 由对应的 *_ENDPOINT 决定,同样必须公网可达 +# +# 内网 IP(192.168.x / 10.x / 172.16-31.x)和 localhost 对飞书 / 企微 / Slack +# 等 IM 平台服务器都不可达;本地开发请用 ngrok / cloudflared / frp 之类的隧道。 # APP_EXTERNAL_URL= # 前端服务端口,默认为80 @@ -312,6 +319,11 @@ CONCURRENCY_POOL_SIZE=5 # 如果使用MinIO作为文件存储,需要配置以下参数 # MinIO访问端点(host:port),连接外部MinIO时需修改 +# +# 重要:用于 IM 渠道时,MINIO_ENDPOINT 必须是 IM 平台 / 客户端公网可达的 host。 +# MinIO SDK 生成的 presigned URL 直接使用这个 host,飞书 / 企微 / Slack 等都 +# 无法解析 docker-compose 的内部服务名 minio:9000,会导致 IM 中图片不显示。 +# 推荐做法:配置一个公网域名(如 minio.example.com)并启用 HTTPS。 # MINIO_ENDPOINT=minio:9000 # MinIO访问密钥 diff --git a/internal/im/service.go b/internal/im/service.go index b8a3034e..1519cc1d 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -81,15 +81,32 @@ 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. +// +// Logging policy: +// - Successful rewrite logs at INFO with the full signed URL so operators +// can copy it out of logs and verify public reachability directly. The +// trade-off: anyone with log access can use a signed URL until it +// expires (WeKnora 2h, MinIO 24h). Acceptable for diagnosability. +// - Failure or no-op rewrite logs at WARN. The no-op case typically means +// APP_EXTERNAL_URL is not configured for the local backend, which is +// the most common cause of "image broken in IM" reports. 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 { + if err != nil { + logger.Warnf(ctx, "[IM] rewriteStorageURLs failed: src=%s err=%v", match, err) return match } + if httpURL == match { + logger.Warnf(ctx, + "[IM] rewriteStorageURLs no-op (URL unchanged; for local storage set APP_EXTERNAL_URL): src=%s", + match) + return match + } + logger.Infof(ctx, "[IM] rewriteStorageURLs: src=%s dst=%s", match, httpURL) return httpURL }) } diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index cff8b5cf..490adf19 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -29,7 +29,10 @@ 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"}, + // IM platforms (Feishu, Slack, etc.) commonly issue a HEAD request + // before GET to validate Content-Type / Content-Length when rendering + // image previews — both verbs must be allowed for image links to work. + "/api/v1/files/presigned": {"GET", "HEAD"}, } // 检查请求是否在无需认证的API列表中 diff --git a/internal/router/router.go b/internal/router/router.go index 73c65192..b0a2044c 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -138,6 +138,9 @@ func NewRouter(params RouterParams) *gin.Engine { // Presigned file access: no auth required, signature-verified. servePresignedFiles(r, params.TenantService) + // Diagnostic preview of presigned URLs (Admin only, behind auth middleware). + servePresignedPreview(r, params.Config) + // 添加OpenTelemetry追踪中间件 // r.Use(middleware.TracingMiddleware()) @@ -1289,8 +1292,17 @@ func serveFiles(r getRouteRegistrar, globalFileService interfaces.FileService) { // 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= +// Routes: +// - GET /api/v1/files/presigned?file_path=&tenant_id=&expires=&sig= +// - HEAD /api/v1/files/presigned?... (IM platforms issue HEAD first to validate +// Content-Type / Content-Length before rendering image previews; HEAD must +// succeed or the inline image renders as broken) +// +// Failure paths log client IP + User-Agent + (truncated) file_path so operators +// can correlate an IM platform's fetch against the upstream signing log line. +// Without this it is otherwise impossible to tell whether a "broken image" is +// caused by an expired signature, a stale URL cached by the platform, the +// platform's IP being blocked, or the URL simply never reaching us. func servePresignedFiles(r *gin.Engine, tenantService interfaces.TenantService) { baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR") if baseDir == "" { @@ -1298,57 +1310,72 @@ func servePresignedFiles(r *gin.Engine, tenantService interfaces.TenantService) } absDir, _ := filepath.Abs(baseDir) - r.GET("/api/v1/files/presigned", func(c *gin.Context) { + handler := presignedFileHandler(tenantService, absDir) + r.GET("/api/v1/files/presigned", handler) + r.HEAD("/api/v1/files/presigned", handler) +} + +// presignedFileHandler returns the shared Gin handler used by both GET and HEAD. +// For HEAD requests it returns the same status + headers but does not stream +// the body — this is enough for IM platforms to validate the URL while saving +// us a full read of the backing object. +func presignedFileHandler(tenantService interfaces.TenantService, absDir string) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := c.Request.Context() + clientIP := c.ClientIP() + userAgent := c.Request.UserAgent() + 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 == "" { + logger.Warnf(ctx, "[Router] /files/presigned missing params: client_ip=%s ua=%q file_path=%q tenant_id=%q expires=%q has_sig=%v", + clientIP, userAgent, filePath, tenantIDStr, expiresStr, sig != "") c.JSON(http.StatusBadRequest, gin.H{"error": "missing required parameters"}) return } if strings.Contains(filePath, "..") { + logger.Warnf(ctx, "[Router] /files/presigned rejected path traversal: client_ip=%s file_path=%q", clientIP, filePath) c.JSON(http.StatusBadRequest, gin.H{"error": "invalid file path"}) return } tenantID, err := strconv.ParseUint(tenantIDStr, 10, 64) if err != nil { + logger.Warnf(ctx, "[Router] /files/presigned invalid tenant_id: client_ip=%s tenant_id=%q err=%v", clientIP, tenantIDStr, err) c.JSON(http.StatusBadRequest, gin.H{"error": "invalid tenant_id"}) return } - // Verify HMAC signature and expiry. + // Verify HMAC signature and expiry. Logged at Warn because every 403 + // here is a signal worth investigating: either the URL was tampered + // with, the IM platform cached an expired URL, or SYSTEM_AES_KEY was + // rotated without invalidating in-flight links. if !secutils.VerifyFileURLSig(filePath, tenantID, expiresStr, sig) { + logger.Warnf(ctx, "[Router] /files/presigned sig invalid or expired: client_ip=%s ua=%q tenant_id=%d file_path=%q expires=%s", + clientIP, userAgent, tenantID, filePath, expiresStr) 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) + tenant, err := tenantService.GetTenantByID(ctx, tenantID) if err != nil { - logger.Warnf(context.Background(), "[Router] /files/presigned tenant lookup failed: tenant_id=%d err=%v", tenantID, err) + logger.Warnf(ctx, "[Router] /files/presigned tenant lookup failed: client_ip=%s tenant_id=%d err=%v", clientIP, 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) + logger.Warnf(ctx, "[Router] /files/presigned resolve file service failed: client_ip=%s tenant_id=%d provider=%s err=%v", + clientIP, 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) { @@ -1368,13 +1395,107 @@ func servePresignedFiles(r *gin.Engine, tenantService interfaces.TenantService) contentType = "application/pdf" } + // HEAD short-circuits the body read. We still need to confirm the + // object exists, but we use a 0-byte content length and skip io.Copy. + // Skipping GetFile entirely for HEAD would risk reporting 200 for a + // signed URL that no longer points at a real object; that mismatch + // would make subsequent GETs from the same client mysteriously fail. + reader, err := fileSvc.GetFile(ctx, filePath) + if err != nil { + logger.Warnf(ctx, "[Router] /files/presigned get file failed: client_ip=%s tenant_id=%d provider=%s path=%q err=%v", + clientIP, tenantID, resolvedProvider, filePath, err) + c.Status(http.StatusNotFound) + return + } + defer reader.Close() + c.Header("Content-Type", contentType) c.Header("Cache-Control", "public, max-age=86400") + if c.Request.Method == http.MethodHead { + c.Status(http.StatusOK) + return + } 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) + logger.Warnf(ctx, "[Router] /files/presigned write response failed: client_ip=%s tenant_id=%d err=%v", clientIP, tenantID, err) } - }) + } +} + +// servePresignedPreview registers an Admin-only diagnostic endpoint that +// returns the presigned HTTP URL that *would be* generated for a given +// storage path by the calling tenant's current storage config — exactly the +// URL an IM channel would embed in a reply. Operators can paste the result +// into a 4G/mobile browser to verify public reachability without having to +// send a real message through an IM bot. +// +// Route: +// - GET /api/v1/files/presigned-preview?file_path= +func servePresignedPreview(r *gin.Engine, cfg *config.Config) { + baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR") + if baseDir == "" { + baseDir = "/data/files" + } + absDir, _ := filepath.Abs(baseDir) + + r.GET("/api/v1/files/presigned-preview", + middleware.RequireRole(types.TenantRoleAdmin, cfg), + func(c *gin.Context) { + ctx := c.Request.Context() + filePath := strings.TrimSpace(c.Query("file_path")) + if filePath == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "missing required parameter: file_path"}) + return + } + if strings.Contains(filePath, "..") { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid file path"}) + return + } + + tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) + if tenant == nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: tenant context missing"}) + return + } + + provider := types.ParseProviderScheme(filePath) + fileSvc, resolvedProvider, err := filesvc.NewFileServiceFromStorageConfig(provider, tenant.StorageEngineConfig, absDir) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{ + "error": err.Error(), + "provider": provider, + "hint": "tenant storage config is missing or incomplete for this provider", + }) + return + } + + httpURL, err := fileSvc.GetFileURL(ctx, filePath) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "error": err.Error(), + "provider": resolvedProvider, + "hint": "GetFileURL failed; for local storage this usually means APP_EXTERNAL_URL is unset", + }) + return + } + + // Detect the "no-op" case where local storage falls back to the + // provider:// path because APP_EXTERNAL_URL is missing. Surfacing + // this explicitly is the whole point of the endpoint. + rewritten := httpURL != filePath + hint := "" + if !rewritten { + hint = "URL unchanged; for local storage set APP_EXTERNAL_URL to enable presigned HTTP URLs" + } + + c.JSON(http.StatusOK, gin.H{ + "file_path": filePath, + "provider": resolvedProvider, + "url": httpURL, + "rewritten": rewritten, + "hint": hint, + }) + }) } // RegisterDataSourceRoutes 注册数据源相关的路由 diff --git a/internal/router/router_presigned_test.go b/internal/router/router_presigned_test.go new file mode 100644 index 00000000..186e2ea7 --- /dev/null +++ b/internal/router/router_presigned_test.go @@ -0,0 +1,219 @@ +package router + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + secutils "github.com/Tencent/WeKnora/internal/utils" +) + +// stubTenantService is a minimal stub of interfaces.TenantService that only +// implements GetTenantByID. Every other method panics — those code paths +// must not be exercised by presigned routes; the panic surfaces test bugs +// instead of silently returning zero values. +type stubTenantService struct { + get func(ctx context.Context, id uint64) (*types.Tenant, error) +} + +var _ interfaces.TenantService = (*stubTenantService)(nil) + +func (s *stubTenantService) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) { + if s.get == nil { + return nil, os.ErrNotExist + } + return s.get(ctx, id) +} + +func (s *stubTenantService) CreateTenant(context.Context, *types.Tenant) (*types.Tenant, error) { + panic("unexpected") +} + +func (s *stubTenantService) GetTenantsByIDs(context.Context, []uint64) (map[uint64]*types.Tenant, error) { + panic("unexpected") +} +func (s *stubTenantService) ListTenants(context.Context) ([]*types.Tenant, error) { + panic("unexpected") +} + +func (s *stubTenantService) UpdateTenant(context.Context, *types.Tenant) (*types.Tenant, error) { + panic("unexpected") +} +func (s *stubTenantService) DeleteTenant(context.Context, uint64) error { panic("unexpected") } +func (s *stubTenantService) UpdateAPIKey(context.Context, uint64) (string, error) { + panic("unexpected") +} +func (s *stubTenantService) ExtractTenantIDFromAPIKey(string) (uint64, error) { panic("unexpected") } +func (s *stubTenantService) ListAllTenants(context.Context) ([]*types.Tenant, error) { + panic("unexpected") +} +func (s *stubTenantService) BulkSetStorageQuota(context.Context, int64) (int64, error) { + panic("unexpected") +} + +func (s *stubTenantService) SearchTenants(context.Context, string, uint64, int, int) ([]*types.Tenant, int64, error) { + panic("unexpected") +} + +func (s *stubTenantService) GetTenantByIDForUser(context.Context, uint64, string) (*types.Tenant, error) { + panic("unexpected") +} + +func (s *stubTenantService) GetWeKnoraCloudCredentials(context.Context) *types.WeKnoraCloudCredentials { + panic("unexpected") +} + +// setupPresignedTestServer wires presignedFileHandler with a real local file +// service rooted at a temp dir, returning the engine, baseDir, and the +// presigned URL generator helper. +func setupPresignedTestServer(t *testing.T) (engine *gin.Engine, baseDir string, signURL func(filePath string, tenantID uint64, ttl time.Duration) string) { + t.Helper() + gin.SetMode(gin.TestMode) + t.Setenv("SYSTEM_AES_KEY", "weknora-test-aes-key-32bytes!!!") + + baseDir = t.TempDir() + + tenant := &types.Tenant{ + ID: 1, + StorageEngineConfig: &types.StorageEngineConfig{ + DefaultProvider: "local", + Local: &types.LocalEngineConfig{}, + }, + } + stubTS := &stubTenantService{ + get: func(_ context.Context, id uint64) (*types.Tenant, error) { + if id == tenant.ID { + return tenant, nil + } + return nil, os.ErrNotExist + }, + } + + engine = gin.New() + handler := presignedFileHandler(stubTS, baseDir) + engine.GET("/api/v1/files/presigned", handler) + engine.HEAD("/api/v1/files/presigned", handler) + + signURL = func(filePath string, tenantID uint64, ttl time.Duration) string { + signed, err := secutils.SignFileURL("https://weknora.example.com", filePath, tenantID, ttl) + if err != nil { + t.Fatalf("SignFileURL: %v", err) + } + // Re-parse so we only keep the query part: the test server is on + // a different host than the canonical signing baseURL. + u, _ := url.Parse(signed) + return "/api/v1/files/presigned?" + u.RawQuery + } + + return engine, baseDir, signURL +} + +// writeTestFile creates baseDir/ with the given content and returns +// the matching `local://` storage path. +func writeTestFile(t *testing.T, baseDir, relPath, content string) string { + t.Helper() + full := filepath.Join(baseDir, filepath.FromSlash(relPath)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatalf("MkdirAll: %v", err) + } + if err := os.WriteFile(full, []byte(content), 0o644); err != nil { + t.Fatalf("WriteFile: %v", err) + } + return "local://" + relPath +} + +func TestPresignedFile_HEAD_Returns200WithoutBody(t *testing.T) { + engine, baseDir, signURL := setupPresignedTestServer(t) + storagePath := writeTestFile(t, baseDir, "1/img.png", "PNG-BYTES") + + req := httptest.NewRequest(http.MethodHead, signURL(storagePath, 1, time.Hour), nil) + w := httptest.NewRecorder() + engine.ServeHTTP(w, req) + + if got, want := w.Code, http.StatusOK; got != want { + t.Fatalf("status = %d, want %d (body=%q)", got, want, w.Body.String()) + } + if got := w.Header().Get("Content-Type"); got != "image/png" { + t.Fatalf("Content-Type = %q, want image/png", got) + } + // HEAD must not stream the body — protects backing storage from a + // full read on every IM preview probe. + if w.Body.Len() != 0 { + t.Fatalf("HEAD response body should be empty, got %d bytes", w.Body.Len()) + } +} + +func TestPresignedFile_GET_ReturnsContent(t *testing.T) { + engine, baseDir, signURL := setupPresignedTestServer(t) + storagePath := writeTestFile(t, baseDir, "1/img.png", "PNG-BYTES") + + req := httptest.NewRequest(http.MethodGet, signURL(storagePath, 1, time.Hour), nil) + w := httptest.NewRecorder() + engine.ServeHTTP(w, req) + + if got, want := w.Code, http.StatusOK; got != want { + t.Fatalf("status = %d, want %d", got, want) + } + if got := w.Body.String(); got != "PNG-BYTES" { + t.Fatalf("body = %q, want %q", got, "PNG-BYTES") + } +} + +func TestPresignedFile_InvalidSig_403(t *testing.T) { + engine, _, _ := setupPresignedTestServer(t) + + // Hand-craft a URL with a tampered signature. + q := url.Values{} + q.Set("file_path", "local://1/img.png") + q.Set("tenant_id", "1") + q.Set("expires", strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10)) + q.Set("sig", "deadbeefdeadbeef") + + for _, method := range []string{http.MethodGet, http.MethodHead} { + t.Run(method, func(t *testing.T) { + req := httptest.NewRequest(method, "/api/v1/files/presigned?"+q.Encode(), nil) + w := httptest.NewRecorder() + engine.ServeHTTP(w, req) + if got, want := w.Code, http.StatusForbidden; got != want { + t.Fatalf("status = %d, want %d", got, want) + } + }) + } +} + +func TestPresignedFile_MissingParams_400(t *testing.T) { + engine, _, _ := setupPresignedTestServer(t) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/files/presigned?file_path=local%3A%2F%2F1%2Fimg.png", nil) + w := httptest.NewRecorder() + engine.ServeHTTP(w, req) + if got, want := w.Code, http.StatusBadRequest; got != want { + t.Fatalf("status = %d, want %d", got, want) + } + if !strings.Contains(w.Body.String(), "missing required parameters") { + t.Fatalf("body = %q, want missing-params error", w.Body.String()) + } +} + +func TestPresignedFile_MissingFile_404(t *testing.T) { + engine, _, signURL := setupPresignedTestServer(t) + + // A legitimately signed URL pointing at a file that does not exist. + req := httptest.NewRequest(http.MethodGet, signURL("local://1/nope.png", 1, time.Hour), nil) + w := httptest.NewRecorder() + engine.ServeHTTP(w, req) + if got, want := w.Code, http.StatusNotFound; got != want { + t.Fatalf("status = %d, want %d", got, want) + } +}