Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(im): preserve attachment filenames (#4752)

Sun Shihao1a55ed4cd695
diff --git a/internal/im/feishu/adapter.go b/internal/im/feishu/adapter.go
index 4fe2d9f26..6d2232995 100644
--- a/internal/im/feishu/adapter.go
+++ b/internal/im/feishu/adapter.go
@@ -22,6 +22,7 @@ import (
"encoding/json"
"fmt"
"io"
+ "mime"
"mime/multipart"
"net/http"
"net/url"
@@ -832,11 +833,7 @@ func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io
// Use the original file name from the message, or extract from Content-Disposition
fileName := msg.FileName
if fileName == "" {
- if cd := resp.Header.Get("Content-Disposition"); cd != "" {
- if idx := strings.Index(cd, "filename="); idx >= 0 {
- fileName = strings.Trim(cd[idx+len("filename="):], "\" ")
- }
- }
+ fileName = contentDispositionFilename(resp.Header.Get("Content-Disposition"))
}
if fileName == "" {
fileName = msg.FileKey
@@ -845,6 +842,37 @@ func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io
return resp.Body, fileName, nil
}
+// contentDispositionFilename extracts a filename using the standard parser so
+// quoted parameters and RFC 5987 filename* are decoded correctly. A fallback
+// keeps accepting malformed headers emitted by some proxies.
+func contentDispositionFilename(cd string) string {
+ if cd == "" {
+ return ""
+ }
+ if _, params, err := mime.ParseMediaType(cd); err == nil {
+ if name := params["filename"]; name != "" {
+ return name
+ }
+ }
+ idx := strings.Index(cd, "filename=")
+ if idx < 0 {
+ return ""
+ }
+ value := strings.TrimSpace(cd[idx+len("filename="):])
+ if value == "" {
+ return ""
+ }
+ if value[0] == '"' {
+ if end := strings.IndexByte(value[1:], '"'); end >= 0 {
+ return value[1 : end+1]
+ }
+ }
+ if semi := strings.IndexByte(value, ';'); semi >= 0 {
+ value = value[:semi]
+ }
+ return strings.Trim(strings.TrimSpace(value), "\"")
+}
+
// ──────────────────────────────────────────────────────────────────────
// Feishu CardKit v1 streaming implementation (official best practice)
//
diff --git a/internal/im/feishu/content_disposition_test.go b/internal/im/feishu/content_disposition_test.go
new file mode 100644
index 000000000..327602339
--- /dev/null
+++ b/internal/im/feishu/content_disposition_test.go
@@ -0,0 +1,31 @@
+package feishu
+
+import "testing"
+
+func TestContentDispositionFilename(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ cd string
+ want string
+ }{
+ {
+ name: "quoted with extra parameter",
+ cd: `attachment; filename="Q4 Final.pdf"; size=123`,
+ want: "Q4 Final.pdf",
+ },
+ {
+ name: "RFC 5987",
+ cd: `attachment; filename*=UTF-8''%E5%AD%A3%E5%BA%A6%E6%8A%A5%E5%91%8A.pdf`,
+ want: "季度报告.pdf",
+ },
+ {name: "unquoted", cd: `attachment; filename=report.md`, want: "report.md"},
+ {name: "malformed trailing params", cd: `attachment; filename=report.md; size=123`, want: "report.md"},
+ {name: "missing", cd: `attachment`, want: ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := contentDispositionFilename(tc.cd); got != tc.want {
+ t.Fatalf("contentDispositionFilename(%q) = %q, want %q", tc.cd, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/im/im_attachment_filename_test.go b/internal/im/im_attachment_filename_test.go
new file mode 100644
index 000000000..7f08b876a
--- /dev/null
+++ b/internal/im/im_attachment_filename_test.go
@@ -0,0 +1,33 @@
+package im
+
+import (
+ "io"
+ "testing"
+)
+
+func TestInMemoryFileHeaderFilenameRoundTrip(t *testing.T) {
+ for _, name := range []string{"report.md", "季度报告.md", "Q4 \"Final\".md", "Q4; Final.md"} {
+ t.Run(name, func(t *testing.T) {
+ fh := newInMemoryFileHeader(name, []byte("body"))
+ if fh.Filename != name {
+ t.Fatalf("Filename = %q, want %q", fh.Filename, name)
+ }
+ f, err := fh.Open()
+ if err != nil {
+ t.Fatalf("Open: %v", err)
+ }
+ defer func() {
+ if err := f.Close(); err != nil {
+ t.Errorf("Close: %v", err)
+ }
+ }()
+ got, err := io.ReadAll(f)
+ if err != nil {
+ t.Fatalf("ReadAll: %v", err)
+ }
+ if string(got) != "body" {
+ t.Fatalf("content = %q, want body", got)
+ }
+ })
+ }
+}
diff --git a/internal/im/service.go b/internal/im/service.go
index f61c700b8..1a17d1d10 100644
--- a/internal/im/service.go
+++ b/internal/im/service.go
@@ -10,7 +10,6 @@ import (
"io"
"mime/multipart"
"net/http"
- "net/textproto"
"os"
"path/filepath"
"reflect"
@@ -3523,11 +3522,10 @@ func newInMemoryFileHeader(filename string, data []byte) *multipart.FileHeader {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
- h := make(textproto.MIMEHeader)
- h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, filename))
- h.Set("Content-Type", "application/octet-stream")
-
- part, err := writer.CreatePart(h)
+ // CreateFormFile escapes the filename for Content-Disposition. Building
+ // the header by string concatenation left quotes unescaped, so an
+ // attachment such as `Q4 "Final".md` parsed back as an unreadable header.
+ part, err := writer.CreateFormFile("file", filename)
if err != nil {
// Fallback: return a minimal FileHeader
return &multipart.FileHeader{Filename: filename, Size: int64(len(data))}