Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5906 feat(wecom): read the photos, files and videos people send the bot (#6605)

Xichang(Seacen) Zhao00e12d340301
diff --git a/.env.example b/.env.example
index 0aef6429f1..e4b607079c 100644
--- a/.env.example
+++ b/.env.example
@@ -182,6 +182,24 @@ GOOGLE_REDIRECT_URI=${FRONTEND_ORIGIN}/auth/callback
# and the wecom Web-UI endpoints return 503.
# Generate with: openssl rand -base64 32
#
+# MULTICA_WECOM_MEDIA_ALLOW_CIDRS
+# Comma-separated ranges the media fetcher may
+# dial even though they look reserved. Empty by
+# default, and that is the right value almost
+# everywhere: the guard exists because a callback
+# hands us a URL somebody else controls, and a
+# redirect to a metadata endpoint is one line of
+# response away.
+# Set it only behind a fake-IP proxy, where every
+# public hostname resolves into the proxy's pool
+# (commonly 198.18.0.0/15) and WeCom's own image
+# host is therefore refused along with everything
+# else. Whatever you list here becomes reachable
+# by a URL WeCom supplies. Loopback, the private
+# ranges and the IPv6 translation prefixes
+# (64:ff9b::/96, 64:ff9b:1::/48, 2002::/16 —
+# IPv4 addresses in an IPv6 spelling) are refused
+# regardless and cannot be opened this way.
# MULTICA_WECOM_TRACE 1 = log every frame this adapter reads and
# writes, so a real-device session can be checked
# against the server afterwards. Empty / anything
@@ -214,6 +232,7 @@ GOOGLE_REDIRECT_URI=${FRONTEND_ORIGIN}/auth/callback
# the lease are dropped and the user sees nothing. Until cross-replica outbound
# routing lands, run the WeCom-enabled backend as a SINGLE replica.
MULTICA_WECOM_SECRET_KEY=
+MULTICA_WECOM_MEDIA_ALLOW_CIDRS=
MULTICA_WECOM_TRACE=
# S3 / CloudFront
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index b9ea70dd85..ed9690d7fd 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -146,6 +146,11 @@ services:
# subscribe credentials at connection time, and to seal the secret when
# an installation is created from the WeCom settings tab.
MULTICA_WECOM_SECRET_KEY: ${MULTICA_WECOM_SECRET_KEY:-}
+ # Comma-separated ranges the inbound media fetcher may dial even though
+ # they look reserved. Empty (the default) keeps the SSRF guard as strict
+ # as it ships; set it only behind a fake-IP proxy whose pool would
+ # otherwise get every attachment refused. See .env.example.
+ MULTICA_WECOM_MEDIA_ALLOW_CIDRS: ${MULTICA_WECOM_MEDIA_ALLOW_CIDRS:-}
# 1 = log every inbound and outbound WeCom frame, including the first
# 120 runes of each message body, so a real-device session can be
# checked against the server afterwards. Off unless set; turn it on only
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 17b18bf83c..a5e3c808ca 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -701,8 +701,23 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
Metrics: wecomMetricsOrNil(opts.WecomMetrics),
Logger: slog.Default(),
})
+ // Inbound media: a callback carries a pre-signed COS url and
+ // a per-url key, so the resolver needs no WeCom credential —
+ // only somewhere durable to put the bytes. Without an object
+ // store there is nothing to point an attachment at, so the
+ // resolver is left nil and attachments stay as their
+ // placeholder text. Same nil-guard as DingTalk above.
+ var wecomMedia engine.MediaResolver
+ if store != nil {
+ wecomMedia = wecom.NewMediaResolver(
+ store,
+ engine.NewDBMediaIntentLedger(queries),
+ wecomSenders,
+ slog.Default(),
+ )
+ }
channelRouter.Register(wecom.TypeWecom, wecom.NewResolverSet(
- wecomStore, wecomSession, wecomReplier,
+ wecomStore, wecomSession, wecomReplier, wecomMedia,
))
// EventChatDone subscriber: pushes the agent's chat reply
@@ -712,6 +727,21 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// user in WeCom sees no response.
wecom.NewOutbound(queries, wecomSenders, slog.Default()).Register(bus)
+ // Ranges the media fetcher may dial despite looking reserved.
+ // Empty by default, which leaves the SSRF guard exactly as
+ // strict as it ships. A deployment behind a fake-IP proxy
+ // needs it: there, every public hostname resolves into the
+ // proxy's pool (198.18.0.0/15 is the common one), so WeCom's
+ // own COS host is indistinguishable from a metadata endpoint
+ // by address alone and every attachment is refused.
+ if raw := strings.TrimSpace(os.Getenv("MULTICA_WECOM_MEDIA_ALLOW_CIDRS")); raw != "" {
+ for _, err := range wecom.SetMediaAllowedPrefixes(strings.Split(raw, ",")) {
+ slog.Error("wecom: ignoring malformed media allow cidr", "error", err)
+ }
+ slog.Warn("wecom: media guard has an operator allow-list; those ranges are reachable by a URL WeCom supplies",
+ "cidrs", raw)
+ }
+
// Frame tracing: off unless an operator asks for it. It
// records a bounded prefix of message text, so the fact that
// it is on has to be visible in the log it is writing into —
diff --git a/server/cmd/server/wecom_media_allow_wiring_test.go b/server/cmd/server/wecom_media_allow_wiring_test.go
new file mode 100644
index 0000000000..2e9f9b3605
--- /dev/null
+++ b/server/cmd/server/wecom_media_allow_wiring_test.go
@@ -0,0 +1,142 @@
+package main
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "testing"
+)
+
+// routerSourceFile is parsed by TestWecomMediaAllowListIsWiredAtBoot. Kept as
+// a constant so a rename shows up as one failing test rather than a silently
+// skipped guard.
+const routerSourceFile = "router.go"
+
+const wecomMediaAllowEnv = "MULTICA_WECOM_MEDIA_ALLOW_CIDRS"
+
+// TestWecomMediaAllowListIsWiredAtBoot guards the operator switch behind the
+// media guard's allow-list.
+//
+// wecom.SetMediaAllowedPrefixes widens the SSRF guard that stands between a
+// WeCom-supplied URL and the deployment's own network. It shipped once with no
+// production caller at all: the exemption existed, its own doc comment claimed
+// it was "called at boot from MULTICA_WECOM_MEDIA_ALLOW_CIDRS", and nothing
+// read that variable. An operator behind a fake-IP proxy — where every
+// hostname resolves into 198.18.0.0/15 and the guard therefore refuses every
+// download — had the exemption and no way to turn it on.
+//
+// This parses router.go rather than asserting on behaviour, for the same
+// reason TestMainUsesRouterOwnedBackgroundServices does: the regression being
+// guarded is the absence of a call, and no value-level assertion can observe a
+// call that was never made. The allow-list itself lives in unexported package
+// state, so the only thing reachable from here is the wiring.
+func TestWecomMediaAllowListIsWiredAtBoot(t *testing.T) {
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, routerSourceFile, nil, 0)
+ if err != nil {
+ t.Fatalf("parse %s: %v", routerSourceFile, err)
+ }
+
+ var (
+ readsEnv string // position of os.Getenv(wecomMediaAllowEnv)
+ appliesIt string // position of wecom.SetMediaAllowedPrefixes(...)
+ )
+ for _, decl := range file.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ // Both must sit in the SAME function. Reading the variable in one
+ // place and calling the setter in another is how the two halves drift
+ // apart again — e.g. a caller that only ever passes a constant.
+ var envHere, applyHere string
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ switch calleeName(call) {
+ case "os.Getenv":
+ if len(call.Args) == 1 && stringLit(call.Args[0]) == wecomMediaAllowEnv {
+ envHere = fset.Position(call.Pos()).String()
+ }
+ case "wecom.SetMediaAllowedPrefixes":
+ applyHere = fset.Position(call.Pos()).String()
+ }
+ return true
+ })
+ if envHere != "" && applyHere != "" {
+ readsEnv, appliesIt = envHere, applyHere
+ break
+ }
+ if envHere != "" {
+ readsEnv = envHere
+ }
+ if applyHere != "" {
+ appliesIt = applyHere
+ }
+ }
+
+ if readsEnv == "" {
+ t.Errorf("no os.Getenv(%q) in %s — the media guard's allow-list has no operator switch again",
+ wecomMediaAllowEnv, routerSourceFile)
+ }
+ if appliesIt == "" {
+ t.Errorf("no call to wecom.SetMediaAllowedPrefixes in %s — %s is read but never reaches the guard",
+ routerSourceFile, wecomMediaAllowEnv)
+ }
+ if t.Failed() {
+ t.FailNow()
+ }
+
+ // The errors SetMediaAllowedPrefixes returns are the only report an
+ // operator gets for a typo'd CIDR. Dropping them on the floor turns a
+ // malformed entry into a guard that is silently narrower than the .env
+ // says it is.
+ if !reportsMalformedCIDRs(fset, file) {
+ t.Errorf("the []error from wecom.SetMediaAllowedPrefixes at %s is discarded — a malformed %s entry would be dropped silently",
+ appliesIt, wecomMediaAllowEnv)
+ }
+}
+
+// reportsMalformedCIDRs reports whether the SetMediaAllowedPrefixes call site
+// consumes the returned errors — ranged over, assigned, or passed on — rather
+// than being used as a bare statement.
+func reportsMalformedCIDRs(fset *token.FileSet, file *ast.File) bool {
+ var consumed bool
+ ast.Inspect(file, func(n ast.Node) bool {
+ if consumed {
+ return false
+ }
+ switch stmt := n.(type) {
+ case *ast.ExprStmt:
+ // A bare `wecom.SetMediaAllowedPrefixes(...)` throws the errors away.
+ if call, ok := stmt.X.(*ast.CallExpr); ok && calleeName(call) == "wecom.SetMediaAllowedPrefixes" {
+ return false
+ }
+ case *ast.RangeStmt:
+ if call, ok := stmt.X.(*ast.CallExpr); ok && calleeName(call) == "wecom.SetMediaAllowedPrefixes" {
+ consumed = true
+ return false
+ }
+ case *ast.AssignStmt:
+ for _, rhs := range stmt.Rhs {
+ if call, ok := rhs.(*ast.CallExpr); ok && calleeName(call) == "wecom.SetMediaAllowedPrefixes" {
+ consumed = true
+ return false
+ }
+ }
+ }
+ return true
+ })
+ return consumed
+}
+
+// stringLit returns the value of a plain string literal, or "".
+func stringLit(e ast.Expr) string {
+ lit, ok := e.(*ast.BasicLit)
+ if !ok || lit.Kind != token.STRING || len(lit.Value) < 2 {
+ return ""
+ }
+ return lit.Value[1 : len(lit.Value)-1]
+}
diff --git a/server/internal/integrations/wecom/dispatch_test.go b/server/internal/integrations/wecom/dispatch_test.go
index 97818a2471..c467ce3982 100644
--- a/server/internal/integrations/wecom/dispatch_test.go
+++ b/server/internal/integrations/wecom/dispatch_test.go
@@ -1,9 +1,10 @@
package wecom
// dispatch_test.go — dispatchFrame routing, driven with a recording wsConn and
-// a capturing handler (no network). Covers the text-only receipt for non-text
-// messages, the text path reaching the handler, the superseded-disconnect
-// escalation, and the server-ping / pong frames.
+// a capturing handler (no network). Covers the receipt for a kind that cannot
+// be read, the text path reaching the handler, the superseded-disconnect
+// escalation, and the server-ping / pong frames. Media routing lives next
+// door in inbound_media_test.go.
import (
"context"
@@ -55,27 +56,35 @@ func TestDispatchFrame_TextReachesHandler(t *testing.T) {
}
}
-func TestDispatchFrame_NonTextGetsReceiptAndSkipsHandler(t *testing.T) {
+func TestDispatchFrame_UnreadableKindGetsReceiptAndSkipsHandler(t *testing.T) {
t.Parallel()
- called := false
- c := testChannel(func(context.Context, channel.InboundMessage) error {
- called = true
- return nil
- })
- conn := &recordingConn{}
- err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "image", ""), conn.autoAck(newWSSender(conn, nil)), slog.Default())
- if err != nil {
- t.Fatalf("dispatchFrame: %v", err)
- }
- if called {
- t.Error("handler must NOT be called for a non-text message")
- }
- if len(conn.frames) != 1 {
- t.Fatalf("expected one text-only receipt, got %d frames", len(conn.frames))
- }
- body := conn.sendBody(t, 0)
- if body["chatid"] != "CHAT_1" {
- t.Errorf("receipt chatid = %v, want the same chat CHAT_1", body["chatid"])
+ // Two ways a callback can be unreadable: a kind this adapter does not
+ // model at all, and a kind it does model that arrived without the one
+ // field that makes it usable (an image frame carrying no url).
+ for _, name := range []string{"location", "image"} {
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+ called := false
+ c := testChannel(func(context.Context, channel.InboundMessage) error {
+ called = true
+ return nil
+ })
+ conn := &recordingConn{}
+ err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, name, ""), conn.autoAck(newWSSender(conn, nil)), slog.Default())
+ if err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if called {
+ t.Error("handler must NOT be called for a message with nothing readable in it")
+ }
+ if len(conn.frames) != 1 {
+ t.Fatalf("expected one receipt, got %d frames", len(conn.frames))
+ }
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "CHAT_1" {
+ t.Errorf("receipt chatid = %v, want the same chat CHAT_1", body["chatid"])
+ }
+ })
}
}
diff --git a/server/internal/integrations/wecom/inbound_media_bind_db_test.go b/server/internal/integrations/wecom/inbound_media_bind_db_test.go
new file mode 100644
index 0000000000..626245c2fb
--- /dev/null
+++ b/server/internal/integrations/wecom/inbound_media_bind_db_test.go
@@ -0,0 +1,614 @@
+package wecom
+
+// inbound_media_bind_db_test.go — the other half of inbound media: what
+// happens to a MediaRef AFTER the resolver has stored the object.
+//
+// media_ingest_test.go proves the download/decrypt/upload works. It cannot
+// see this defect, because it calls ResolveMedia directly and never asks who
+// consumes what it returns. The answer, on the shipped code, was nobody: the
+// wecom sessionBinder's BindMedia returned nil without touching the session
+// store, so a photo landed in object storage, its intent row stayed 'pending'
+// forever, no attachment row was ever created, and the agent kept seeing the
+// bare "[Image]" placeholder. Nothing was logged on that path — the Router
+// only warns when BindMedia returns an error, and returning nil is how you
+// say "bound fine".
+//
+// So this test drives the whole real path — engine.Router.Handle over the
+// real wecom ResolverSet, the real engine.ChatSession, a real Postgres and a
+// real HTTP download of really-encrypted bytes — and asks the database the
+// one question the user asked: is there an attachment on that message?
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func mediaBindTestDB(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+ dsn := os.Getenv("DATABASE_URL")
+ if dsn == "" {
+ dsn = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Skipf("no database: %v", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ t.Skipf("database not reachable: %v", err)
+ }
+ var migrated bool
+ if err := pool.QueryRow(ctx, `
+ SELECT to_regclass('public.attachment') IS NOT NULL
+ AND to_regclass('public.channel_media_pending_object') IS NOT NULL`).Scan(&migrated); err != nil || !migrated {
+ pool.Close()
+ t.Skip("channel media tables not present (database not migrated)")
+ }
+ t.Cleanup(pool.Close)
+ return pool
+}
+
+type mediaBindFixture struct {
+ workspaceID pgtype.UUID
+ userID pgtype.UUID
+ agentID pgtype.UUID
+ installationID pgtype.UUID
+ botID string
+ senderID string
+}
+
+// seedMediaBindFixture builds exactly what the wecom ResolverSet resolves
+// against: an installation keyed by bot id, and a user binding keyed by the
+// anonymized aibot userid. Everything hangs off one workspace so cleanup is
+// a single cascade.
+func seedMediaBindFixture(t *testing.T, pool *pgxpool.Pool) mediaBindFixture {
+ t.Helper()
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ f := mediaBindFixture{
+ botID: fmt.Sprintf("wb-bind-%d", suffix),
+ senderID: fmt.Sprintf("T-bind-%d", suffix),
+ }
+ var runtimeID pgtype.UUID
+
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ "wecom media bind", fmt.Sprintf("wecom-media-bind-%[email protected]", suffix)).Scan(&f.userID); err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+ t.Cleanup(func() {
+ cleanup := context.Background()
+ if f.workspaceID.Valid {
+ _, _ = pool.Exec(cleanup, `DELETE FROM channel_media_pending_object WHERE workspace_id = $1`, f.workspaceID)
+ _, _ = pool.Exec(cleanup, `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, f.installationID)
+ _, _ = pool.Exec(cleanup, `DELETE FROM workspace WHERE id = $1`, f.workspaceID)
+ }
+ if f.userID.Valid {
+ _, _ = pool.Exec(cleanup, `DELETE FROM "user" WHERE id = $1`, f.userID)
+ }
+ })
+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug, description) VALUES ($1, $2, '') RETURNING id`,
+ "wecom media bind", fmt.Sprintf("wecom-media-bind-%d", suffix)).Scan(&f.workspaceID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`,
+ f.workspaceID, f.userID); err != nil {
+ t.Fatalf("create member: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, owner_id)
+ VALUES ($1, $2, 'local', 'multica_daemon', $3) RETURNING id`,
+ f.workspaceID, fmt.Sprintf("wecom-bind-runtime-%d", suffix), f.userID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent (workspace_id, name, runtime_mode, runtime_id, owner_id)
+ VALUES ($1, $2, 'local', $3, $4) RETURNING id`,
+ f.workspaceID, fmt.Sprintf("wecom-bind-agent-%d", suffix), runtimeID, f.userID).Scan(&f.agentID); err != nil {
+ t.Fatalf("create agent: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, installer_user_id, status)
+ VALUES ($1, $2, 'wecom',
+ jsonb_build_object('app_id', $3::text, 'bot_id', $3::text, 'app_secret_encrypted', ''),
+ $4, 'active')
+ RETURNING id`, f.workspaceID, f.agentID, f.botID, f.userID).Scan(&f.installationID); err != nil {
+ t.Fatalf("create installation: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_user_binding (workspace_id, multica_user_id, installation_id, channel_type, channel_user_id)
+ VALUES ($1, $2, $3, 'wecom', $4)`,
+ f.workspaceID, f.userID, f.installationID, f.senderID); err != nil {
+ t.Fatalf("create user binding: %v", err)
+ }
+ return f
+}
+
+// ---- the Router's collaborators, reduced to what this path touches ----
+
+type bindTestIssues struct{}
+
+func (bindTestIssues) Create(context.Context, service.IssueCreateParams, service.IssueCreateOpts) (service.IssueCreateResult, error) {
+ return service.IssueCreateResult{}, errors.New("no /issue in this test")
+}
+func (bindTestIssues) PublishAttachmentsChanged(context.Context, db.Issue, pgtype.UUID) {}
+
+// bindTestTasks stands in for the task service. Enqueueing a real chat task
+// would need a live runtime, and the run trigger is not what is under test —
+// but the media-ready promotion IS called on the media path, so it is
+// recorded rather than ignored.
+//
+// The counter is guarded because the two sides sit on different goroutines:
+// the Router calls the promotion from the detached media goroutine it spawns
+// in enqueueMedia, while the test reads the count on its own. The database
+// poll the test waits on is not a synchronisation edge between them — it
+// observes the bind transaction, which commits one call EARLIER than this one
+// in resolveAndBindMedia, so an unguarded read is both a data race and, on the
+// wrong interleaving, a read of zero.
+type bindTestTasks struct {
+ mu sync.Mutex
+ promoted int
+}
+
+func (*bindTestTasks) EnqueueChatTask(context.Context, db.ChatSession, pgtype.UUID, bool) (db.AgentTaskQueue, error) {
+ return db.AgentTaskQueue{}, nil
+}
+func (b *bindTestTasks) PromoteChannelChatTasksIfMediaReady(context.Context, pgtype.UUID) error {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ b.promoted++
+ return nil
+}
+func (*bindTestTasks) PromoteDeferredChannelIssueTask(context.Context, pgtype.UUID) error {
+ return nil
+}
+
+// promotions is the only way to read the counter from the test goroutine.
+func (b *bindTestTasks) promotions() int {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.promoted
+}
+
+// wecomImageCallback builds the inbound envelope for a standalone image,
+// through the real frame decoder so the fixture cannot drift from the wire.
+func wecomImageCallback(t *testing.T, botID, senderID, msgID, url string) channel.InboundMessage {
+ t.Helper()
+ raw, err := json.Marshal(map[string]any{
+ "msgid": msgID,
+ "aibotid": botID,
+ "chattype": "single",
+ "chatid": senderID,
+ "from": map[string]any{"userid": senderID},
+ "msgtype": "image",
+ "image": map[string]any{"url": url, "aeskey": testAESKey},
+ })
+ if err != nil {
+ t.Fatalf("marshal callback: %v", err)
+ }
+ var mc aibotMsgCallback
+ if err := json.Unmarshal(raw, &mc); err != nil {
+ t.Fatalf("decode callback: %v", err)
+ }
+ text, ok := mc.ownText()
+ if !ok {
+ t.Fatal("image callback is not routable; the fixture is wrong")
+ }
+ return channelMessageFromCallback(botID, "", mc, text, "req-bind-1")
+}
+
+// stalledCOSServer accepts the request and then holds it open, so the media
+// path is genuinely still in flight while the durable message is inspected.
+func stalledCOSServer(release <-chan struct{}) *httptest.Server {
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ }
+ }))
+}
+
+// TestInboundImageBecomesAnAttachmentOnTheChatMessage is the regression for
+// "the image downloads fine and the agent still only sees [Image]".
+//
+// Every assertion here is a thing the user could check by hand in the
+// database, and on the shipped code all four were false while the file sat
+// happily in object storage.
+func TestInboundImageBecomesAnAttachmentOnTheChatMessage(t *testing.T) {
+ pool := mediaBindTestDB(t)
+ fixture := seedMediaBindFixture(t, pool)
+ ctx := context.Background()
+ queries := db.New(pool)
+
+ plaintext := []byte("\xff\xd8\xff\xe0 not really a jpeg, but really encrypted")
+ srv := cosServer(t, plaintext, `attachment; filename="holiday.jpg"`)
+ defer srv.Close()
+
+ // The production wiring, with two seams swapped for test doubles that do
+ // not change the path: object bytes go to memory instead of disk/S3, and
+ // the HTTP client also permits loopback so the httptest server is
+ // reachable. The intent ledger is the REAL database one — the bind
+ // transaction claims those rows, so a fake would hide the claim.
+ storage := &fakeMediaStorage{}
+ resolver := newTestResolver(storage, engine.NewDBMediaIntentLedger(queries), nil)
+ session := engine.NewChatSession(queries, pool, TypeWecom, engine.SessionTitles{
+ Group: "群聊", Direct: "单聊", Fallback: "会话",
+ })
+ tasks := &bindTestTasks{}
+ router := engine.NewRouter(bindTestIssues{}, tasks, queries, engine.RouterConfig{
+ MediaTimeout: 20 * time.Second,
+ Logger: testLogger(),
+ })
+ router.Register(TypeWecom, NewResolverSet(NewStore(queries), session, nil, resolver))
+
+ msgID := fmt.Sprintf("MSGID-BIND-%d", time.Now().UnixNano())
+ if err := router.Handle(ctx, wecomImageCallback(t, fixture.botID, fixture.senderID, msgID, srv.URL)); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+
+ // The durable message lands on the ACK path; media binding is detached,
+ // so poll rather than sleep. Drain is not usable here: it cancels the
+ // media context, which is the very thing being waited on.
+ var chatMessageID, sessionID pgtype.UUID
+ var body string
+ var pendingUntil pgtype.Timestamptz
+ deadline := time.Now().Add(15 * time.Second)
+ var attachments int
+ for {
+ if err := pool.QueryRow(ctx, `
+ SELECT cm.id, cm.chat_session_id, cm.content, cm.channel_media_pending_until
+ FROM chat_message cm
+ JOIN chat_session cs ON cs.id = cm.chat_session_id
+ WHERE cs.workspace_id = $1 AND cm.role = 'user'
+ ORDER BY cm.created_at DESC LIMIT 1`,
+ fixture.workspaceID).Scan(&chatMessageID, &sessionID, &body, &pendingUntil); err != nil {
+ if time.Now().After(deadline) {
+ t.Fatalf("no durable chat_message was ever written: %v", err)
+ }
+ time.Sleep(100 * time.Millisecond)
+ continue
+ }
+ if err := pool.QueryRow(ctx,
+ `SELECT count(*) FROM attachment WHERE chat_message_id = $1`, chatMessageID).Scan(&attachments); err != nil {
+ t.Fatalf("count attachments: %v", err)
+ }
+ // Both, not just the attachment row: the promotion is the call AFTER
+ // the bind transaction in resolveAndBindMedia, so an attachment row is
+ // not evidence that the media goroutine has reached the end of its
+ // work. Waiting on the row alone leaves assertion 4 reading a counter
+ // that is still about to be incremented.
+ if (attachments > 0 && tasks.promotions() > 0) || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+
+ // 1. The resolver did its job — this is the precondition, not the point.
+ // If it fails, the defect is upstream of the binder and the rest of this
+ // test is meaningless.
+ if stored := storage.stored(); len(stored) != 1 {
+ t.Fatalf("objects in storage = %d, want 1 — the download/decrypt/upload failed, so this test is not exercising the binder", len(stored))
+ }
+ if body != "[Image]" {
+ t.Errorf("durable body = %q, want the %q placeholder", body, "[Image]")
+ }
+
+ // 2. The attachment row: what the agent actually reads.
+ if attachments != 1 {
+ t.Fatalf("attachment rows on the chat message = %d, want 1 — the image was stored but never bound, so the agent only ever sees %q", attachments, body)
+ }
+ var filename, contentType, url string
+ var sizeBytes int64
+ var attSession, uploader pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT filename, content_type, url, size_bytes, chat_session_id, uploader_id
+ FROM attachment WHERE chat_message_id = $1`, chatMessageID).
+ Scan(&filename, &contentType, &url, &sizeBytes, &attSession, &uploader); err != nil {
+ t.Fatalf("load attachment: %v", err)
+ }
+ if filename != "holiday.jpg" {
+ t.Errorf("filename = %q, want holiday.jpg (from the download's Content-Disposition)", filename)
+ }
+ if contentType != "image/jpeg" {
+ t.Errorf("content_type = %q, want image/jpeg", contentType)
+ }
+ if sizeBytes != int64(len(plaintext)) {
+ t.Errorf("size_bytes = %d, want the decrypted length %d", sizeBytes, len(plaintext))
+ }
+ if url != storage.ObjectURL(storage.stored()[0].key) {
+ t.Errorf("attachment url = %q, does not point at the object that was stored", url)
+ }
+ if attSession != sessionID {
+ t.Errorf("attachment chat_session_id = %v, want the message's session %v", attSession, sessionID)
+ }
+ if uploader != fixture.userID {
+ t.Errorf("uploader_id = %v, want the bound sender %v", uploader, fixture.userID)
+ }
+
+ // 3. The intent ledger settled. A row left 'pending' is the ledger saying
+ // an object was uploaded and never claimed — the reconciler would
+ // eventually delete the very file the user sent.
+ var pending int
+ if err := pool.QueryRow(ctx,
+ `SELECT count(*) FROM channel_media_pending_object WHERE workspace_id = $1`,
+ fixture.workspaceID).Scan(&pending); err != nil {
+ t.Fatalf("count pending intents: %v", err)
+ }
+ if pending != 0 {
+ t.Errorf("channel_media_pending_object rows = %d, want 0 — the bind never claimed the intent, so the reconciler will reclaim a live attachment", pending)
+ }
+
+ // 4. The pending marker is cleared, which is what releases the agent run.
+ if pendingUntil.Valid {
+ t.Errorf("channel_media_pending_until = %v, want NULL after binding", pendingUntil.Time)
+ }
+ if tasks.promotions() == 0 {
+ t.Error("PromoteChannelChatTasksIfMediaReady was never called")
+ }
+}
+
+// TestInboundImageMessageHoldsTheAgentRunUntilMediaLands covers the second
+// half of the same wiring gap. The budget the Router computes has to reach
+// the append, or the message row carries a NULL channel_media_pending_until,
+// EnqueueChatTask reads FireAt = NULL, and the run starts immediately on the
+// placeholder while the download is still in flight — the same user-visible
+// symptom, arrived at a different way.
+func TestInboundImageMessageHoldsTheAgentRunUntilMediaLands(t *testing.T) {
+ pool := mediaBindTestDB(t)
+ fixture := seedMediaBindFixture(t, pool)
+ ctx := context.Background()
+ queries := db.New(pool)
+
+ // A server that never answers: the message must be durable, and marked
+ // as awaiting media, long before the download resolves.
+ blocked := make(chan struct{})
+ t.Cleanup(func() { close(blocked) })
+ srv := stalledCOSServer(blocked)
+ defer srv.Close()
+
+ storage := &fakeMediaStorage{}
+ resolver := newTestResolver(storage, engine.NewDBMediaIntentLedger(queries), nil)
+ session := engine.NewChatSession(queries, pool, TypeWecom, engine.SessionTitles{})
+ router := engine.NewRouter(bindTestIssues{}, &bindTestTasks{}, queries, engine.RouterConfig{
+ MediaTimeout: 25 * time.Second,
+ Logger: testLogger(),
+ })
+ router.Register(TypeWecom, NewResolverSet(NewStore(queries), session, nil, resolver))
+
+ msgID := fmt.Sprintf("MSGID-HOLD-%d", time.Now().UnixNano())
+ if err := router.Handle(ctx, wecomImageCallback(t, fixture.botID, fixture.senderID, msgID, srv.URL)); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+
+ var pendingUntil pgtype.Timestamptz
+ var content string
+ if err := pool.QueryRow(ctx, `
+ SELECT cm.channel_media_pending_until, cm.content
+ FROM chat_message cm
+ JOIN chat_session cs ON cs.id = cm.chat_session_id
+ WHERE cs.workspace_id = $1 AND cm.role = 'user'
+ ORDER BY cm.created_at DESC LIMIT 1`, fixture.workspaceID).Scan(&pendingUntil, &content); err != nil {
+ t.Fatalf("load durable message: %v", err)
+ }
+ if content != "[Image]" {
+ t.Fatalf("durable body = %q, want the [Image] placeholder", content)
+ }
+ if !pendingUntil.Valid {
+ t.Fatal("channel_media_pending_until is NULL on a message carrying an image — the chat task will fire at once and hand the agent the placeholder while the download is still running")
+ }
+ if !pendingUntil.Time.After(time.Now()) {
+ t.Errorf("channel_media_pending_until = %v, already in the past — it buys the download no time at all", pendingUntil.Time)
+ }
+}
+
+// recordingIssues is an IssueCreator that answers yes and remembers what it
+// was asked to file. The issue row itself is synthetic: nothing downstream of
+// the create reads it here (an invalid IssueID skips the issue-media lock in
+// BindMediaRefs), and what these tests need to know is whether an issue was
+// filed at all and under what title.
+type recordingIssues struct {
+ mu sync.Mutex
+ params []service.IssueCreateParams
+}
+
+func (r *recordingIssues) Create(_ context.Context, p service.IssueCreateParams, _ service.IssueCreateOpts) (service.IssueCreateResult, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.params = append(r.params, p)
+ return service.IssueCreateResult{Issue: db.Issue{Title: p.Title}}, nil
+}
+
+func (r *recordingIssues) PublishAttachmentsChanged(context.Context, db.Issue, pgtype.UUID) {}
+
+func (r *recordingIssues) filed() []service.IssueCreateParams {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return append([]service.IssueCreateParams(nil), r.params...)
+}
+
+// wecomMixedCallback builds a 图文混排 callback whose FIRST run is the
+// screenshot and whose second is what the sender typed — the ordering that
+// filed nothing. It goes through the real frame decoder and the real
+// normalization, including the group mention strip, so nothing about the
+// command source is decided by the fixture.
+// spoken picks which kind of run carries the sender's words. Both are the
+// sender's own words — WeCom recognises a voice run on its side and delivers
+// the transcript — and the command source has to read them the same way.
+func wecomMixedCallback(t *testing.T, botID, botDisplayName, senderID, msgID, chatType, chatID, imageURL, words string, spoken bool) channel.InboundMessage {
+ t.Helper()
+ wordRun := map[string]any{"msgtype": "text", "text": map[string]any{"content": words}}
+ if spoken {
+ wordRun = map[string]any{"msgtype": "voice", "voice": map[string]any{"content": words}}
+ }
+ raw, err := json.Marshal(map[string]any{
+ "msgid": msgID,
+ "aibotid": botID,
+ "chattype": chatType,
+ "chatid": chatID,
+ "from": map[string]any{"userid": senderID},
+ "msgtype": "mixed",
+ "mixed": map[string]any{"msg_item": []map[string]any{
+ {"msgtype": "image", "image": map[string]any{"url": imageURL, "aeskey": testAESKey}},
+ wordRun,
+ }},
+ })
+ if err != nil {
+ t.Fatalf("marshal callback: %v", err)
+ }
+ var mc aibotMsgCallback
+ if err := json.Unmarshal(raw, &mc); err != nil {
+ t.Fatalf("decode callback: %v", err)
+ }
+ text, ok := mc.ownText()
+ if !ok {
+ t.Fatal("mixed callback is not routable; the fixture is wrong")
+ }
+ return channelMessageFromCallback(botID, botDisplayName, mc, text, "req-mixed-1")
+}
+
+// runMixedIssueThroughTheRouter drives one 图文混排 through the real Router,
+// the real ChatSession and a real Postgres, and reports what got filed and
+// what the durable message says.
+func runMixedIssueThroughTheRouter(t *testing.T, botDisplayName, chatType, chatID, words string, spoken bool) (*recordingIssues, string) {
+ t.Helper()
+ pool := mediaBindTestDB(t)
+ fixture := seedMediaBindFixture(t, pool)
+ ctx := context.Background()
+ queries := db.New(pool)
+
+ srv := cosServer(t, []byte("\xff\xd8\xff\xe0 a screenshot"), `attachment; filename="shot.jpg"`)
+ defer srv.Close()
+
+ storage := &fakeMediaStorage{}
+ resolver := newTestResolver(storage, engine.NewDBMediaIntentLedger(queries), nil)
+ session := engine.NewChatSession(queries, pool, TypeWecom, engine.SessionTitles{
+ Group: "群聊", Direct: "单聊", Fallback: "会话",
+ })
+ issues := &recordingIssues{}
+ router := engine.NewRouter(issues, &bindTestTasks{}, queries, engine.RouterConfig{
+ MediaTimeout: 20 * time.Second,
+ Logger: testLogger(),
+ })
+ router.Register(TypeWecom, NewResolverSet(NewStore(queries), session, nil, resolver))
+
+ if chatID == "" {
+ chatID = fixture.senderID
+ }
+ msgID := fmt.Sprintf("MSGID-MIXED-%d", time.Now().UnixNano())
+ msg := wecomMixedCallback(t, fixture.botID, botDisplayName, fixture.senderID, msgID, chatType, chatID, srv.URL, words, spoken)
+ if err := router.Handle(ctx, msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+
+ var body string
+ deadline := time.Now().Add(15 * time.Second)
+ for {
+ err := pool.QueryRow(ctx, `
+ SELECT cm.content
+ FROM chat_message cm
+ JOIN chat_session cs ON cs.id = cm.chat_session_id
+ WHERE cs.workspace_id = $1 AND cm.role = 'user'
+ ORDER BY cm.created_at DESC LIMIT 1`, fixture.workspaceID).Scan(&body)
+ if err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("no durable chat_message was ever written: %v", err)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ return issues, body
+}
+
+// TestIssueAfterAnImageIsStillFiled is the user-visible half of the ordering
+// defect, checked where the user would check it: was an issue created.
+//
+// The sender attaches the screenshot, types "/issue 登录坏了", and sends one
+// 图文混排. ownText renders it "[Image]\n/issue 登录坏了", the engine's parser
+// reads the first non-empty line and only the first, and on the shipped code
+// that line was "[Image]" — no issue, no error, no reply saying why. Typing
+// the same two things the other way round worked, which is the part that makes
+// it impossible to report.
+func TestIssueAfterAnImageIsStillFiled(t *testing.T) {
+ issues, body := runMixedIssueThroughTheRouter(t, "", "single", "", "/issue 登录坏了", false)
+
+ filed := issues.filed()
+ if len(filed) != 1 {
+ t.Fatalf("issues created = %d, want 1 — the sender attached a screenshot, typed /issue 登录坏了, and nothing was filed and nothing said why", len(filed))
+ }
+ if filed[0].Title != "登录坏了" {
+ t.Errorf("issue title = %q, want 登录坏了", filed[0].Title)
+ }
+ // The transcript still shows the attachment and where it sat. Cutting the
+ // placeholder out of the body is the other way to break this, and it costs
+ // the agent the one signal that a picture was sent.
+ if want := "[Image]\n/issue 登录坏了"; body != want {
+ t.Errorf("durable body = %q, want %q", body, want)
+ }
+}
+
+// TestGroupMentionedIssueAfterAnImageIsStillFiled is the conflict-resolution
+// test. It fails if EITHER half is lost.
+//
+// In a group the @-mention is how the bot is reached, so it arrives glued to
+// the front of the text run: "@Multica Bot /issue 登录坏了". main strips that
+// (stripLeadingMentions) and this PR keeps the placeholders out of the
+// command source, and the parser needs both to see "/issue" on the line it
+// reads. Take main's version of ws_frame.go wholesale and the strip goes and
+// the parser sees "@Multica Bot"; derive the command from the resolved body
+// and it sees "[Image]". Either way no issue is filed, and this is the
+// assertion that says so.
+func TestGroupMentionedIssueAfterAnImageIsStillFiled(t *testing.T) {
+ issues, body := runMixedIssueThroughTheRouter(t, "Multica Bot", "group", "GROUP-BIND-1", "@Multica Bot /issue 登录坏了", false)
+
+ filed := issues.filed()
+ if len(filed) != 1 {
+ t.Fatalf("issues created = %d, want 1 — an @-mentioned /issue with a screenshot in a group filed nothing", len(filed))
+ }
+ if filed[0].Title != "登录坏了" {
+ t.Errorf("issue title = %q, want 登录坏了 (a title carrying the bot's own name means the mention strip was lost)", filed[0].Title)
+ }
+ if want := "[Image]\n@Multica Bot /issue 登录坏了"; body != want {
+ t.Errorf("durable body = %q, want %q — the transcript keeps who was addressed", body, want)
+ }
+}
+
+// TestGroupMentionedSpokenIssueAfterAnImageIsStillFiled is the same question
+// with the words spoken instead of typed, which is the third change meeting
+// the other two: WeCom recognises a voice run on its side and hands over the
+// transcript, so those are the sender's own words and a spoken "/issue" is a
+// command. Read the command off the typed field and it is empty; read it off
+// the resolved body and it starts with "[Image]"; skip the mention strip and
+// it starts with the bot's own name. All three have to hold at once, and
+// unlike the dispatch-level test this one asks the database whether an issue
+// exists.
+func TestGroupMentionedSpokenIssueAfterAnImageIsStillFiled(t *testing.T) {
+ issues, body := runMixedIssueThroughTheRouter(t, "Multica Bot", "group", "GROUP-BIND-2", "@Multica Bot /issue 登录坏了", true)
+
+ filed := issues.filed()
+ if len(filed) != 1 {
+ t.Fatalf("issues created = %d, want 1 — an @-mentioned /issue said out loud with a screenshot filed nothing", len(filed))
+ }
+ if filed[0].Title != "登录坏了" {
+ t.Errorf("issue title = %q, want 登录坏了", filed[0].Title)
+ }
+ if want := "[Image]\n@Multica Bot /issue 登录坏了"; body != want {
+ t.Errorf("durable body = %q, want %q — a spoken run reads into the body like a typed one", body, want)
+ }
+}
diff --git a/server/internal/integrations/wecom/inbound_media_test.go b/server/internal/integrations/wecom/inbound_media_test.go
new file mode 100644
index 0000000000..b00fbfc731
--- /dev/null
+++ b/server/internal/integrations/wecom/inbound_media_test.go
@@ -0,0 +1,507 @@
+package wecom
+
+// inbound_media_test.go — what a media callback becomes on the way in:
+// whether it reaches the handler at all, what the stored body says, and what
+// the resolver is handed to download.
+//
+// The frames here are the shapes WeCom's aibot long-connection docs specify
+// (developer.work.weixin.qq.com/document/path/101463): a standalone
+// image/file/video carries {url, aeskey} under its own key, and a 图文混排
+// carries mixed.msg_item, each item typed like a standalone message.
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// mediaFrame builds an aibot_msg_callback frame from a raw body map, going
+// through the real JSON decoder so a test cannot drift from the wire.
+func mediaFrame(t *testing.T, msgType string, extra map[string]any) frameEnvelope {
+ t.Helper()
+ full := map[string]any{
+ "msgid": "MSGID-1",
+ "aibotid": "bot-1",
+ "chatid": "CHAT_1",
+ "chattype": "single",
+ "from": map[string]any{"userid": "USER_A"},
+ "msgtype": msgType,
+ }
+ for k, v := range extra {
+ full[k] = v
+ }
+ body, err := json.Marshal(full)
+ if err != nil {
+ t.Fatalf("marshal callback: %v", err)
+ }
+ return frameEnvelope{Cmd: cmdMsgCallback, Body: body}
+}
+
+// dispatchOne runs one frame through dispatchFrame and reports what the
+// handler saw plus what went back over the socket.
+func dispatchOne(t *testing.T, env frameEnvelope) (channel.InboundMessage, bool, *recordingConn) {
+ t.Helper()
+ return dispatchOneAs(t, env, "")
+}
+
+// dispatchOneAs is dispatchOne with the bot's configured display name — the
+// one thing stripLeadingMentions has to match a group's addressing against.
+func dispatchOneAs(t *testing.T, env frameEnvelope, botDisplayName string) (channel.InboundMessage, bool, *recordingConn) {
+ t.Helper()
+ var got channel.InboundMessage
+ called := false
+ c := testChannel(func(_ context.Context, m channel.InboundMessage) error {
+ called, got = true, m
+ return nil
+ })
+ c.botDisplayName = botDisplayName
+ conn := &recordingConn{}
+ if err := c.dispatchFrame(context.Background(), env, newWSSender(conn, slog.Default()), slog.Default()); err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ return got, called, conn
+}
+
+// mixedFrame builds a 图文混排 callback from its runs, in composition order.
+func mixedFrame(t *testing.T, extra map[string]any, items ...map[string]any) frameEnvelope {
+ t.Helper()
+ full := map[string]any{"mixed": map[string]any{"msg_item": items}}
+ for k, v := range extra {
+ full[k] = v
+ }
+ return mediaFrame(t, "mixed", full)
+}
+
+func textRun(content string) map[string]any {
+ return map[string]any{"msgtype": "text", "text": map[string]any{"content": content}}
+}
+
+func imageRun(url string) map[string]any {
+ return map[string]any{"msgtype": "image", "image": map[string]any{"url": url, "aeskey": "k"}}
+}
+
+// voiceRun is a spoken run: WeCom sends the transcript it recognised, never
+// audio, so there is no url and no key on it.
+func voiceRun(transcript string) map[string]any {
+ return map[string]any{"msgtype": "voice", "voice": map[string]any{"content": transcript}}
+}
+
+// TestDispatchFrame_MediaCallbacksReachTheHandler is the defect this file
+// exists for. Before inbound media, dispatchFrame routed only msgtype ==
+// "text" and answered every other kind with a receipt, so a photo, a file, a
+// video and a 图文混排 all ended at the socket: no chat_message, no session,
+// no agent run, nothing in the web UI either.
+func TestDispatchFrame_MediaCallbacksReachTheHandler(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ msgType string
+ extra map[string]any
+ wantText string
+ wantType channel.MsgType
+ wantURLs []string
+ }{
+ {
+ name: "image",
+ msgType: "image",
+ extra: map[string]any{"image": map[string]any{"url": "https://cos.example.com/i", "aeskey": "k1"}},
+ wantText: "[Image]",
+ wantType: channel.MsgTypeImage,
+ wantURLs: []string{"https://cos.example.com/i"},
+ },
+ {
+ name: "file",
+ msgType: "file",
+ extra: map[string]any{"file": map[string]any{"url": "https://cos.example.com/f", "aeskey": "k2"}},
+ wantText: "[File]",
+ wantType: channel.MsgTypeFile,
+ wantURLs: []string{"https://cos.example.com/f"},
+ },
+ {
+ name: "video",
+ msgType: "video",
+ extra: map[string]any{"video": map[string]any{"url": "https://cos.example.com/v", "aeskey": "k3"}},
+ wantText: "[Video]",
+ wantType: channel.MsgTypeVideo,
+ wantURLs: []string{"https://cos.example.com/v"},
+ },
+ {
+ name: "mixed keeps composition order",
+ msgType: "mixed",
+ extra: map[string]any{"mixed": map[string]any{"msg_item": []map[string]any{
+ {"msgtype": "text", "text": map[string]any{"content": "看下这个报错"}},
+ {"msgtype": "image", "image": map[string]any{"url": "https://cos.example.com/m1", "aeskey": "k4"}},
+ {"msgtype": "text", "text": map[string]any{"content": "还有这个"}},
+ {"msgtype": "image", "image": map[string]any{"url": "https://cos.example.com/m2", "aeskey": "k5"}},
+ }}},
+ wantText: "看下这个报错\n[Image]\n还有这个\n[Image]",
+ wantType: channel.MsgTypeText,
+ wantURLs: []string{"https://cos.example.com/m1", "https://cos.example.com/m2"},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got, called, conn := dispatchOne(t, mediaFrame(t, tc.msgType, tc.extra))
+ if !called {
+ t.Fatalf("a %s message never reached the handler — it was answered and dropped", tc.msgType)
+ }
+ if len(conn.frames) != 0 {
+ t.Errorf("a routable %s message should not also get a receipt, got %d frames", tc.msgType, len(conn.frames))
+ }
+ if got.Text != tc.wantText {
+ t.Errorf("stored body = %q, want %q", got.Text, tc.wantText)
+ }
+ if got.Type != tc.wantType {
+ t.Errorf("normalized type = %v, want %v", got.Type, tc.wantType)
+ }
+ var wm InboundMessage
+ if err := json.Unmarshal(got.Raw, &wm); err != nil {
+ t.Fatalf("decode Raw: %v", err)
+ }
+ if len(wm.Media) != len(tc.wantURLs) {
+ t.Fatalf("Raw carried %d attachments, want %d", len(wm.Media), len(tc.wantURLs))
+ }
+ for i, want := range tc.wantURLs {
+ if wm.Media[i].URL != want {
+ t.Errorf("attachment %d url = %q, want %q (order must be composition order)", i, wm.Media[i].URL, want)
+ }
+ }
+ })
+ }
+}
+
+// TestMediaPlaceholders_MatchLarkAndDingTalk pins the placeholder strings to
+// their siblings byte for byte. An agent reads every channel through the same
+// prompt, so a wecom-only spelling is a wecom-only thing for it to learn.
+//
+// Sources: lark/content_flatten.go flattenContent ("[Image]" / "[File]" /
+// "[Video]") and dingtalk/inbound.go dingtalkImagePlaceholder = "[Image]"
+// with "[File]" beside it.
+func TestMediaPlaceholders_MatchLarkAndDingTalk(t *testing.T) {
+ t.Parallel()
+ cases := map[channel.MsgType]string{
+ channel.MsgTypeImage: "[Image]",
+ channel.MsgTypeFile: "[File]",
+ channel.MsgTypeVideo: "[Video]",
+ }
+ for kind, want := range cases {
+ if got := mediaPlaceholder(kind); got != want {
+ t.Errorf("mediaPlaceholder(%v) = %q, want %q — lark and dingtalk emit %q", kind, got, want, want)
+ }
+ }
+}
+
+// TestOwnText_MixedDropsRunsItCannotRead: a run of a kind the adapter does
+// not model contributes nothing, rather than a stray placeholder for an
+// attachment nobody will ever download.
+func TestOwnText_MixedDropsRunsItCannotRead(t *testing.T) {
+ t.Parallel()
+ env := mediaFrame(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []map[string]any{
+ {"msgtype": "text", "text": map[string]any{"content": "hi"}},
+ {"msgtype": "location", "location": map[string]any{"name": "office"}},
+ {"msgtype": "image", "image": map[string]any{"url": "", "aeskey": "k"}},
+ }}})
+ got, called, _ := dispatchOne(t, env)
+ if !called {
+ t.Fatal("a mixed message with one readable run must still be routed")
+ }
+ if got.Text != "hi" {
+ t.Errorf("body = %q, want just the readable run", got.Text)
+ }
+ var wm InboundMessage
+ if err := json.Unmarshal(got.Raw, &wm); err != nil {
+ t.Fatalf("decode Raw: %v", err)
+ }
+ if len(wm.Media) != 0 {
+ t.Errorf("an image run with no url produced %d attachments, want 0 — an intent row for an object that can never exist", len(wm.Media))
+ }
+}
+
+// TestOwnText_MixedWithNothingReadableTakesTheReceipt: a mixed message whose
+// every run is a kind we cannot read is not an empty message to ingest.
+func TestOwnText_MixedWithNothingReadableTakesTheReceipt(t *testing.T) {
+ t.Parallel()
+ env := mediaFrame(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []map[string]any{
+ {"msgtype": "location", "location": map[string]any{"name": "office"}},
+ }}})
+ _, called, conn := dispatchOne(t, env)
+ if called {
+ t.Error("a mixed message with nothing readable must not be ingested as an empty turn")
+ }
+ if len(conn.frames) != 1 {
+ t.Fatalf("expected one receipt, got %d frames", len(conn.frames))
+ }
+}
+
+// TestUnsupportedReceipt_DoesNotClaimTextOnly: the receipt used to say the
+// bot only handles text. It now routes photos, files, videos and 图文混排, so
+// a person who just watched it answer a screenshot must not then be told it
+// handles text only.
+func TestUnsupportedReceipt_DoesNotClaimTextOnly(t *testing.T) {
+ t.Parallel()
+ if strings.Contains(unsupportedMsgTypeReceipt, "只能处理文字") {
+ t.Errorf("receipt %q still claims text-only while image/file/video/mixed route", unsupportedMsgTypeReceipt)
+ }
+}
+
+// TestAVoiceNoteIsReadWhereverItArrives: WeCom runs the speech recognition on
+// its side and hands over the transcript, so a spoken sentence needs no
+// download and no key — it is words, and it is read like words whether it
+// arrives on its own or as one run of a 图文混排. An empty transcript is the
+// one exception: background noise and a half-second press produce nothing to
+// route, and an empty body would reach the agent as a turn with nothing in it.
+func TestAVoiceNoteIsReadWhereverItArrives(t *testing.T) {
+ t.Parallel()
+
+ standalone := mediaFrame(t, "voice", map[string]any{"voice": map[string]any{"content": "把报表发我"}})
+ got, called, conn := dispatchOne(t, standalone)
+ if !called {
+ t.Fatal("a voice note with a transcript was refused — the sentence was already in hand")
+ }
+ if got.Text != "把报表发我" {
+ t.Errorf("body = %q, want the transcript", got.Text)
+ }
+ if len(conn.frames) != 0 {
+ t.Errorf("a readable voice note got %d receipt(s); it was answered instead of routed", len(conn.frames))
+ }
+
+ empty := mediaFrame(t, "voice", map[string]any{"voice": map[string]any{"content": " "}})
+ if _, called, conn := dispatchOne(t, empty); called || len(conn.frames) != 1 {
+ t.Errorf("an empty transcript should take the receipt path (called=%v, frames=%d)", called, len(conn.frames))
+ }
+
+ inMixed := mediaFrame(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []map[string]any{
+ {"msgtype": "voice", "voice": map[string]any{"content": "把报表发我"}},
+ {"msgtype": "file", "file": map[string]any{"url": "https://cos.example.com/x", "aeskey": "k"}},
+ }}})
+ got, called, _ = dispatchOne(t, inMixed)
+ if !called {
+ t.Fatal("a mixed message with a voice run must be routed")
+ }
+ if got.Text != "把报表发我\n[File]" {
+ t.Errorf("body = %q, want the transcript above the file placeholder", got.Text)
+ }
+}
+
+// TestDispatchFrame_TheCommandSourceHasNoPlaceholdersInIt is the ordering
+// defect. A person reporting a bug attaches the screenshot and then types
+// "/issue 登录坏了" — that order, because you pick the picture while you are
+// still deciding what to say. WeCom sends it as one 图文混排, ownText renders
+// it "[Image]\n/issue 登录坏了", and engine.ParseIssueCommand looks at the
+// first non-empty line and only the first: it sees "[Image]", declines, and no
+// issue is filed. Nothing is said about it either, in the chat or the log. The
+// same two things typed the other way round work. Nobody can be expected to
+// know that.
+//
+// So the command source is the runs the sender authored and nothing else,
+// while the stored body keeps the placeholders — the agent still has to be
+// able to see that a picture was attached and where.
+func TestDispatchFrame_TheCommandSourceHasNoPlaceholdersInIt(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ items []map[string]any
+ wantBody string
+ wantCommand string
+ }{
+ {
+ name: "image before the command — the ordering that was broken",
+ items: []map[string]any{imageRun("https://cos.example.com/a"), textRun("/issue 登录坏了")},
+ wantBody: "[Image]\n/issue 登录坏了",
+ wantCommand: "/issue 登录坏了",
+ },
+ {
+ name: "image after the command — the ordering that happened to work",
+ items: []map[string]any{textRun("/issue 登录坏了"), imageRun("https://cos.example.com/a")},
+ wantBody: "/issue 登录坏了\n[Image]",
+ wantCommand: "/issue 登录坏了",
+ },
+ {
+ name: "image between two runs the sender typed",
+ items: []map[string]any{imageRun("https://cos.example.com/a"), textRun("/issue 登录坏了"), imageRun("https://cos.example.com/b"), textRun("复现步骤见图")},
+ wantBody: "[Image]\n/issue 登录坏了\n[Image]\n复现步骤见图",
+ wantCommand: "/issue 登录坏了\n复现步骤见图",
+ },
+ {
+ name: "a spoken command counts, WeCom already transcribed it",
+ items: []map[string]any{imageRun("https://cos.example.com/a"), map[string]any{"msgtype": "voice", "voice": map[string]any{"content": "/issue 登录坏了"}}},
+ wantBody: "[Image]\n/issue 登录坏了",
+ wantCommand: "/issue 登录坏了",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got, called, _ := dispatchOne(t, mixedFrame(t, nil, tc.items...))
+ if !called {
+ t.Fatal("the message never reached the handler")
+ }
+ if got.Text != tc.wantBody {
+ t.Errorf("stored body = %q, want %q — the placeholders belong in the body", got.Text, tc.wantBody)
+ }
+ if got.CommandText != tc.wantCommand {
+ t.Errorf("CommandText = %q, want %q — a placeholder in the command source is a line the sender never typed", got.CommandText, tc.wantCommand)
+ }
+ cmd, ok := engine.ParseIssueCommand(got.CommandText)
+ if !ok {
+ t.Fatalf("engine.ParseIssueCommand(%q) declined — the sender attached a screenshot, typed /issue, and got no issue and no explanation", got.CommandText)
+ }
+ if cmd.Title != "登录坏了" {
+ t.Errorf("issue title = %q, want 登录坏了", cmd.Title)
+ }
+ if !got.SkipAgentRun {
+ t.Error("SkipAgentRun = false on a pure /issue; the agent would answer the slash command back at the sender")
+ }
+ })
+ }
+}
+
+// TestDispatchFrame_GroupMentionedMixedCommand is the two defects together,
+// and it is the one that has to keep passing for both of them to stay fixed.
+//
+// A group is the only place the bot can be reached by @-mentioning it, so the
+// mention arrives glued to the front of the text run: "@Multica Bot /issue
+// 登录坏了". main strips that (stripLeadingMentions) and this PR removes the
+// placeholders, and the command source needs BOTH — drop the strip and the
+// parser sees "@Multica Bot", drop the placeholder removal and it sees
+// "[Image]". Either way the sender gets nothing.
+func TestDispatchFrame_GroupMentionedMixedCommand(t *testing.T) {
+ t.Parallel()
+ group := map[string]any{"chattype": "group", "chatid": "GROUP_1"}
+ env := mixedFrame(t, group,
+ imageRun("https://cos.example.com/a"),
+ textRun("@Multica Bot /issue 登录坏了"),
+ )
+ got, called, _ := dispatchOneAs(t, env, "Multica Bot")
+ if !called {
+ t.Fatal("the group message never reached the handler")
+ }
+ if got.Source.ChatType != channel.ChatTypeGroup {
+ t.Fatalf("chat type = %v, want group — the mention strip is gated on it", got.Source.ChatType)
+ }
+ // The transcript keeps what was said, including who was addressed.
+ if want := "[Image]\n@Multica Bot /issue 登录坏了"; got.Text != want {
+ t.Errorf("stored body = %q, want %q", got.Text, want)
+ }
+ if want := "/issue 登录坏了"; got.CommandText != want {
+ t.Errorf("CommandText = %q, want %q — the placeholder and the addressing both have to come off", got.CommandText, want)
+ }
+ cmd, ok := engine.ParseIssueCommand(got.CommandText)
+ if !ok {
+ t.Fatalf("engine.ParseIssueCommand(%q) declined — an @-mentioned /issue with a screenshot files nothing", got.CommandText)
+ }
+ if cmd.Title != "登录坏了" {
+ t.Errorf("issue title = %q, want 登录坏了", cmd.Title)
+ }
+ if !got.SkipAgentRun {
+ t.Error("SkipAgentRun = false; the group would get the slash command read back to it")
+ }
+}
+
+// TestDispatchFrame_GroupMentionedSpokenIssueWithAnImage is the intersection
+// of all three decisions that meet in this function, and the only test that
+// holds them together.
+//
+// Someone in a group photographs the broken screen, holds the mic and says
+// "@Multica Bot /issue 登录坏了". WeCom delivers one 图文混排 with an image run
+// and a voice run, and the command has to survive three separate strips:
+//
+// - the placeholder — the image run is first, and the parser reads the first
+// non-empty line and only that one, so a body opening with "[Image]" files
+// nothing;
+// - the transcript — the spoken words live in voice.content, and a command
+// source built from the typed field is empty, at which point the engine
+// falls back to the body and reads "[Image]" anyway;
+// - the addressing — an @-mention is the only way to reach a bot in a group,
+// so it arrives glued to the front of the words.
+//
+// Take any one side of the merge wholesale and one of the three is missing.
+// The sender then gets no issue and no explanation, and the message they would
+// have to send to report it is the one that does not work.
+func TestDispatchFrame_GroupMentionedSpokenIssueWithAnImage(t *testing.T) {
+ t.Parallel()
+ group := map[string]any{"chattype": "group", "chatid": "GROUP_1"}
+
+ for _, tc := range []struct {
+ name string
+ items []map[string]any
+ wantBody string
+ }{
+ {
+ // Everything spoken: the mention rides in front of the transcript,
+ // which is how it arrives when the whole message is said out loud.
+ name: "the mention and the command are both in the voice run",
+ items: []map[string]any{imageRun("https://cos.example.com/a"), voiceRun("@Multica Bot /issue 登录坏了")},
+ wantBody: "[Image]\n@Multica Bot /issue 登录坏了",
+ },
+ {
+ // Mention typed, command spoken — the composer's own order when
+ // someone picks the bot from the @ menu and then talks.
+ name: "the mention is typed and the command is spoken",
+ items: []map[string]any{textRun("@Multica Bot"), imageRun("https://cos.example.com/a"), voiceRun("/issue 登录坏了")},
+ wantBody: "@Multica Bot\n[Image]\n/issue 登录坏了",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got, called, _ := dispatchOneAs(t, mixedFrame(t, group, tc.items...), "Multica Bot")
+ if !called {
+ t.Fatal("the group message never reached the handler")
+ }
+ if got.Source.ChatType != channel.ChatTypeGroup {
+ t.Fatalf("chat type = %v, want group — the mention strip is gated on it", got.Source.ChatType)
+ }
+ // The stored body keeps everything: the placeholder marks where the
+ // screenshot goes, and the addressing is part of what was said.
+ if got.Text != tc.wantBody {
+ t.Errorf("stored body = %q, want %q", got.Text, tc.wantBody)
+ }
+ cmd, ok := engine.ParseIssueCommand(got.CommandText)
+ if !ok {
+ t.Fatalf("engine.ParseIssueCommand(%q) declined — a spoken, @-mentioned /issue with a screenshot files nothing and says nothing", got.CommandText)
+ }
+ if cmd.Title != "登录坏了" {
+ t.Errorf("issue title = %q, want 登录坏了 — the title is what the strips left behind", cmd.Title)
+ }
+ if !got.SkipAgentRun {
+ t.Error("SkipAgentRun = false; the group would get the issue AND the agent reading the slash command back at it")
+ }
+ // The picture still travels. Losing it here would file the issue
+ // without the one thing the sender attached to explain it.
+ wm, err := wecomMsgFromRaw(got)
+ if err != nil {
+ t.Fatalf("decode raw: %v", err)
+ }
+ if len(wm.Media) != 1 || wm.Media[0].URL != "https://cos.example.com/a" {
+ t.Errorf("attachments = %+v, want the one image the sender took", wm.Media)
+ }
+ })
+ }
+}
+
+// A standalone photo has no words in it. Its whole body is a placeholder, so
+// the command source is empty rather than "[Image]" — the engine's own
+// fallback then reads the body, which is the behaviour every adapter has, and
+// "[Image]" is not a command in any of them.
+func TestDispatchFrame_AStandalonePhotoCarriesNoCommand(t *testing.T) {
+ t.Parallel()
+ env := mediaFrame(t, "image", map[string]any{
+ "image": map[string]any{"url": "https://cos.example.com/a", "aeskey": "k"},
+ })
+ got, called, _ := dispatchOne(t, env)
+ if !called {
+ t.Fatal("the photo never reached the handler")
+ }
+ if got.CommandText != "" {
+ t.Errorf("CommandText = %q, want empty — the sender typed nothing", got.CommandText)
+ }
+ if got.SkipAgentRun {
+ t.Error("SkipAgentRun = true on a bare photo; the agent would never see the picture it was sent")
+ }
+}
diff --git a/server/internal/integrations/wecom/media_crypt.go b/server/internal/integrations/wecom/media_crypt.go
new file mode 100644
index 0000000000..a764214761
--- /dev/null
+++ b/server/internal/integrations/wecom/media_crypt.go
@@ -0,0 +1,102 @@
+package wecom
+
+// media_crypt.go — what a callback's aeskey unlocks.
+//
+// A smart-bot message that carries a photo, a file or a video gives the bot
+// two strings: a Tencent COS URL good for five minutes, and the key the bytes
+// behind it are encrypted with. Long-connection mode mints a fresh key per
+// URL, which is the difference from callback mode's one deployment-wide
+// EncodingAESKey — there is nothing to configure and nothing to rotate, but
+// also nothing to fall back on if the key on the frame is unusable.
+//
+// The algorithm is AES-256-CBC with the IV taken from the front of the key
+// itself, and the plaintext PKCS#7-padded to a multiple of 32 bytes
+// (developer.work.weixin.qq.com/document/path/101463).
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "strings"
+)
+
+// mediaAESKeyBytes is the decoded key length AES-256 requires.
+const mediaAESKeyBytes = 32
+
+// mediaPadBlock is the block the plaintext is padded up to. It is NOT the AES
+// block size, and that gap is the trap: AES works in 16-byte blocks, so a
+// PKCS#7 unpadder written against the cipher rejects any pad longer than 16 —
+// and a file whose length is already a multiple of 32 is padded with a whole
+// 32-byte block. Ordinary payloads land there often enough that such an
+// unpadder looks fine in a smoke test and fails in production.
+const mediaPadBlock = 32
+
+// decryptMedia turns one downloaded body back into the file the user sent.
+// Every failure is an error rather than a best guess: a wrong answer here is
+// an attachment that opens as garbage, which is worse than an attachment that
+// is honestly missing.
+func decryptMedia(aesKey string, ciphertext []byte) ([]byte, error) {
+ key, err := decodeMediaAESKey(aesKey)
+ if err != nil {
+ return nil, err
+ }
+ if len(ciphertext) == 0 {
+ return nil, errors.New("wecom: media ciphertext is empty")
+ }
+ if len(ciphertext)%aes.BlockSize != 0 {
+ return nil, fmt.Errorf("wecom: media ciphertext is %d bytes, not a multiple of the %d-byte AES block", len(ciphertext), aes.BlockSize)
+ }
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, fmt.Errorf("wecom: media cipher: %w", err)
+ }
+ plain := make([]byte, len(ciphertext))
+ // The IV is the front of the key. Reusing key material as an IV is
+ // WeCom's choice, not ours; we only have to match it.
+ cipher.NewCBCDecrypter(block, key[:aes.BlockSize]).CryptBlocks(plain, ciphertext)
+ return unpadMedia(plain)
+}
+
+// decodeMediaAESKey decodes the base64 the frame carries. Both the padded
+// 44-character form and the unpadded 43-character form appear in WeCom's own
+// surfaces, so both are accepted; anything that does not come out at exactly
+// 32 bytes is refused rather than stretched or truncated into one.
+func decodeMediaAESKey(raw string) ([]byte, error) {
+ s := strings.TrimSpace(raw)
+ if s == "" {
+ return nil, errors.New("wecom: media aeskey is empty")
+ }
+ for _, enc := range []*base64.Encoding{
+ base64.StdEncoding,
+ base64.RawStdEncoding,
+ base64.URLEncoding,
+ base64.RawURLEncoding,
+ } {
+ if key, err := enc.DecodeString(s); err == nil && len(key) == mediaAESKeyBytes {
+ return key, nil
+ }
+ }
+ return nil, fmt.Errorf("wecom: media aeskey does not decode to %d bytes", mediaAESKeyBytes)
+}
+
+// unpadMedia strips the PKCS#7 tail, validating every byte of it. A tail that
+// does not check out means the key was wrong or the body was truncated, and
+// either way the bytes in front of it cannot be trusted to be the file.
+func unpadMedia(plain []byte) ([]byte, error) {
+ n := len(plain)
+ if n == 0 {
+ return nil, errors.New("wecom: media plaintext is empty")
+ }
+ pad := int(plain[n-1])
+ if pad < 1 || pad > mediaPadBlock || pad > n {
+ return nil, fmt.Errorf("wecom: media padding length %d is out of range (1..%d)", pad, mediaPadBlock)
+ }
+ for _, b := range plain[n-pad:] {
+ if int(b) != pad {
+ return nil, errors.New("wecom: media padding bytes disagree; wrong key or truncated body")
+ }
+ }
+ return plain[:n-pad], nil
+}
diff --git a/server/internal/integrations/wecom/media_crypt_test.go b/server/internal/integrations/wecom/media_crypt_test.go
new file mode 100644
index 0000000000..8ec329272a
--- /dev/null
+++ b/server/internal/integrations/wecom/media_crypt_test.go
@@ -0,0 +1,153 @@
+package wecom
+
+// media_crypt_test.go — the decryptor is checked against a from-scratch
+// encryptor written here, not against itself. Every case below encrypts a
+// known plaintext with the algorithm WeCom documents (AES-256-CBC, IV = the
+// first 16 bytes of the decoded aeskey, PKCS#7 padded to a multiple of 32)
+// and asserts the bytes come back byte-identical.
+//
+// The 32-byte padding block is the whole reason this file exists. AES blocks
+// are 16 bytes, so every unpadder that assumes the pad length can be at most
+// the block size rejects a WeCom payload whose plaintext happens to land on a
+// 32-byte boundary — the pad is then a full 32 bytes and the "impossible"
+// branch fires on a perfectly ordinary file.
+
+import (
+ "bytes"
+ "crypto/aes"
+ "crypto/cipher"
+ "encoding/base64"
+ "strings"
+ "testing"
+)
+
+// encryptLikeWecom is an independent implementation of the sender side. It
+// deliberately does not call anything in media_crypt.go.
+func encryptLikeWecom(t *testing.T, aesKeyB64 string, plaintext []byte) []byte {
+ t.Helper()
+ key, err := base64.StdEncoding.DecodeString(aesKeyB64)
+ if err != nil {
+ t.Fatalf("test key is not base64: %v", err)
+ }
+ if len(key) != 32 {
+ t.Fatalf("test key is %d bytes, want 32", len(key))
+ }
+ // PKCS#7 to a multiple of 32. A plaintext already on the boundary gets a
+ // whole extra 32-byte block, which is the case that breaks naive code.
+ pad := 32 - (len(plaintext) % 32)
+ padded := append(append([]byte{}, plaintext...), bytes.Repeat([]byte{byte(pad)}, pad)...)
+
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ t.Fatalf("aes.NewCipher: %v", err)
+ }
+ out := make([]byte, len(padded))
+ cipher.NewCBCEncrypter(block, key[:aes.BlockSize]).CryptBlocks(out, padded)
+ return out
+}
+
+// testAESKey is 32 bytes of key material, base64'd the way a callback carries
+// it. Fixed rather than random so a failure is reproducible.
+const testAESKey = "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY="
+
+func TestDecryptMediaRoundTripsRealCiphertext(t *testing.T) {
+ cases := []struct {
+ name string
+ plain []byte
+ }{
+ {"one byte", []byte("x")},
+ {"exactly 15 bytes", bytes.Repeat([]byte("a"), 15)},
+ {"exactly 16 bytes — one AES block", bytes.Repeat([]byte("b"), 16)},
+ {"17 bytes", bytes.Repeat([]byte("c"), 17)},
+ {"31 bytes", bytes.Repeat([]byte("d"), 31)},
+ {"exactly 32 bytes — a full 32-byte pad block follows", bytes.Repeat([]byte("e"), 32)},
+ {"33 bytes", bytes.Repeat([]byte("f"), 33)},
+ {"64 bytes", bytes.Repeat([]byte("g"), 64)},
+ {"a PNG header", []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR")},
+ {"utf-8 text", []byte("这是一份季度报告,请查收。")},
+ {"a megabyte", bytes.Repeat([]byte("multica"), 150000)},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ ciphertext := encryptLikeWecom(t, testAESKey, tc.plain)
+ if len(ciphertext)%32 != 0 {
+ t.Fatalf("the encryptor produced %d bytes, not a multiple of 32", len(ciphertext))
+ }
+ got, err := decryptMedia(testAESKey, ciphertext)
+ if err != nil {
+ t.Fatalf("decryptMedia: %v", err)
+ }
+ if !bytes.Equal(got, tc.plain) {
+ t.Fatalf("round trip changed the bytes: got %d bytes, want %d", len(got), len(tc.plain))
+ }
+ })
+ }
+}
+
+// TestDecryptMediaAcceptsAnUnpaddedBase64Key: WeCom's own console prints the
+// 43-character form of a 32-byte key (no "=" tail). Refusing it would fail on
+// a key that is perfectly valid.
+func TestDecryptMediaAcceptsAnUnpaddedBase64Key(t *testing.T) {
+ unpadded := strings.TrimRight(testAESKey, "=")
+ if unpadded == testAESKey {
+ t.Fatal("the fixture key has no padding to trim; pick another")
+ }
+ ciphertext := encryptLikeWecom(t, testAESKey, []byte("hello"))
+ got, err := decryptMedia(unpadded, ciphertext)
+ if err != nil {
+ t.Fatalf("decryptMedia with a 43-char key: %v", err)
+ }
+ if string(got) != "hello" {
+ t.Fatalf("got %q", got)
+ }
+}
+
+func TestDecryptMediaRejectsWhatItCannotTrust(t *testing.T) {
+ good := encryptLikeWecom(t, testAESKey, []byte("payload"))
+
+ cases := []struct {
+ name string
+ key string
+ ciphertext []byte
+ }{
+ {"no key at all", "", good},
+ {"key that is not base64", "not base64 !!!", good},
+ {"key that decodes to 16 bytes", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte("k"), 16)), good},
+ {"empty ciphertext", testAESKey, nil},
+ {"ciphertext off the AES block boundary", testAESKey, good[:len(good)-1]},
+ {"ciphertext encrypted under a different key", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte("z"), 32)), good},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if _, err := decryptMedia(tc.key, tc.ciphertext); err == nil {
+ t.Fatal("want an error, got none — a silent wrong answer here becomes a corrupt attachment")
+ }
+ })
+ }
+}
+
+// TestDecryptMediaRejectsATamperedPadTail: the last block decides how many
+// bytes come off the end. A pad that does not check out must be an error, not
+// a truncated file.
+func TestDecryptMediaRejectsATamperedPadTail(t *testing.T) {
+ // Build the padded plaintext by hand with a pad length outside 1..32 and
+ // encrypt it, so the ciphertext is well-formed but the tail is not.
+ key, _ := base64.StdEncoding.DecodeString(testAESKey)
+ block, _ := aes.NewCipher(key)
+ for _, tc := range []struct {
+ name string
+ padded []byte
+ }{
+ {"pad byte 0", append(bytes.Repeat([]byte("p"), 31), 0)},
+ {"pad byte 33 — past the 32-byte block", append(bytes.Repeat([]byte("p"), 31), 33)},
+ {"pad bytes disagree", append(append(bytes.Repeat([]byte("p"), 28), 4, 4, 3), 4)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ciphertext := make([]byte, len(tc.padded))
+ cipher.NewCBCEncrypter(block, key[:aes.BlockSize]).CryptBlocks(ciphertext, tc.padded)
+ if _, err := decryptMedia(testAESKey, ciphertext); err == nil {
+ t.Fatal("want an error for a pad tail that does not check out")
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/wecom/media_download.go b/server/internal/integrations/wecom/media_download.go
new file mode 100644
index 0000000000..f34516404a
--- /dev/null
+++ b/server/internal/integrations/wecom/media_download.go
@@ -0,0 +1,444 @@
+package wecom
+
+// media_download.go — fetching the bytes a callback points at.
+//
+// The URL is a pre-signed Tencent COS address: no access_token, no header,
+// good for five minutes. That makes the fetch itself trivial and puts all the
+// care somewhere else — the body arrives encrypted, its size is not declared
+// anywhere in the callback, and the only description of what the file IS
+// comes back in the response headers.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "path"
+ "strings"
+ "time"
+ "unicode"
+)
+
+// maxMediaBytes is the ceiling on one downloaded body. WeCom caps smart-bot
+// files and video at 100 MB and does not document a cap for images, so this
+// is the ceiling for everything: whatever arrives above it is not something
+// the callback was supposed to hand us.
+//
+// On this path the body is buffered whole — CBC decryption needs the tail
+// before the head can be trusted — so the ceiling is also the per-download
+// memory bound, multiplied by the router's media concurrency. This path is the
+// fallback: a storage backend implementing UploadStream (both shipped ones do)
+// goes through media_stream.go instead, where the same ceiling bounds disk.
+const maxMediaBytes = 100 << 20
+
+// mediaDownloadTimeout caps a single fetch. The router already runs media
+// resolution under a 45s budget shared by every attachment on the message and
+// by whatever is queued ahead of it, so one slow object must not eat all of
+// it.
+const mediaDownloadTimeout = 30 * time.Second
+
+// errMediaTooLarge is returned for a body past maxMediaBytes, either declared
+// in Content-Length or discovered while reading. Callers match on it to tell
+// the user the file was too big rather than that something went wrong.
+var errMediaTooLarge = fmt.Errorf("wecom: media exceeds the %d byte limit", maxMediaBytes)
+
+// mediaHeaders is what the response said about the file. Both fetch paths
+// return it, so the buffered and the streaming ingest learn the same things.
+type mediaHeaders struct {
+ // Filename is the display name parsed out of Content-Disposition, or
+ // empty. The callback body carries no name, size or MIME type of its
+ // own, so this header is the only place the original name exists.
+ Filename string
+ // Disposition is the Content-Disposition value exactly as it arrived,
+ // kept for the trace and for nothing else. What COS puts in that header
+ // is the one thing this package cannot check locally — the URL it came
+ // from lapses after five minutes, so a name that looks wrong cannot be
+ // re-fetched and must have been recorded at the time.
+ Disposition string
+}
+
+// downloadedMedia is one fetched body plus what the response said about it.
+type downloadedMedia struct {
+ // Body is the raw response — still encrypted. decryptMedia turns it into
+ // the file.
+ Body []byte
+ mediaHeaders
+}
+
+// downloadMedia GETs one media URL. Errors carry the reason (expired link,
+// oversize body, stalled server) because the caller turns them into something
+// a person reads.
+func downloadMedia(ctx context.Context, hc *http.Client, rawURL string) (downloadedMedia, error) {
+ if err := checkMediaURL(rawURL); err != nil {
+ return downloadedMedia{}, err
+ }
+ // A missing client is a wiring bug, and the tempting recovery —
+ // http.DefaultClient — is precisely the unguarded fetch media_guard.go
+ // exists to prevent. Refusing turns that bug into a failed download
+ // instead of an SSRF.
+ if hc == nil {
+ return downloadedMedia{}, errors.New("wecom: media download: no guarded http client configured")
+ }
+ ctx, cancel := context.WithTimeout(ctx, mediaDownloadTimeout)
+ defer cancel()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
+ if err != nil {
+ return downloadedMedia{}, fmt.Errorf("wecom: media request: %w", stripURL(err))
+ }
+ resp, err := hc.Do(req)
+ if err != nil {
+ return downloadedMedia{}, fmt.Errorf("wecom: media download: %w", stripURL(err))
+ }
+ defer resp.Body.Close()
+
+ if resp.ContentLength > maxMediaBytes {
+ return downloadedMedia{}, errMediaTooLarge
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ // A five-minute URL that has already lapsed is the ordinary failure
+ // here, and COS explains itself in a short XML body. Carry a snippet
+ // so the log says which kind of refusal it was.
+ snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
+ return downloadedMedia{}, fmt.Errorf("wecom: media download: http %d %s: %s",
+ resp.StatusCode, http.StatusText(resp.StatusCode), strings.TrimSpace(string(snippet)))
+ }
+
+ // LimitReader with one byte of headroom: reading exactly the cap cannot
+ // tell "the file is exactly at the limit" from "there is more coming".
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxMediaBytes+1))
+ if err != nil {
+ return downloadedMedia{}, fmt.Errorf("wecom: media download: read body: %w", err)
+ }
+ if len(body) > maxMediaBytes {
+ return downloadedMedia{}, errMediaTooLarge
+ }
+ return downloadedMedia{
+ Body: body,
+ mediaHeaders: mediaHeadersOf(resp),
+ }, nil
+}
+
+// mediaHeadersOf reads the one response header that describes the file.
+func mediaHeadersOf(resp *http.Response) mediaHeaders {
+ raw := resp.Header.Get("Content-Disposition")
+ return mediaHeaders{Filename: mediaFilenameFromDisposition(raw), Disposition: raw}
+}
+
+// stripURL removes the request URL from a transport error before it can be
+// logged.
+//
+// net/http wraps every failure in a *url.Error whose Error() prints the URL
+// it was fetching — and the URL here is a pre-signed COS link: a five-minute
+// bearer credential for a colleague's private attachment, good to anyone who
+// presents it. A DNS hiccup, a TCP reset, a TLS error or the download timeout
+// would each have written one into the application log, and from there into
+// whatever ships those logs onward. The wrapped cause carries the same
+// diagnosis with none of the credential, so that is what we keep.
+func stripURL(err error) error {
+ var urlErr *url.Error
+ if errors.As(err, &urlErr) && urlErr.Err != nil {
+ return urlErr.Err
+ }
+ return err
+}
+
+// checkMediaURL refuses anything the transport should not be pointed at. The
+// URL arrives over the authenticated socket, so this is a guard rail rather
+// than a defence, but it is a string from outside naming a host we then GET.
+func checkMediaURL(rawURL string) error {
+ s := strings.TrimSpace(rawURL)
+ if s == "" {
+ return errors.New("wecom: media url is empty")
+ }
+ u, err := url.Parse(s)
+ if err != nil {
+ // url.Parse's error text quotes the whole input, and the input here
+ // is a live pre-signed link. Say what was wrong, not what it was.
+ return errors.New("wecom: media url is unparseable")
+ }
+ if u.Scheme != "http" && u.Scheme != "https" {
+ return fmt.Errorf("wecom: media url scheme %q is not fetchable", u.Scheme)
+ }
+ if u.Host == "" {
+ return errors.New("wecom: media url has no host")
+ }
+ return nil
+}
+
+// mediaFilenameFromDisposition reads the display name out of
+// Content-Disposition, preferring RFC 5987's extended `filename*` form over the
+// plain `filename=` beside it. Servers that send both put the real (non-ASCII)
+// name in the extended form and a mangled ASCII approximation in the plain
+// one, so taking the plain one would rename every Chinese attachment to
+// underscores. mime.ParseMediaType already resolves that preference for us
+// regardless of the order the two appear in; the tests pin it because it is a
+// property we depend on, not one we implement.
+//
+// A plain `filename=` from COS arrives form-urlencoded, and ParseMediaType
+// does not undo that (it percent-decodes only the extended form), so the
+// value needs decodeFormEncodedFilename before it is fit to show anyone. The
+// extended form is skipped there, because a server that sent `filename*`
+// declared its own encoding and ParseMediaType has already applied it —
+// decoding a second time would be guessing on top of a declaration.
+//
+// The decode runs BEFORE the base-name reduction, not after: an escaped
+// separator (`..%2F..%2Fetc%2Fpasswd`) is a path only once it is decoded, and
+// a cleaner that ran first would hand a traversal straight through.
+//
+// The result goes through cleanMediaFilename, which reduces it to a base name
+// and strips control characters: the header is remote input, and once the
+// escapes above are undone it can carry a separator or a NUL that the raw
+// header could not.
+func mediaFilenameFromDisposition(raw string) string {
+ if strings.TrimSpace(raw) == "" {
+ return ""
+ }
+ _, params, err := mime.ParseMediaType(raw)
+ if err != nil {
+ return ""
+ }
+ name := params["filename"]
+ if !hasExtendedFilename(raw) {
+ name = decodeFormEncodedFilename(name)
+ }
+ return cleanMediaFilename(name)
+}
+
+// hasExtendedFilename reports whether the header offered an RFC 5987
+// `filename*` at all. mime.ParseMediaType folds the extended parameter into
+// params["filename"] and does not say which form it came from, so the raw
+// header is the only place left to ask.
+//
+// A plain filename whose VALUE contains the text "filename*" reads as a false
+// positive here. That costs nothing: the only consequence is that the value
+// is left exactly as it arrived.
+func hasExtendedFilename(raw string) bool {
+ return strings.Contains(strings.ToLower(raw), "filename*")
+}
+
+// decodeFormEncodedFilename undoes application/x-www-form-urlencoding on a
+// filename that provably carries it, and leaves every other name byte for
+// byte.
+//
+// Why this is needed: a live tenant sent "PC D&T Strategy 2026.docx" and it
+// was stored as "PC+D%26T+Strategy+2026.docx" — space as '+', '&' as %26,
+// which is exactly url.QueryEscape of the original. COS form-encodes the
+// plain filename parameter because that parameter is ASCII-only by
+// specification, and Chinese names take the same route: a non-ASCII name
+// cannot legally sit there, so it arrives as a run of percent escapes, and
+// without this the user is shown the escapes.
+//
+// Why it is conditional: url.QueryUnescape on its own reads '+' as a space,
+// so it would rewrite "C++ notes.docx" to "C notes.docx". Both readings of
+// a bare '+' are legitimate and no header field distinguishes them. What does
+// distinguish them is self-consistency — a genuine form-encoding survives a
+// round trip through the encoder, and an accidental one usually does not:
+// "C++ notes.docx" re-encodes to "C+++notes.docx" (the literal space would
+// have been a '+' too) and is therefore left alone. So the rule is: decode
+// only when re-encoding the result reproduces the header value.
+//
+// What this does NOT handle, and why:
+//
+// - Any name whose only encoder-touched character is a '+' IS a canonical
+// encoding of the same name with spaces, so the round trip cannot rule it
+// out and this decodes it, losing the pluses. That is a wider class than
+// one odd example: "C++.docx" → "C .docx", and so do "React+Redux.md",
+// "Q1+Q2.xlsx", "C++11.pdf", "10+1.pdf". The ambiguity is irreducible from
+// the header alone, and this is the side chosen deliberately — a name with
+// a space is far more common than one with a '+' and no space, and a name
+// with both is already safe by the round trip above.
+// - A name percent-encoded in the RFC 3986 style, with %20 for space rather
+// than '+' ("PC%20D&T.docx"), re-encodes to "PC+D%26T.docx", fails the
+// check, and keeps its escapes.
+// - A name from a server whose unreserved set is not Go's. The round trip
+// re-encodes with url.QueryEscape, which leaves A-Za-z0-9-_.~ alone, so
+// the check silently assumes the sender agreed on that set. Java's
+// URLEncoder also passes '*', and PHP's urlencode escapes '~' as %7E, so
+// "backup~.docx" from either arrives as "backup%7E.docx", re-encodes to
+// "backup~.docx", and the lengths no longer match. The failure is
+// all-or-nothing rather than partial: ONE character outside Go's set and
+// the entire name keeps its escapes, so "Q1 report~.docx" is shown as
+// "Q1+report%7E.docx" — the unreadable state this decode exists to
+// remove, with the '+' still in it. Widening the comparison to tolerate
+// an escape on either side would mean deciding which of several encoders
+// wrote the header, and the evidence for that decision does not exist
+// yet.
+//
+// The gaps stay open because one stored filename is all the evidence there
+// is, and the URL that produced it is long expired. traceMediaHeaders records
+// the header as it arrives, so the next live run settles what COS really
+// sends with bytes rather than with another inference from one sample.
+func decodeFormEncodedFilename(name string) string {
+ // Nothing an encoder produces looks like this, so there is nothing to
+ // undo and no round trip worth running.
+ if !strings.ContainsAny(name, "+%") {
+ return name
+ }
+ decoded, err := url.QueryUnescape(name)
+ if err != nil {
+ // A stray '%' that begins no valid escape ("100%.docx") means this is
+ // not an encoding at all, so there is nothing to undo.
+ return name
+ }
+ if decoded == name || !sameFormEncoding(url.QueryEscape(decoded), name) {
+ return name
+ }
+ return decoded
+}
+
+// sameFormEncoding reports whether two form-encodings of the same value agree,
+// allowing only for the case of the hex digits inside percent escapes.
+//
+// The tolerance is not cosmetic. url.QueryEscape writes upper-case hex and
+// plenty of servers write lower-case, so a byte comparison would reject
+// "%e5%ad%a3%e6%8a%a5.png" — a Chinese filename, the case this decode matters
+// most for, since a non-ASCII name is nothing but escapes — and quietly do
+// nothing.
+//
+// Hex case is the ONLY tolerance, which is what makes the round trip assume
+// the sender's unreserved set is url.QueryEscape's. A server that escapes one
+// character Go leaves alone fails the comparison outright; see the third gap
+// listed on decodeFormEncodedFilename for what that costs.
+func sameFormEncoding(a, b string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := 0; i < len(a); {
+ if a[i] == '%' && b[i] == '%' && i+2 < len(a) {
+ if !strings.EqualFold(a[i+1:i+3], b[i+1:i+3]) {
+ return false
+ }
+ i += 3
+ continue
+ }
+ if a[i] != b[i] {
+ return false
+ }
+ i++
+ }
+ return true
+}
+
+// cleanMediaFilename reduces a name from anywhere to a single path segment
+// with no control characters in it, or empty when nothing usable is left.
+//
+// The control-character strip is here because decodeFormEncodedFilename
+// widened what can reach this function. Of the control characters, exactly one
+// used to get this far: measured against net/http, a raw TAB in a header value
+// is passed through and every other control byte — NUL, CR, LF, ESC, DEL —
+// makes the transport reject the whole response. Since ParseMediaType never
+// percent-decodes the plain filename= form, `filename="a%00b.docx"` stayed the
+// printable string it looks like. Undoing the escapes turns all of them into
+// the bytes they name: %00 into a real NUL, %0D%0A into a real CRLF.
+//
+// NUL is the one that costs something. This name is written to
+// attachments.filename, which is Postgres TEXT, and Postgres cannot store a
+// NUL in a text value at all — the insert fails and the whole attachment is
+// lost, for a file whose bytes downloaded and decrypted perfectly. CR and LF
+// are the header-injection shape; internal/storage's ContentDisposition
+// already replaces them when it builds the download header, so that end is
+// covered, but the attachments row is written before that and there is no
+// reason to carry them to it.
+//
+// Reaching any of this needs a malicious or buggy CDN — a user cannot type a
+// NUL into a filename. That is the right bar anyway: this header is remote
+// input, and this function is the single choke point both fetch paths reach it
+// through.
+func cleanMediaFilename(name string) string {
+ name = strings.TrimSpace(stripControlRunes(name))
+ if name == "" {
+ return ""
+ }
+ name = path.Base(strings.ReplaceAll(name, "\\", "/"))
+ if name == "." || name == "/" || name == ".." {
+ return ""
+ }
+ return name
+}
+
+// stripControlRunes drops every control character, dropping rather than
+// substituting: a placeholder would put a character in the name that the
+// sender did not type, and an attachment called "a_b.docx" that was really
+// called "ab.docx" is its own small lie. Runes that decoded to invalid UTF-8
+// are left as they are — RuneError is not a control character, and mangling a
+// name further is not an improvement.
+func stripControlRunes(s string) string {
+ return strings.Map(func(r rune) rune {
+ if unicode.IsControl(r) {
+ return -1
+ }
+ return r
+ }, s)
+}
+
+// openMedia is downloadMedia without the buffer: it returns the body as a
+// stream so the caller can decrypt it as it arrives, plus the same
+// mediaHeaders the buffered path reads. Same guard, same status handling,
+// same ceiling — the ceiling is enforced by the LimitReader the caller reads
+// through, so a body that lies about its length still cannot run away with
+// the process.
+//
+// The caller closes the reader. It owns the underlying response, so an early
+// return without a Close leaks a connection.
+func openMedia(ctx context.Context, hc *http.Client, rawURL string) (io.ReadCloser, mediaHeaders, error) {
+ if err := checkMediaURL(rawURL); err != nil {
+ return nil, mediaHeaders{}, err
+ }
+ if hc == nil {
+ return nil, mediaHeaders{}, errors.New("wecom: media download: no guarded http client configured")
+ }
+
+ // No context timeout here the way downloadMedia has one: the caller reads
+ // this body over the length of a decrypt, and a deadline that covers the
+ // fetch would cut the read off mid-file. The router's own media budget
+ // bounds the whole operation.
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
+ if err != nil {
+ return nil, mediaHeaders{}, fmt.Errorf("wecom: media request: %w", stripURL(err))
+ }
+ resp, err := hc.Do(req)
+ if err != nil {
+ return nil, mediaHeaders{}, fmt.Errorf("wecom: media download: %w", stripURL(err))
+ }
+ if resp.ContentLength > maxMediaBytes {
+ resp.Body.Close()
+ return nil, mediaHeaders{}, errMediaTooLarge
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
+ resp.Body.Close()
+ return nil, mediaHeaders{}, fmt.Errorf("wecom: media download: http %d %s: %s",
+ resp.StatusCode, http.StatusText(resp.StatusCode), strings.TrimSpace(string(snippet)))
+ }
+ return &cappedBody{
+ ReadCloser: resp.Body,
+ remaining: maxMediaBytes + 1, // one byte of headroom, as downloadMedia has
+ }, mediaHeadersOf(resp), nil
+}
+
+// cappedBody stops a response that keeps going past the ceiling, so an
+// undeclared length cannot be used to fill the disk the way it used to be
+// able to fill the heap.
+type cappedBody struct {
+ io.ReadCloser
+ remaining int64
+}
+
+func (c *cappedBody) Read(p []byte) (int, error) {
+ if c.remaining <= 0 {
+ return 0, errMediaTooLarge
+ }
+ if int64(len(p)) > c.remaining {
+ p = p[:c.remaining]
+ }
+ n, err := c.ReadCloser.Read(p)
+ c.remaining -= int64(n)
+ if c.remaining <= 0 && err == nil {
+ return n, errMediaTooLarge
+ }
+ return n, err
+}
diff --git a/server/internal/integrations/wecom/media_download_test.go b/server/internal/integrations/wecom/media_download_test.go
new file mode 100644
index 0000000000..4350624283
--- /dev/null
+++ b/server/internal/integrations/wecom/media_download_test.go
@@ -0,0 +1,350 @@
+package wecom
+
+// media_download_test.go — the fetch half, against a real HTTP server.
+// A callback gives us a Tencent COS URL that is good for five minutes and
+// carries no auth; everything we learn about the file beyond its bytes comes
+// out of the response headers, so those are what these tests pin.
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+ "unicode"
+)
+
+func TestDownloadMediaReturnsTheBytes(t *testing.T) {
+ payload := strings.Repeat("ciphertext", 100)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ t.Errorf("method = %s, want GET", r.Method)
+ }
+ if auth := r.Header.Get("Authorization"); auth != "" {
+ t.Errorf("the COS url is pre-signed; sending %q leaks a credential", auth)
+ }
+ w.Header().Set("Content-Type", "application/octet-stream")
+ _, _ = w.Write([]byte(payload))
+ }))
+ defer srv.Close()
+
+ got, err := downloadMedia(context.Background(), srv.Client(), srv.URL)
+ if err != nil {
+ t.Fatalf("downloadMedia: %v", err)
+ }
+ if string(got.Body) != payload {
+ t.Fatalf("got %d bytes, want %d", len(got.Body), len(payload))
+ }
+ if got.Filename != "" {
+ t.Fatalf("no Content-Disposition means no filename, got %q", got.Filename)
+ }
+}
+
+// TestDownloadMediaReadsTheFilename covers both header forms and, crucially,
+// which one wins when a server sends both: RFC 5987's filename* carries the
+// non-ASCII name, and the plain filename beside it is the mangled fallback
+// for old clients. Taking the fallback would name every Chinese attachment
+// something like "____.pdf".
+func TestDownloadMediaReadsTheFilename(t *testing.T) {
+ cases := []struct {
+ name string
+ disposition string
+ want string
+ }{
+ {"plain filename", `attachment; filename="quarterly report.pdf"`, "quarterly report.pdf"},
+ {"rfc 5987 only", `attachment; filename*=UTF-8''%E5%AD%A3%E6%8A%A5.pdf`, "季报.pdf"},
+ {"both, rfc 5987 wins", `attachment; filename="____.pdf"; filename*=UTF-8''%E5%AD%A3%E6%8A%A5.pdf`, "季报.pdf"},
+ {"both, reversed order", `attachment; filename*=UTF-8''%E5%AD%A3%E6%8A%A5.pdf; filename="____.pdf"`, "季报.pdf"},
+ {"unquoted", `attachment;filename=notes.txt`, "notes.txt"},
+ {"no filename param", `inline`, ""},
+ {"unparseable", `attachment; filename=`, ""},
+ {"path traversal is stripped to the base name", `attachment; filename="../../etc/passwd"`, "passwd"},
+ {"windows separators too", `attachment; filename="C:\\Users\\alex\\a.docx"`, "a.docx"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Disposition", tc.disposition)
+ _, _ = w.Write([]byte("bytes"))
+ }))
+ defer srv.Close()
+
+ got, err := downloadMedia(context.Background(), srv.Client(), srv.URL)
+ if err != nil {
+ t.Fatalf("downloadMedia: %v", err)
+ }
+ if got.Filename != tc.want {
+ t.Fatalf("filename = %q, want %q", got.Filename, tc.want)
+ }
+ if got.Disposition != tc.disposition {
+ t.Errorf("raw disposition = %q, want it kept verbatim for the trace", got.Disposition)
+ }
+ })
+ }
+}
+
+// TestTheDispositionFilenameIsFormDecoded pins the encoding COS actually puts
+// in the plain filename parameter, and the exact line drawn around undoing
+// it. A live tenant sent "PC D&T Strategy 2026.docx" and the object was
+// stored as "PC+D%26T+Strategy+2026.docx": the header arrives
+// form-urlencoded, mime.ParseMediaType percent-decodes only the extended
+// filename* form, and nothing was undoing the rest.
+//
+// The three groups matter as much as the individual rows. The first is what
+// the fix buys. The second is what a bare url.QueryUnescape would have cost —
+// those rows fail on the obvious implementation, not on the absent one. The
+// third is what this choice knowingly gives up, written down as expected
+// values so the trade is on the record instead of in a reviewer's memory.
+func TestTheDispositionFilenameIsFormDecoded(t *testing.T) {
+ cases := []struct {
+ name string
+ disposition string
+ want string
+ }{
+ // -- decoded, because re-encoding reproduces the header exactly --
+ {"the reported case", `attachment; filename="PC+D%26T+Strategy+2026.docx"`, "PC D&T Strategy 2026.docx"},
+ {"spaces on their own", `attachment; filename="Meeting+notes+2026.docx"`, "Meeting notes 2026.docx"},
+ {"non-ascii, upper-case hex", `attachment; filename="%E5%AD%A3%E6%8A%A5.png"`, "季报.png"},
+ {"non-ascii, lower-case hex", `attachment; filename="%e5%ad%a3%e6%8a%a5.png"`, "季报.png"},
+ {"an escaped plus survives the decode", `attachment; filename="C%2B%2B+notes.docx"`, "C++ notes.docx"},
+ {"escaped separators are decoded, then reduced", `attachment; filename="..%2F..%2Fetc%2Fpasswd"`, "passwd"},
+
+ // -- left alone, because the value cannot have been form-encoded --
+ {"a plus beside a real space is a real plus", `attachment; filename="C++ notes.docx"`, "C++ notes.docx"},
+ {"a percent that begins no escape", `attachment; filename="100%.docx"`, "100%.docx"},
+ {"filename* is already decoded and is not decoded twice", `attachment; filename*=UTF-8''A%2BB.docx`, "A+B.docx"},
+
+ // -- the sacrifices, named --
+ {
+ // "C++.docx" is byte-identical to a form-encoding of "C .docx",
+ // so no rule reading only this header can tell them apart. We
+ // decode, and this name loses its pluses.
+ "a plus with no space anywhere is decoded as a space",
+ `attachment; filename="C++.docx"`, "C .docx",
+ },
+ {
+ // The same trade, and the rows are here because "C++.docx" reads
+ // as a curiosity while the class it stands for does not: every
+ // name whose only encoder-touched character is a '+' loses it.
+ "a product name loses its plus too",
+ `attachment; filename="React+Redux.md"`, "React Redux.md",
+ },
+ {
+ "and so does a version number",
+ `attachment; filename="C++11.pdf"`, "C 11.pdf",
+ },
+ {
+ // RFC 3986 spelling rather than the form one. Re-encoding gives
+ // "Meeting+notes.docx", the check fails, and the escapes stay.
+ "a %20-encoded name keeps its escapes",
+ `attachment; filename="Meeting%20notes.docx"`, "Meeting%20notes.docx",
+ },
+ {
+ // The round trip re-encodes with url.QueryEscape, whose unreserved
+ // set is A-Za-z0-9-_.~ — so it assumes the server agreed on that
+ // set. Java's URLEncoder also passes '*', and PHP's urlencode
+ // escapes '~' as %7E, which Go would have left alone. Re-encoding
+ // "backup~.docx" gives back the tilde, the lengths differ, and
+ // nothing is decoded.
+ "a tilde escaped by a non-Go encoder keeps its escape",
+ `attachment; filename="backup%7E.docx"`, "backup%7E.docx",
+ },
+ {
+ // The reason the row above is worth pinning: the check is
+ // all-or-nothing. One character outside Go's set and the WHOLE
+ // name stays escaped — including the '+' this decode exists to
+ // remove — so the user is shown exactly the unreadable string the
+ // fix was written to stop showing them.
+ "one foreign escape keeps the whole name escaped, plus and all",
+ `attachment; filename="Q1+report%7E.docx"`, "Q1+report%7E.docx",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Disposition", tc.disposition)
+ _, _ = w.Write([]byte("bytes"))
+ }))
+ defer srv.Close()
+
+ got, err := downloadMedia(context.Background(), srv.Client(), srv.URL)
+ if err != nil {
+ t.Fatalf("downloadMedia: %v", err)
+ }
+ if got.Filename != tc.want {
+ t.Fatalf("filename = %q, want %q", got.Filename, tc.want)
+ }
+ })
+ }
+}
+
+// TestDownloadMediaFailsLoudlyOn404: a five-minute URL that has already
+// expired is the ordinary failure here, and it must not look like an empty
+// file.
+func TestDownloadMediaFailsLoudlyOnAnErrorStatus(t *testing.T) {
+ for _, status := range []int{http.StatusNotFound, http.StatusForbidden, http.StatusInternalServerError} {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte("<Error><Code>AccessDenied</Code></Error>"))
+ }))
+ _, err := downloadMedia(context.Background(), srv.Client(), srv.URL)
+ srv.Close()
+ if err == nil {
+ t.Fatalf("http %d returned no error", status)
+ }
+ if !strings.Contains(err.Error(), http.StatusText(status)) && !strings.Contains(err.Error(), "http "+itoa(status)) {
+ t.Fatalf("http %d error does not name the status: %v", status, err)
+ }
+ }
+}
+
+func itoa(n int) string {
+ if n == 0 {
+ return "0"
+ }
+ var b []byte
+ for n > 0 {
+ b = append([]byte{byte('0' + n%10)}, b...)
+ n /= 10
+ }
+ return string(b)
+}
+
+// TestDownloadMediaGivesUpWhenTheServerStalls: COS is normally fast, but a
+// download that never finishes would otherwise hold a media slot for the
+// whole 45s router budget and starve everything queued behind it.
+func TestDownloadMediaGivesUpWhenTheServerStalls(t *testing.T) {
+ release := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ }
+ }))
+ defer func() {
+ close(release)
+ srv.Close()
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
+ defer cancel()
+
+ start := time.Now()
+ _, err := downloadMedia(ctx, srv.Client(), srv.URL)
+ if err == nil {
+ t.Fatal("a stalled download must return an error")
+ }
+ if elapsed := time.Since(start); elapsed > 5*time.Second {
+ t.Fatalf("gave up after %s — the caller's deadline was not honoured", elapsed)
+ }
+}
+
+// TestDownloadMediaRefusesAnOversizeBody, both ways a server can present one:
+// an honest Content-Length we can reject before reading a byte, and a
+// chunked response that only reveals its size as it arrives.
+func TestDownloadMediaRefusesAnOversizeBody(t *testing.T) {
+ t.Run("declared up front", func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Length", "209715200") // 200 MB
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+ _, err := downloadMedia(context.Background(), srv.Client(), srv.URL)
+ if !errors.Is(err, errMediaTooLarge) {
+ t.Fatalf("err = %v, want errMediaTooLarge", err)
+ }
+ })
+
+ t.Run("only discovered while reading", func(t *testing.T) {
+ chunk := make([]byte, 1<<20)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // No Content-Length: the body streams until we stop it.
+ for i := 0; i < 200; i++ {
+ if _, err := w.Write(chunk); err != nil {
+ return
+ }
+ if r.Context().Err() != nil {
+ return
+ }
+ }
+ }))
+ defer srv.Close()
+ _, err := downloadMedia(context.Background(), srv.Client(), srv.URL)
+ if !errors.Is(err, errMediaTooLarge) {
+ t.Fatalf("err = %v, want errMediaTooLarge", err)
+ }
+ })
+}
+
+// TestDownloadMediaRefusesAUrlItShouldNotFetch: the URL arrives over the
+// authenticated socket, but it is still a string from outside naming a host
+// we then GET. Anything that is not http(s) is refused rather than handed to
+// the transport.
+func TestDownloadMediaRefusesAUrlItShouldNotFetch(t *testing.T) {
+ for _, raw := range []string{"", " ", "file:///etc/passwd", "ftp://example.invalid/a", "not a url at all"} {
+ if _, err := downloadMedia(context.Background(), http.DefaultClient, raw); err == nil {
+ t.Fatalf("downloadMedia(%q) returned no error", raw)
+ }
+ }
+}
+
+// TestControlCharactersNeverReachTheFilename covers what the decode widened.
+//
+// Undoing the escapes widened the byte domain of this name. Exactly one
+// control character used to get here: a raw TAB, which net/http passes
+// through in a header value where it rejects the whole response for a NUL, a
+// CR, an LF, an ESC or a DEL. Since mime.ParseMediaType never percent-decodes
+// the plain filename= form, `filename="a%00b.docx"` stayed the printable
+// string it looks like. Decoding turns those escapes into the bytes they name.
+//
+// NUL is the one that costs something. The name is written to
+// attachments.filename, which is Postgres TEXT, and Postgres cannot store a
+// NUL in a text value — so a file whose bytes downloaded and decrypted
+// perfectly is lost on the insert. CR and LF are the header-injection shape;
+// internal/storage's ContentDisposition already replaces them when it builds
+// the download header, so nothing is injectable either way, but the row is
+// written before that and there is no reason to carry them.
+//
+// Every escaped row's value really does survive the round-trip check — that
+// is why it reaches cleanMediaFilename decoded at all — so these assert the
+// strip, not the decode declining to run. The last row is the one that needed
+// no decode to get here and was never handled.
+func TestControlCharactersNeverReachTheFilename(t *testing.T) {
+ cases := []struct {
+ name string
+ disposition string
+ want string
+ }{
+ {"a NUL, which Postgres TEXT cannot store", `attachment; filename="a%00b.docx"`, "ab.docx"},
+ {"a CRLF, the header-injection shape", `attachment; filename="a%0D%0Ab.docx"`, "ab.docx"},
+ {"a tab", `attachment; filename="a%09b.docx"`, "ab.docx"},
+ {"an ESC, which a terminal reading the log would act on", `attachment; filename="a%1Bb.docx"`, "ab.docx"},
+ {"a DEL", `attachment; filename="a%7Fb.docx"`, "ab.docx"},
+ {"nothing but control characters leaves no name at all", `attachment; filename="%00%01%02"`, ""},
+ {"a raw tab, the one that never needed the decode", "attachment; filename=\"a\tb.docx\"", "ab.docx"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Disposition", tc.disposition)
+ _, _ = w.Write([]byte("bytes"))
+ }))
+ defer srv.Close()
+
+ got, err := downloadMedia(context.Background(), srv.Client(), srv.URL)
+ if err != nil {
+ t.Fatalf("downloadMedia: %v", err)
+ }
+ if got.Filename != tc.want {
+ t.Fatalf("filename = %q, want %q", got.Filename, tc.want)
+ }
+ for _, r := range got.Filename {
+ if unicode.IsControl(r) {
+ t.Fatalf("filename %q still carries a control character %U", got.Filename, r)
+ }
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/wecom/media_guard.go b/server/internal/integrations/wecom/media_guard.go
new file mode 100644
index 0000000000..1180344d4c
--- /dev/null
+++ b/server/internal/integrations/wecom/media_guard.go
@@ -0,0 +1,306 @@
+package wecom
+
+// media_guard.go — the media fetcher is pointed at an address by somebody else.
+//
+// A callback carries a pre-signed COS URL and we GET it. The URL is a string
+// that arrived over the socket: WeCom put it there, but the adapter cannot
+// prove that, and the fetch runs from inside the deployment's network with
+// whatever reach that network has. On this machine alone that reach includes
+// a Tailscale tailnet (100.64.0.0/10), a proxy's fake-IP range
+// (198.18.0.0/15), Docker's bridges, and the loopback the backend's own
+// admin endpoints listen on.
+//
+// So the guard is not on the URL, it is on the CONNECTION. Checking the
+// hostname is worth nothing on its own: the URL can redirect (a 302 to
+// http://169.254.169.254/ is one line of attacker-controlled response), and
+// a hostname that passed a check can resolve to something else a moment
+// later. A DialContext that resolves the destination and refuses a
+// non-public address runs on every hop of every redirect, against the answer
+// actually being connected to, which is the only place both of those are
+// covered at once.
+//
+// The shape is @leroy-chen's, from the other WeCom media PR (#6524,
+// newSecureMediaClient / isAllowedMediaIP) — that PR raised this first and
+// its fix is the right one. Two things are added here: the reserved ranges
+// below (a predicate list built on netip's own helpers misses CGNAT-adjacent
+// and IETF-reserved space, and CGNAT is where a Tailscale tailnet lives), and
+// an injectable resolver so the rebinding case can be tested rather than
+// argued about.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/netip"
+ "strings"
+ "time"
+)
+
+// ErrMediaAddrBlocked is returned instead of a connection when every address
+// a media host resolves to is one the deployment must not be pointed at. It
+// is deliberately distinct from a dial failure: the caller logs the two
+// differently, and only this one means somebody sent us a URL they should
+// not have.
+var ErrMediaAddrBlocked = errors.New("wecom: media host resolves to a non-public address")
+
+// mediaDialTimeout bounds one TCP connect. It sits inside
+// mediaDownloadTimeout, which bounds the whole fetch.
+const mediaDialTimeout = 10 * time.Second
+
+// The reserved ranges come in two groups, and the difference is not
+// taxonomy — it is whether an operator is allowed to open them.
+//
+// Both lists are the IANA IPv4 and IPv6 Special-Purpose Address Registries
+// minus what netip's own predicates already catch (IsLoopback / IsPrivate /
+// IsLinkLocal* / IsMulticast / IsUnspecified), minus the handful of
+// special-purpose blocks that are ordinary globally-routed unicast (the AS112
+// delegations 192.31.196.0/24, 192.175.48.0/24 and 2620:4f:8000::/48, and
+// AMT's 192.52.193.0/24) — those are "special" in who runs them, not in where
+// they point, and refusing them would buy nothing.
+//
+// reservedMediaPrefixes is space that is not the public internet: a media URL
+// resolving there is either a mistake or an attempt, and either way there is
+// no object at the end of it. 100.64.0.0/10 is the one that matters most —
+// RFC 6598 shared address space, which no standard-library predicate reports
+// as private, and which is exactly what Tailscale hands out. A tailnet peer
+// is a machine inside the trust boundary reachable by IP with no credential.
+//
+// This group is what mediaAllowedPrefixes can reopen, because a real
+// deployment shape lives in it: a fake-IP proxy hands out 198.18.0.0/15 for
+// every public hostname, WeCom's own COS host included. An operator who knows
+// their proxy's pool can say so.
+var reservedMediaPrefixes = []netip.Prefix{
+ // ---- IPv4 ----
+ netip.MustParsePrefix("0.0.0.0/8"), // "this network"
+ netip.MustParsePrefix("100.64.0.0/10"), // RFC 6598 CGNAT — Tailscale lives here
+ netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments
+ netip.MustParsePrefix("192.0.2.0/24"), // TEST-NET-1
+ netip.MustParsePrefix("198.18.0.0/15"), // benchmarking — and a proxy's fake-IP range
+ netip.MustParsePrefix("198.51.100.0/24"), // TEST-NET-2
+ netip.MustParsePrefix("203.0.113.0/24"), // TEST-NET-3
+ netip.MustParsePrefix("240.0.0.0/4"), // reserved, includes 255.255.255.255
+ netip.MustParsePrefix("192.88.99.0/24"), // deprecated 6to4 relay anycast — the v4 end of 2002::/16
+
+ // ---- IPv6 ----
+ netip.MustParsePrefix("100::/64"), // discard-only
+ netip.MustParsePrefix("100:0:0:1::/64"), // dummy prefix, also discard-only
+ // The whole IETF protocol-assignments block, not its dozen sub-entries.
+ // It holds Teredo (2001::/32), benchmarking (2001:2::/48 — the twin of
+ // 198.18.0.0/15 above), AMT, AS112-v6, ORCHID/ORCHIDv2, DET, and the PCP
+ // / TURN / DNS-SD anycast addresses. None of it is somewhere a COS object
+ // lives, and one prefix is easier to keep true than eight. Same call the
+ // v4 side already makes with 192.0.0.0/24. Documentation space is
+ // 2001:db8::/32, which is outside this /23 and listed separately.
+ netip.MustParsePrefix("2001::/23"),
+ netip.MustParsePrefix("2001:db8::/32"), // documentation
+ netip.MustParsePrefix("3fff::/20"), // documentation, RFC 9637
+ netip.MustParsePrefix("5f00::/16"), // SRv6 SIDs, RFC 9602 — routing labels, not hosts
+ // Site-local. RFC 3879 deprecated it and IANA delisted it, which is why
+ // no predicate and no registry row covers it — but the networks that
+ // were numbered out of it before 2004 still route it internally, and it
+ // is one line.
+ netip.MustParsePrefix("fec0::/10"),
+}
+
+// translationMediaPrefixes is TRANSLATION space, and no configuration reopens
+// it. These addresses are not destinations, they are IPv4 destinations
+// wearing an IPv6 costume: 64:ff9b:1::a9fe:a9fe is 169.254.169.254 the moment
+// a NAT64 translator sees it, and 2002:7f00:1::1 is 127.0.0.1 through a 6to4
+// relay.
+//
+// That costume is why the split exists. The early IsLoopback / IsPrivate /
+// IsLinkLocalUnicast checks never fire on these — at that point they are
+// IPv6 addresses, and every one of them reaches straight past a guard that
+// only knows how to recognise an IPv4 address when it is written as one. This
+// list is the ONLY thing standing between the guard and the address embedded
+// inside. Letting mediaAllowedPrefixes override it would mean
+// MULTICA_WECOM_MEDIA_ALLOW_CIDRS=::/0 — or, just as well, =2002::/16 —
+// reaching the loopback and the metadata endpoint the guard exists to refuse,
+// written in a spelling the operator never thought they were opening.
+//
+// So it is a hard block, and it costs nothing: no COS object, no proxy pool
+// and no deployment lives in translation space, so there is no shape to
+// accommodate here the way there is for a fake-IP proxy.
+var translationMediaPrefixes = []netip.Prefix{
+ netip.MustParsePrefix("64:ff9b::/96"), // NAT64, well-known prefix
+ netip.MustParsePrefix("64:ff9b:1::/48"), // NAT64, local-use prefix (RFC 8215)
+ netip.MustParsePrefix("2002::/16"), // 6to4 — the last 112 bits open with an IPv4 address
+}
+
+// addrPolicy answers whether one resolved address may be dialed. Production
+// uses publicAddrOnly; tests substitute a policy that allows the loopback
+// their own server is on, so that what is under test is the guard's decision
+// rather than the test harness's address.
+type addrPolicy func(netip.Addr) bool
+
+// mediaAllowedPrefixes are ranges an operator has declared safe for media
+// fetches despite looking reserved. It exists for one real deployment shape:
+// a machine behind a fake-IP proxy, where the resolver answers every public
+// hostname with an address out of 198.18.0.0/15 and the proxy forwards the
+// traffic onward. On such a machine WeCom's own COS host is indistinguishable
+// from a link-local metadata endpoint by address alone, so the guard refuses
+// every attachment and inbound media stops working entirely.
+//
+// Empty by default. Widening this is a decision with a cost: whatever range is
+// listed here can be reached by a URL somebody else controls, which is exactly
+// what the guard exists to prevent. It is opt-in per deployment, and worth
+// setting only where the operator knows the range belongs to their proxy.
+//
+// What it CANNOT open, at any width: loopback, the private ranges and
+// link-local, which are refused above the loop this list is consulted in; and
+// translationMediaPrefixes, which is refused for the same reason one step
+// later. Those are the ranges an over-wide CIDR would otherwise hand to
+// whoever supplied the URL.
+var mediaAllowedPrefixes []netip.Prefix
+
+// SetMediaAllowedPrefixes declares ranges the media guard may dial. Called at
+// boot from MULTICA_WECOM_MEDIA_ALLOW_CIDRS. An unparseable entry is reported
+// and skipped rather than silently widening or silently narrowing the guard.
+func SetMediaAllowedPrefixes(cidrs []string) []error {
+ var (
+ out []netip.Prefix
+ errs []error
+ )
+ for _, raw := range cidrs {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ continue
+ }
+ p, err := netip.ParsePrefix(raw)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("wecom: media allow cidr %q: %w", raw, err))
+ continue
+ }
+ out = append(out, p)
+ }
+ mediaAllowedPrefixes = out
+ return errs
+}
+
+// publicAddrOnly is the production policy: everything that is not routable
+// public internet is refused.
+func publicAddrOnly(a netip.Addr) bool {
+ // An IPv4-mapped IPv6 address (::ffff:127.0.0.1) reports none of the IPv4
+ // predicates until it is unmapped, which is the whole trick.
+ a = a.Unmap()
+ if !a.IsValid() {
+ return false
+ }
+ if a.IsLoopback() || a.IsPrivate() || a.IsUnspecified() ||
+ a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() ||
+ a.IsInterfaceLocalMulticast() || a.IsMulticast() {
+ return false
+ }
+ // Translation space first, and before the allow-list is consulted at all.
+ // The address inside one of these is an IPv4 address the checks above
+ // would have refused on sight; the only reason they did not fire is the
+ // spelling. Nothing an operator configures reopens it.
+ for _, p := range translationMediaPrefixes {
+ if p.Contains(a) {
+ return false
+ }
+ }
+ for _, p := range reservedMediaPrefixes {
+ if p.Contains(a) {
+ // An operator may have declared this range theirs — a fake-IP
+ // proxy's pool is the case this exists for. Checked only for
+ // addresses the guard would otherwise refuse, so an empty
+ // allow-list leaves the guard exactly as strict as before.
+ for _, allowed := range mediaAllowedPrefixes {
+ if allowed.Contains(a) {
+ return true
+ }
+ }
+ return false
+ }
+ }
+ return true
+}
+
+// hostResolver is net.DefaultResolver's one method we need, so a test can
+// hand back an address of its choosing for a name of its choosing.
+type hostResolver interface {
+ LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
+}
+
+// mediaGuard is the dialer the media client connects through.
+type mediaGuard struct {
+ allow addrPolicy
+ resolve hostResolver
+ onRefuse func(host string, addr netip.Addr) // test hook; nil in production
+}
+
+// dial resolves the destination itself and connects to a checked address —
+// never to the hostname, because resolving twice is the rebinding window.
+//
+// Every address is checked before any is dialed, and the connection is made
+// to the literal that passed. A host that answers with a mix of public and
+// internal addresses gets the public ones tried and the internal ones
+// refused, rather than the whole name allowed on the strength of one good
+// answer.
+func (g mediaGuard) dial(ctx context.Context, network, addr string) (net.Conn, error) {
+ host, port, err := net.SplitHostPort(addr)
+ if err != nil {
+ return nil, fmt.Errorf("wecom: media dial: %w", err)
+ }
+ addrs, err := g.resolver().LookupNetIP(ctx, "ip", host)
+ if err != nil {
+ return nil, fmt.Errorf("wecom: media dial: resolve %s: %w", host, err)
+ }
+ allow := g.allow
+ if allow == nil {
+ allow = publicAddrOnly
+ }
+
+ d := &net.Dialer{Timeout: mediaDialTimeout}
+ lastErr := error(ErrMediaAddrBlocked)
+ for _, a := range addrs {
+ if !allow(a) {
+ if g.onRefuse != nil {
+ g.onRefuse(host, a)
+ }
+ continue
+ }
+ conn, dialErr := d.DialContext(ctx, network, net.JoinHostPort(a.String(), port))
+ if dialErr == nil {
+ return conn, nil
+ }
+ lastErr = dialErr
+ }
+ return nil, lastErr
+}
+
+func (g mediaGuard) resolver() hostResolver {
+ if g.resolve != nil {
+ return g.resolve
+ }
+ return net.DefaultResolver
+}
+
+// newMediaHTTPClient builds the client every media download goes through.
+//
+// Two guards, and they cover different things. The dialer refuses a
+// destination; CheckRedirect refuses a SCHEME, because a redirect to
+// file:// or gopher:// never reaches a dialer at all and the transport
+// would happily hand it to a protocol handler.
+func newMediaHTTPClient(g mediaGuard) *http.Client {
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.DialContext = g.dial
+ // Nothing about a COS object needs a proxy, and honouring HTTP_PROXY here
+ // would send the fetch to an address the dial guard never sees.
+ transport.Proxy = nil
+ return &http.Client{
+ Transport: transport,
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ if len(via) >= 5 {
+ return errors.New("wecom: media download: too many redirects")
+ }
+ if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
+ return fmt.Errorf("wecom: media redirect to scheme %q refused", req.URL.Scheme)
+ }
+ return nil
+ },
+ }
+}
diff --git a/server/internal/integrations/wecom/media_guard_allow_test.go b/server/internal/integrations/wecom/media_guard_allow_test.go
new file mode 100644
index 0000000000..2ec1aa10ce
--- /dev/null
+++ b/server/internal/integrations/wecom/media_guard_allow_test.go
@@ -0,0 +1,325 @@
+package wecom
+
+// media_guard_allow_test.go — a machine behind a fake-IP proxy resolves every
+// public hostname into 198.18.0.0/15, so WeCom's own COS host is
+// indistinguishable from a metadata endpoint by address alone and the guard
+// refuses every attachment. The allow-list is how an operator says "that range
+// is my proxy". It must not become a way to reach loopback or the private
+// ranges, which is what the guard is actually for.
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+func withAllowed(t *testing.T, cidrs ...string) {
+ t.Helper()
+ prev := mediaAllowedPrefixes
+ t.Cleanup(func() { mediaAllowedPrefixes = prev })
+ if errs := SetMediaAllowedPrefixes(cidrs); len(errs) > 0 {
+ t.Fatalf("SetMediaAllowedPrefixes: %v", errs)
+ }
+}
+
+func TestAnEmptyAllowListLeavesTheGuardUnchanged(t *testing.T) {
+ withAllowed(t)
+ for _, addr := range []string{
+ "127.0.0.1", "10.0.0.1", "192.168.1.1", "172.16.0.1",
+ "169.254.169.254", "100.100.100.100", "198.18.0.80", "::1",
+ } {
+ if publicAddrOnly(netip.MustParseAddr(addr)) {
+ t.Errorf("%s was allowed with an empty allow-list", addr)
+ }
+ }
+ for _, addr := range []string{"1.1.1.1", "8.8.8.8", "2606:4700::1111"} {
+ if !publicAddrOnly(netip.MustParseAddr(addr)) {
+ t.Errorf("%s was refused — ordinary public addresses must still work", addr)
+ }
+ }
+}
+
+func TestADeclaredProxyRangeBecomesReachable(t *testing.T) {
+ withAllowed(t, "198.18.0.0/15")
+ if !publicAddrOnly(netip.MustParseAddr("198.18.0.80")) {
+ t.Fatal("a declared proxy range is still refused — media stays broken on a fake-IP machine")
+ }
+}
+
+// The whole point of the guard. Declaring one range must not open the others.
+func TestDeclaringOneRangeDoesNotOpenTheRest(t *testing.T) {
+ withAllowed(t, "198.18.0.0/15")
+ for _, addr := range []string{
+ "127.0.0.1", // the backend's own admin endpoints
+ "169.254.169.254", // cloud metadata
+ "100.100.100.100", // Alibaba cloud metadata
+ "10.0.0.1", "192.168.1.1", "172.16.0.1",
+ "::1", "::ffff:127.0.0.1", // the IPv4-mapped trick
+ } {
+ if publicAddrOnly(netip.MustParseAddr(addr)) {
+ t.Errorf("declaring 198.18.0.0/15 also opened %s", addr)
+ }
+ }
+}
+
+// Loopback and the private ranges are refused before the allow-list is even
+// consulted, so an operator cannot open them by mistake or by pasting a
+// too-wide CIDR.
+func TestLoopbackAndPrivateCannotBeAllowedAtAll(t *testing.T) {
+ withAllowed(t, "0.0.0.0/0", "::/0")
+ for _, addr := range []string{"127.0.0.1", "10.0.0.1", "192.168.1.1", "::1"} {
+ if publicAddrOnly(netip.MustParseAddr(addr)) {
+ t.Errorf("%s became reachable via a 0.0.0.0/0 allow-list — the guard's core promise is broken", addr)
+ }
+ }
+}
+
+func TestAnUnparseableCidrIsReportedNotIgnored(t *testing.T) {
+ prev := mediaAllowedPrefixes
+ t.Cleanup(func() { mediaAllowedPrefixes = prev })
+ errs := SetMediaAllowedPrefixes([]string{"198.18.0.0/15", "not-a-cidr", " "})
+ if len(errs) != 1 {
+ t.Fatalf("got %d errors, want exactly one for the malformed entry", len(errs))
+ }
+ if !publicAddrOnly(netip.MustParseAddr("198.18.0.80")) {
+ t.Error("the valid entry was dropped because a sibling was malformed")
+ }
+}
+
+// The dangerous shape of this switch is an operator pasting the widest CIDR
+// there is. `0.0.0.0/0` must still not reach the loopback the backend's own
+// admin endpoints listen on: the allow-list is consulted only inside the
+// reservedMediaPrefixes loop, and loopback, private and link-local are refused
+// before that loop is reached.
+//
+// Driven through the real dialer against a real listening server, not through
+// publicAddrOnly alone. A policy that answers "no" while the transport
+// connects anyway is exactly the failure a predicate-level test cannot see, so
+// the assertion that matters is that the server was never reached.
+func TestAWideOpenAllowListStillCannotReachLoopback(t *testing.T) {
+ var reached bool
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ reached = true
+ w.Write([]byte("the backend's own admin endpoint"))
+ }))
+ defer srv.Close()
+
+ u, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatalf("parse test server url: %v", err)
+ }
+
+ withAllowed(t, "0.0.0.0/0", "::/0")
+
+ // Both spellings of the same loopback: the IPv4-mapped form reports none
+ // of the IPv4 predicates until it is unmapped, which is the trick the
+ // guard has to survive whether or not an allow-list is in play.
+ for _, resolved := range []string{"127.0.0.1", "::ffff:127.0.0.1"} {
+ reached = false
+ client := newMediaHTTPClient(mediaGuard{
+ resolve: staticResolver{addr: netip.MustParseAddr(resolved)},
+ })
+ _, err := downloadMedia(context.Background(),
+ client, "http://cos.example.com:"+u.Port()+"/object")
+ if !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Errorf("resolving to %s under a 0.0.0.0/0 allow-list: err = %v, want the guard's refusal", resolved, err)
+ }
+ if reached {
+ t.Errorf("resolving to %s under a 0.0.0.0/0 allow-list opened a socket to loopback — the guard's core promise is broken", resolved)
+ }
+ }
+}
+
+// Translation space is the other half of that promise, and it is the half the
+// IPv4 literals above cannot see.
+//
+// Loopback and the private ranges are refused above the allow-list loop by
+// IsLoopback / IsPrivate / IsLinkLocalUnicast. Those predicates never fire on
+// a NAT64 or 6to4 address, because at that point it IS an IPv6 address — the
+// IPv4 destination is embedded in the low bits and only the translator on the
+// other end unwraps it. So for these prefixes the deny list was the only thing
+// in the way, and letting an operator's CIDR override it put
+// 64:ff9b:1::a9fe:a9fe (→ 169.254.169.254) and 2002:7f00:1::1 (→ 127.0.0.1)
+// back within reach of a URL WeCom supplies — the exact addresses the entry
+// above proves are unreachable when they are written as IPv4.
+//
+// ::/0 is the widest an operator can paste, and 2002::/16 is the narrow,
+// plausible version of the same mistake: someone widening the range until
+// images load. Neither may open translation space.
+//
+// Driven through the real dialer, like the loopback case, and for the same
+// reason: WHICH error comes back is the whole assertion. ErrMediaAddrBlocked
+// means the address never got past the policy; a connect timeout or "no route
+// to host" means a socket was opened toward an address that reaches inside.
+func TestAWideOpenAllowListStillCannotReachTranslationSpace(t *testing.T) {
+ // nat64 carries 169.254.169.254, sixToFour carries 127.0.0.1.
+ const (
+ nat64 = "64:ff9b:1::a9fe:a9fe"
+ sixToFour = "2002:7f00:1::1"
+ )
+
+ for _, allow := range [][]string{
+ {"0.0.0.0/0", "::/0"}, // the widest thing there is
+ {"2002::/16"}, // widened until images loaded
+ {"64:ff9b:1::/48"}, // the same mistake, NAT64 side
+ } {
+ t.Run(strings.Join(allow, ","), func(t *testing.T) {
+ withAllowed(t, allow...)
+
+ for _, addr := range []string{nat64, sixToFour} {
+ if publicAddrOnly(netip.MustParseAddr(addr)) {
+ t.Errorf("%s became reachable under an allow-list of %v — it is %s in an IPv6 spelling",
+ addr, allow, map[string]string{nat64: "169.254.169.254", sixToFour: "127.0.0.1"}[addr])
+ }
+ }
+
+ // A literal in the signed URL, straight through the client every
+ // media fetch goes through.
+ for _, target := range []string{
+ "http://[" + nat64 + "]/latest/meta-data/",
+ "http://[" + sixToFour + "]:9/object",
+ } {
+ _, err := downloadMedia(context.Background(), newMediaHTTPClient(mediaGuard{}), target)
+ if !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Errorf("%s under an allow-list of %v: err = %v, want the guard's refusal — anything else means a socket was opened", target, allow, err)
+ }
+ }
+
+ // And an innocent hostname whose answer is not, which is the shape
+ // a rebinding attempt takes.
+ for _, resolved := range []string{nat64, sixToFour} {
+ var refused []netip.Addr
+ client := newMediaHTTPClient(mediaGuard{
+ resolve: staticResolver{addr: netip.MustParseAddr(resolved)},
+ onRefuse: func(_ string, a netip.Addr) { refused = append(refused, a) },
+ })
+ _, err := downloadMedia(context.Background(), client, "https://cos.example.com/object")
+ if !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Errorf("a host resolving to %s under an allow-list of %v: err = %v, want the guard's refusal", resolved, allow, err)
+ }
+ if len(refused) != 1 || refused[0].String() != resolved {
+ t.Errorf("refused = %v, want exactly %s — the refusal has to come from the policy, not from a failed connect", refused, resolved)
+ }
+ }
+ })
+ }
+}
+
+// The escape hatch still has to work, or the split above would have been paid
+// for by breaking the deployment it exists for.
+func TestTheProxyEscapeHatchSurvivesTheTranslationBlock(t *testing.T) {
+ withAllowed(t, "198.18.0.0/15")
+ if !publicAddrOnly(netip.MustParseAddr("198.18.0.80")) {
+ t.Fatal("a declared proxy range is refused — media stays broken on a fake-IP machine")
+ }
+}
+
+// classifyMediaFailure has to tell the guard's refusal apart from an ordinary
+// failed download, because those two put an operator in completely different
+// places: one is a URL that should not have been sent (or a proxy range that
+// needs declaring in MULTICA_WECOM_MEDIA_ALLOW_CIDRS), the other is WeCom or
+// the network.
+//
+// Driven from real errors rather than hand-built ones. The refusal travels
+// from the dialer through http.Client (which wraps it in a *url.Error) and
+// through stripURL before anything classifies it, so a test that constructs
+// ErrMediaAddrBlocked directly would pass even if that chain stopped
+// preserving errors.Is — which is exactly how this went unnoticed.
+func TestAGuardRefusalIsClassifiedApartFromAnOrdinaryFailure(t *testing.T) {
+ withAllowed(t) // the guard as it ships
+
+ // Blocked: the production policy, pointed inward.
+ _, err := downloadMedia(context.Background(), newMediaHTTPClient(mediaGuard{}), "http://127.0.0.1:9/object")
+ if !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Fatalf("err = %v, want the guard's refusal — this test is not exercising the blocked path", err)
+ }
+ if got := classifyMediaFailure(err); got != mediaFailureBlocked {
+ t.Errorf("classifyMediaFailure(guard refusal) = %d, want mediaFailureBlocked (%d)", got, mediaFailureBlocked)
+ }
+
+ // Too large: still its own kind, not swallowed by the new branch.
+ oversize := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Length", "209715200")
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer oversize.Close()
+ _, err = downloadMedia(context.Background(), testMediaClient(), oversize.URL)
+ if !errors.Is(err, errMediaTooLarge) {
+ t.Fatalf("err = %v, want the size refusal", err)
+ }
+ if got := classifyMediaFailure(err); got != mediaFailureTooLarge {
+ t.Errorf("classifyMediaFailure(oversize) = %d, want mediaFailureTooLarge (%d)", got, mediaFailureTooLarge)
+ }
+
+ // An expired link is neither.
+ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusForbidden)
+ }))
+ defer expired.Close()
+ _, err = downloadMedia(context.Background(), testMediaClient(), expired.URL)
+ if got := classifyMediaFailure(err); got != mediaFailureUnreadable {
+ t.Errorf("classifyMediaFailure(http 403) = %d, want mediaFailureUnreadable (%d)", got, mediaFailureUnreadable)
+ }
+}
+
+// The refusal reaches an operator through the log and stops there. Whatever
+// the sender is told must not name the address the host resolved to, or the
+// signed url — a chat message is the one place neither belongs.
+//
+// The message carries one attachment the guard refuses and one it never tries
+// (an unfetchable scheme, rejected before any client is involved). Those are
+// two different mediaFailure kinds that deliberately render to the SAME
+// sentence, because neither is anything the sender can act on. So the sender
+// must still hear it once: two lines here would be the adapter repeating
+// itself at the one person who can do nothing about either.
+func TestAGuardRefusalNeverPutsAnAddressOrUrlInTheChat(t *testing.T) {
+ withAllowed(t)
+
+ // A real server on loopback, so the refusal is about a genuine address
+ // the guard declined rather than a name that failed to resolve.
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Write([]byte("should never be fetched"))
+ }))
+ defer srv.Close()
+
+ storage := &fakeMediaStorage{}
+ senders, conn := notifierWithLiveSocket(uuidOf(1))
+ // NOT newTestResolver: that one swaps in a client which permits loopback,
+ // which is the very thing under test here. This keeps the production
+ // guard.
+ r := NewMediaResolver(storage, newFakeMediaLedger(storage), senders, testLogger()).(*wecomMediaResolver)
+
+ msg := mediaMessage(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []any{
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": srv.URL, "aeskey": testAESKey}},
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": "ftp://cos.example.com/object", "aeskey": testAESKey}},
+ }}})
+ out := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+
+ if len(out.MediaRefs) != 0 {
+ t.Fatalf("MediaRefs = %d, want 0 — the guard was supposed to refuse this fetch", len(out.MediaRefs))
+ }
+ if len(storage.stored()) != 0 {
+ t.Fatal("an object was stored from an address the guard refuses")
+ }
+ if len(conn.frames) != 1 {
+ t.Fatalf("notices = %d, want exactly 1", len(conn.frames))
+ }
+ body := conn.sendBody(t, 0)
+ md, _ := body["markdown"].(map[string]any)
+ content, _ := md["content"].(string)
+ if content != mediaUnreadableNotice {
+ t.Errorf("notice = %q, want the plain did-not-arrive wording exactly once", content)
+ }
+ for _, secret := range []string{"127.0.0.1", "::1", srv.URL, testAESKey} {
+ if strings.Contains(content, secret) {
+ t.Errorf("the chat notice leaks %q: %q", secret, content)
+ }
+ }
+}
diff --git a/server/internal/integrations/wecom/media_guard_test.go b/server/internal/integrations/wecom/media_guard_test.go
new file mode 100644
index 0000000000..57e9df4263
--- /dev/null
+++ b/server/internal/integrations/wecom/media_guard_test.go
@@ -0,0 +1,463 @@
+package wecom
+
+// media_guard_test.go — the fetcher must refuse to be pointed inward.
+//
+// The tests come in two shapes because the guard has two halves. The policy
+// is pure and is tested exhaustively by table: it is where a missed range
+// hides. The dialer is tested against real sockets, because the parts worth
+// doubting — that a redirect is re-checked, that an IPv4-mapped address is
+// unmapped first, that a hostname resolving to something internal is refused
+// at connect time rather than at parse time — are all properties of the
+// connection, not of the URL.
+//
+// The harness's own server is on loopback, which the production policy
+// refuses. So the tests that need a live server inject a policy that permits
+// loopback and nothing else extra; what they exercise is still the real
+// guard, with the one address the test itself occupies allowed.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "strings"
+ "testing"
+)
+
+// allowLoopbackPolicy is the production policy with loopback permitted, for
+// tests that host their own server. Everything else it refuses is refused
+// for the production reason.
+func allowLoopbackPolicy(a netip.Addr) bool {
+ if a.Unmap().IsLoopback() {
+ return true
+ }
+ return publicAddrOnly(a)
+}
+
+// testMediaClient is what every media test fetches through, so the whole
+// media suite runs against a real guard rather than a bare http.Client.
+func testMediaClient() *http.Client {
+ return newMediaHTTPClient(mediaGuard{allow: allowLoopbackPolicy})
+}
+
+// staticResolver answers every lookup with one address, so a test can make a
+// public-looking hostname resolve wherever it likes.
+type staticResolver struct{ addr netip.Addr }
+
+func (r staticResolver) LookupNetIP(context.Context, string, string) ([]netip.Addr, error) {
+ return []netip.Addr{r.addr}, nil
+}
+
+// ---- the policy ----
+
+func TestPublicAddrOnlyRefusesEverythingInward(t *testing.T) {
+ blocked := []string{
+ // loopback
+ "127.0.0.1", "127.0.0.53", "::1",
+ // the IPv4-mapped forms of the same — the predicate only sees these
+ // after Unmap, which is the trap this exists for
+ "::ffff:127.0.0.1", "::ffff:10.0.0.1", "::ffff:169.254.169.254",
+ // RFC 1918
+ "10.0.0.1", "172.16.0.1", "172.31.255.254", "192.168.1.1",
+ // link-local, and the cloud metadata address that lives in it
+ "169.254.169.254", "169.254.1.1", "fe80::1",
+ // RFC 6598 shared space — this machine's tailnet
+ "100.64.0.1", "100.100.100.100", "100.127.255.254",
+ // IPv6 unique local
+ "fc00::1", "fd12:3456::1",
+ // unspecified, multicast, broadcast
+ "0.0.0.0", "::", "224.0.0.1", "ff02::1", "255.255.255.255",
+ // IETF reserved, including the proxy fake-IP range on this machine
+ "192.0.0.1", "192.0.2.1", "198.18.0.18", "198.19.255.1",
+ "198.51.100.1", "203.0.113.1", "240.0.0.1",
+ "192.88.99.1", // deprecated 6to4 relay anycast
+ "2001:db8::1",
+ // Translation space. Each of these is an IPv4 address in an IPv6
+ // costume, and the IPv4 it carries is 169.254.169.254 or 127.0.0.1 —
+ // a guard that only recognises those written as IPv4 lets all of
+ // them straight through.
+ "64:ff9b::7f00:1", // NAT64 well-known → 127.0.0.1
+ "64:ff9b::a9fe:a9fe", // NAT64 well-known → 169.254.169.254
+ "64:ff9b:1::7f00:1", // NAT64 local-use (RFC 8215) → 127.0.0.1
+ "64:ff9b:1::a9fe:a9fe", // NAT64 local-use → 169.254.169.254
+ "64:ff9b:1:ffff::c0a8:1", // anywhere else in that /48
+ "2002:a9fe:a9fe::1", // 6to4 → 169.254.169.254 through a relay
+ "2002:7f00:1::1", // 6to4 → 127.0.0.1
+ // IETF protocol assignments, 2001::/23 end to end
+ "2001::1", // Teredo, which also carries an IPv4 endpoint
+ "2001:2::1", // benchmarking — the twin of 198.18.0.0/15
+ "2001:1::1", // PCP anycast
+ "2001:1ff::1", // the last address in the /23
+ "2001:20::1", // ORCHIDv2
+ // Discard-only, documentation, routing labels, deprecated site-local
+ "100::1", "100:0:0:1::1", "3fff::1", "5f00::1", "fec0::1",
+ }
+ for _, s := range blocked {
+ a := netip.MustParseAddr(s)
+ if publicAddrOnly(a) {
+ t.Errorf("publicAddrOnly(%s) allowed a non-public address", s)
+ }
+ }
+
+ allowed := []string{
+ "1.1.1.1", "8.8.8.8", "140.82.121.4", // public v4
+ "101.226.0.1", // a Tencent COS range — the real traffic
+ "2001:4860:4860::8888", // public v6
+ "2400:3200::1", // public v6
+ // The blocks above end where they say they end. 2001:200:: is one
+ // group past 2001::/23 and is ordinary APNIC unicast; 2001:db8:: is
+ // blocked by its own entry, not by the /23. 64:ff9c:: is one nibble
+ // past both NAT64 prefixes. A guard that swallowed these would refuse
+ // real attachments, which fails just as loudly as letting one through.
+ "2001:200::1",
+ "2003::1",
+ "64:ff9c::1",
+ "2402:4e00::1", // Tencent's v6 space
+ }
+ for _, s := range allowed {
+ a := netip.MustParseAddr(s)
+ if !publicAddrOnly(a) {
+ t.Errorf("publicAddrOnly(%s) refused a public address — real media would fail", s)
+ }
+ }
+}
+
+func TestPublicAddrOnlyRefusesAnInvalidAddress(t *testing.T) {
+ if publicAddrOnly(netip.Addr{}) {
+ t.Error("the zero address was allowed")
+ }
+}
+
+// ---- the dialer ----
+
+// The whole point: a URL naming an internal address never opens a socket.
+func TestTheGuardRefusesAnInternalAddressOutright(t *testing.T) {
+ client := newMediaHTTPClient(mediaGuard{}) // production policy
+ for _, target := range []string{
+ "http://127.0.0.1:9/",
+ "http://169.254.169.254/latest/meta-data/",
+ "http://10.0.0.1/",
+ "http://[::1]:9/",
+ "http://100.100.100.100/", // the tailnet resolver
+ "http://198.18.0.18/", // a fake-IP address
+ } {
+ _, err := downloadMedia(context.Background(), client, target)
+ if err == nil {
+ t.Errorf("%s was fetched", target)
+ continue
+ }
+ if !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Errorf("%s failed with %v, want the guard's refusal (a connection error means it tried)", target, err)
+ }
+ }
+}
+
+// TestTheGuardRefusesBothNAT64Prefixes: a NAT64 address is not a destination,
+// it is an IPv4 destination the translator will unwrap. 64:ff9b:1::a9fe:a9fe
+// arrives at 169.254.169.254 — the cloud metadata endpoint — on any deployment
+// that runs the RFC 8215 local-use prefix, which is the prefix an operator
+// picks when the well-known one is already in use. The guard knew the
+// well-known prefix and not that one, so the whole "we only dial public
+// addresses" promise came apart on a deployment that had done nothing wrong.
+//
+// Driven through the real dialer, not through publicAddrOnly. The distinction
+// is the same one TestAWideOpenAllowListStillCannotReachLoopback rests on: a
+// predicate that answers "no" while the transport connects anyway is a guard
+// that does not guard, and only a test that watches what the transport does
+// can tell those apart. Here that shows up in WHICH error comes back —
+// ErrMediaAddrBlocked means the address never left the policy, and anything
+// else (a connect timeout, "no route to host") means a socket was attempted
+// against an address that reaches inside.
+func TestTheGuardRefusesBothNAT64Prefixes(t *testing.T) {
+ client := newMediaHTTPClient(mediaGuard{}) // production policy
+
+ // Written as a literal, which is how it arrives in a signed URL.
+ for _, target := range []string{
+ "http://[64:ff9b::a9fe:a9fe]/latest/meta-data/", // well-known → 169.254.169.254
+ "http://[64:ff9b:1::a9fe:a9fe]/latest/meta-data/", // local-use → 169.254.169.254
+ "http://[64:ff9b:1::7f00:1]:9/", // local-use → 127.0.0.1
+ "http://[64:ff9b:1::a00:1]/", // local-use → 10.0.0.1
+ "http://[2002:a9fe:a9fe::1]/latest/meta-data/", // 6to4 → 169.254.169.254
+ } {
+ _, err := downloadMedia(context.Background(), client, target)
+ if err == nil {
+ t.Errorf("%s was fetched", target)
+ continue
+ }
+ if !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Errorf("%s failed with %v, want the guard's refusal (any other error means a socket was opened toward an address that reaches IPv4 private space through the translator)", target, err)
+ }
+ }
+
+ // And resolved from a hostname, which is how it arrives when the name is
+ // innocent and the answer is not.
+ for _, resolved := range []string{"64:ff9b:1::a9fe:a9fe", "64:ff9b:1::7f00:1", "2002:7f00:1::1"} {
+ c := newMediaHTTPClient(mediaGuard{
+ resolve: staticResolver{addr: netip.MustParseAddr(resolved)},
+ })
+ _, err := downloadMedia(context.Background(), c, "https://cos.example.com/object")
+ if !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Errorf("a host resolving to %s: err = %v, want the guard's refusal", resolved, err)
+ }
+ }
+}
+
+// And on the redirect hop, against a real socket: the first fetch is allowed
+// and answered, the Location header points into the local-use NAT64 prefix,
+// and the second hop has to be refused by the same policy the first passed.
+func TestARedirectIntoTheLocalUseNAT64PrefixIsRefused(t *testing.T) {
+ var reached bool
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/meta" {
+ reached = true
+ w.Write([]byte("secrets"))
+ return
+ }
+ http.Redirect(w, r, "http://[64:ff9b:1::a9fe:a9fe]/latest/meta-data/", http.StatusFound)
+ }))
+ defer srv.Close()
+
+ _, err := downloadMedia(context.Background(), testMediaClient(), srv.URL+"/object")
+ if err == nil {
+ t.Fatal("the redirect into NAT64 space was followed")
+ }
+ if !strings.Contains(err.Error(), ErrMediaAddrBlocked.Error()) {
+ t.Fatalf("err = %v, want the guard's refusal on the second hop", err)
+ }
+ if reached {
+ t.Error("the redirect target was actually fetched")
+ }
+}
+
+// A public hostname is not a promise about where it points. The check has to
+// happen against the resolved address at connect time, which is also what
+// makes a rebinding answer useless.
+func TestAPublicHostnameResolvingInwardIsRefused(t *testing.T) {
+ client := newMediaHTTPClient(mediaGuard{
+ resolve: staticResolver{addr: netip.MustParseAddr("169.254.169.254")},
+ })
+ _, err := downloadMedia(context.Background(), client, "https://cos.example.com/object")
+ if !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Fatalf("err = %v, want the guard's refusal", err)
+ }
+}
+
+// The redirect is the cheap attack: one Location header turns an allowed
+// fetch into an internal one, and a check on the original URL never sees it.
+func TestARedirectToAnInternalAddressIsRefused(t *testing.T) {
+ var reached bool
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/meta" {
+ reached = true
+ w.Write([]byte("secrets"))
+ return
+ }
+ http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
+ }))
+ defer srv.Close()
+
+ _, err := downloadMedia(context.Background(), testMediaClient(), srv.URL+"/object")
+ if err == nil {
+ t.Fatal("the redirect was followed")
+ }
+ if !strings.Contains(err.Error(), ErrMediaAddrBlocked.Error()) {
+ t.Fatalf("err = %v, want the guard's refusal on the second hop", err)
+ }
+ if reached {
+ t.Error("the redirect target was actually fetched")
+ }
+}
+
+// A redirect chain that stays public still has to terminate.
+func TestARedirectLoopIsCutOff(t *testing.T) {
+ var hops int
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hops++
+ http.Redirect(w, r, r.URL.String(), http.StatusFound)
+ }))
+ defer srv.Close()
+
+ _, err := downloadMedia(context.Background(), testMediaClient(), srv.URL+"/loop")
+ if err == nil {
+ t.Fatal("the loop was followed to completion")
+ }
+ if hops > 8 {
+ t.Errorf("followed %d hops before giving up", hops)
+ }
+}
+
+// A redirect out of HTTP entirely never reaches a dialer, so the scheme guard
+// is a separate half.
+func TestARedirectToANonHTTPSchemeIsRefused(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, "file:///etc/passwd", http.StatusFound)
+ }))
+ defer srv.Close()
+
+ _, err := downloadMedia(context.Background(), testMediaClient(), srv.URL+"/object")
+ if err == nil || !strings.Contains(err.Error(), "scheme") {
+ t.Fatalf("err = %v, want the scheme refusal", err)
+ }
+}
+
+// The guard must not have broken the thing it guards.
+func TestAnAllowedFetchStillWorks(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Disposition", `attachment; filename="report.pdf"`)
+ w.Write([]byte("the bytes"))
+ }))
+ defer srv.Close()
+
+ got, err := downloadMedia(context.Background(), testMediaClient(), srv.URL+"/object")
+ if err != nil {
+ t.Fatalf("a permitted fetch failed: %v", err)
+ }
+ if string(got.Body) != "the bytes" {
+ t.Errorf("body = %q", got.Body)
+ }
+ if got.Filename != "report.pdf" {
+ t.Errorf("filename = %q", got.Filename)
+ }
+}
+
+// A host with one internal and one public answer must be reached on the
+// public one rather than refused wholesale or allowed wholesale.
+func TestAMixedAnswerDialsOnlyThePermittedAddress(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("ok"))
+ }))
+ defer srv.Close()
+ _, port, _ := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://"))
+
+ var refused []netip.Addr
+ g := mediaGuard{
+ allow: allowLoopbackPolicy,
+ resolve: multiResolver{addrs: []netip.Addr{
+ netip.MustParseAddr("10.1.2.3"), // refused
+ netip.MustParseAddr("127.0.0.1"), // permitted by the test policy
+ }},
+ onRefuse: func(_ string, a netip.Addr) { refused = append(refused, a) },
+ }
+ got, err := downloadMedia(context.Background(), newMediaHTTPClient(g),
+ fmt.Sprintf("http://cos.example.com:%s/object", port))
+ if err != nil {
+ t.Fatalf("the public answer was not used: %v", err)
+ }
+ if string(got.Body) != "ok" {
+ t.Errorf("body = %q", got.Body)
+ }
+ if len(refused) != 1 || refused[0].String() != "10.1.2.3" {
+ t.Errorf("refused = %v, want exactly the internal answer", refused)
+ }
+}
+
+type multiResolver struct{ addrs []netip.Addr }
+
+func (r multiResolver) LookupNetIP(context.Context, string, string) ([]netip.Addr, error) {
+ return r.addrs, nil
+}
+
+// A nil client used to fall through to http.DefaultClient, which is the
+// unguarded fetch this whole file exists to prevent.
+func TestANilClientRefusesRatherThanFallingBackToTheDefault(t *testing.T) {
+ _, err := downloadMedia(context.Background(), nil, "https://cos.example.com/object")
+ if err == nil || !strings.Contains(err.Error(), "guarded http client") {
+ t.Fatalf("err = %v, want a refusal naming the missing guarded client", err)
+ }
+}
+
+// The proxy environment must not become a way around the dial guard.
+func TestTheMediaClientIgnoresProxyEnvironment(t *testing.T) {
+ tr, ok := newMediaHTTPClient(mediaGuard{}).Transport.(*http.Transport)
+ if !ok {
+ t.Fatal("the media client's transport is not an *http.Transport")
+ }
+ if tr.Proxy != nil {
+ t.Error("the media transport honours a proxy; a proxied fetch never reaches the dial guard")
+ }
+ // Not "DialContext is non-nil" — Transport.Clone() carries the default
+ // dialer over, so that assertion passes on a transport with no guard at
+ // all. Drive the installed dialer instead and require it to refuse.
+ if tr.DialContext == nil {
+ t.Fatal("the media transport has no dialer at all")
+ }
+ if _, err := tr.DialContext(context.Background(), "tcp", "169.254.169.254:80"); !errors.Is(err, ErrMediaAddrBlocked) {
+ t.Errorf("the installed dialer answered %v for the metadata address, want the guard's refusal", err)
+ }
+}
+
+// A transport failure must not write the pre-signed link into the error.
+//
+// The COS URL is a five-minute bearer credential for someone's private
+// attachment: whoever holds the string can GET the file with no credential of
+// their own. net/http wraps every failure in a *url.Error that prints the URL,
+// and these errors go straight to r.logger.Warn — so a DNS hiccup, a reset or
+// a timeout used to put a live link in the application log, and from there
+// into whatever ships those logs onward.
+func TestATransportFailureNeverCarriesTheSignedURL(t *testing.T) {
+ const secret = "sig=AKIDSUPERSECRETSIGNATURE&t=1"
+
+ // A server that accepts the connection and drops it mid-response, so the
+ // failure is a genuine transport error rather than a status code.
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hj, ok := w.(http.Hijacker)
+ if !ok {
+ t.Errorf("test server cannot hijack")
+ return
+ }
+ conn, _, err := hj.Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ conn.Close() // no status line at all
+ }))
+ defer srv.Close()
+
+ target := srv.URL + "/object?" + secret
+
+ t.Run("buffered", func(t *testing.T) {
+ _, err := downloadMedia(context.Background(), testMediaClient(), target)
+ if err == nil {
+ t.Fatal("download succeeded, want a transport failure")
+ }
+ assertNoSignedURL(t, err, secret, srv.URL)
+ })
+
+ t.Run("streaming", func(t *testing.T) {
+ _, _, err := openMedia(context.Background(), testMediaClient(), target)
+ if err == nil {
+ t.Fatal("open succeeded, want a transport failure")
+ }
+ assertNoSignedURL(t, err, secret, srv.URL)
+ })
+}
+
+// A URL too malformed to parse is still a URL somebody signed.
+func TestAnUnparseableURLIsNotEchoedBack(t *testing.T) {
+ err := checkMediaURL("https://cos.example.com/o\x7f?sig=AKIDSECRET")
+ if err == nil {
+ t.Fatal("checkMediaURL accepted a control character, want a refusal")
+ }
+ if strings.Contains(err.Error(), "AKIDSECRET") {
+ t.Fatalf("the refusal quoted the link back: %v", err)
+ }
+}
+
+func assertNoSignedURL(t *testing.T, err error, secret, host string) {
+ t.Helper()
+ msg := err.Error()
+ if strings.Contains(msg, secret) {
+ t.Fatalf("the error carries the signature: %v", err)
+ }
+ if strings.Contains(msg, host) {
+ t.Fatalf("the error carries the link: %v", err)
+ }
+ // It still has to say what went wrong.
+ if !strings.Contains(msg, "wecom: media") {
+ t.Fatalf("the error lost its diagnosis: %v", err)
+ }
+}
diff --git a/server/internal/integrations/wecom/media_ingest.go b/server/internal/integrations/wecom/media_ingest.go
new file mode 100644
index 0000000000..3e2ca4803c
--- /dev/null
+++ b/server/internal/integrations/wecom/media_ingest.go
@@ -0,0 +1,480 @@
+package wecom
+
+// media_ingest.go — the engine.MediaResolver for WeCom.
+//
+// The shape is the one lark/media_ingest.go established and the Router
+// depends on: HasMedia is a pure in-memory look at the payload we already
+// have, ResolveMedia runs detached from the connector ACK path, every upload
+// is covered by an intent-ledger row written BEFORE the PUT, and nothing is
+// ever deleted inline — a failure anywhere leaves the row for the reconciler
+// and leaves the message's placeholder text intact.
+//
+// What is wecom-specific is the middle: WeCom hands over a pre-signed COS url
+// and a per-url key instead of a resource id to be fetched with a tenant
+// token, so there is no API client and no credential here — just an HTTP GET
+// and a decrypt (media_download.go, media_crypt.go). The callback body says
+// nothing about the file besides those two strings, so the name comes out of
+// the download's Content-Disposition and the type is worked out from the name
+// or sniffed from the decrypted bytes.
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "mime"
+ "net/http"
+ "path"
+ "slices"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// mediaFailureNotice lines. WeCom deployments are China-only, so these follow
+// the Chinese product voice the rest of this adapter already writes in
+// (wecom_channel.go's receipt, router.go's session titles).
+const (
+ mediaUnreadableNotice = "抱歉,有附件没能收到,麻烦重新发一次。"
+ mediaTooLargeNotice = "抱歉,附件太大了,我这边收不下。"
+)
+
+// mediaStorage is the slice of storage.Storage this resolver drives.
+// ObjectURL is a pure function of configuration, which is what lets the
+// intent ledger persist the object's URL before the object exists.
+type mediaStorage interface {
+ Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error)
+ ObjectURL(key string) string
+}
+
+// mediaStreamStorage is the streaming half, which both production backends
+// implement (storage.S3Storage, storage.LocalStorage). A backend without it
+// falls back to the buffered path — correct, just not memory-flat.
+type mediaStreamStorage interface {
+ UploadStream(ctx context.Context, key string, data io.Reader, sizeBytes int64, contentType string, filename string) (string, error)
+}
+
+type wecomMediaResolver struct {
+ storage mediaStorage
+ ledger engine.MediaIntentLedger
+ http *http.Client
+ // notify reaches the live aibot socket for the installation, to tell the
+ // sender an attachment did not make it. nil disables the notice and
+ // leaves only the log.
+ notify *sendersRegistry
+ logger *slog.Logger
+}
+
+// NewMediaResolver builds the wecom MediaResolver. storage and ledger are
+// required — without either there is nothing durable to point an attachment
+// at, and the resolver degrades to leaving the placeholder in place. senders
+// is optional: without it a failed attachment is only logged.
+func NewMediaResolver(storage mediaStorage, ledger engine.MediaIntentLedger, senders *sendersRegistry, logger *slog.Logger) engine.MediaResolver {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &wecomMediaResolver{
+ storage: storage,
+ ledger: ledger,
+ // Never a bare http.Client: the URL being fetched came off the wire,
+ // and this client refuses to connect to anything that is not public
+ // internet (media_guard.go).
+ http: newMediaHTTPClient(mediaGuard{}),
+ notify: senders,
+ logger: logger,
+ }
+}
+
+// HasMedia reports whether this callback carried anything to download. It
+// runs synchronously on the connector ACK path and decides whether the
+// message pays for a media deadline, a deferred run and a semaphore slot at
+// all, so it stays a decode of bytes already in hand.
+func (r *wecomMediaResolver) HasMedia(msg channel.InboundMessage) bool {
+ wm, err := wecomMsgFromRaw(msg)
+ if err != nil {
+ return false
+ }
+ return len(wm.Media) > 0
+}
+
+// ResolveMedia downloads, decrypts and stores every attachment on the
+// message, returning it with a MediaRef per object that landed. Attachments
+// are independent: one that fails does not stop the rest, and the sender is
+// told once at the end about whatever did not arrive.
+func (r *wecomMediaResolver) ResolveMedia(ctx context.Context, inst engine.ResolvedInstallation, _ engine.ResolvedIdentity, _ pgtype.UUID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage {
+ wm, err := wecomMsgFromRaw(msg)
+ if err != nil {
+ r.logger.Warn("wecom media ingest skipped: raw decode failed", "message_id", msg.MessageID, "err", err)
+ return msg
+ }
+ if len(wm.Media) == 0 {
+ return msg
+ }
+ if r.storage == nil || r.ledger == nil {
+ r.logger.Warn("wecom media ingest skipped: no storage configured",
+ "msg_id", wm.MsgID, "attachments", len(wm.Media))
+ return msg
+ }
+
+ var failures []mediaFailure
+ for i, m := range wm.Media {
+ ref, err := r.ingestOne(ctx, inst, chatMessageID, wm, i, m)
+ if err != nil {
+ failure := classifyMediaFailure(err)
+ failures = appendFailure(failures, failure)
+ // A refused address gets its own line because the operator's next
+ // move is different from every other failure here: the attachment
+ // is fine and the deployment declined to dial where its host
+ // resolved, so the fix is configuration, not a retry. Saying only
+ // "ingest failed" for this sends them looking at WeCom.
+ logLine := "wecom media ingest failed"
+ if failure == mediaFailureBlocked {
+ logLine = "wecom media ingest refused by the media address guard: the host resolved to a non-public address and was not dialed. If this deployment sits behind a fake-IP proxy, declare its range in MULTICA_WECOM_MEDIA_ALLOW_CIDRS; otherwise this is a URL that should not have been sent."
+ }
+ // The url and the key never reach the log: one is a signed
+ // address anyone could then fetch, the other unlocks it. stripURL
+ // has already taken the url out of err, and the guard's refusal
+ // carries no address of its own, so err is safe to log whole.
+ r.logger.Warn(logLine,
+ "installation_id", util.UUIDToString(inst.ID),
+ "msg_id", wm.MsgID,
+ "attachment", i,
+ "kind", string(m.Kind),
+ "err", err)
+ continue
+ }
+ msg.MediaRefs = append(msg.MediaRefs, ref)
+ }
+
+ r.tellTheSender(inst, wm, failures)
+ return msg
+}
+
+// ingestOne carries a single attachment from url to MediaRef. The ledger row
+// goes first: from that point on every failure — download, decrypt, upload,
+// a crash — leaves an intent the reconciler settles, and nothing here deletes
+// anything.
+func (r *wecomMediaResolver) ingestOne(ctx context.Context, inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, wm InboundMessage, index int, m InboundMedia) (channel.MediaRef, error) {
+ key := mediaObjectKey(inst, chatMessageID, wm.MsgID, index, m.Kind)
+ link := r.storage.ObjectURL(key)
+
+ ok, err := r.ledger.RecordPendingMediaObject(ctx, engine.RecordPendingMediaObjectParams{
+ StorageKey: key,
+ WorkspaceID: inst.WorkspaceID,
+ ChatMessageID: chatMessageID,
+ StorageURL: link,
+ InstallationID: inst.ID,
+ })
+ if err != nil {
+ // No durable intent, no upload — the fail-safe direction.
+ return channel.MediaRef{}, fmt.Errorf("record media intent: %w", err)
+ }
+ if !ok {
+ // The reconciler owns this key; never resurrect it.
+ return channel.MediaRef{}, fmt.Errorf("media key %s is owned by the reconciler", key)
+ }
+
+ streamer, canStream := r.storage.(mediaStreamStorage)
+ if canStream {
+ // The memory-flat path: ciphertext streams from the socket into the
+ // decrypt, the plaintext lands in an unlinked temp file, and the
+ // upload reads from there. Nothing holds a whole attachment.
+ ref, err := r.ingestStreaming(ctx, streamer, wm, index, m, key, link)
+ if err == nil || !errors.Is(err, errStreamingUnavailable) {
+ return ref, err
+ }
+ // Fall through: the backend said it could stream and then could not.
+ }
+
+ got, err := downloadMedia(ctx, r.http, m.URL)
+ if err != nil {
+ return channel.MediaRef{}, err
+ }
+ traceMediaHeaders(r.logger, wm.MsgID, index, got.mediaHeaders)
+ plain, err := decryptMedia(m.AESKey, got.Body)
+ if err != nil {
+ return channel.MediaRef{}, err
+ }
+
+ filename, contentType := describeMedia(wm, index, m, got.Filename, plain)
+ if _, err := r.storage.Upload(ctx, key, plain, contentType, filename); err != nil {
+ // The store may still be processing the PUT; deleting here could
+ // reorder with it. The intent row covers the object either way.
+ return channel.MediaRef{}, fmt.Errorf("upload media: %w", err)
+ }
+ return channel.MediaRef{
+ Type: m.Kind,
+ StorageKey: key,
+ StorageURL: link,
+ Filename: filename,
+ MimeType: contentType,
+ SizeBytes: int64(len(plain)),
+ }, nil
+}
+
+// mediaObjectKey names the object. It is derived from the CHAT message rather
+// than the WeCom message for the reason lark documents: one platform message
+// can be ingested twice (the inbound dedup claim is reclaimable once stale),
+// and a shared key would run the second ingest into the first one's ledger
+// row — possibly a tombstone the intent upsert refuses, silently dropping the
+// media. The attachment's position in the message is part of the key too,
+// since a 图文混排 can carry several and the url is not stable enough to key on.
+func mediaObjectKey(inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, msgID string, index int, kind channel.MsgType) string {
+ sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%s\x00%d",
+ util.UUIDToString(chatMessageID), msgID, string(kind), index)))
+ return path.Join(
+ "workspaces",
+ util.UUIDToString(inst.WorkspaceID),
+ "wecom",
+ util.UUIDToString(inst.ID),
+ hex.EncodeToString(sum[:]),
+ )
+}
+
+// describeMedia works out what to call the file and what to say it is. The
+// callback body carries neither, so the name comes from the download's
+// Content-Disposition and the type from the name's extension, falling back to
+// sniffing the decrypted bytes — the extension is the better signal for the
+// formats that are really zip containers (.docx, .xlsx), sniffing is the
+// better one when there is no name at all.
+func describeMedia(wm InboundMessage, index int, m InboundMedia, headerName string, plain []byte) (filename, contentType string) {
+ filename = cleanMediaFilename(headerName)
+ if ext := path.Ext(filename); ext != "" {
+ contentType = mime.TypeByExtension(ext)
+ }
+ if contentType == "" {
+ contentType = http.DetectContentType(plain)
+ }
+ if contentType == "" {
+ contentType = "application/octet-stream"
+ }
+ if filename == "" {
+ filename = fallbackMediaName(wm.MsgID, index, m.Kind, contentType)
+ }
+ return filename, contentType
+}
+
+// fallbackMediaName builds a name for an attachment the server did not name.
+// It has to be unique within the message, so the attachment's position is in
+// it — two photos in one 图文混排 otherwise land as one name twice.
+func fallbackMediaName(msgID string, index int, kind channel.MsgType, contentType string) string {
+ prefix := "wecom-file"
+ switch kind {
+ case channel.MsgTypeImage:
+ prefix = "wecom-image"
+ case channel.MsgTypeVideo:
+ prefix = "wecom-video"
+ }
+ return fmt.Sprintf("%s-%s-%d%s", prefix, safeMediaSegment(msgID), index, mediaExtension(contentType))
+}
+
+// mediaExtension picks a file extension for a content type, preferring the
+// familiar spelling over whatever the mime database happens to list first
+// (image/jpeg resolves to ".jfif" on some systems).
+func mediaExtension(contentType string) string {
+ if semi := strings.IndexByte(contentType, ';'); semi >= 0 {
+ contentType = strings.TrimSpace(contentType[:semi])
+ }
+ switch contentType {
+ case "image/jpeg":
+ return ".jpg"
+ case "image/png":
+ return ".png"
+ case "image/gif":
+ return ".gif"
+ case "image/webp":
+ return ".webp"
+ case "video/mp4":
+ return ".mp4"
+ case "application/pdf":
+ return ".pdf"
+ }
+ if exts, err := mime.ExtensionsByType(contentType); err == nil && len(exts) > 0 {
+ return exts[0]
+ }
+ return ""
+}
+
+// safeMediaSegment reduces an id to characters that are safe in a filename.
+func safeMediaSegment(s string) string {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return "unknown"
+ }
+ var b strings.Builder
+ for _, r := range s {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
+ b.WriteRune(r)
+ default:
+ b.WriteByte('_')
+ }
+ }
+ out := strings.Trim(b.String(), "_")
+ if out == "" {
+ return "unknown"
+ }
+ return out
+}
+
+// ---- telling the sender ----
+
+// mediaFailure is the kind of bad news, not the error itself: the sender gets
+// told what to do differently, and "too big" and "did not arrive" have
+// different answers.
+type mediaFailure int
+
+const (
+ mediaFailureUnreadable mediaFailure = iota
+ mediaFailureTooLarge
+ // mediaFailureBlocked is the guard refusing the address the media host
+ // resolved to. It is separated from mediaFailureUnreadable for the
+ // OPERATOR, not the sender: nothing is wrong with the attachment, and no
+ // number of retries will help until the deployment's own configuration
+ // changes. See the log branch in ResolveMedia.
+ mediaFailureBlocked
+)
+
+func classifyMediaFailure(err error) mediaFailure {
+ if errors.Is(err, errMediaTooLarge) {
+ return mediaFailureTooLarge
+ }
+ if errors.Is(err, ErrMediaAddrBlocked) {
+ return mediaFailureBlocked
+ }
+ return mediaFailureUnreadable
+}
+
+// appendFailure keeps one entry per kind. A message with four attachments
+// that all expired is one thing that went wrong, and saying it four times
+// helps nobody.
+func appendFailure(list []mediaFailure, f mediaFailure) []mediaFailure {
+ for _, existing := range list {
+ if existing == f {
+ return list
+ }
+ }
+ return append(list, f)
+}
+
+// tellTheSender writes one short notice into the chat the attachments came
+// from, over the same live aibot socket every other wecom message uses.
+//
+// Without it the failure is invisible in the worst way: the stored body still
+// says [Image], so the agent answers as if it had been shown a picture it
+// never received. The agent run itself is deliberately left to proceed — the
+// person can see for themselves that the picture did not get through, and the
+// answer to whatever they typed beside it is still worth having.
+func (r *wecomMediaResolver) tellTheSender(inst engine.ResolvedInstallation, wm InboundMessage, failures []mediaFailure) {
+ if len(failures) == 0 || r.notify == nil || !inst.ID.Valid {
+ return
+ }
+ chatID := wm.ChatID
+ if chatID == "" {
+ chatID = wm.SenderUserID
+ }
+ if chatID == "" {
+ return
+ }
+ sender := r.notify.get(inst.ID)
+ if sender == nil {
+ // Mid-reconnect: the socket this installation writes over does not
+ // exist right now. The log below is the whole record.
+ r.logger.Warn("wecom media failure notice not delivered: no live connection",
+ "installation_id", util.UUIDToString(inst.ID), "msg_id", wm.MsgID)
+ return
+ }
+ chatType := chatTypeSingleInt
+ if strings.EqualFold(wm.ChatType, "group") {
+ chatType = chatTypeGroupInt
+ }
+ lines := make([]string, 0, len(failures))
+ for _, f := range failures {
+ notice := mediaUnreadableNotice
+ if f == mediaFailureTooLarge {
+ notice = mediaTooLargeNotice
+ }
+ // mediaFailureBlocked lands on the unreadable wording deliberately.
+ // From the sender's side a refused address and a download that fell
+ // over are the same event — the attachment did not arrive — and the
+ // thing that separates them is what the operator must change, which
+ // belongs in the log. Neither the resolved address nor the signed url
+ // goes into a chat message.
+ //
+ // Two kinds sharing one wording is why the dedupe moved here from
+ // appendFailure: a message with one blocked and one unreadable
+ // attachment is still one piece of news.
+ if !slices.Contains(lines, notice) {
+ lines = append(lines, notice)
+ }
+ }
+ if err := sender.sendText(chatID, chatType, strings.Join(lines, "\n")); err != nil {
+ r.logger.Warn("wecom media failure notice not delivered",
+ "installation_id", util.UUIDToString(inst.ID), "msg_id", wm.MsgID, "err", err)
+ }
+}
+
+// errStreamingUnavailable says the memory-flat path could not be taken for a
+// reason that is not the attachment's fault — no temp space, a backend that
+// advertises UploadStream and rejects it. The caller falls back to the
+// buffered path rather than failing an attachment over an optimisation.
+var errStreamingUnavailable = errors.New("wecom: streaming media ingest unavailable")
+
+// ingestStreaming carries one attachment without ever holding it whole:
+// ciphertext streams from the response body into the decrypt, the plaintext
+// lands in an unlinked temp file, and the upload reads from that file with
+// the exact length it now knows.
+func (r *wecomMediaResolver) ingestStreaming(
+ ctx context.Context,
+ streamer mediaStreamStorage,
+ wm InboundMessage,
+ index int,
+ m InboundMedia,
+ key, link string,
+) (channel.MediaRef, error) {
+ body, headers, err := openMedia(ctx, r.http, m.URL)
+ if err != nil {
+ return channel.MediaRef{}, err
+ }
+ defer body.Close()
+ traceMediaHeaders(r.logger, wm.MsgID, index, headers)
+
+ plain, size, err := decryptToFile(m.AESKey, body, "")
+ if err != nil {
+ // A decrypt failure is the attachment's problem and must be reported
+ // as one; only a failure to make the temp file is grounds to fall
+ // back, and decryptToFile says so in its message.
+ if strings.Contains(err.Error(), "media temp file") {
+ return channel.MediaRef{}, fmt.Errorf("%w: %v", errStreamingUnavailable, err)
+ }
+ return channel.MediaRef{}, err
+ }
+ defer plain.Close()
+
+ // The type is sniffed from the head of the file rather than from the
+ // whole thing — http.DetectContentType only ever reads 512 bytes.
+ head, err := peekFile(plain, 512)
+ if err != nil {
+ return channel.MediaRef{}, fmt.Errorf("wecom: media sniff: %w", err)
+ }
+ filename, contentType := describeMedia(wm, index, m, headers.Filename, head)
+
+ if _, err := streamer.UploadStream(ctx, key, plain, size, contentType, filename); err != nil {
+ return channel.MediaRef{}, fmt.Errorf("upload media: %w", err)
+ }
+ return channel.MediaRef{
+ Type: m.Kind,
+ StorageKey: key,
+ StorageURL: link,
+ Filename: filename,
+ MimeType: contentType,
+ SizeBytes: size,
+ }, nil
+}
diff --git a/server/internal/integrations/wecom/media_ingest_test.go b/server/internal/integrations/wecom/media_ingest_test.go
new file mode 100644
index 0000000000..b21f22914e
--- /dev/null
+++ b/server/internal/integrations/wecom/media_ingest_test.go
@@ -0,0 +1,710 @@
+package wecom
+
+// media_ingest_test.go — the resolver, driven against a real HTTP server
+// serving really-encrypted bytes. Nothing here stubs the download or the
+// decrypt: the test server encrypts a known payload with the same algorithm
+// WeCom uses, and the assertion is that exactly those bytes reach storage.
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// ---- fakes for the two durable seams ----
+
+type storedObject struct {
+ key string
+ data []byte
+ contentType string
+ filename string
+}
+
+type fakeMediaStorage struct {
+ mu sync.Mutex
+ uploads []storedObject
+ err error
+}
+
+func (s *fakeMediaStorage) Upload(_ context.Context, key string, data []byte, contentType, filename string) (string, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.err != nil {
+ return "", s.err
+ }
+ s.uploads = append(s.uploads, storedObject{key: key, data: append([]byte{}, data...), contentType: contentType, filename: filename})
+ return s.ObjectURL(key), nil
+}
+
+func (s *fakeMediaStorage) ObjectURL(key string) string { return "https://objects.invalid/" + key }
+
+func (s *fakeMediaStorage) stored() []storedObject {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return append([]storedObject{}, s.uploads...)
+}
+
+// fakeStreamStorage is fakeMediaStorage plus UploadStream, so the memory-flat
+// path is exercised by the same assertions as the buffered one.
+type fakeStreamStorage struct{ fakeMediaStorage }
+
+func (s *fakeStreamStorage) UploadStream(_ context.Context, key string, data io.Reader, sizeBytes int64, contentType, filename string) (string, error) {
+ body, err := io.ReadAll(data)
+ if err != nil {
+ return "", err
+ }
+ if int64(len(body)) != sizeBytes {
+ return "", io.ErrUnexpectedEOF
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.uploads = append(s.uploads, storedObject{key: key, data: body, contentType: contentType, filename: filename})
+ return s.ObjectURL(key), nil
+}
+
+type fakeMediaLedger struct {
+ mu sync.Mutex
+ records []engine.RecordPendingMediaObjectParams
+ ok bool
+ err error
+ // seenUploads snapshots how many objects were already in storage when
+ // each intent row was written, so the ordering can be asserted.
+ seenUploads []int
+ storage *fakeMediaStorage
+}
+
+func newFakeMediaLedger(storage *fakeMediaStorage) *fakeMediaLedger {
+ return &fakeMediaLedger{ok: true, storage: storage}
+}
+
+func (l *fakeMediaLedger) RecordPendingMediaObject(_ context.Context, p engine.RecordPendingMediaObjectParams) (bool, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.records = append(l.records, p)
+ if l.storage != nil {
+ l.seenUploads = append(l.seenUploads, len(l.storage.stored()))
+ }
+ return l.ok, l.err
+}
+
+// notifierWithLiveSocket is the production notifier — a real sendersRegistry
+// — holding a wsSender over a recording connection, so a failure notice is
+// asserted as the aibot frame it actually is.
+func notifierWithLiveSocket(id pgtype.UUID) (*sendersRegistry, *recordingConn) {
+ conn := &recordingConn{}
+ reg := newSendersRegistry()
+ reg.set(id, newWSSender(conn, slog.Default()))
+ return reg, conn
+}
+
+func testLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}
+
+func uuidOf(n byte) pgtype.UUID {
+ var u pgtype.UUID
+ u.Valid = true
+ u.Bytes[15] = n
+ return u
+}
+
+// ---- harness ----
+
+// cosServer stands in for the Tencent COS address a callback points at: it
+// serves one encrypted payload, with whatever Content-Disposition the test
+// wants.
+func cosServer(t *testing.T, plaintext []byte, disposition string) *httptest.Server {
+ t.Helper()
+ ciphertext := encryptLikeWecom(t, testAESKey, plaintext)
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ if disposition != "" {
+ w.Header().Set("Content-Disposition", disposition)
+ }
+ w.Header().Set("Content-Type", "application/octet-stream")
+ _, _ = w.Write(ciphertext)
+ }))
+}
+
+// mediaMessage builds the envelope the Router hands the resolver, going
+// through the real frame decoder so the test cannot drift from the wire.
+func mediaMessage(t *testing.T, msgType string, body map[string]any) channel.InboundMessage {
+ t.Helper()
+ full := map[string]any{
+ "msgid": "MSGID-MEDIA",
+ "aibotid": "wb-1",
+ "chattype": "single",
+ "chatid": "T-alex",
+ "from": map[string]any{"userid": "T-alex"},
+ "msgtype": msgType,
+ }
+ for k, v := range body {
+ full[k] = v
+ }
+ raw, err := json.Marshal(full)
+ if err != nil {
+ t.Fatalf("marshal callback: %v", err)
+ }
+ var mc aibotMsgCallback
+ if err := json.Unmarshal(raw, &mc); err != nil {
+ t.Fatalf("decode callback: %v", err)
+ }
+ text, ok := mc.ownText()
+ if !ok {
+ t.Fatalf("callback of type %q is not routable; the fixture is wrong", msgType)
+ }
+ return channelMessageFromCallback("wb-1", "", mc, text, "req-1")
+}
+
+func mediaInstallation() engine.ResolvedInstallation {
+ return engine.ResolvedInstallation{
+ ID: uuidOf(1),
+ WorkspaceID: uuidOf(2),
+ AgentID: uuidOf(3),
+ Active: true,
+ Platform: Installation{ID: uuidOf(1), BotID: "wb-1"},
+ }
+}
+
+// ---- HasMedia ----
+
+func TestHasMediaLooksOnlyAtWhatIsAlreadyInHand(t *testing.T) {
+ t.Parallel()
+ r := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, testLogger())
+ cases := []struct {
+ name string
+ msgType string
+ body map[string]any
+ want bool
+ }{
+ {"text", "text", map[string]any{"text": map[string]any{"content": "hi"}}, false},
+ {"image", "image", map[string]any{"image": map[string]any{"url": "https://cos.invalid/a", "aeskey": testAESKey}}, true},
+ {"file", "file", map[string]any{"file": map[string]any{"url": "https://cos.invalid/b", "aeskey": testAESKey}}, true},
+ {"video", "video", map[string]any{"video": map[string]any{"url": "https://cos.invalid/c", "aeskey": testAESKey}}, true},
+ {"mixed with a picture", "mixed", map[string]any{"mixed": map[string]any{"msg_item": []any{
+ map[string]any{"msgtype": "text", "text": map[string]any{"content": "look"}},
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": "https://cos.invalid/d", "aeskey": testAESKey}},
+ }}}, true},
+ {"mixed, text only", "mixed", map[string]any{"mixed": map[string]any{"msg_item": []any{
+ map[string]any{"msgtype": "text", "text": map[string]any{"content": "look"}},
+ }}}, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := r.HasMedia(mediaMessage(t, tc.msgType, tc.body)); got != tc.want {
+ t.Fatalf("HasMedia = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestHasMediaSaysNoWhenThereIsNoUrlToFetch(t *testing.T) {
+ t.Parallel()
+ r := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, testLogger())
+ // A body with an aeskey and no url is not something we can download; it
+ // must not buy the message a media deadline and a deferred agent run.
+ mc := aibotMsgCallback{MsgType: "image"}
+ mc.Image = mediaBody{AESKey: testAESKey}
+ msg := channelMessageFromCallback("wb-1", "", mc, "[Image]", "req-1")
+ if r.HasMedia(msg) {
+ t.Fatal("HasMedia said yes to a body with no url")
+ }
+}
+
+// ---- the whole ingest ----
+
+// newTestResolver builds the production resolver with the guarded client
+// swapped for one that also permits loopback, so the httptest server the test
+// runs is reachable while the guard's own decision stays under test in
+// media_guard_test.go.
+func newTestResolver(storage mediaStorage, ledger engine.MediaIntentLedger, senders *sendersRegistry) *wecomMediaResolver {
+ r := NewMediaResolver(storage, ledger, senders, testLogger()).(*wecomMediaResolver)
+ r.http = testMediaClient()
+ return r
+}
+
+// TestResolveMediaStoresTheDecryptedFile is the load-bearing one: real HTTP,
+// real AES, and the bytes in storage are the bytes the user sent. Run over
+// both storage backends, because the streaming one takes a different path
+// through decryptToFile.
+func TestResolveMediaStoresTheDecryptedFile(t *testing.T) {
+ t.Parallel()
+ plaintext := []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("pixels", 500))
+ srv := cosServer(t, plaintext, `attachment; filename*=UTF-8''%E5%AD%A3%E6%8A%A5.png`)
+ defer srv.Close()
+
+ backends := map[string]func() (mediaStorage, *fakeMediaStorage){
+ "buffered": func() (mediaStorage, *fakeMediaStorage) {
+ s := &fakeMediaStorage{}
+ return s, s
+ },
+ "streaming": func() (mediaStorage, *fakeMediaStorage) {
+ s := &fakeStreamStorage{}
+ return s, &s.fakeMediaStorage
+ },
+ }
+ for name, build := range backends {
+ t.Run(name, func(t *testing.T) {
+ storage, inspect := build()
+ r := newTestResolver(storage, newFakeMediaLedger(inspect), nil)
+
+ msg := mediaMessage(t, "image", map[string]any{
+ "image": map[string]any{"url": srv.URL, "aeskey": testAESKey},
+ })
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("MediaRefs = %d, want 1", len(got.MediaRefs))
+ }
+ uploads := inspect.stored()
+ if len(uploads) != 1 {
+ t.Fatalf("uploads = %d, want 1", len(uploads))
+ }
+ if string(uploads[0].data) != string(plaintext) {
+ t.Fatalf("stored %d bytes, want the %d decrypted bytes the user sent", len(uploads[0].data), len(plaintext))
+ }
+ ref := got.MediaRefs[0]
+ if ref.Type != channel.MsgTypeImage {
+ t.Errorf("ref type = %v, want image", ref.Type)
+ }
+ if ref.Filename != "季报.png" {
+ t.Errorf("filename = %q, want the Content-Disposition name", ref.Filename)
+ }
+ if ref.MimeType != "image/png" {
+ t.Errorf("mime = %q, want image/png from the .png extension", ref.MimeType)
+ }
+ if ref.SizeBytes != int64(len(plaintext)) {
+ t.Errorf("size = %d, want the decrypted length %d", ref.SizeBytes, len(plaintext))
+ }
+ if ref.StorageKey != uploads[0].key || ref.StorageURL != inspect.ObjectURL(ref.StorageKey) {
+ t.Errorf("ref does not point at what was uploaded: %+v", ref)
+ }
+ if !strings.Contains(ref.StorageKey, "wecom") {
+ t.Errorf("storage key %q does not name the channel", ref.StorageKey)
+ }
+ })
+ }
+}
+
+// TestResolveMediaRecordsIntentBeforeUploading pins the ordering the whole
+// no-inline-delete design rests on: nothing is written to the object store
+// until a ledger row exists to cover it. Same invariant lark states at
+// lark/media_ingest.go's RecordPendingMediaObject call.
+func TestResolveMediaRecordsIntentBeforeUploading(t *testing.T) {
+ t.Parallel()
+ srv := cosServer(t, []byte("payload"), "")
+ defer srv.Close()
+
+ storage := &fakeMediaStorage{}
+ ledger := newFakeMediaLedger(storage)
+ r := newTestResolver(storage, ledger, nil)
+
+ msg := mediaMessage(t, "file", map[string]any{
+ "file": map[string]any{"url": srv.URL, "aeskey": testAESKey},
+ })
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+
+ if len(ledger.records) != 1 {
+ t.Fatalf("intent rows = %d, want 1", len(ledger.records))
+ }
+ if ledger.seenUploads[0] != 0 {
+ t.Fatal("the intent row was written after the upload; a crash in between would leave an uncovered object")
+ }
+ rec := ledger.records[0]
+ if rec.StorageKey != storage.stored()[0].key {
+ t.Errorf("intent key %q != uploaded key %q", rec.StorageKey, storage.stored()[0].key)
+ }
+ if rec.StorageURL != got.MediaRefs[0].StorageURL {
+ t.Errorf("intent url %q != attachment url %q", rec.StorageURL, got.MediaRefs[0].StorageURL)
+ }
+ if rec.ChatMessageID != uuidOf(5) || rec.WorkspaceID != uuidOf(2) || rec.InstallationID != uuidOf(1) {
+ t.Errorf("intent row is not scoped to the message: %+v", rec)
+ }
+}
+
+// TestResolveMediaSkipsAKeyTheReconcilerOwns: ok=false means the row has left
+// 'pending'. Uploading anyway would resurrect an object that is being deleted.
+func TestResolveMediaSkipsAKeyTheReconcilerOwns(t *testing.T) {
+ t.Parallel()
+ srv := cosServer(t, []byte("payload"), "")
+ defer srv.Close()
+
+ storage := &fakeMediaStorage{}
+ ledger := newFakeMediaLedger(storage)
+ ledger.ok = false
+ r := newTestResolver(storage, ledger, nil)
+
+ msg := mediaMessage(t, "image", map[string]any{
+ "image": map[string]any{"url": srv.URL, "aeskey": testAESKey},
+ })
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(storage.stored()) != 0 {
+ t.Fatal("uploaded into a key the reconciler owns")
+ }
+ if len(got.MediaRefs) != 0 {
+ t.Fatal("produced a ref for an object that was never written")
+ }
+}
+
+// TestResolveMediaKeepsGoingWhenOneAttachmentFails: a 图文混排 with a good
+// picture and an expired one must still deliver the good one.
+func TestResolveMediaKeepsGoingWhenOneAttachmentFails(t *testing.T) {
+ t.Parallel()
+ good := cosServer(t, []byte("the good picture"), `attachment; filename="ok.png"`)
+ defer good.Close()
+ gone := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusNotFound)
+ }))
+ defer gone.Close()
+
+ storage := &fakeMediaStorage{}
+ senders, conn := notifierWithLiveSocket(uuidOf(1))
+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)
+
+ msg := mediaMessage(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []any{
+ map[string]any{"msgtype": "text", "text": map[string]any{"content": "these two"}},
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": gone.URL, "aeskey": testAESKey}},
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": good.URL, "aeskey": testAESKey}},
+ }}})
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("MediaRefs = %d, want the one that downloaded", len(got.MediaRefs))
+ }
+ if got.MediaRefs[0].Filename != "ok.png" {
+ t.Errorf("kept the wrong attachment: %+v", got.MediaRefs[0])
+ }
+ if len(conn.frames) != 1 {
+ t.Fatalf("the sender was told %d times, want exactly one notice", len(conn.frames))
+ }
+}
+
+// TestResolveMediaTellsTheSenderWhatWentWrong: too big and did-not-arrive get
+// different wording, because they need different things done about them. Two
+// failures of the same kind are still one notice.
+//
+// Without a notice the failure is invisible in the worst way: the stored body
+// still says [Image], so the agent answers as if it had been shown a picture
+// it never received.
+func TestResolveMediaTellsTheSenderWhatWentWrong(t *testing.T) {
+ t.Parallel()
+ oversize := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Length", "209715200")
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer oversize.Close()
+ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusForbidden)
+ }))
+ defer expired.Close()
+
+ noticeText := func(t *testing.T, conn *recordingConn) string {
+ t.Helper()
+ if len(conn.frames) != 1 {
+ t.Fatalf("notices = %d, want 1", len(conn.frames))
+ }
+ body := conn.sendBody(t, 0)
+ md, ok := body["markdown"].(map[string]any)
+ if !ok {
+ t.Fatalf("notice body has no markdown: %#v", body)
+ }
+ if body["chatid"] != "T-alex" || body["chat_type"] != float64(chatTypeSingleInt) {
+ t.Fatalf("notice went to %#v, want the chat the attachment came from", body)
+ }
+ content, _ := md["content"].(string)
+ return content
+ }
+
+ t.Run("one notice names the size limit", func(t *testing.T) {
+ storage := &fakeMediaStorage{}
+ senders, conn := notifierWithLiveSocket(uuidOf(1))
+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)
+ msg := mediaMessage(t, "file", map[string]any{
+ "file": map[string]any{"url": oversize.URL, "aeskey": testAESKey},
+ })
+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if got := noticeText(t, conn); got != mediaTooLargeNotice {
+ t.Fatalf("notice = %q, want the too-large wording", got)
+ }
+ })
+
+ t.Run("two failures of one kind are one notice", func(t *testing.T) {
+ storage := &fakeMediaStorage{}
+ senders, conn := notifierWithLiveSocket(uuidOf(1))
+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)
+ msg := mediaMessage(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []any{
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": expired.URL, "aeskey": testAESKey}},
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": expired.URL, "aeskey": testAESKey}},
+ }}})
+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if got := noticeText(t, conn); got != mediaUnreadableNotice {
+ t.Fatalf("notice = %q, want the unreadable wording once", got)
+ }
+ })
+
+ t.Run("nothing is said when everything worked", func(t *testing.T) {
+ srv := cosServer(t, []byte("fine"), "")
+ defer srv.Close()
+ storage := &fakeMediaStorage{}
+ senders, conn := notifierWithLiveSocket(uuidOf(1))
+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)
+ msg := mediaMessage(t, "image", map[string]any{
+ "image": map[string]any{"url": srv.URL, "aeskey": testAESKey},
+ })
+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(conn.frames) != 0 {
+ t.Fatalf("sent %d notices for a message that worked", len(conn.frames))
+ }
+ })
+
+ t.Run("a group notice goes to the room, not the sender", func(t *testing.T) {
+ storage := &fakeMediaStorage{}
+ senders, conn := notifierWithLiveSocket(uuidOf(1))
+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)
+ msg := mediaMessage(t, "image", map[string]any{
+ "chattype": "group",
+ "chatid": "ROOM_1",
+ "image": map[string]any{"url": expired.URL, "aeskey": testAESKey},
+ })
+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(conn.frames) != 1 {
+ t.Fatalf("notices = %d, want 1", len(conn.frames))
+ }
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "ROOM_1" || body["chat_type"] != float64(chatTypeGroupInt) {
+ t.Fatalf("group notice addressed %#v, want the room as chat_type 2", body)
+ }
+ })
+}
+
+// TestResolveMediaRefusesAnUndecryptablePayload: a wrong or missing key must
+// never put ciphertext in the object store labelled as a picture.
+func TestResolveMediaRefusesAnUndecryptablePayload(t *testing.T) {
+ t.Parallel()
+ srv := cosServer(t, []byte("secret report"), "")
+ defer srv.Close()
+
+ for _, tc := range []struct {
+ name string
+ aeskey string
+ }{
+ {"no key on the frame", ""},
+ {"a key that is not the one it was encrypted with", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ storage := &fakeMediaStorage{}
+ r := newTestResolver(storage, newFakeMediaLedger(storage), nil)
+ mc := aibotMsgCallback{MsgID: "MSGID-BAD", ChatID: "T-alex", ChatType: "single", MsgType: "image"}
+ mc.Image = mediaBody{URL: srv.URL, AESKey: tc.aeskey}
+ msg := channelMessageFromCallback("wb-1", "", mc, "[Image]", "req-1")
+
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(storage.stored()) != 0 {
+ t.Fatal("stored bytes it could not decrypt")
+ }
+ if len(got.MediaRefs) != 0 {
+ t.Fatal("produced a ref for an object that was never written")
+ }
+ })
+ }
+}
+
+// TestResolveMediaNamesAnUnnamedFile: COS does not always send a
+// Content-Disposition. The name then has to come from somewhere, and two
+// attachments in one message must not collide on it.
+func TestResolveMediaNamesAnUnnamedFile(t *testing.T) {
+ t.Parallel()
+ png := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR" + strings.Repeat("x", 64))
+ srv := cosServer(t, png, "")
+ defer srv.Close()
+
+ storage := &fakeMediaStorage{}
+ r := newTestResolver(storage, newFakeMediaLedger(storage), nil)
+ msg := mediaMessage(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []any{
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": srv.URL, "aeskey": testAESKey}},
+ map[string]any{"msgtype": "image", "image": map[string]any{"url": srv.URL, "aeskey": testAESKey}},
+ }}})
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+
+ if len(got.MediaRefs) != 2 {
+ t.Fatalf("MediaRefs = %d, want 2", len(got.MediaRefs))
+ }
+ first, second := got.MediaRefs[0], got.MediaRefs[1]
+ if first.Filename == second.Filename {
+ t.Fatalf("both attachments are called %q", first.Filename)
+ }
+ if first.StorageKey == second.StorageKey {
+ t.Fatal("both attachments share a storage key; the second would overwrite the first")
+ }
+ if !strings.HasSuffix(first.Filename, ".png") {
+ t.Errorf("filename %q does not carry the sniffed type", first.Filename)
+ }
+ if first.MimeType != "image/png" {
+ t.Errorf("mime = %q, want image/png sniffed from the decrypted bytes", first.MimeType)
+ }
+}
+
+// TestResolveMediaKeepsTheKeyPerChatMessage: the same WeCom message can be
+// ingested twice once its dedup claim goes stale. Sharing a key would run the
+// second ingest into the first one's ledger row — possibly a tombstone the
+// intent upsert refuses, silently dropping the media. Lark keys the same way
+// and says so at lark/media_ingest.go mediaObjectKey.
+func TestResolveMediaKeepsTheKeyPerChatMessage(t *testing.T) {
+ t.Parallel()
+ srv := cosServer(t, []byte("same bytes"), "")
+ defer srv.Close()
+
+ keyFor := func(chatMessageID pgtype.UUID) string {
+ storage := &fakeMediaStorage{}
+ r := newTestResolver(storage, newFakeMediaLedger(storage), nil)
+ msg := mediaMessage(t, "image", map[string]any{
+ "image": map[string]any{"url": srv.URL, "aeskey": testAESKey},
+ })
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), chatMessageID, msg)
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("MediaRefs = %d", len(got.MediaRefs))
+ }
+ return got.MediaRefs[0].StorageKey
+ }
+ if keyFor(uuidOf(5)) == keyFor(uuidOf(8)) {
+ t.Fatal("two chat messages derived the same object key")
+ }
+ if keyFor(uuidOf(5)) != keyFor(uuidOf(5)) {
+ t.Fatal("the key is not a function of the message; a retry would orphan the first object")
+ }
+}
+
+// TestResolveMediaWithoutStorageLeavesThePlaceholder: a deployment with no
+// object store must degrade to the text, not to a panic or a broken ref.
+func TestResolveMediaWithoutStorageLeavesThePlaceholder(t *testing.T) {
+ t.Parallel()
+ r := newTestResolver(nil, nil, nil)
+ msg := mediaMessage(t, "image", map[string]any{
+ "image": map[string]any{"url": "https://cos.invalid/a", "aeskey": testAESKey},
+ })
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(got.MediaRefs) != 0 {
+ t.Fatal("produced refs with no storage configured")
+ }
+ if got.Text != "[Image]" {
+ t.Fatalf("body = %q, want the placeholder left intact", got.Text)
+ }
+}
+
+// TestResolveMediaSurvivesAConnectionThatWentAway: the notice needs a live
+// socket and there may not be one. That must not take the ingest down with it.
+func TestResolveMediaSurvivesAConnectionThatWentAway(t *testing.T) {
+ t.Parallel()
+ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusForbidden)
+ }))
+ defer expired.Close()
+
+ storage := &fakeMediaStorage{}
+ // A registry with no entry for this installation: mid-reconnect.
+ r := newTestResolver(storage, newFakeMediaLedger(storage), newSendersRegistry())
+ msg := mediaMessage(t, "image", map[string]any{
+ "image": map[string]any{"url": expired.URL, "aeskey": testAESKey},
+ })
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(got.MediaRefs) != 0 {
+ t.Fatal("produced a ref for an attachment that never downloaded")
+ }
+}
+
+// TestTheTraceRecordsTheDispositionThatArrived: media_download.go logs
+// nothing on its own, and the one thing it learns that cannot be recovered
+// later is what Content-Disposition the object came with — the URL it came
+// from lapses in five minutes, so a filename questioned tomorrow can never be
+// checked against the header that produced it. Under MULTICA_WECOM_TRACE the
+// raw value goes to the log beside the name parsed out of it, on both ingest
+// paths, and the pre-signed URL does not.
+//
+// No t.Parallel, for the reason trace_test.go gives: `tracing` is a
+// package-level atomic and these assertions are about whether a line exists.
+func TestTheTraceRecordsTheDispositionThatArrived(t *testing.T) {
+ const (
+ disposition = `attachment; filename="PC+D%26T+Strategy+2026.docx"`
+ encoded = "PC+D%26T+Strategy+2026.docx"
+ decoded = "PC D&T Strategy 2026.docx"
+ signature = "sig=AKIDSUPERSECRETSIGNATURE"
+ )
+ plaintext := []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("pixels", 200))
+ srv := cosServer(t, plaintext, disposition)
+ defer srv.Close()
+ mediaURL := srv.URL + "/object?" + signature
+
+ // Both backends: the streaming path is the one production takes, and it
+ // reads the headers through a different call than the buffered one.
+ backends := map[string]func() mediaStorage{
+ "buffered": func() mediaStorage { return &fakeMediaStorage{} },
+ "streaming": func() mediaStorage { return &fakeStreamStorage{} },
+ }
+ for name, build := range backends {
+ t.Run(name, func(t *testing.T) {
+ t.Run("off, and there is no line at all", func(t *testing.T) {
+ withTrace(t, false)
+ logged := resolveOneAttachment(t, build(), mediaURL)
+ if strings.Contains(logged, "in.media") {
+ t.Fatalf("the switch is off and the trace still wrote: %s", logged)
+ }
+ })
+
+ t.Run("on, and the line carries the bytes", func(t *testing.T) {
+ withTrace(t, true)
+ logged := resolveOneAttachment(t, build(), mediaURL)
+ if !strings.Contains(logged, "dir=in.media") {
+ t.Fatalf("no in.media line was written: %s", logged)
+ }
+ if !strings.Contains(logged, encoded) {
+ t.Fatalf("the header did not reach the log as it arrived; want %q in: %s", encoded, logged)
+ }
+ if !strings.Contains(logged, decoded) {
+ t.Fatalf("the parsed name is not beside it; want %q in: %s", decoded, logged)
+ }
+ if !strings.Contains(logged, "msg_id=MSGID-MEDIA") {
+ t.Fatalf("the line does not say which message it belongs to: %s", logged)
+ }
+ if strings.Contains(logged, signature) || strings.Contains(logged, srv.URL) {
+ t.Fatalf("the pre-signed url reached the log: %s", logged)
+ }
+ })
+ })
+ }
+}
+
+// resolveOneAttachment runs one image through the resolver with a capturing
+// logger and returns everything that was logged.
+func resolveOneAttachment(t *testing.T, storage mediaStorage, url string) string {
+ t.Helper()
+ logger, buf := capturingLogger()
+ inspect, _ := storage.(*fakeMediaStorage)
+ if s, ok := storage.(*fakeStreamStorage); ok {
+ inspect = &s.fakeMediaStorage
+ }
+ r := NewMediaResolver(storage, newFakeMediaLedger(inspect), nil, logger).(*wecomMediaResolver)
+ r.http = testMediaClient()
+
+ msg := mediaMessage(t, "image", map[string]any{
+ "image": map[string]any{"url": url, "aeskey": testAESKey},
+ })
+ got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("MediaRefs = %d, want the attachment to have landed", len(got.MediaRefs))
+ }
+ if got.MediaRefs[0].Filename != "PC D&T Strategy 2026.docx" {
+ t.Fatalf("stored filename = %q, want the decoded name", got.MediaRefs[0].Filename)
+ }
+ return buf.String()
+}
diff --git a/server/internal/integrations/wecom/media_stream.go b/server/internal/integrations/wecom/media_stream.go
new file mode 100644
index 0000000000..14b3f91114
--- /dev/null
+++ b/server/internal/integrations/wecom/media_stream.go
@@ -0,0 +1,171 @@
+package wecom
+
+// media_stream.go — an attachment that never has to fit in memory.
+//
+// The buffered path in media_download.go holds each attachment twice: the
+// whole ciphertext from the download, then the whole plaintext from the
+// decrypt, both live at once while the upload runs. The engine caps concurrent
+// media resolutions at eight, and the resource cap is 100 MiB, so the worst
+// case a perfectly ordinary workspace can reach — four people sending two
+// large files each — is eight times two hundred megabytes of live heap. On a
+// self-hosted box that is an OOM, and the process it kills is serving Lark,
+// Slack and DingTalk as well. That path remains only as the fallback for a
+// storage backend without UploadStream; both shipped backends have one, so
+// this file is what a real deployment runs.
+//
+// One temp file instead, and the ciphertext never reaches disk at all: it
+// streams from the socket, decrypts block by block into the file, and the
+// upload reads back from there. Peak heap per attachment becomes one buffer,
+// and the number that would otherwise multiply is bounded by disk.
+//
+// The temp file is also what makes the streaming upload possible at all.
+// S3Storage.UploadStream requires an exact ContentLength, and the plaintext
+// length is the ciphertext length minus a pad that is only known after the
+// final block is read — unknowable at the moment the upload must start. A
+// file on disk has already answered the question: its size IS the length.
+//
+// Files are created 0600 and removed on every path. They hold decrypted
+// attachment content, so their permissions are part of the feature rather
+// than housekeeping.
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+)
+
+// mediaStreamChunk is how much ciphertext is decrypted at a time. Large
+// enough that the syscall overhead disappears against a 100 MiB file, small
+// enough that the buffers stay incidental next to everything else the process
+// is holding.
+const mediaStreamChunk = 256 << 10
+
+// decryptToFile reads ciphertext from src, decrypts it into a new temp file,
+// and returns the file positioned at its start along with the plaintext
+// length. The caller closes and removes it.
+//
+// CBC needs the tail before the head can be trusted — the pad is on the last
+// block — so the final block is held back until the source is exhausted and
+// unpadded then. Everything before it is written as it goes.
+func decryptToFile(aesKey string, src io.Reader, dir string) (f *os.File, size int64, err error) {
+ key, err := decodeMediaAESKey(aesKey)
+ if err != nil {
+ return nil, 0, err
+ }
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, 0, fmt.Errorf("wecom: media cipher: %w", err)
+ }
+ // The IV is the first 16 bytes of the key, as WeCom's own libraries do.
+ mode := cipher.NewCBCDecrypter(block, key[:aes.BlockSize])
+
+ out, err := os.CreateTemp(dir, "wecom-media-*.bin")
+ if err != nil {
+ return nil, 0, fmt.Errorf("wecom: media temp file: %w", err)
+ }
+ // Unlink now: the file stays readable through the handle and disappears
+ // the moment the process lets go of it, including on a crash. Nothing
+ // with decrypted attachment content is left behind for anyone to find.
+ if err := os.Remove(out.Name()); err != nil {
+ out.Close()
+ return nil, 0, fmt.Errorf("wecom: media temp file: %w", err)
+ }
+ if err := out.Chmod(0o600); err != nil && !errors.Is(err, os.ErrNotExist) {
+ // Best effort: the file is already unlinked, so this is belt as well
+ // as braces.
+ _ = err
+ }
+ defer func() {
+ if err != nil {
+ out.Close()
+ }
+ }()
+
+ buf := make([]byte, mediaStreamChunk)
+ // tail holds back the last mediaPadBlock bytes of plaintext, because the
+ // PKCS#7 pad is up to 32 bytes and therefore spans TWO AES blocks — the
+ // pad block and the cipher block are not the same size here, which is the
+ // trap media_crypt.go documents. Holding one AES block back would unpad
+ // correctly only for pads of 16 or less, i.e. about half of all files.
+ tail := make([]byte, 0, mediaPadBlock+aes.BlockSize)
+ var carry []byte // ciphertext bytes not yet on a block boundary
+ var written int64
+
+ emit := func(plain []byte) error {
+ tail = append(tail, plain...)
+ if len(tail) <= mediaPadBlock {
+ return nil
+ }
+ cut := len(tail) - mediaPadBlock
+ if _, werr := out.Write(tail[:cut]); werr != nil {
+ return werr
+ }
+ written += int64(cut)
+ tail = append(tail[:0], tail[cut:]...)
+ return nil
+ }
+
+ for {
+ n, readErr := src.Read(buf)
+ if n > 0 {
+ carry = append(carry, buf[:n]...)
+ usable := len(carry) - len(carry)%aes.BlockSize
+ if usable > 0 {
+ chunk := carry[:usable]
+ mode.CryptBlocks(chunk, chunk)
+ if err = emit(chunk); err != nil {
+ return nil, 0, fmt.Errorf("wecom: media decrypt: write: %w", err)
+ }
+ carry = append(carry[:0], carry[usable:]...)
+ }
+ }
+ if readErr == io.EOF {
+ break
+ }
+ if readErr != nil {
+ return nil, 0, fmt.Errorf("wecom: media decrypt: read: %w", readErr)
+ }
+ }
+
+ if len(carry) != 0 {
+ return nil, 0, fmt.Errorf("wecom: media ciphertext is not a multiple of the block size (%d trailing bytes)", len(carry))
+ }
+ if written == 0 && len(tail) == 0 {
+ return nil, 0, errors.New("wecom: media ciphertext is empty")
+ }
+
+ // The pad is inside what was held back, and unpadMedia validates every
+ // byte of it — a tail that does not check out means a wrong key or a
+ // truncated body, and the file in front of it cannot be trusted either.
+ unpadded, err := unpadMedia(tail)
+ if err != nil {
+ return nil, 0, err
+ }
+ if len(unpadded) > 0 {
+ if _, err = out.Write(unpadded); err != nil {
+ return nil, 0, fmt.Errorf("wecom: media decrypt: write: %w", err)
+ }
+ written += int64(len(unpadded))
+ }
+ if _, err = out.Seek(0, io.SeekStart); err != nil {
+ return nil, 0, fmt.Errorf("wecom: media decrypt: rewind: %w", err)
+ }
+ return out, written, nil
+}
+
+// peekFile reads up to n bytes from the head of f and rewinds it, so a caller
+// that needs to sniff a content type does not have to hold the whole file.
+func peekFile(f *os.File, n int) ([]byte, error) {
+ head := make([]byte, n)
+ read, err := io.ReadFull(f, head)
+ if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
+ return nil, err
+ }
+ if _, err := f.Seek(0, io.SeekStart); err != nil {
+ return nil, err
+ }
+ return head[:read], nil
+}
diff --git a/server/internal/integrations/wecom/media_stream_test.go b/server/internal/integrations/wecom/media_stream_test.go
new file mode 100644
index 0000000000..3bed0dfcc2
--- /dev/null
+++ b/server/internal/integrations/wecom/media_stream_test.go
@@ -0,0 +1,388 @@
+package wecom
+
+// media_stream_test.go — the streaming decrypt has to agree with the one it
+// replaces, byte for byte, at every size that matters.
+//
+// The buffered path holds the whole ciphertext and the whole plaintext at
+// once. Eight of those in flight — the engine's own concurrency cap, reached
+// by four people sending two large files each — is an OOM on a self-hosted
+// box, and the process it kills serves every other channel too.
+//
+// The trap the streaming version has to get right is the pad. WeCom pads
+// plaintext to a 32-byte block while AES works in 16, so the pad spans TWO
+// cipher blocks and a decoder that holds one block back unpads correctly for
+// only about half of all files. These tests walk every pad length.
+
+import (
+ "bytes"
+ "context"
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// sealMedia builds ciphertext the way WeCom does: PKCS#7 to a 32-byte block,
+// AES-256-CBC, IV = the first 16 bytes of the key.
+func sealMedia(t *testing.T, key []byte, plain []byte) string {
+ t.Helper()
+ pad := mediaPadBlock - len(plain)%mediaPadBlock
+ padded := append(append([]byte(nil), plain...), bytes.Repeat([]byte{byte(pad)}, pad)...)
+
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ t.Fatalf("aes.NewCipher: %v", err)
+ }
+ out := make([]byte, len(padded))
+ cipher.NewCBCEncrypter(block, key[:aes.BlockSize]).CryptBlocks(out, padded)
+ return string(out)
+}
+
+func mediaTestKey(t *testing.T) ([]byte, string) {
+ t.Helper()
+ key := make([]byte, mediaAESKeyBytes)
+ if _, err := rand.Read(key); err != nil {
+ t.Fatalf("rand: %v", err)
+ }
+ return key, base64.StdEncoding.EncodeToString(key)
+}
+
+// TestStreamingDecryptMatchesTheBufferedOneAtEveryPadLength is the one that
+// matters. A pad of 1..32 covers both cipher blocks the pad can occupy, and
+// the sizes are chosen to land on each.
+func TestStreamingDecryptMatchesTheBufferedOneAtEveryPadLength(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+
+ // Every residue mod 32 — so every possible pad length — plus sizes that
+ // cross the read-chunk boundary.
+ sizes := []int{0, 1, 15, 16, 17, 31, 32, 33, 63, 64, 65, 1000}
+ for i := 0; i < 32; i++ {
+ sizes = append(sizes, mediaPadBlock*3+i)
+ }
+ sizes = append(sizes, mediaStreamChunk-1, mediaStreamChunk, mediaStreamChunk+1, mediaStreamChunk*2+7)
+
+ for _, n := range sizes {
+ plain := make([]byte, n)
+ if _, err := rand.Read(plain); err != nil {
+ t.Fatalf("rand: %v", err)
+ }
+ ct := sealMedia(t, key, plain)
+
+ want, err := decryptMedia(keyB64, []byte(ct))
+ if err != nil {
+ t.Fatalf("buffered decrypt of %d bytes: %v", n, err)
+ }
+
+ f, size, err := decryptToFile(keyB64, strings.NewReader(ct), t.TempDir())
+ if err != nil {
+ t.Fatalf("streaming decrypt of %d bytes: %v", n, err)
+ }
+ got, readErr := io.ReadAll(f)
+ f.Close()
+ if readErr != nil {
+ t.Fatalf("read back %d bytes: %v", n, readErr)
+ }
+
+ if size != int64(len(want)) {
+ t.Fatalf("size for %d bytes = %d, want %d — an upload with the wrong ContentLength is a corrupt object",
+ n, size, len(want))
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("streaming and buffered decrypt disagree at %d bytes (pad %d)",
+ n, mediaPadBlock-n%mediaPadBlock)
+ }
+ if !bytes.Equal(got, plain) {
+ t.Fatalf("the decrypt did not round-trip at %d bytes", n)
+ }
+ }
+}
+
+// A source that hands over a few bytes at a time must produce the same file —
+// this is what an actual socket does, and a decoder that assumed whole blocks
+// per Read would corrupt everything.
+func TestStreamingDecryptSurvivesADribblingReader(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+ plain := []byte(strings.Repeat("这是一个文件的内容。", 500))
+ ct := sealMedia(t, key, plain)
+
+ f, size, err := decryptToFile(keyB64, &iotest1ByteReader{s: ct}, t.TempDir())
+ if err != nil {
+ t.Fatalf("decryptToFile: %v", err)
+ }
+ defer f.Close()
+ got, err := io.ReadAll(f)
+ if err != nil {
+ t.Fatalf("read back: %v", err)
+ }
+ if int64(len(got)) != size || !bytes.Equal(got, plain) {
+ t.Fatalf("a one-byte-at-a-time source produced %d bytes, want %d", len(got), len(plain))
+ }
+}
+
+// iotest1ByteReader hands over a single byte per Read.
+type iotest1ByteReader struct {
+ s string
+ i int
+}
+
+func (r *iotest1ByteReader) Read(p []byte) (int, error) {
+ if r.i >= len(r.s) {
+ return 0, io.EOF
+ }
+ p[0] = r.s[r.i]
+ r.i++
+ return 1, nil
+}
+
+// A wrong key must be refused rather than producing a file of noise the agent
+// would then be handed.
+func TestStreamingDecryptRefusesAWrongKey(t *testing.T) {
+ key, _ := mediaTestKey(t)
+ _, otherB64 := mediaTestKey(t)
+ ct := sealMedia(t, key, []byte("the real contents"))
+
+ if _, _, err := decryptToFile(otherB64, strings.NewReader(ct), t.TempDir()); err == nil {
+ t.Fatal("a wrong key produced a file")
+ }
+}
+
+// A truncated body is the same class of failure and must not half-succeed.
+func TestStreamingDecryptRefusesATruncatedBody(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+ ct := sealMedia(t, key, []byte(strings.Repeat("x", 200)))
+
+ // Cut mid-block: not a multiple of the cipher block at all.
+ if _, _, err := decryptToFile(keyB64, strings.NewReader(ct[:len(ct)-5]), t.TempDir()); err == nil {
+ t.Fatal("a body cut mid-block produced a file")
+ }
+ // And cut on a block boundary, which only the pad check can catch.
+ if _, _, err := decryptToFile(keyB64, strings.NewReader(ct[:len(ct)-aes.BlockSize]), t.TempDir()); err == nil {
+ t.Fatal("a body cut on a block boundary produced a file")
+ }
+}
+
+func TestStreamingDecryptRefusesAnEmptyBody(t *testing.T) {
+ _, keyB64 := mediaTestKey(t)
+ if _, _, err := decryptToFile(keyB64, strings.NewReader(""), t.TempDir()); err == nil {
+ t.Fatal("an empty body produced a file")
+ }
+}
+
+// The plaintext is an attachment. Its temp file must not be readable by
+// anyone else, and must not outlive the handle — including if the process
+// dies holding it.
+func TestTheTempFileIsPrivateAndUnlinked(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+ dir := t.TempDir()
+ ct := sealMedia(t, key, []byte("secret contents"))
+
+ f, _, err := decryptToFile(keyB64, strings.NewReader(ct), dir)
+ if err != nil {
+ t.Fatalf("decryptToFile: %v", err)
+ }
+ defer f.Close()
+
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatalf("read dir: %v", err)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("the temp directory still holds %d entries; the plaintext file was not unlinked", len(entries))
+ }
+
+ info, err := f.Stat()
+ if err != nil {
+ t.Fatalf("stat: %v", err)
+ }
+ if perm := info.Mode().Perm(); perm&0o077 != 0 {
+ t.Errorf("the plaintext file is mode %v, want no group or other access", perm)
+ }
+}
+
+// peekFile has to leave the file where it found it, or the upload sends a
+// truncated object.
+func TestPeekFileRewinds(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+ plain := []byte("0123456789abcdefghij")
+ f, size, err := decryptToFile(keyB64, strings.NewReader(sealMedia(t, key, plain)), t.TempDir())
+ if err != nil {
+ t.Fatalf("decryptToFile: %v", err)
+ }
+ defer f.Close()
+
+ head, err := peekFile(f, 4)
+ if err != nil {
+ t.Fatalf("peekFile: %v", err)
+ }
+ if string(head) != "0123" {
+ t.Fatalf("peek = %q", head)
+ }
+ all, err := io.ReadAll(f)
+ if err != nil {
+ t.Fatalf("read after peek: %v", err)
+ }
+ if int64(len(all)) != size || !bytes.Equal(all, plain) {
+ t.Fatalf("after peeking, the file read back %d bytes, want %d", len(all), size)
+ }
+}
+
+// A peek longer than the file is what a small attachment produces, and must
+// not be an error.
+func TestPeekFileHandlesAShortFile(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+ f, _, err := decryptToFile(keyB64, strings.NewReader(sealMedia(t, key, []byte("hi"))), t.TempDir())
+ if err != nil {
+ t.Fatalf("decryptToFile: %v", err)
+ }
+ defer f.Close()
+
+ head, err := peekFile(f, 512)
+ if err != nil {
+ t.Fatalf("peekFile: %v", err)
+ }
+ if string(head) != "hi" {
+ t.Fatalf("peek = %q, want the whole short file", head)
+ }
+}
+
+// streamingStorage records what UploadStream was handed, and how much of the
+// heap it had to take to do it.
+type streamingStorage struct {
+ fakeMediaStorage
+ streamed int
+ gotSize int64
+ gotBytes []byte
+ gotType string
+ streamErr error
+}
+
+func (s *streamingStorage) UploadStream(_ context.Context, key string, data io.Reader, size int64, contentType, filename string) (string, error) {
+ if s.streamErr != nil {
+ return "", s.streamErr
+ }
+ s.streamed++
+ s.gotSize = size
+ s.gotType = contentType
+ b, err := io.ReadAll(data)
+ if err != nil {
+ return "", err
+ }
+ s.gotBytes = b
+ return "https://objects.example/" + key, nil
+}
+
+// TestIngestPrefersTheStreamingPathAndUploadsTheRightBytes — the whole point
+// of the temp file. A backend that can stream must be handed the plaintext
+// with its exact length, and the object must be byte-identical to what the
+// buffered path would have produced.
+func TestIngestPrefersTheStreamingPathAndUploadsTheRightBytes(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+ plain := []byte(strings.Repeat("报告正文。", 4000))
+ ct := sealMedia(t, key, plain)
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Disposition", `attachment; filename="report.txt"`)
+ w.Write([]byte(ct))
+ }))
+ defer srv.Close()
+
+ storage := &streamingStorage{}
+ r := &wecomMediaResolver{
+ storage: storage,
+ ledger: newFakeMediaLedger(nil),
+ http: testMediaClient(),
+ logger: testLogger(),
+ }
+
+ msg := mediaMessage(t, "file", map[string]any{
+ "file": map[string]any{"url": srv.URL + "/object", "aeskey": keyB64},
+ })
+ out := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+
+ if storage.streamed != 1 {
+ t.Fatalf("UploadStream was called %d times, want the streaming path taken", storage.streamed)
+ }
+ if storage.gotSize != int64(len(plain)) {
+ t.Fatalf("ContentLength = %d, want %d — a wrong length is a corrupt object", storage.gotSize, len(plain))
+ }
+ if !bytes.Equal(storage.gotBytes, plain) {
+ t.Fatalf("the uploaded object is %d bytes, want the %d-byte plaintext", len(storage.gotBytes), len(plain))
+ }
+ if len(out.MediaRefs) != 1 {
+ t.Fatalf("MediaRefs = %d, want the attachment bound", len(out.MediaRefs))
+ }
+ if out.MediaRefs[0].SizeBytes != int64(len(plain)) {
+ t.Errorf("the ref carries size %d, want %d", out.MediaRefs[0].SizeBytes, len(plain))
+ }
+ if out.MediaRefs[0].Filename != "report.txt" {
+ t.Errorf("filename = %q", out.MediaRefs[0].Filename)
+ }
+}
+
+// A backend with no streaming half still works — the buffered path is the
+// fallback, not a dead branch.
+func TestIngestFallsBackWhenTheBackendCannotStream(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+ plain := []byte("a short attachment")
+ ct := sealMedia(t, key, plain)
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Write([]byte(ct))
+ }))
+ defer srv.Close()
+
+ storage := &fakeMediaStorage{}
+ r := &wecomMediaResolver{
+ storage: storage,
+ ledger: newFakeMediaLedger(storage),
+ http: testMediaClient(),
+ logger: testLogger(),
+ }
+
+ msg := mediaMessage(t, "file", map[string]any{
+ "file": map[string]any{"url": srv.URL + "/object", "aeskey": keyB64},
+ })
+ out := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(out.MediaRefs) != 1 {
+ t.Fatalf("MediaRefs = %d, want the buffered path to have carried it", len(out.MediaRefs))
+ }
+}
+
+// The ceiling still holds on the streaming path. A body that keeps going past
+// it must be cut off rather than allowed to fill the disk the way it used to
+// be able to fill the heap.
+func TestTheStreamingPathStillRefusesAnOversizeBody(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ // No Content-Length, and more bytes than the cap.
+ chunk := bytes.Repeat([]byte("x"), 1<<20)
+ for written := 0; written <= maxMediaBytes; written += len(chunk) {
+ if _, err := w.Write(chunk); err != nil {
+ return
+ }
+ }
+ }))
+ defer srv.Close()
+
+ body, _, err := openMedia(context.Background(), testMediaClient(), srv.URL+"/object")
+ if err != nil {
+ t.Fatalf("openMedia: %v", err)
+ }
+ defer body.Close()
+
+ n, err := io.Copy(io.Discard, body)
+ if !errors.Is(err, errMediaTooLarge) {
+ t.Fatalf("read %d bytes with err %v, want the size refusal", n, err)
+ }
+ if n > maxMediaBytes+1 {
+ t.Fatalf("read %d bytes before stopping, want the cap to hold", n)
+ }
+}
diff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.go
index 394a07964f..7f4df8eefa 100644
--- a/server/internal/integrations/wecom/resolvers_test.go
+++ b/server/internal/integrations/wecom/resolvers_test.go
@@ -27,9 +27,17 @@ import (
type fakeSessionBinder struct {
ensureIn engine.EnsureSessionInput
appendIn engine.AppendInput
+ bindIn engine.BindMediaInput
+ binds int
sessID pgtype.UUID
}
+func (f *fakeSessionBinder) BindMediaRefs(_ context.Context, in engine.BindMediaInput) error {
+ f.bindIn = in
+ f.binds++
+ return nil
+}
+
func (f *fakeSessionBinder) EnsureSession(_ context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error) {
f.ensureIn = in
return f.sessID, nil
@@ -78,23 +86,79 @@ func TestSessionBinder_AppendUsesTextAsCommand(t *testing.T) {
}
}
-func TestSessionBinder_BindMediaIsNoop(t *testing.T) {
+// The resolver downloads, decrypts and stores an attachment; this is the step
+// that attaches it to the message. Returning nil without binding reads to the
+// Router as success, so every attachment would be fetched and then silently
+// discarded — the agent sees only "[Image]" and nothing is logged.
+func TestSessionBinder_BindMediaReachesTheSessionStore(t *testing.T) {
t.Parallel()
- b := &sessionBinder{session: &fakeSessionBinder{}}
- if err := b.BindMedia(context.Background(), engine.BindMediaParams{}); err != nil {
- t.Errorf("BindMedia = %v, want nil (wecom resolves no media)", err)
+ fb := &fakeSessionBinder{}
+ b := &sessionBinder{session: fb}
+ refs := []channel.MediaRef{{StorageKey: "k", Filename: "photo.jpg"}}
+ issue := pgtype.UUID{Bytes: [16]byte{7}, Valid: true}
+
+ if err := b.BindMedia(context.Background(), engine.BindMediaParams{
+ MediaRefs: refs,
+ IssueID: issue,
+ }); err != nil {
+ t.Fatalf("BindMedia: %v", err)
+ }
+ if fb.binds != 1 {
+ t.Fatalf("BindMediaRefs called %d times, want 1 — the refs never reached the session store", fb.binds)
+ }
+ if len(fb.bindIn.MediaRefs) != 1 {
+ t.Errorf("MediaRefs = %d, want 1", len(fb.bindIn.MediaRefs))
+ }
+ // IssueID is what makes an /issue turn's attachment belong to the issue
+ // rather than to a chat message nobody opens again.
+ if fb.bindIn.IssueID != issue {
+ t.Error("IssueID was dropped; an /issue attachment would land on the chat message instead")
+ }
+}
+
+// The media budget is how long the chat task waits before running. Dropped, the
+// run fires at once and the agent is handed the placeholder mid-download.
+func TestSessionBinder_AppendCarriesTheMediaBudget(t *testing.T) {
+ t.Parallel()
+ fb := &fakeSessionBinder{}
+ b := &sessionBinder{session: fb}
+ if _, err := b.AppendMessage(context.Background(), engine.AppendParams{
+ MediaPendingSeconds: 45,
+ }); err != nil {
+ t.Fatalf("AppendMessage: %v", err)
+ }
+ if fb.appendIn.MediaPendingSeconds != 45 {
+ t.Errorf("MediaPendingSeconds = %v, want 45 — the media budget never reached the append", fb.appendIn.MediaPendingSeconds)
}
}
func TestNewResolverSet_WiresAllResolvers(t *testing.T) {
t.Parallel()
- set := NewResolverSet(&Store{}, &fakeSessionBinder{}, nil)
+ set := NewResolverSet(&Store{}, &fakeSessionBinder{}, nil, nil)
if set.Installation == nil || set.Identity == nil || set.Dedup == nil || set.Session == nil || set.Audit == nil {
t.Error("NewResolverSet left a required resolver nil")
}
if set.OriginType != originWecomChat {
t.Errorf("OriginType = %q, want %q", set.OriginType, originWecomChat)
}
+ // A deployment with no object store passes nil and must degrade to
+ // placeholder text, which the Router only does when Media is nil.
+ if set.Media != nil {
+ t.Error("nil media argument produced a non-nil Media resolver")
+ }
+ // And a configured one must actually reach the Router — this is the
+ // whole wiring, and a resolver built at boot and dropped here would look
+ // exactly like media ingestion never having been written.
+ media := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, testLogger())
+ withMedia := NewResolverSet(&Store{}, &fakeSessionBinder{}, nil, media)
+ if withMedia.Media == nil {
+ t.Fatal("a media resolver was passed and dropped")
+ }
+ if !withMedia.Media.HasMedia(mediaMessage(t, "image", map[string]any{
+ "image": map[string]any{"url": "https://cos.invalid/a", "aeskey": testAESKey},
+ })) {
+ t.Error("the wired resolver does not recognize a media message")
+ }
}
func TestWecomMsgFromRaw(t *testing.T) {
diff --git a/server/internal/integrations/wecom/trace.go b/server/internal/integrations/wecom/trace.go
index 93fc37fe57..dd44913a8e 100644
--- a/server/internal/integrations/wecom/trace.go
+++ b/server/internal/integrations/wecom/trace.go
@@ -13,6 +13,9 @@ package wecom
// With MULTICA_WECOM_TRACE=1 the server records enough to check a real-device
// session afterwards: which way the frame went, what chat it was addressed
// to, whether that chat is a room or a person, and what the server said back.
+// The switch also covers the one thing a frame does not carry — what an
+// attachment's own response said its name was (traceMediaHeaders), which no
+// later inspection can recover once the five-minute media URL has lapsed.
//
// Why not slog.Debug, which the siblings use for their per-frame lines
// (slack_channel.go:162, lark/ws_connector.go:339): logger.parseLevel
@@ -25,9 +28,15 @@ package wecom
// that" cannot be answered from lengths alone — so it is message content, in
// a log, and it should be turned on deliberately and turned off after. The
// prefix is capped rather than full, the cap counts runes so a Chinese
-// message is not cut mid-character, bearer tokens are redacted out of it, and
-// nothing here reads a credential field: the bot secret rides in the
-// aibot_subscribe body, which traceOutFields never descends into.
+// message is not cut mid-character, bearer tokens are redacted out of every
+// message string, and nothing here reads a credential field: the bot secret
+// rides in the aibot_subscribe body, which traceOutFields never descends
+// into.
+//
+// One string skips the redactor: an attachment's Content-Disposition, which
+// traceMediaHeaders writes verbatim under a cap of its own. That function
+// says why the redactor would destroy the only thing the line is for, and why
+// nothing in that header is a credential.
import (
"log/slog"
@@ -54,6 +63,28 @@ func tracingOn() bool { return tracing.Load() }
// in; short enough that a transcript is not reconstructable from the log.
const tracePreviewRunes = 120
+// traceHeaderRunes bounds an attachment's Content-Disposition, and the name
+// parsed out of it, on their way to the trace. It is a runaway guard on a
+// remote string, not a preview cap, which is why it is not tracePreviewRunes.
+//
+// 120 would defeat the line. `attachment; filename=""` is 23 runes on its own
+// and a percent-escaped CJK character is 9, so a name of eleven Chinese
+// characters is already over the preview cap — and non-ASCII names are the
+// whole reason this line exists, since a name that is nothing but escapes is
+// the one most likely to come out wrong. Worse than losing the tail: the cut
+// lands mid-escape ("…%E7%89%8…"), and a half-written escape cannot be
+// decoded back into the character it stood for, so a truncated line does not
+// even answer the question it was written to answer.
+//
+// 2048 is sized against the largest thing this can legitimately be rather
+// than picked round. Common filesystems stop a name at 255 bytes;
+// percent-escaping every one of those triples it to 765, and a header
+// carrying BOTH parameter forms of such a name — filename= and filename*= —
+// comes to about 1570 runes with its scaffolding. Anything past this is not a
+// filename, and a log line is not where an unbounded remote string should
+// land.
+const traceHeaderRunes = 2048
+
// tracePreview returns a bounded, single-line prefix of s with any bearer
// token redacted. Newlines become spaces so one frame stays one log line, and
// the cut is on a rune boundary.
@@ -75,11 +106,21 @@ const tracePreviewRunes = 120
// (OutboundReplier owns it, and BindingPath is configurable). A "token=" in a
// URL is the shape worth hiding wherever it appears.
func tracePreview(s string) string {
- s = redactBearerTokens(s)
- out := make([]rune, 0, tracePreviewRunes)
+ return traceBound(redactBearerTokens(s), tracePreviewRunes)
+}
+
+// traceBound is tracePreview's second half on its own: the single-line
+// flattening and a cap, without the redaction. The cap is a parameter because
+// its two callers bound different things for different reasons — a message
+// preview is deliberately short (tracePreviewRunes), an attachment header is
+// bounded only so a remote string cannot run away (traceHeaderRunes).
+// traceMediaHeaders is the only caller that skips the redaction, and it says
+// there why.
+func traceBound(s string, limit int) string {
+ out := make([]rune, 0, limit)
cut := false
for _, r := range s {
- if len(out) == tracePreviewRunes {
+ if len(out) == limit {
cut = true
break
}
@@ -188,7 +229,9 @@ func traceOutAttempt(log *slog.Logger, seq uint64, t *outTrace) {
// by another goroutine's frame.
//
// The error text goes through tracePreview: it is the socket's words, not
-// ours, and everything else this file writes is bounded and redacted.
+// ours, so it is bounded and redacted like every other message string here.
+// The one string in this file that is bounded but NOT redacted is an
+// attachment's Content-Disposition, and traceMediaHeaders says why.
func traceOutResult(log *slog.Logger, seq uint64, t *outTrace, stage string, err error) {
if t == nil {
return
@@ -247,6 +290,45 @@ func traceInbound(log *slog.Logger, mc aibotMsgCallback, text string) {
)
}
+// traceMediaHeaders records what an attachment's response said about itself:
+// the Content-Disposition exactly as it arrived, and the name this package
+// parsed out of it. Those two side by side are the whole diagnosis for a
+// filename that comes out looking wrong, and they cannot be recovered later —
+// the URL they came from is good for five minutes, so an attachment whose
+// name is questioned tomorrow can never be re-fetched to settle it.
+//
+// Both values are flattened to one line and capped at traceHeaderRunes, and
+// neither is run through redactBearerTokens the way every other traced string
+// is. Two deliberate departures, for one reason: the point of this line is
+// the exact bytes.
+//
+// The redactor rewrites anything shaped like "token=…", and a file may
+// legitimately be called that — a redacted filename is a filename nobody can
+// diagnose. Nothing here is a credential anyway: the header carries a name,
+// and the pre-signed URL that does carry one is deliberately absent from this
+// line and from everything else media_download.go emits.
+//
+// The cap is traceHeaderRunes rather than the message preview's because a
+// percent-escaped name spends nine runes per Chinese character; the preview
+// cap would cut an ordinary filename in half and leave a fragment of an
+// escape behind. traceHeaderRunes says what it is sized against.
+//
+// It fires even when the header was absent, recording an empty value. A run
+// that produced no line at all would leave the reader unable to tell "the
+// server sent no Content-Disposition" from "the switch was off".
+func traceMediaHeaders(log *slog.Logger, msgID string, index int, h mediaHeaders) {
+ if !tracingOn() || log == nil {
+ return
+ }
+ log.Info("wecom trace",
+ "dir", "in.media",
+ "msg_id", msgID,
+ "index", index,
+ "content_disposition", traceBound(h.Disposition, traceHeaderRunes),
+ "filename", traceBound(h.Filename, traceHeaderRunes),
+ )
+}
+
// tokenParamPattern finds a token carried as a query parameter, whatever path
// it sits on. Deliberately broad: an access_token or a code is no safer in a
// log than a binding token.
diff --git a/server/internal/integrations/wecom/trace_test.go b/server/internal/integrations/wecom/trace_test.go
index a09c18bf4c..63b37bcd58 100644
--- a/server/internal/integrations/wecom/trace_test.go
+++ b/server/internal/integrations/wecom/trace_test.go
@@ -1,11 +1,13 @@
package wecom
-// trace_test.go — guards for the MULTICA_WECOM_TRACE operator switch. Five
+// trace_test.go — guards for the MULTICA_WECOM_TRACE operator switch. Six
// things have to hold or the switch is not shippable: it records nothing at
// all when off, it records enough to be worth turning on, what it records is
// never a credential, the order it records outbound frames in is the order
-// they reached the socket, and a frame that failed to go out does not read
-// like one that went.
+// they reached the socket, a frame that failed to go out does not read like
+// one that went, and the one line whose value is its exact bytes — an
+// attachment's Content-Disposition — is not cut down to the message preview's
+// cap.
//
// These tests do NOT call t.Parallel: `tracing` is a package-level atomic and
// the assertions are about whether a log line exists. `go test` runs top-level
@@ -769,3 +771,82 @@ func TestTraceOffRecordsNoOutcomeEither(t *testing.T) {
t.Errorf("tracing is off but %d trace lines were written: %v", len(lines), lines)
}
}
+
+// TestTheMediaHeaderIsNotCutToTheMessagePreviewCap is the case traceMediaHeaders
+// was added for, and the one the message preview cap silently failed.
+//
+// A non-ASCII filename cannot sit in the plain filename= parameter, so it
+// arrives as nothing but percent escapes: nine runes per Chinese character,
+// after 23 runes of `attachment; filename=""` scaffolding. Under
+// tracePreviewRunes (120) an eleven-character name is already over, and the
+// cut lands inside an escape — so an operator who turned MULTICA_WECOM_TRACE
+// on precisely to learn how the CDN encodes a Chinese name got a prefix
+// ending in half an escape, which cannot even be decoded back into the
+// character it stood for.
+func TestTheMediaHeaderIsNotCutToTheMessagePreviewCap(t *testing.T) {
+ withTrace(t, true)
+
+ const name = "季度经营分析报告最终版本二零二六.docx"
+ encoded := url.QueryEscape(name)
+ // Both forms together, which is what a server sends when it offers a
+ // legacy fallback beside the extended parameter — the longest shape this
+ // line has to carry in practice.
+ raw := `attachment; filename="` + encoded + `"; filename*=UTF-8''` + encoded
+
+ if n := utf8.RuneCountInString(raw); n <= tracePreviewRunes {
+ t.Fatalf("fixture proves nothing: the header is %d runes, under the preview cap of %d", n, tracePreviewRunes)
+ }
+
+ logger, buf := capturingLogger()
+ traceMediaHeaders(logger, "MSGID-MEDIA", 0, mediaHeaders{Disposition: raw, Filename: name})
+ logged := buf.String()
+
+ // slog's TextHandler quotes the value and escapes the quotes inside it,
+ // so the assertion is on the escaped name — which is the part that
+ // matters and contains no character the handler rewrites. Both parameters
+ // carry it, so it must appear twice.
+ if n := strings.Count(logged, encoded); n != 2 {
+ t.Fatalf("the escaped name appears %d times, want both parameters intact: %s", n, logged)
+ }
+ if strings.Contains(logged, "…") {
+ t.Fatalf("the header was truncated, which is the whole failure: %s", logged)
+ }
+}
+
+// TestTheMediaHeaderIsStillBounded keeps the larger cap a runaway guard rather
+// than an open door. The value is a remote string on a log line; no real
+// Content-Disposition approaches traceHeaderRunes, so anything that does is
+// not a filename and must not be written whole.
+func TestTheMediaHeaderIsStillBounded(t *testing.T) {
+ withTrace(t, true)
+
+ logger, buf := capturingLogger()
+ runaway := `attachment; filename="` + strings.Repeat("A", traceHeaderRunes*2) + `"`
+ traceMediaHeaders(logger, "MSGID-MEDIA", 0, mediaHeaders{Disposition: runaway, Filename: runaway})
+ logged := buf.String()
+
+ if !strings.Contains(logged, "…") {
+ t.Fatalf("a %d-rune header was written without a cut: %d bytes logged",
+ utf8.RuneCountInString(runaway), len(logged))
+ }
+ if n := utf8.RuneCountInString(logged); n > 4*traceHeaderRunes {
+ t.Fatalf("the line grew to %d runes; both fields are meant to be capped at %d", n, traceHeaderRunes)
+ }
+}
+
+// TestTheMediaHeaderStaysOnOneLine keeps a header carrying a newline from
+// splitting one attachment across two log records. net/http rejects a
+// response header with a bare LF in it today, so this guards the flattening
+// rather than a reachable input — but the trace's whole contract is one line
+// per event, and traceBound is shared with the message preview.
+func TestTheMediaHeaderStaysOnOneLine(t *testing.T) {
+ withTrace(t, true)
+
+ logger, buf := capturingLogger()
+ traceMediaHeaders(logger, "MSGID-MEDIA", 0, mediaHeaders{
+ Disposition: "attachment;\r\n filename=\"a.docx\"",
+ })
+ if got := strings.TrimSuffix(buf.String(), "\n"); strings.ContainsAny(got, "\n\r") {
+ t.Fatalf("the media line was split across records: %q", got)
+ }
+}
diff --git a/server/internal/integrations/wecom/types.go b/server/internal/integrations/wecom/types.go
index 0b6370a35e..f6aea6784b 100644
--- a/server/internal/integrations/wecom/types.go
+++ b/server/internal/integrations/wecom/types.go
@@ -28,13 +28,15 @@
// shared channel engine? Keep this adapter building — and loop in the code
// owners for anything that changes WeCom-visible behavior.
//
-// Known limits of the first version, both deliberate: inbound handling takes
-// only what arrives as words — typed text, and the transcript WeCom returns
-// for a voice note — while the kinds carrying a downloadable payload get a
-// short "text only" receipt; and outbound
-// delivery requires a SINGLE backend replica, because the only send path is the
-// in-process WebSocket in sendersRegistry while EventChatDone dispatches on the
-// in-process events.Bus. See SELF_HOSTING.md.
+// Inbound handles text, the transcript WeCom returns for a voice note,
+// photos, files, videos and 图文混排 (media_ingest.go downloads and decrypts
+// what a callback points at); a kind it cannot read still gets a short
+// receipt.
+//
+// Known limit, deliberate: outbound delivery requires a SINGLE backend
+// replica, because the only send path is the in-process WebSocket in
+// sendersRegistry while EventChatDone dispatches on the in-process
+// events.Bus. See SELF_HOSTING.md.
package wecom
import (
diff --git a/server/internal/integrations/wecom/voice_test.go b/server/internal/integrations/wecom/voice_test.go
index b1935490db..4a56b794e6 100644
--- a/server/internal/integrations/wecom/voice_test.go
+++ b/server/internal/integrations/wecom/voice_test.go
@@ -10,7 +10,7 @@ func TestVoiceTranscriptIsTreatedAsText(t *testing.T) {
mc := aibotMsgCallback{MsgType: "voice"}
mc.Voice.Content = "把登录跳转的 bug 记一下"
- body, ok := mc.bodyText()
+ body, ok := mc.ownText()
if !ok {
t.Fatal("a voice note with a transcript was refused — the sentence was already in hand")
}
@@ -18,7 +18,7 @@ func TestVoiceTranscriptIsTreatedAsText(t *testing.T) {
t.Errorf("body = %q, want the transcript", body)
}
- msg := channelMessageFromCallback("bot-1", "", mc, "req-1")
+ msg := channelMessageFromCallback("bot-1", "", mc, body, "req-1")
if msg.Text != "把登录跳转的 bug 记一下" {
t.Errorf("InboundMessage.Text = %q, want the transcript", msg.Text)
}
@@ -28,7 +28,8 @@ func TestVoiceTranscriptIsTreatedAsText(t *testing.T) {
func TestSpokenIssueCommandIsACommand(t *testing.T) {
mc := aibotMsgCallback{MsgType: "voice"}
mc.Voice.Content = "/issue the login redirect is broken"
- msg := channelMessageFromCallback("bot-1", "", mc, "req-1")
+ body, _ := mc.ownText()
+ msg := channelMessageFromCallback("bot-1", "", mc, body, "req-1")
if !msg.SkipAgentRun {
t.Error("a spoken /issue did not register as a command")
}
@@ -40,7 +41,7 @@ func TestEmptyTranscriptIsNotIngested(t *testing.T) {
for _, content := range []string{"", " ", "\t\n"} {
mc := aibotMsgCallback{MsgType: "voice"}
mc.Voice.Content = content
- if _, ok := mc.bodyText(); ok {
+ if _, ok := mc.ownText(); ok {
t.Errorf("an empty transcript (%q) was ingested as a turn", content)
}
}
@@ -49,19 +50,20 @@ func TestEmptyTranscriptIsNotIngested(t *testing.T) {
func TestTextIsUnaffected(t *testing.T) {
mc := aibotMsgCallback{MsgType: "text"}
mc.Text.Content = "typed as usual"
- body, ok := mc.bodyText()
+ body, ok := mc.ownText()
if !ok || body != "typed as usual" {
- t.Errorf("bodyText() = (%q, %v), want the typed text", body, ok)
+ t.Errorf("ownText() = (%q, %v), want the typed text", body, ok)
}
}
-// The downloadable kinds still take the receipt path — reading a transcript
-// adds no media ingestion.
-func TestDownloadableKindsStillTakeTheReceiptPath(t *testing.T) {
+// A downloadable kind is read from its url, so one that arrives without a url
+// has nothing to fetch and nothing to say — it takes the receipt path, the
+// same as a kind the adapter does not know at all.
+func TestDownloadableKindsWithoutAUrlTakeTheReceiptPath(t *testing.T) {
for _, kind := range []string{"image", "file", "video", "mixed"} {
mc := aibotMsgCallback{MsgType: kind}
- if _, ok := mc.bodyText(); ok {
- t.Errorf("%s was routed as text", kind)
+ if _, ok := mc.ownText(); ok {
+ t.Errorf("%s with no url was routed anyway", kind)
}
}
}
diff --git a/server/internal/integrations/wecom/wecom_channel.go b/server/internal/integrations/wecom/wecom_channel.go
index 3da005948c..6c18b5decb 100644
--- a/server/internal/integrations/wecom/wecom_channel.go
+++ b/server/internal/integrations/wecom/wecom_channel.go
@@ -60,6 +60,14 @@ const writeDeadline = 10 * time.Second
// handshakeTimeout bounds the initial TCP + WS handshake dial.
const handshakeTimeout = 15 * time.Second
+// unsupportedMsgTypeReceipt is the one line sent back for a message this
+// adapter cannot read at all. It used to say "我目前只能处理文字消息" — text
+// only — which stopped being true the moment photos, files, videos and
+// 图文混排 started routing: a person who has just watched the bot answer a
+// screenshot, then gets told it only handles text, reads that as the bot
+// being broken rather than as this one kind not being supported.
+const unsupportedMsgTypeReceipt = "抱歉,我暂时无法处理这类消息。"
+
// wecomChannel is one installation's aibot smart-bot WebSocket connection.
// The engine.Supervisor builds one per active installation via the
// registered Factory and drives lease / reconnect lifecycle; Connect blocks
@@ -101,12 +109,13 @@ func (c *wecomChannel) mx() Metrics {
return c.metrics
}
-// Capabilities declares what the aibot adapter supports today. Text is the
-// only fully wired capability; attachments arrive as MsgTypeImage / File /
-// Audio / Video but we do not yet download the media (WeCom's aibot API
-// requires an additional aibot_upload_media_* dance to send back media).
+// Capabilities declares what the aibot adapter supports today. Inbound
+// attachments are downloaded, decrypted and bound (media_ingest.go), so
+// CapAttachment holds in the same direction it holds for DingTalk
+// (dingtalk_channel.go:52). Sending media back out is a separate matter —
+// it needs WeCom's aibot_upload_media_* handshake — and is not claimed here.
func (c *wecomChannel) Capabilities() channel.Capability {
- return channel.CapText
+ return channel.CapText | channel.CapAttachment
}
// Disconnect is a no-op: the WS connection's whole lifetime is scoped to
@@ -442,28 +451,24 @@ func (c *wecomChannel) dispatchFrame(ctx context.Context, env frameEnvelope, sen
log.Warn("wecom: bad aibot_msg_callback body", "error", err)
return nil
}
- // Trace the body the adapter will actually route, not the typed
- // field: a voice note carries its words in voice.content, and an
- // operator who turned tracing on to follow one would otherwise read
- // len=0 next to a bot that answered.
- body, routable := mc.bodyText()
- traceInbound(log, mc, body)
- msg := channelMessageFromCallback(c.botID, c.botDisplayName, mc, env.Headers.ReqID)
- // A voice note is a sentence that happened to be spoken: WeCom does
- // the recognition and hands over the transcript, so it needs no
- // download, no media key and no storage. Answering it with "I only
- // handle text" was refusing content we already had in hand.
- if !routable {
- // Kinds that carry a downloadable payload (image / file / video /
- // mixed), and a voice note whose recognition came back empty.
- // Rather than drop them silently — which reads as a broken bot —
- // answer the same chat with a one-line "text only" receipt, then
- // stop. Media routing, and dedup'd receipts that never double-answer
- // a WeCom delivery retry, are a follow-up. Best-effort: a send
- // failure degrades to the prior silent drop.
- log.Debug("wecom: unroutable message, replying text-only", "msg_type", mc.MsgType, "msg_id", mc.MsgID)
- if err := sender.sendText(msg.Source.ChatID, aibotChatTypeFromChannel(msg.Source.ChatType), "抱歉,我目前只能处理文字消息。"); err != nil {
- log.Debug("wecom: text-only receipt send failed", "error", err, "msg_id", mc.MsgID)
+ text, ok := mc.ownText()
+ // Traced with the RESOLVED body, not mc.Text.Content: that field is
+ // empty for every voice, media and 图文混排 callback, so tracing it
+ // would print len=0 for exactly the messages an operator turned
+ // tracing on to look at.
+ traceInbound(log, mc, text)
+ msg := channelMessageFromCallback(c.botID, c.botDisplayName, mc, text, env.Headers.ReqID)
+ if !ok {
+ // Nothing in this message can be read: a kind the adapter does
+ // not know (a location card), or a known kind that arrived
+ // without the one field that makes it usable — a voice note whose
+ // recognition came back empty, an image callback carrying no url.
+ // Silence reads as a broken bot, so answer the same chat with a
+ // one-line receipt and stop. Best-effort: a send failure degrades
+ // to the prior silent drop.
+ log.Debug("wecom: unsupported message kind, replying with a receipt", "msg_type", mc.MsgType, "msg_id", mc.MsgID)
+ if err := sender.sendText(msg.Source.ChatID, aibotChatTypeFromChannel(msg.Source.ChatType), unsupportedMsgTypeReceipt); err != nil {
+ log.Debug("wecom: unsupported-kind receipt send failed", "error", err, "msg_id", mc.MsgID)
}
return nil
}
diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.go
index ac0173c719..1868ae26c3 100644
--- a/server/internal/integrations/wecom/wecom_resolvers.go
+++ b/server/internal/integrations/wecom/wecom_resolvers.go
@@ -48,10 +48,13 @@ func wecomMsgFromRaw(msg channel.InboundMessage) (InboundMessage, error) {
// Typing as a no-op.
//
// The replier is optional: pass nil to disable outbound binding prompts.
+// Media is optional too: pass nil when no object-storage backend is
+// configured, and inbound attachments degrade to their placeholder text.
func NewResolverSet(
store *Store,
session engineSessionBinder,
replier engine.OutboundReplier,
+ media engine.MediaResolver,
) engine.ResolverSet {
set := engine.ResolverSet{
Installation: &installationResolver{store: store},
@@ -60,6 +63,13 @@ func NewResolverSet(
Session: &sessionBinder{session: session},
Audit: &auditor{store: store},
OriginType: originWecomChat,
+ // Assigned straight through: media is already an interface, so a nil
+ // argument lands as a nil interface and the Router's `set.Media !=
+ // nil` guard holds. (DingTalk guards the same assignment with an if,
+ // which is redundant for that same reason — its media parameter is an
+ // engine.MediaResolver too. The typed-nil hazard there is on the if
+ // above it, where ack is a concrete *ackNotifier.)
+ Media: media,
}
if replier != nil {
set.Replier = replier
@@ -75,6 +85,7 @@ type engineSessionBinder interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
+ BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
// ---- installation routing ----
@@ -238,17 +249,35 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
MessageID: p.Message.MessageID,
ClaimToken: p.ClaimToken,
ForceFresh: p.Message.ForceFresh,
+ // How long the chat task waits before it runs. Without this the run
+ // fires the moment the message lands and the agent is handed the
+ // "[Image]" placeholder while the download is still going.
+ MediaPendingSeconds: p.MediaPendingSeconds,
})
}
-// BindMedia is a no-op for wecom. The wecom ResolverSet registers no
-// MediaResolver, so the Router never resolves media for a wecom message
-// (resolveMedia stays false) and this method is never called at runtime; it
-// exists only to satisfy engine.SessionBinder. If wecom gains inbound media
-// support, wire this to a BindMediaRefs on the session store, mirroring the
-// lark binder.
+// BindMedia attaches the objects the resolver stored to the message they came
+// with. Until the media resolver existed this was correctly a no-op — there
+// was nothing to bind — and returning nil reads to the Router as "bound
+// fine", so leaving it that way once media resolves means every attachment is
+// downloaded, decrypted, stored, and then silently discarded.
+//
+// IssueID is what makes an /issue turn's attachments belong to the issue
+// rather than to the chat message that created it; the other issue fields are
+// what let the description reference them. Feishu passes all of them
+// (lark/feishu_resolvers.go:223).
func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
- return nil
+ return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ IssueID: p.IssueID,
+ IssueDescriptionBase: p.IssueDescriptionBase,
+ IssueCommandText: p.IssueCommandText,
+ Body: p.Body,
+ MediaRefs: p.MediaRefs,
+ })
}
// ---- audit ----
diff --git a/server/internal/integrations/wecom/ws_frame.go b/server/internal/integrations/wecom/ws_frame.go
index 5a5eca63b1..47f4d3671f 100644
--- a/server/internal/integrations/wecom/ws_frame.go
+++ b/server/internal/integrations/wecom/ws_frame.go
@@ -91,26 +91,232 @@ type aibotMsgCallback struct {
Voice struct {
Content string `json:"content"`
} `json:"voice"`
- // Image / file / video / mixed have their own fields and carry a
- // downloadable payload; they are not surfaced yet.
+ // Image / File / Video are the downloadable kinds. Each carries only a
+ // pre-signed COS url and the key its bytes are encrypted with — no name,
+ // no size, no MIME type (see media_download.go for where those come from
+ // instead).
+ Image mediaBody `json:"image"`
+ File mediaBody `json:"file"`
+ Video mediaBody `json:"video"`
+ // Mixed carries 图文混排 — a message the user composed with text runs
+ // and attachments interleaved. Each item is itself typed and carries the
+ // same bodies a standalone message of that type would.
+ Mixed struct {
+ MsgItem []mixedItem `json:"msg_item"`
+ } `json:"mixed"`
}
-// bodyText is the message's text, whether it was typed or spoken. Recognition
-// comes back empty on background noise or a half-second press, and an empty
-// body would reach the agent as a turn with nothing in it — so an empty
-// transcript reports false and takes the receipt path instead.
-func (mc aibotMsgCallback) bodyText() (string, bool) {
+// mediaBody is the {url, aeskey} pair every downloadable kind carries. In
+// long-connection mode the key is minted per url, so it lives on the message
+// rather than in configuration.
+type mediaBody struct {
+ URL string `json:"url"`
+ AESKey string `json:"aeskey"`
+}
+
+// mixedItem is one run of a 图文混排 message: a sentence, a spoken sentence,
+// or an attachment, in the order the user composed them.
+type mixedItem struct {
+ MsgType string `json:"msgtype"`
+ Text struct {
+ Content string `json:"content"`
+ } `json:"text"`
+ Voice struct {
+ Content string `json:"content"`
+ } `json:"voice"`
+ Image mediaBody `json:"image"`
+ File mediaBody `json:"file"`
+ Video mediaBody `json:"video"`
+}
+
+// words is the part of one 图文混排 run the SENDER typed or said. An
+// attachment contributes nothing, which is the difference between this and
+// render below.
+func (item mixedItem) words() string {
+ switch strings.ToLower(item.MsgType) {
+ case "text":
+ return strings.TrimSpace(item.Text.Content)
+ case "voice":
+ // WeCom runs the speech recognition on its side and delivers only
+ // the result, so a voice run is a sentence that happened to be
+ // spoken — no download, no key. It is the sender's own words, so a
+ // spoken "/issue 登录坏了" is a command like the typed one.
+ return strings.TrimSpace(item.Voice.Content)
+ default:
+ return ""
+ }
+}
+
+// render turns one 图文混排 run into the line it contributes to the message
+// body. An item of a kind this adapter does not know contributes nothing
+// rather than a stray placeholder.
+func (item mixedItem) render() string {
+ if s := item.words(); s != "" {
+ return s
+ }
+ body, kind, ok := mediaFor(item.MsgType, item.Image, item.File, item.Video)
+ if !ok || strings.TrimSpace(body.URL) == "" {
+ return ""
+ }
+ return mediaPlaceholder(kind)
+}
+
+// mediaPlaceholder is the marker that stands in for an attachment in the
+// stored message body, so the agent can see that something was attached
+// before (or instead of) the bytes arriving on the detached media path.
+//
+// The exact strings are Lark's and DingTalk's, byte for byte:
+// lark/content_flatten.go flattenContent returns "[Image]" / "[File]" /
+// "[Video]", and dingtalk/inbound.go:95 pins dingtalkImagePlaceholder =
+// "[Image]" with "[File]" at inbound.go:205. An agent reads every channel
+// through the same prompt; a wecom-only spelling would be one more thing
+// for it to learn for no reason.
+func mediaPlaceholder(kind channel.MsgType) string {
+ switch kind {
+ case channel.MsgTypeImage:
+ return "[Image]"
+ case channel.MsgTypeVideo:
+ return "[Video]"
+ default:
+ return "[File]"
+ }
+}
+
+// mediaFor returns the body and normalized kind for a raw wecom msgtype, and
+// whether that type is one we download at all.
+func mediaFor(msgType string, image, file, video mediaBody) (mediaBody, channel.MsgType, bool) {
+ switch strings.ToLower(msgType) {
+ case "image":
+ return image, channel.MsgTypeImage, true
+ case "file":
+ return file, channel.MsgTypeFile, true
+ case "video":
+ return video, channel.MsgTypeVideo, true
+ default:
+ return mediaBody{}, channel.MsgTypeUnknown, false
+ }
+}
+
+// attachments lists the downloadable media on this callback, in the order the
+// user sent it. A body with no url is skipped: there is nothing to fetch, and
+// carrying it forward would only produce an intent-ledger row for an object
+// that can never exist.
+func (mc aibotMsgCallback) attachments() []InboundMedia {
+ var out []InboundMedia
+ add := func(body mediaBody, kind channel.MsgType) {
+ if strings.TrimSpace(body.URL) == "" {
+ return
+ }
+ out = append(out, InboundMedia{Kind: kind, URL: body.URL, AESKey: body.AESKey})
+ }
+ if body, kind, ok := mediaFor(mc.MsgType, mc.Image, mc.File, mc.Video); ok {
+ add(body, kind)
+ return out
+ }
+ if !strings.EqualFold(mc.MsgType, "mixed") {
+ return nil
+ }
+ for _, item := range mc.Mixed.MsgItem {
+ if body, kind, ok := mediaFor(item.MsgType, item.Image, item.File, item.Video); ok {
+ add(body, kind)
+ }
+ }
+ return out
+}
+
+// ownText is the agent-readable body of this callback, and whether there is
+// one at all.
+//
+// Plain text answers with its body; a voice note answers with the transcript
+// WeCom recognised, which is the sender's own words and needs no download; a
+// photo, file or video answers with a bracketed placeholder, because the bytes
+// arrive later on a detached path and the message has to say something in the
+// meantime (the placeholder is also what survives if the download never
+// succeeds); 图文混排 answers with its runs rendered in the order they were
+// composed, so "look at this" still reads above the picture it was written
+// about.
+//
+// Recognition comes back empty on background noise or a half-second press, and
+// an empty body would reach the agent as a turn with nothing in it — so an
+// empty transcript answers false and takes the receipt path, exactly like a
+// location card or a kind WeCom adds next year.
+func (mc aibotMsgCallback) ownText() (string, bool) {
switch strings.ToLower(mc.MsgType) {
case "text":
return mc.Text.Content, true
case "voice":
transcript := strings.TrimSpace(mc.Voice.Content)
return transcript, transcript != ""
+ case "image", "file", "video":
+ body, kind, _ := mediaFor(mc.MsgType, mc.Image, mc.File, mc.Video)
+ if strings.TrimSpace(body.URL) == "" {
+ return "", false
+ }
+ return mediaPlaceholder(kind), true
+ case "mixed":
+ var runs []string
+ for _, item := range mc.Mixed.MsgItem {
+ if s := item.render(); s != "" {
+ runs = append(runs, s)
+ }
+ }
+ if len(runs) == 0 {
+ return "", false
+ }
+ return strings.Join(runs, "\n"), true
default:
return "", false
}
}
+// ownCommandSource is what the slash-command parsers read: the sender's own
+// words, and nothing this adapter wrote.
+//
+// It is not ownText. ownText inserts "[Image]" / "[File]" / "[Video]" where
+// the attachments were, because the stored body has to show that something
+// was attached and where. engine.ParseIssueCommand only ever looks at the
+// FIRST non-empty line, so a person who attaches a screenshot and then types
+// "/issue 登录坏了" — the natural order, and the one WeCom's composer
+// encourages — produces a body opening with "[Image]", the parser sees a
+// placeholder instead of the command, no issue is filed, and nothing anywhere
+// tells them why. Typing the same two things in the other order works. That
+// is not a distinction a user can be expected to know about.
+//
+// So the command source drops the placeholders and keeps the runs the sender
+// authored, in order. The stored body still carries them: cutting them there
+// would lose the position the detached media binder materializes into
+// (engine/issue_command.go issueDescriptionFromCommandBody says the same
+// thing from the other end).
+//
+// A spoken message answers with its transcript. Those are the sender's own
+// words as much as a typed line is, so "/issue 登录坏了" said out loud files
+// the same issue it would have typed — and sourcing the command from the typed
+// field instead would leave it empty, at which point the engine falls back to
+// Text, files the issue anyway and, with SkipAgentRun false, runs the agent
+// over it as well.
+//
+// A standalone photo, file or video answers with nothing. Its whole body is a
+// placeholder, so there are no words in it to parse, and handing the parser a
+// string the sender never typed is the defect this exists to remove.
+func (mc aibotMsgCallback) ownCommandSource() string {
+ switch strings.ToLower(mc.MsgType) {
+ case "text":
+ return mc.Text.Content
+ case "voice":
+ return strings.TrimSpace(mc.Voice.Content)
+ case "mixed":
+ var runs []string
+ for _, item := range mc.Mixed.MsgItem {
+ if s := item.words(); s != "" {
+ runs = append(runs, s)
+ }
+ }
+ return strings.Join(runs, "\n")
+ default:
+ return ""
+ }
+}
+
// aibotEventCallback is the body of an aibot_event_callback frame. We only
// look at the event type; specific event fields (template-card selection,
// feedback vote) are not surfaced yet.
@@ -151,16 +357,35 @@ type InboundMessage struct {
// SenderUserID is the userid of the person who typed the message.
SenderUserID string `json:"sender_user_id,omitempty"`
- // Content is the human-readable body of the message — what was typed
- // for MsgType == "text", what WeCom's recognition returned for
- // MsgType == "voice". Empty for the downloadable kinds and for events.
- // The cross-platform envelope's Text field is populated from this.
+ // Content is the human-readable body: the user's words — typed, or as
+ // WeCom's recognition returned them for a voice note — and the
+ // placeholders standing in for their attachments. The cross-platform
+ // envelope's Text field is populated from this.
Content string `json:"content,omitempty"`
// ReqID is the frame req_id the server sent this message with. We
// keep it so a future aibot_respond_msg (5s window) can echo it back;
// iteration 1 uses aibot_send_msg unconditionally and does not need it.
ReqID string `json:"req_id,omitempty"`
+
+ // Media lists the attachments to fetch, in the order the user sent them.
+ // It is the MediaResolver's input and travels only in
+ // channel.InboundMessage.Raw, which the engine passes along in memory and
+ // never persists — the urls lapse after five minutes and the keys are
+ // single-use, so neither belongs in a table or a log line.
+ Media []InboundMedia `json:"media,omitempty"`
+}
+
+// InboundMedia is one downloadable attachment on a callback.
+type InboundMedia struct {
+ // Kind is the normalized media type the attachment row is labelled with.
+ Kind channel.MsgType `json:"kind"`
+ // URL is the pre-signed COS address, good for five minutes, needing no
+ // access token.
+ URL string `json:"url"`
+ // AESKey unlocks what comes back from URL. Long-connection mode mints one
+ // per url; see media_crypt.go.
+ AESKey string `json:"aeskey"`
}
// channelMessageFromCallback converts a wecom-side aibot_msg_callback into
@@ -176,11 +401,16 @@ type InboundMessage struct {
// group message on the wire — WeCom only forwards to the bot when it was
// addressed, so any received group message counts as addressed.
//
+// text is the agent-readable body the caller already resolved via ownText.
+// It is passed in rather than recomputed because the caller has to know
+// whether the message is routable at all before it gets here. The command
+// source is a different string and is derived here from mc — see
+// ownCommandSource for why they must not be the same one.
+//
// botDisplayName is the bot's name in a chat, from the installation config. It
// is used for one thing: recognising where the sender's @-mention ends. Empty
// is fine and falls back to a whitespace heuristic; see stripLeadingMentions.
-func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallback, reqID string) channel.InboundMessage {
- body, _ := mc.bodyText()
+func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallback, text, reqID string) channel.InboundMessage {
chatType := channel.ChatTypeP2P
if strings.EqualFold(mc.ChatType, "group") {
chatType = channel.ChatTypeGroup
@@ -192,25 +422,26 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
chatID = senderID
}
- // The command source is the sender's own words. In a group the @-mention IS
- // how you reach the bot, so it arrives glued to whatever was typed after it
- // — "@Andrew /new" is a person asking for a fresh session, not prose that
- // happens to contain a word — and the addressing comes off the front.
+ // The command source is the sender's own words — ownCommandSource, not the
+ // resolved body, so a 图文混排 whose first run is a screenshot still has
+ // its "/issue …" on the first line the parser reads.
+ //
+ // In a group the @-mention IS how you reach the bot, so it arrives glued to
+ // whatever was typed after it — "@Andrew /new" is a person asking for a
+ // fresh session, not prose that happens to contain a word — and the
+ // addressing comes off the front.
//
// Groups only. In a 1:1 nobody has to address the bot, so a leading "@" is
// the sender naming a colleague they are talking ABOUT: "@李雷 /issue 帮我
// 问问他" is a question, and stripping the name would turn it into a filed
// issue nobody asked for plus, via SkipAgentRun below, no answer at all.
- // Passing the raw content through keeps p2p exactly where it was before
- // CommandText was set here.
//
- // Read off bodyText, not Text.Content: a spoken "/issue …" carries the
- // words in voice.content, and sourcing the command from the typed field
- // would leave it empty — the engine would then fall back to Text, file the
- // issue and, with SkipAgentRun false, run the agent over it as well.
- command := body
+ // For a plain text message this is mc.Text.Content, which is what p2p was
+ // passing through before CommandText was set here; for a voice note it is
+ // the transcript, so a spoken command is a command.
+ command := mc.ownCommandSource()
if chatType == channel.ChatTypeGroup {
- command = stripLeadingMentions(body, botDisplayName)
+ command = stripLeadingMentions(command, botDisplayName)
}
wm := InboundMessage{
@@ -220,8 +451,9 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
ChatType: mc.ChatType,
ChatID: chatID,
SenderUserID: senderID,
- Content: body,
+ Content: text,
ReqID: reqID,
+ Media: mc.attachments(),
}
raw, _ := json.Marshal(wm)
@@ -229,16 +461,16 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
EventID: mc.MsgID,
MessageID: mc.MsgID,
Type: channelMsgType(mc.MsgType),
- Text: body,
+ Text: text,
AddressedToBot: true,
- // The sender's own words, with a group's addressing removed. Command
- // classification is shared (channel/message.go) and falls back to Text
- // when this is empty — and in a group Text starts with the mention, so
- // every slash command read as ordinary prose. Lark sets this from its
- // command body (feishu_channel.go:139) and Slack from its cleaned text
+ // The sender's own words, with a group's addressing removed and the
+ // media placeholders left out. Command classification is shared
+ // (channel/message.go) and falls back to Text when this is empty — and
+ // Text starts with the mention in a group, and with "[Image]" whenever
+ // a screenshot came first, so on that fallback every such slash command
+ // read as ordinary prose. Lark sets this from its command body
+ // (feishu_channel.go:139) and Slack from its cleaned text
// (slack/inbound.go:131); WeCom was the one adapter leaving it empty.
- // In a p2p chat this is Text verbatim, which is what the fallback was
- // already producing.
CommandText: command,
// A pure /issue command in WeCom should NOT trigger the
// agent — the engine already creates the issue and the
@@ -252,7 +484,10 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
// behaves like the p2p one instead of filing the issue and then also
// asking the agent about it. It has to be the same source: read off the
// raw text instead and a p2p "@李雷 /issue …" would file an issue and
- // stay silent, which is the whole reason the strip above is gated.
+ // stay silent, which is the whole reason the strip above is gated; read
+ // off the resolved body instead and a screenshot-then-"/issue" message
+ // would skip the agent while the parser declined the placeholder line,
+ // leaving the sender with neither an issue nor an answer.
SkipAgentRun: isIssueCommand(command),
Source: channel.Source{
ChannelType: TypeWecom,
@@ -345,13 +580,27 @@ func channelMsgType(wecomType string) channel.MsgType {
return channel.MsgTypeAudio
case "video":
return channel.MsgTypeVideo
+ case "mixed":
+ // 图文混排: text runs and attachments interleaved. It maps to Text
+ // because the message IS text once ownText has rendered it — runs in
+ // composition order, each attachment standing in as its placeholder —
+ // and the attachments travel separately as MediaRefs, exactly as they
+ // do for Lark's `post`, the same shape under another name:
+ // lark/feishu_channel.go:167 maps post → MsgTypeText while
+ // lark/media_ingest.go:272 pulls that same post's img/media spans.
+ //
+ // This line previously read Unknown, and the comment there was right
+ // for the code that existed: dispatchFrame routed only the kinds
+ // that arrived as words, so a mixed message never reached
+ // normalization and calling it Text would have claimed a routing that
+ // did not happen. That claim is what this change makes true. The two
+ // must land together — mapping to Text without the routing is the
+ // dead, misleading mapping the old comment warned about.
+ return channel.MsgTypeText
default:
- // Includes "mixed" (text + media): dispatchFrame routes the kinds
- // bodyText answers for — "text", and "voice" with a non-empty
- // transcript — so anything else is answered with the text-only
- // receipt and never reaches this normalization. Kept as Unknown
- // rather than mapping "mixed" → Text, which was dead and implied
- // mixed messages were routed as text when they are not.
+ // A kind the adapter cannot read at all. dispatchFrame answers it
+ // with the unsupported-kind receipt and stops, so this normalization
+ // is never reached for one.
return channel.MsgTypeUnknown
}
}
diff --git a/server/internal/integrations/wecom/ws_frame_test.go b/server/internal/integrations/wecom/ws_frame_test.go
index c0b62ad25e..4aa6bcf97a 100644
--- a/server/internal/integrations/wecom/ws_frame_test.go
+++ b/server/internal/integrations/wecom/ws_frame_test.go
@@ -23,7 +23,7 @@ func TestChannelMessageFromCallback_GroupKeepsSenderDistinctFromChat(t *testing.
mc.From.UserID = "SENDER_USERID"
mc.Text.Content = "hello"
- msg := channelMessageFromCallback("bot-1", "", mc, "req-1")
+ msg := channelMessageFromCallback("bot-1", "", mc, "hello", "req-1")
if msg.Source.ChatType != channel.ChatTypeGroup {
t.Errorf("chat type = %v, want group", msg.Source.ChatType)
@@ -43,7 +43,7 @@ func TestChannelMessageFromCallback_P2PFallsBackChatIDToSender(t *testing.T) {
mc := aibotMsgCallback{MsgID: "m2", ChatID: "", ChatType: "single", MsgType: "text"}
mc.From.UserID = "USER_A"
- msg := channelMessageFromCallback("bot-1", "", mc, "req-2")
+ msg := channelMessageFromCallback("bot-1", "", mc, "", "req-2")
if msg.Source.ChatType != channel.ChatTypeP2P {
t.Errorf("chat type = %v, want p2p", msg.Source.ChatType)
@@ -77,7 +77,7 @@ func TestChannelMessageFromCallback_P2PMentionIsProseNotACommand(t *testing.T) {
// A configured display name must not change this either: it is the
// chat type that decides, not whose name is at the front.
- msg := channelMessageFromCallback("bot-1", "Multica Bot", mc, "req-p2p")
+ msg := channelMessageFromCallback("bot-1", "Multica Bot", mc, tc.content, "req-p2p")
if msg.CommandText != tc.content {
t.Errorf("CommandText = %q, want %q untouched — in a 1:1 the leading @ is a colleague's "+
@@ -107,7 +107,7 @@ func TestChannelMessageFromCallback_P2PCommandStillWorks(t *testing.T) {
mc.From.UserID = "USER_A"
mc.Text.Content = "/issue 登录失败"
- msg := channelMessageFromCallback("bot-1", "Multica Bot", mc, "req-p2p-cmd")
+ msg := channelMessageFromCallback("bot-1", "Multica Bot", mc, mc.Text.Content, "req-p2p-cmd")
cmd, ok := engine.ParseIssueCommand(msg.CommandText)
if !ok {
@@ -121,7 +121,7 @@ func TestChannelMessageFromCallback_P2PCommandStillWorks(t *testing.T) {
}
}
-func TestChannelMsgType_NonTextIsUnknown(t *testing.T) {
+func TestChannelMsgType_Normalization(t *testing.T) {
t.Parallel()
cases := map[string]channel.MsgType{
"text": channel.MsgTypeText,
@@ -130,9 +130,11 @@ func TestChannelMsgType_NonTextIsUnknown(t *testing.T) {
"voice": channel.MsgTypeAudio,
"audio": channel.MsgTypeAudio,
"video": channel.MsgTypeVideo,
- // "mixed" must NOT map to Text: dispatchFrame drops non-text before
- // normalization, so mapping it to Text was dead and misleading.
- "mixed": channel.MsgTypeUnknown,
+ // 图文混排 is Text: ownText renders it to text runs plus a
+ // placeholder per attachment, and the attachments travel separately
+ // as MediaRefs. Same treatment Lark gives `post`
+ // (lark/feishu_channel.go:167).
+ "mixed": channel.MsgTypeText,
"": channel.MsgTypeUnknown,
"greetings": channel.MsgTypeUnknown,
}