Skip to content

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

Go

MUL-6193 Support Slack message attachments in chat (#6975)

Tim9f85d72a06a6
diff --git a/apps/docs/content/docs/slack-bot-integration.ja.mdx b/apps/docs/content/docs/slack-bot-integration.ja.mdx
index b98ec890a0..73d85bc296 100644
--- a/apps/docs/content/docs/slack-bot-integration.ja.mdx
+++ b/apps/docs/content/docs/slack-bot-integration.ja.mdx
@@ -40,6 +40,7 @@ oauth_config:
bot:
- app_mentions:read
- channels:history
+ - files:read
- groups:history
- im:history
- mpim:history
@@ -64,6 +65,10 @@ settings:
作成前に、2 か所の `Multica` をエージェント名に変更してもかまいません。manifest の権限やイベントは削除しないでください。削除すると、DM、チャンネルでのメンション、返信、`/issue` が動作しないことがあります。
+<Callout type="warning">
+添付ファイル対応が追加される前にこの Slack app をインストールしていた場合は、Bot scope に `files:read` を追加し、workspace に app を再インストールしてください。app を再インストールするまで、新しい scope は既存の Bot token に反映されません。
+</Callout>
+
Bot は Socket Mode で Slack へ接続するため、公開 Request URL や OAuth Redirect URL の設定は不要です。
## 2. 2 つの token を取得する
@@ -114,6 +119,12 @@ Slack サイドバーの **Apps** から Bot を開き、そのままメッセ
Bot が応答するのは、明示的に @メンションされたチャンネルメッセージだけです。実行時には、権限の範囲内でそのスレッドの直近のコンテキストを読み取ります。
+### ファイルを送る
+
+DM、または Bot を @ メンションしたチャンネルのメッセージに、そのままファイルを添付します。ファイルは同じ作業の添付ファイルとして届くので、エージェントは依頼内容と合わせて読み取れます。
+
+これには `files:read` scope が必要です。添付ファイル対応より前にインストールした app の場合は、手順 1 の注意書きを参照してください。1 ファイルあたり 20 MiB 以下、1 メッセージにつき最大 10 件です。サイズ超過、アップロード処理中、または Slack 以外(Google Drive や Dropbox のリンクなど)にあるファイルはスキップされますが、メッセージ本文はエージェントに渡ります。
+
### `/issue` でイシューを作成する
チャンネルまたは DM で、次のように入力します。
@@ -155,6 +166,7 @@ API サービスを再起動してから Slack app を接続します。この
- **DM の入口がない**: `app_home.messages_tab_enabled` が `true` であることを確認します。
- **チャンネルで返信がない**: Bot がチャンネルに招待されており、メッセージで @メンションされていることを確認します。
- **`/issue` がない**: manifest に slash command と `commands` scope が含まれていることを確認し、app を再インストールします。
+- **ファイルがエージェントに届かない**: manifest に `files:read` が含まれていること、scope を追加した後に app を再インストールしたことを確認し、ファイルが 20 MiB 以下かも確認します。
- **Bot が実行しない**: エージェントがアーカイブされていないことと、使用する[ランタイム](/daemon-runtimes)がオンラインであることを確認します。
## 次のステップ
diff --git a/apps/docs/content/docs/slack-bot-integration.ko.mdx b/apps/docs/content/docs/slack-bot-integration.ko.mdx
index 3195ca002d..9f3f0566e9 100644
--- a/apps/docs/content/docs/slack-bot-integration.ko.mdx
+++ b/apps/docs/content/docs/slack-bot-integration.ko.mdx
@@ -40,6 +40,7 @@ oauth_config:
bot:
- app_mentions:read
- channels:history
+ - files:read
- groups:history
- im:history
- mpim:history
@@ -64,6 +65,10 @@ settings:
만들기 전에 두 `Multica` 값을 에이전트 이름으로 바꿀 수 있습니다. manifest의 권한이나 이벤트를 삭제하지 마세요. 삭제하면 DM, 채널 멘션, 답글, `/issue`가 작동하지 않을 수 있습니다.
+<Callout type="warning">
+첨부 파일 지원이 추가되기 전에 이 Slack app을 설치했다면 Bot scope에 `files:read`를 추가하고 workspace에 app을 다시 설치하세요. app을 다시 설치하기 전에는 새 scope가 기존 Bot token에 적용되지 않습니다.
+</Callout>
+
Bot은 Socket Mode로 Slack에 능동적으로 연결하므로 공개 Request URL이나 OAuth Redirect URL을 설정할 필요가 없습니다.
## 2. 두 token 받기
@@ -114,6 +119,12 @@ Slack 사이드바의 **Apps**에서 Bot을 열고 바로 메시지를 보냅니
Bot은 자신을 명시적으로 @멘션한 채널 메시지에만 응답합니다. 실행할 때 권한 범위 안에서 해당 thread의 최근 컨텍스트를 읽습니다.
+### 파일 보내기
+
+DM이나 Bot을 @멘션한 채널 메시지에 파일을 그대로 첨부하세요. 파일은 같은 작업의 첨부 파일로 전달되므로 에이전트가 요청 내용과 함께 읽을 수 있습니다.
+
+이 기능에는 `files:read` scope가 필요합니다. 첨부 파일 지원 이전에 설치한 app이라면 1단계의 안내를 참고하세요. 파일 하나는 20 MiB 이하여야 하고 메시지 하나에 최대 10개까지 담깁니다. 용량을 초과했거나 아직 업로드 중이거나 Slack 외부에 있는 파일(예: Google Drive, Dropbox 링크)은 건너뛰며, 메시지 본문은 그대로 에이전트에 전달됩니다.
+
### `/issue`로 이슈 만들기
채널이나 DM에서 다음을 입력합니다.
@@ -155,6 +166,7 @@ API 서비스를 다시 시작한 뒤 Slack app을 연결하세요. 이 키는
- **DM 메뉴가 없음**: `app_home.messages_tab_enabled`가 `true`인지 확인합니다.
- **채널에서 답변이 없음**: Bot이 채널에 초대되었고 메시지에서 @멘션했는지 확인합니다.
- **`/issue`가 없음**: manifest에 slash command와 `commands` scope가 포함되어 있는지 확인하고 app을 다시 설치합니다.
+- **파일이 에이전트에 도착하지 않음**: manifest에 `files:read`가 포함되어 있는지, scope를 추가한 뒤 app을 다시 설치했는지 확인하고, 파일이 20 MiB 이하인지도 확인합니다.
- **Bot이 실행되지 않음**: 에이전트가 보관 처리되었는지, 사용하는 [런타임](/daemon-runtimes)이 온라인인지 확인합니다.
## 다음 단계
diff --git a/apps/docs/content/docs/slack-bot-integration.mdx b/apps/docs/content/docs/slack-bot-integration.mdx
index 3b4399c5fd..87aad9fca2 100644
--- a/apps/docs/content/docs/slack-bot-integration.mdx
+++ b/apps/docs/content/docs/slack-bot-integration.mdx
@@ -40,6 +40,7 @@ oauth_config:
bot:
- app_mentions:read
- channels:history
+ - files:read
- groups:history
- im:history
- mpim:history
@@ -64,6 +65,10 @@ settings:
Before creating, you can replace both occurrences of `Multica` with the agent's name. Do not remove scopes or events from the manifest, or DMs, channel mentions, replies, or `/issue` may stop working.
+<Callout type="warning">
+If this Slack app was installed before attachment support was available, add the `files:read` Bot scope and reinstall the app to the workspace. Slack does not apply newly added scopes to the existing Bot token until the app is reinstalled.
+</Callout>
+
The Bot connects out to Slack over Socket Mode, so no public Request URL or OAuth Redirect URL is needed.
## 2. Get the two tokens
@@ -116,6 +121,12 @@ Run `/invite @your-bot` to add the Bot to the channel first, then send `@your-bo
The Bot only responds to channel messages that explicitly @-mention it. When it runs, it reads the thread's recent context within the scopes its permissions allow.
+### Send files
+
+Attach files to a DM, or to a channel message that @-mentions the Bot. They arrive as attachments on the same piece of work, so the agent reads them together with your request.
+
+This needs the `files:read` scope — if the app was installed before attachment support existed, see the note in step 1. Each file must be 20 MiB or smaller, and one message carries at most 10. Files that are larger, still uploading, or hosted outside Slack (a Google Drive or Dropbox link, for example) are skipped; the message text still reaches the agent.
+
### Create issues with `/issue`
In a channel or DM, type:
@@ -157,6 +168,7 @@ Account binding links use `MULTICA_APP_URL`, falling back to `FRONTEND_ORIGIN` w
- **No DM entry point**: confirm `app_home.messages_tab_enabled` is `true`.
- **No reply in a channel**: confirm the Bot has been invited to the channel and the message @-mentions it.
- **`/issue` doesn't exist**: confirm the manifest includes the slash command and the `commands` scope, then reinstall the app.
+- **Files don't reach the agent**: confirm the manifest includes `files:read` and that the app was reinstalled after the scope was added, and check the file is 20 MiB or smaller.
- **The Bot doesn't run**: check whether the agent is archived and whether the [runtime](/daemon-runtimes) it uses is online.
## Next steps
diff --git a/apps/docs/content/docs/slack-bot-integration.zh.mdx b/apps/docs/content/docs/slack-bot-integration.zh.mdx
index 536cc7487f..8a6b667591 100644
--- a/apps/docs/content/docs/slack-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/slack-bot-integration.zh.mdx
@@ -40,6 +40,7 @@ oauth_config:
bot:
- app_mentions:read
- channels:history
+ - files:read
- groups:history
- im:history
- mpim:history
@@ -64,6 +65,10 @@ settings:
创建前可以把两个 `Multica` 改成智能体的名字。不要删除 manifest 中的权限或事件,否则私聊、频道提及、回复或 `/issue` 可能无法工作。
+<Callout type="warning">
+如果这个 Slack app 是在附件支持上线前安装的,请添加 `files:read` Bot scope,并将 app 重新安装到 workspace。在重新安装 app 前,新增 scope 不会应用到现有 Bot token。
+</Callout>
+
Bot 使用 Socket Mode 主动连接 Slack,不需要配置公网 Request URL 或 OAuth Redirect URL。
## 2. 获取两个 token
@@ -116,6 +121,12 @@ Multica 会验证两个 token 是否来自同一个 app。连接成功后,页
Bot 只会响应明确 @ 它的频道消息。执行时,它会在权限允许的范围内读取该 thread 的近期上下文。
+### 发送文件
+
+在私聊里,或者在 @ 提及 Bot 的频道消息里直接带上文件。文件会作为附件进入同一项工作,智能体可以结合文件和你的诉求一起处理。
+
+这需要 `files:read` 权限 —— 如果这个应用是在附件支持之前安装的,参考第 1 步的提示。单个文件不超过 20 MiB,一条消息最多带 10 个。超出大小、仍在上传,或者存放在 Slack 之外(比如 Google Drive、Dropbox 链接)的文件会被跳过,消息文本仍然会交给智能体。
+
### 用 `/issue` 创建 issue
在频道或私聊中输入:
@@ -157,6 +168,7 @@ openssl rand -base64 32
- **私聊没有入口**:确认 `app_home.messages_tab_enabled` 为 `true`。
- **频道里没有回复**:确认 Bot 已被邀请进频道,并在消息中 @ 了它。
- **`/issue` 不存在**:确认 manifest 包含 slash command 和 `commands` scope,随后重新安装 app。
+- **文件没有送达智能体**:确认 manifest 里包含 `files:read`,并且在添加该权限后重新安装过应用,同时确认文件不超过 20 MiB。
- **Bot 不执行**:检查智能体是否已归档,以及它使用的[运行时](/daemon-runtimes)是否在线。
## 接下来
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index ac1e958227..329fc31959 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -547,7 +547,19 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// reaction on a failed run, which the outbound replier does not handle.
slackTyping := slack.NewTypingIndicatorManager(queries, box.Open, slog.Default())
slackTyping.Register(bus)
- channelRouter.Register(slack.TypeSlack, slack.NewSlackResolverSet(queries, pool, slackReplier, slackTyping))
+ // Slack attachments require object storage because each chat
+ // attachment points to an uploaded object. When storage is disabled,
+ // leave the media resolver unset and ingest Slack messages as text.
+ var slackMedia engine.MediaResolver
+ if store != nil {
+ slackMedia = slack.NewMediaResolver(
+ box.Open,
+ store,
+ engine.NewDBMediaIntentLedger(queries),
+ slog.Default(),
+ )
+ }
+ channelRouter.Register(slack.TypeSlack, slack.NewSlackResolverSet(queries, pool, slackReplier, slackTyping, slackMedia))
slack.NewOutbound(queries, box.Open, slog.Default()).Register(bus)
// On-demand history reader behind the unified `multica chat history`
diff --git a/server/internal/integrations/slack/inbound.go b/server/internal/integrations/slack/inbound.go
index 8390ce37ff..e0dccaa100 100644
--- a/server/internal/integrations/slack/inbound.go
+++ b/server/internal/integrations/slack/inbound.go
@@ -5,6 +5,7 @@ import (
"regexp"
"strings"
+ "github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -20,11 +21,52 @@ import (
// does not — read back only inside the Slack resolvers (team_id routes the
// installation; the core never reads Raw).
type slackRawEvent struct {
- TeamID string `json:"team_id"`
- APIAppID string `json:"api_app_id,omitempty"`
- EventType string `json:"event_type"`
- SubType string `json:"subtype,omitempty"`
- ChannelType string `json:"channel_type,omitempty"`
+ TeamID string `json:"team_id"`
+ APIAppID string `json:"api_app_id,omitempty"`
+ EventType string `json:"event_type"`
+ SubType string `json:"subtype,omitempty"`
+ ChannelType string `json:"channel_type,omitempty"`
+ Files []slackRawFile `json:"files,omitempty"`
+}
+
+// slackRawFile is the subset of a Slack file object the media resolver needs
+// to fetch the file later, off the connector ACK path. The download URL is a
+// Slack-hosted url_private(_download) that requires the installation's bot
+// token — it is never handed to the core or persisted beyond Raw.
+type slackRawFile struct {
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ Mimetype string `json:"mimetype,omitempty"`
+ Size int64 `json:"size,omitempty"`
+ DownloadURL string `json:"download_url"`
+}
+
+// rawFilesFrom maps the event's file objects to the raw envelope, keeping only
+// files the media resolver could actually fetch: ones with a downloadable URL
+// on a Slack host. That drops uploads still processing (no URL yet) and remote
+// "external" files whose url_private points at Google Drive or Dropbox — the
+// resolver refuses to send the bot token off-domain, so carrying them would
+// only make HasMedia promise media the pipeline can never bind, costing the
+// message a deferred run and an intent-ledger row per doomed download.
+func rawFilesFrom(files []slack.File) []slackRawFile {
+ var out []slackRawFile
+ for _, f := range files {
+ downloadURL := f.URLPrivateDownload
+ if downloadURL == "" {
+ downloadURL = f.URLPrivate
+ }
+ if !isFetchableSlackFileURL(downloadURL) {
+ continue
+ }
+ out = append(out, slackRawFile{
+ ID: f.ID,
+ Name: f.Name,
+ Mimetype: f.Mimetype,
+ Size: int64(f.Size),
+ DownloadURL: downloadURL,
+ })
+ }
+ return out
}
// compileMentionRe builds the regexp that matches an @-mention of botUserID.
@@ -64,6 +106,12 @@ func inboundFromMessage(e slackevents.EventsAPIEvent, m *slackevents.MessageEven
chatType := slackChatType(m.Channel, m.ChannelType)
addressed := chatType == channel.ChatTypeP2P || mentionsBot(m.Text, mentionRe)
+ // File attachments live on the normalized Msg (slackevents copies the
+ // top-level message payload there for brand-new messages).
+ var files []slackRawFile
+ if m.Message != nil {
+ files = rawFilesFrom(m.Message.Files)
+ }
return buildInbound(e, buildInboundParams{
eventType: "message",
subType: m.SubType,
@@ -74,6 +122,7 @@ func inboundFromMessage(e slackevents.EventsAPIEvent, m *slackevents.MessageEven
threadTS: m.ThreadTimeStamp,
chatType: chatType,
addressed: addressed,
+ files: files,
}, mentionRe), true
}
@@ -95,6 +144,7 @@ func inboundFromAppMention(e slackevents.EventsAPIEvent, m *slackevents.AppMenti
threadTS: m.ThreadTimeStamp,
chatType: channel.ChatTypeGroup,
addressed: true,
+ files: rawFilesFrom(m.Files),
}, mentionRe), true
}
@@ -108,6 +158,7 @@ type buildInboundParams struct {
threadTS string
chatType channel.ChatType
addressed bool
+ files []slackRawFile
}
func buildInbound(e slackevents.EventsAPIEvent, p buildInboundParams, mentionRe *regexp.Regexp) channel.InboundMessage {
@@ -117,6 +168,7 @@ func buildInbound(e slackevents.EventsAPIEvent, p buildInboundParams, mentionRe
EventType: p.eventType,
SubType: p.subType,
ChannelType: string(p.chatType),
+ Files: p.files,
})
var reply *channel.ReplyCtx
if p.threadTS != "" && p.threadTS != p.ts {
diff --git a/server/internal/integrations/slack/inbound_test.go b/server/internal/integrations/slack/inbound_test.go
index 77984cf0c7..139bbbb484 100644
--- a/server/internal/integrations/slack/inbound_test.go
+++ b/server/internal/integrations/slack/inbound_test.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"testing"
+ "github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -175,6 +176,115 @@ func TestInboundFromAppMention(t *testing.T) {
}
}
+// Files are read off the normalized Msg, which slack-go's custom unmarshaller
+// populates from the top-level payload for brand-new messages. That behaviour
+// is the whole feature's foundation, so this drives the real decoder rather
+// than hand-building MessageEvent.Message — a struct literal would keep
+// passing if slack-go ever stopped normalizing.
+func TestInboundFromMessage_FileShare(t *testing.T) {
+ payload := `{
+ "token": "z", "team_id": "T1", "api_app_id": "A1", "type": "event_callback", "event_id": "Ev1",
+ "event": {
+ "type": "message", "subtype": "file_share",
+ "channel": "D123", "channel_type": "im",
+ "user": "UALICE", "text": "here is the doc", "ts": "1700000000.000800",
+ "files": [
+ {"id": "F1", "name": "report.pdf", "mimetype": "application/pdf", "size": 42,
+ "url_private": "https://files.slack.com/files-pri/T1-F1/report.pdf",
+ "url_private_download": "https://files.slack.com/files-pri/T1-F1/download/report.pdf"},
+ {"id": "F2", "name": "shot.png", "mimetype": "image/png",
+ "url_private": "https://files.slack.com/files-pri/T1-F2/shot.png"},
+ {"id": "F3", "name": "external.doc"},
+ {"id": "F4", "name": "spec.gdoc", "mode": "external",
+ "url_private": "https://docs.google.com/document/d/abc/edit"}
+ ]
+ }
+ }`
+ e, err := slackevents.ParseEvent(json.RawMessage(payload), slackevents.OptionNoVerifyToken())
+ if err != nil {
+ t.Fatalf("parse event: %v", err)
+ }
+ inner, isMessage := e.InnerEvent.Data.(*slackevents.MessageEvent)
+ if !isMessage {
+ t.Fatalf("inner event = %T, want *slackevents.MessageEvent", e.InnerEvent.Data)
+ }
+ msg, ok := translateMessage("UBOT", e, inner)
+ if !ok {
+ t.Fatal("file_share message should be ingestable")
+ }
+ var raw slackRawEvent
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ t.Fatalf("decode raw: %v", err)
+ }
+ if len(raw.Files) != 2 {
+ t.Fatalf("raw files = %+v, want only F1 and F2 (no URL, and off-Slack, are dropped)", raw.Files)
+ }
+ if raw.Files[0].ID != "F1" || raw.Files[0].Name != "report.pdf" || raw.Files[0].Mimetype != "application/pdf" || raw.Files[0].Size != 42 {
+ t.Errorf("file[0] = %+v", raw.Files[0])
+ }
+ if raw.Files[0].DownloadURL != "https://files.slack.com/files-pri/T1-F1/download/report.pdf" {
+ t.Errorf("file[0] url = %q, want url_private_download", raw.Files[0].DownloadURL)
+ }
+ if raw.Files[1].ID != "F2" || raw.Files[1].DownloadURL != "https://files.slack.com/files-pri/T1-F2/shot.png" {
+ t.Errorf("file[1] = %+v, want url_private fallback", raw.Files[1])
+ }
+}
+
+// A message whose only file lives off Slack must not claim media at all: the
+// resolver could never fetch it, and pretending otherwise defers the run and
+// reserves a storage key for a download that always fails.
+func TestInboundFromMessage_ExternalFilesCarryNoMedia(t *testing.T) {
+ msg, ok := translateMessage("UBOT", eventsAPI(nil), &slackevents.MessageEvent{
+ User: "UALICE",
+ Text: "shared a doc",
+ SubType: "file_share",
+ Channel: "D123",
+ ChannelType: "im",
+ TimeStamp: "1700000000.001000",
+ Message: &slack.Msg{
+ Files: []slack.File{
+ {ID: "F1", Name: "spec.gdoc", Mode: "external", URLPrivate: "https://docs.google.com/document/d/abc/edit"},
+ },
+ },
+ })
+ if !ok {
+ t.Fatal("the message itself is still ingestable as text")
+ }
+ var raw slackRawEvent
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ t.Fatalf("decode raw: %v", err)
+ }
+ if len(raw.Files) != 0 {
+ t.Errorf("raw files = %+v, want none for an off-Slack file", raw.Files)
+ }
+ resolver := NewMediaResolver(nil, newFakeMediaStorage(), &fakeMediaLedger{}, nil)
+ if resolver.HasMedia(msg) {
+ t.Error("HasMedia = true for a message whose only file is unfetchable")
+ }
+}
+
+func TestInboundFromAppMention_Files(t *testing.T) {
+ msg, ok := translateAppMention("UBOT", eventsAPI(nil), &slackevents.AppMentionEvent{
+ User: "UALICE",
+ Text: "<@UBOT> look at this",
+ Channel: "C123",
+ TimeStamp: "1700000000.000900",
+ Files: []slack.File{
+ {ID: "F9", Name: "log.txt", Mimetype: "text/plain", URLPrivateDownload: "https://files.slack.com/files-pri/T1-F9/download/log.txt"},
+ },
+ })
+ if !ok {
+ t.Fatal("app_mention with files should be ingestable")
+ }
+ var raw slackRawEvent
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ t.Fatalf("decode raw: %v", err)
+ }
+ if len(raw.Files) != 1 || raw.Files[0].ID != "F9" {
+ t.Errorf("raw files = %+v, want the mention's file", raw.Files)
+ }
+}
+
func TestSlackChatType(t *testing.T) {
cases := []struct {
channelID, channelType string
diff --git a/server/internal/integrations/slack/media_ingest.go b/server/internal/integrations/slack/media_ingest.go
new file mode 100644
index 0000000000..318f94c1cb
--- /dev/null
+++ b/server/internal/integrations/slack/media_ingest.go
@@ -0,0 +1,445 @@
+package slack
+
+// Slack media ingestion runs after a message has been accepted and persisted,
+// keeping network and storage I/O off the connector acknowledgement path.
+//
+// HasMedia only inspects the translated event payload. ResolveMedia fetches
+// each file and records a durable intent before uploading it, so failures or
+// crashes leave enough state for the reconciler to remove unbound objects.
+//
+// Slack private file URLs require the installation's bot token as a bearer
+// credential. The download client therefore accepts only HTTPS URLs on
+// Slack-owned hosts, including every redirect destination.
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "mime"
+ "net/http"
+ "net/url"
+ "path"
+ "strings"
+ "time"
+
+ "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"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Slack caps a message at 10 files; the byte cap keeps the buffered download
+// path well inside the Router's 45-second media deadline and memory budget.
+const (
+ maxFilesPerMessage = 10
+ maxInboundFileBytes = 20 << 20
+ fileFetchTimeout = 30 * time.Second
+ maxDownloadRedirects = 3
+)
+
+// mediaStorage defines the object-store operations required for ingestion.
+// ObjectURL must derive the final URL without performing I/O so the resolver
+// can persist that URL in the intent ledger before uploading the object.
+type mediaStorage interface {
+ Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error)
+ ObjectURL(key string) string
+}
+
+type slackMediaResolver struct {
+ decrypt Decrypter
+ storage mediaStorage
+ ledger engine.MediaIntentLedger
+ fetch *http.Client
+ logger *slog.Logger
+ // allowedHost gates which hosts may receive the bot token. Production is
+ // always isSlackFileHost; tests substitute their httptest host.
+ allowedHost func(host string) bool
+}
+
+var _ engine.MediaResolver = (*slackMediaResolver)(nil)
+
+// NewMediaResolver builds the Slack media resolver. Storage and the intent
+// ledger are both required; ResolveMedia logs and returns the original message
+// unchanged if either dependency is unavailable.
+func NewMediaResolver(decrypt Decrypter, storage mediaStorage, ledger engine.MediaIntentLedger, logger *slog.Logger) engine.MediaResolver {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ r := &slackMediaResolver{
+ decrypt: decrypt,
+ storage: storage,
+ ledger: ledger,
+ logger: logger,
+ allowedHost: isSlackFileHost,
+ }
+ r.fetch = &http.Client{
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ if len(via) >= maxDownloadRedirects {
+ return errors.New("too many redirects")
+ }
+ // Validate every redirect before net/http follows it. This host check
+ // prevents redirected requests from leaving Slack's domains regardless
+ // of how net/http propagates the Authorization header.
+ if err := r.validateDownloadURL(req.URL); err != nil {
+ return err
+ }
+ // net/http forwards Authorization only to the same host or a
+ // subdomain of it, so a hop to a sibling such as
+ // files-origin.slack.com arrives unauthenticated and Slack answers
+ // with its HTML login page — indistinguishable from a missing
+ // scope, and the file would be dropped. The check above already
+ // proved this destination is Slack-owned, so restore the token.
+ if auth := via[0].Header.Get("Authorization"); auth != "" {
+ req.Header.Set("Authorization", auth)
+ }
+ return nil
+ },
+ }
+ return r
+}
+
+// isSlackFileHost reports whether host is Slack's own. url_private URLs live
+// on files.slack.com (enterprise variants are still *.slack.com subdomains).
+func isSlackFileHost(host string) bool {
+ host = strings.ToLower(host)
+ return host == "slack.com" || strings.HasSuffix(host, ".slack.com")
+}
+
+// isFetchableSlackFileURL is the pure form of validateDownloadURL, pinned to
+// the production host predicate instead of the resolver's test seam. The
+// inbound translation uses it to drop files the resolver could never fetch
+// before they ever reach the envelope.
+func isFetchableSlackFileURL(rawURL string) bool {
+ parsed, err := url.Parse(rawURL)
+ if err != nil || parsed.Host == "" || parsed.User != nil {
+ return false
+ }
+ return strings.EqualFold(parsed.Scheme, "https") && isSlackFileHost(parsed.Hostname())
+}
+
+// HasMedia is a pure decode of the already-translated event payload. It runs
+// synchronously on the connector ACK path, so no I/O.
+func (r *slackMediaResolver) HasMedia(msg channel.InboundMessage) bool {
+ raw, err := decodeSlackRaw(msg)
+ return err == nil && len(raw.Files) > 0
+}
+
+// ResolveMedia downloads and stores every file on the message, returning it
+// with a MediaRef per object that landed. Files are independent: one that
+// fails does not stop the rest.
+func (r *slackMediaResolver) ResolveMedia(ctx context.Context, inst engine.ResolvedInstallation, _ engine.ResolvedIdentity, _ pgtype.UUID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage {
+ raw, err := decodeSlackRaw(msg)
+ if err != nil || len(raw.Files) == 0 {
+ return msg
+ }
+ if r.storage == nil || r.ledger == nil {
+ r.logWarn(msg, errors.New("media dependency missing"))
+ return msg
+ }
+ row, ok := inst.Platform.(db.ChannelInstallation)
+ if !ok {
+ r.logWarn(msg, errors.New("installation platform row unavailable"))
+ return msg
+ }
+ creds, err := decodeCredentials(row.Config, r.decrypt)
+ if err != nil {
+ r.logWarn(msg, fmt.Errorf("decode credentials: %w", err))
+ return msg
+ }
+ files := raw.Files
+ if len(files) > maxFilesPerMessage {
+ r.logWarn(msg, fmt.Errorf("%d files exceed the limit of %d; extra files skipped", len(files), maxFilesPerMessage))
+ files = files[:maxFilesPerMessage]
+ }
+ for i, f := range files {
+ if err := ctx.Err(); err != nil {
+ // The Router discards every ref once the media deadline passes, so
+ // there is nothing left to win by starting another file.
+ r.logWarn(msg, fmt.Errorf("media budget spent after %d of %d files: %w", i, len(files), err))
+ break
+ }
+ fileCtx, cancel := context.WithTimeout(ctx, fileFetchBudget(ctx, len(files)-i))
+ ref, err := r.ingestOne(fileCtx, inst, chatMessageID, i, f, creds.BotToken)
+ cancel()
+ if err != nil {
+ r.logger.Warn("slack media ingest failed",
+ "installation_id", util.UUIDToString(inst.ID),
+ "message_id", msg.MessageID,
+ "file", i,
+ "err", err)
+ continue
+ }
+ msg.MediaRefs = append(msg.MediaRefs, ref)
+ }
+ return msg
+}
+
+// fileFetchBudget caps one file's download and upload. The flat timeout bounds
+// a single stalled transfer, but maxFilesPerMessage of them in series would run
+// far past the Router's media deadline — and the Router drops EVERY ref once
+// that deadline passes, so one slow file would cost the whole message its
+// attachments. Sharing what is left of the budget over the files still to fetch
+// keeps a slow early file from starving the rest; files that finish quickly
+// hand their unused share back to the ones behind them.
+func fileFetchBudget(ctx context.Context, remainingFiles int) time.Duration {
+ if remainingFiles < 1 {
+ remainingFiles = 1
+ }
+ budget := fileFetchTimeout
+ if deadline, ok := ctx.Deadline(); ok {
+ if share := time.Until(deadline) / time.Duration(remainingFiles); share < budget {
+ budget = share
+ }
+ }
+ return budget
+}
+
+// ingestOne carries a single file from URL to MediaRef. The ledger row goes
+// first: from that point on every failure — download, upload, a crash — leaves
+// an intent the reconciler settles, and nothing here deletes anything.
+func (r *slackMediaResolver) ingestOne(ctx context.Context, inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, index int, f slackRawFile, botToken string) (channel.MediaRef, error) {
+ // Slack states the size up front, so an oversized file is refused before it
+ // costs an intent row and a full transfer. A file that under-reports still
+ // hits the byte cap in download.
+ if f.Size > maxInboundFileBytes {
+ return channel.MediaRef{}, fmt.Errorf("file size %d exceeds the %d MiB limit", f.Size, maxInboundFileBytes>>20)
+ }
+ key := slackMediaObjectKey(inst, chatMessageID, f, index)
+ link := r.storage.ObjectURL(key)
+ owned, 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 !owned {
+ // The reconciler owns this key; never resurrect it.
+ return channel.MediaRef{}, errors.New("media key owned by reconciler")
+ }
+ data, responseType, err := r.download(ctx, f.DownloadURL, botToken)
+ if err != nil {
+ return channel.MediaRef{}, err
+ }
+ contentType, err := slackFileContentType(f, responseType, data)
+ if err != nil {
+ return channel.MediaRef{}, err
+ }
+ filename := slackFileName(f, index, contentType)
+ if _, err := r.storage.Upload(ctx, key, data, contentType, filename); err != nil {
+ // The store may still be processing the PUT; the intent row covers the
+ // object either way.
+ return channel.MediaRef{}, fmt.Errorf("upload file: %w", err)
+ }
+ return channel.MediaRef{
+ Type: slackMediaKind(contentType),
+ StorageKey: key,
+ StorageURL: link,
+ Filename: filename,
+ MimeType: contentType,
+ SizeBytes: int64(len(data)),
+ }, nil
+}
+
+func (r *slackMediaResolver) download(ctx context.Context, rawURL, botToken string) ([]byte, string, error) {
+ parsed, err := url.Parse(rawURL)
+ if err != nil {
+ return nil, "", errors.New("invalid file download URL")
+ }
+ if err := r.validateDownloadURL(parsed); err != nil {
+ return nil, "", err
+ }
+ // The per-file budget is already on ctx (see fileFetchBudget), which also
+ // covers the upload that follows.
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
+ if err != nil {
+ return nil, "", errors.New("build file download request failed")
+ }
+ req.Header.Set("Authorization", "Bearer "+botToken)
+ resp, err := r.fetch.Do(req)
+ if err != nil {
+ // net/http's *url.Error echoes the full request URL; keep private
+ // Slack file URLs out of the logs.
+ var urlErr *url.Error
+ if errors.As(err, &urlErr) {
+ return nil, "", fmt.Errorf("download file request failed: %w", urlErr.Err)
+ }
+ return nil, "", errors.New("download file request failed")
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return nil, "", fmt.Errorf("download file: http %d", resp.StatusCode)
+ }
+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxInboundFileBytes+1))
+ if err != nil {
+ return nil, "", fmt.Errorf("read file: %w", err)
+ }
+ if len(data) > maxInboundFileBytes {
+ return nil, "", fmt.Errorf("file exceeds the %d MiB limit", maxInboundFileBytes>>20)
+ }
+ contentType := resp.Header.Get("Content-Type")
+ if semi := strings.IndexByte(contentType, ';'); semi >= 0 {
+ contentType = strings.TrimSpace(contentType[:semi])
+ }
+ return data, contentType, nil
+}
+
+func (r *slackMediaResolver) validateDownloadURL(parsed *url.URL) error {
+ if parsed == nil || parsed.Host == "" || parsed.User != nil {
+ return errors.New("invalid file download URL shape")
+ }
+ if !strings.EqualFold(parsed.Scheme, "https") {
+ return fmt.Errorf("invalid file download URL scheme %q", parsed.Scheme)
+ }
+ if !r.allowedHost(parsed.Hostname()) {
+ return errors.New("blocked non-Slack file download host")
+ }
+ return nil
+}
+
+// slackFileContentType decides what the stored object is. An unauthorized or
+// unscoped token makes Slack answer 200 with its HTML login page, so an HTML
+// response for a file that did not claim to be HTML is a failed download, not
+// a file — attaching it would hand the agent a login page as the user's
+// document.
+func slackFileContentType(f slackRawFile, responseType string, data []byte) (string, error) {
+ declared := strings.ToLower(strings.TrimSpace(f.Mimetype))
+ responseType = strings.ToLower(strings.TrimSpace(responseType))
+ if responseType == "text/html" && declared != "text/html" {
+ return "", errors.New("download returned an HTML page instead of the file (missing files:read scope?)")
+ }
+ if declared != "" {
+ return declared, nil
+ }
+ if responseType != "" {
+ return responseType, nil
+ }
+ sniff := data
+ if len(sniff) > 512 {
+ sniff = sniff[:512]
+ }
+ contentType := http.DetectContentType(sniff)
+ if semi := strings.IndexByte(contentType, ';'); semi >= 0 {
+ contentType = strings.TrimSpace(contentType[:semi])
+ }
+ if contentType == "" {
+ contentType = "application/octet-stream"
+ }
+ return contentType, nil
+}
+
+// slackMediaKind maps a mime type onto the normalized media kinds.
+func slackMediaKind(contentType string) channel.MsgType {
+ switch {
+ case strings.HasPrefix(contentType, "image/"):
+ return channel.MsgTypeImage
+ case strings.HasPrefix(contentType, "video/"):
+ return channel.MsgTypeVideo
+ case strings.HasPrefix(contentType, "audio/"):
+ return channel.MsgTypeAudio
+ }
+ return channel.MsgTypeFile
+}
+
+// slackMediaObjectKey derives the object key from the CHAT message the object
+// will be attached to, not from the platform message alone: a 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.
+func slackMediaObjectKey(inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, f slackRawFile, index int) string {
+ sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d", util.UUIDToString(chatMessageID), f.ID, index)))
+ return path.Join(
+ "workspaces",
+ util.UUIDToString(inst.WorkspaceID),
+ "slack",
+ util.UUIDToString(inst.ID),
+ hex.EncodeToString(sum[:]),
+ )
+}
+
+// slackFileName picks the stored display name: the uploader's own name when it
+// is a usable filename, otherwise a generated one keyed by file id + position.
+func slackFileName(f slackRawFile, index int, contentType string) string {
+ if name := cleanFileName(f.Name); name != "" {
+ return name
+ }
+ return fmt.Sprintf("slack-file-%s-%d%s", safeMediaSegment(f.ID), index+1, mediaExtension(contentType))
+}
+
+func cleanFileName(name string) string {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return ""
+ }
+ name = path.Base(strings.ReplaceAll(name, "\\", "/"))
+ // path.Base hands back ".." and "..." unchanged; a name made only of dots
+ // is not a filename.
+ if strings.Trim(name, ".") == "" || name == "/" {
+ return ""
+ }
+ return name
+}
+
+// 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), and pinning the common
+// types a slim container image's mime database may not carry.
+func mediaExtension(contentType string) string {
+ 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"
+ case "text/plain":
+ return ".txt"
+ }
+ 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
+}
+
+func (r *slackMediaResolver) logWarn(msg channel.InboundMessage, err error) {
+ r.logger.Warn("slack media resolve skipped", "message_id", msg.MessageID, "error", err)
+}
diff --git a/server/internal/integrations/slack/media_ingest_test.go b/server/internal/integrations/slack/media_ingest_test.go
new file mode 100644
index 0000000000..6243e7badd
--- /dev/null
+++ b/server/internal/integrations/slack/media_ingest_test.go
@@ -0,0 +1,471 @@
+package slack
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "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"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type fakeMediaStorage struct {
+ mu sync.Mutex
+ uploads map[string][]byte
+ names map[string]string
+ types map[string]string
+}
+
+func newFakeMediaStorage() *fakeMediaStorage {
+ return &fakeMediaStorage{uploads: map[string][]byte{}, names: map[string]string{}, types: map[string]string{}}
+}
+
+func (f *fakeMediaStorage) Upload(_ context.Context, key string, data []byte, contentType string, filename string) (string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.uploads[key] = append([]byte(nil), data...)
+ f.names[key] = filename
+ f.types[key] = contentType
+ return f.ObjectURL(key), nil
+}
+
+func (f *fakeMediaStorage) ObjectURL(key string) string { return "https://cdn.example/" + key }
+
+type fakeMediaLedger struct {
+ mu sync.Mutex
+ records []engine.RecordPendingMediaObjectParams
+ refuse bool
+}
+
+func (f *fakeMediaLedger) RecordPendingMediaObject(_ context.Context, p engine.RecordPendingMediaObjectParams) (bool, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.records = append(f.records, p)
+ return !f.refuse, nil
+}
+
+type slackMediaTestEnv struct {
+ resolver *slackMediaResolver
+ store *fakeMediaStorage
+ ledger *fakeMediaLedger
+ host *httptest.Server
+ // authHeader records the Authorization header of the last download.
+ authHeader string
+ // requests counts download attempts that reached the server.
+ requests int
+}
+
+// newSlackMediaTestEnv serves files at /files/<id>. The resolver's host
+// allowlist is widened to the httptest host — production keeps isSlackFileHost.
+func newSlackMediaTestEnv(t *testing.T, files map[string][]byte, contentType string) *slackMediaTestEnv {
+ t.Helper()
+ env := &slackMediaTestEnv{store: newFakeMediaStorage(), ledger: &fakeMediaLedger{}}
+ env.host = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ env.authHeader = r.Header.Get("Authorization")
+ env.requests++
+ data, ok := files[strings.TrimPrefix(r.URL.Path, "/files/")]
+ if !ok {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ if contentType != "" {
+ w.Header().Set("Content-Type", contentType)
+ }
+ _, _ = w.Write(data)
+ }))
+ t.Cleanup(env.host.Close)
+ env.resolver = NewMediaResolver(nil, env.store, env.ledger, nil).(*slackMediaResolver)
+ env.resolver.fetch.Transport = env.host.Client().Transport
+ env.resolver.allowedHost = func(string) bool { return true }
+ return env
+}
+
+func slackMediaFixture(t *testing.T, files ...slackRawFile) (engine.ResolvedInstallation, pgtype.UUID, channel.InboundMessage) {
+ t.Helper()
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "A1",
+ TeamID: "T1",
+ // nil Decrypter treats the base64-decoded bytes as the plaintext token.
+ BotTokenEncrypted: base64.StdEncoding.EncodeToString([]byte("xoxb-test-token")),
+ })
+ var ws, instID, chatMessageID pgtype.UUID
+ ws.Bytes[0], instID.Bytes[0], chatMessageID.Bytes[0] = 0xAB, 0xCD, 0xEF
+ ws.Valid, instID.Valid, chatMessageID.Valid = true, true, true
+ raw, _ := json.Marshal(slackRawEvent{TeamID: "T1", APIAppID: "A1", EventType: "message", Files: files})
+ inst := engine.ResolvedInstallation{
+ ID: instID, WorkspaceID: ws,
+ Platform: db.ChannelInstallation{Config: cfg},
+ }
+ return inst, chatMessageID, channel.InboundMessage{MessageID: "1700000000.000100", Type: channel.MsgTypeText, Text: "see attached", Raw: raw}
+}
+
+func (env *slackMediaTestEnv) fileURL(id string) string { return env.host.URL + "/files/" + id }
+
+func TestSlackMediaResolver_HasMedia(t *testing.T) {
+ env := newSlackMediaTestEnv(t, nil, "")
+ _, _, withFiles := slackMediaFixture(t, slackRawFile{ID: "F1", DownloadURL: "https://files.slack.com/f"})
+ if !env.resolver.HasMedia(withFiles) {
+ t.Error("HasMedia = false for a message with files")
+ }
+ _, _, without := slackMediaFixture(t)
+ if env.resolver.HasMedia(without) {
+ t.Error("HasMedia = true for a message without files")
+ }
+}
+
+func TestSlackMediaResolver_HappyPath(t *testing.T) {
+ pdf := []byte("%PDF-1.4 fake body")
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F1": pdf}, "application/pdf")
+ inst, chatMessageID, msg := slackMediaFixture(t, slackRawFile{
+ ID: "F1", Name: "report.pdf", Mimetype: "application/pdf", Size: int64(len(pdf)), DownloadURL: env.fileURL("F1"),
+ })
+
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("MediaRefs = %d, want 1", len(got.MediaRefs))
+ }
+ ref := got.MediaRefs[0]
+ if ref.Type != channel.MsgTypeFile {
+ t.Errorf("Type = %q, want file", ref.Type)
+ }
+ if ref.Filename != "report.pdf" || ref.MimeType != "application/pdf" || ref.SizeBytes != int64(len(pdf)) {
+ t.Errorf("ref = %+v", ref)
+ }
+ if len(env.ledger.records) != 1 || env.ledger.records[0].StorageKey != ref.StorageKey {
+ t.Errorf("ledger records = %+v", env.ledger.records)
+ }
+ if string(env.store.uploads[ref.StorageKey]) != string(pdf) {
+ t.Error("uploaded bytes do not match the served file")
+ }
+ if env.authHeader != "Bearer xoxb-test-token" {
+ t.Errorf("Authorization = %q, want the bot token", env.authHeader)
+ }
+ if !strings.Contains(ref.StorageKey, "workspaces/") || !strings.Contains(ref.StorageKey, "/slack/") {
+ t.Errorf("StorageKey = %q", ref.StorageKey)
+ }
+}
+
+func TestSlackMediaResolver_MediaKinds(t *testing.T) {
+ png := append([]byte{0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A}, make([]byte, 16)...)
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F1": png}, "image/png")
+ inst, chatMessageID, msg := slackMediaFixture(t, slackRawFile{
+ ID: "F1", Name: "shot.png", Mimetype: "image/png", DownloadURL: env.fileURL("F1"),
+ })
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 1 || got.MediaRefs[0].Type != channel.MsgTypeImage {
+ t.Fatalf("MediaRefs = %+v, want one image ref", got.MediaRefs)
+ }
+}
+
+func TestSlackMediaResolver_BlockedHost(t *testing.T) {
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F1": []byte("data")}, "")
+ env.resolver.allowedHost = isSlackFileHost
+ inst, chatMessageID, msg := slackMediaFixture(t, slackRawFile{
+ ID: "F1", Name: "x.bin", DownloadURL: env.fileURL("F1"),
+ })
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 0 {
+ t.Fatalf("MediaRefs = %d, want 0 for a non-Slack host", len(got.MediaRefs))
+ }
+ if env.authHeader != "" {
+ t.Error("bot token was sent to a non-Slack host")
+ }
+ if len(env.store.uploads) != 0 {
+ t.Error("nothing should be uploaded")
+ }
+}
+
+func TestSlackMediaResolver_HTMLResponseRequiresExplicitDeclaration(t *testing.T) {
+ html := []byte("<!DOCTYPE html><html><body>Sign in to Slack</body></html>")
+ for _, tt := range []struct {
+ name string
+ declaredType string
+ wantRefs int
+ }{
+ {name: "non-HTML file", declaredType: "application/pdf", wantRefs: 0},
+ {name: "missing MIME type", declaredType: "", wantRefs: 0},
+ {name: "explicit HTML file is case-insensitive", declaredType: "TEXT/HTML", wantRefs: 1},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F1": html}, "Text/HTML; charset=utf-8")
+ inst, chatMessageID, msg := slackMediaFixture(t, slackRawFile{
+ ID: "F1", Name: "report.html", Mimetype: tt.declaredType, DownloadURL: env.fileURL("F1"),
+ })
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != tt.wantRefs {
+ t.Fatalf("MediaRefs = %d, want %d", len(got.MediaRefs), tt.wantRefs)
+ }
+ if tt.wantRefs == 0 && len(env.store.uploads) != 0 {
+ t.Error("the login page must not be stored as the file")
+ }
+ if tt.wantRefs == 1 && got.MediaRefs[0].MimeType != "text/html" {
+ t.Errorf("MimeType = %q, want normalized text/html", got.MediaRefs[0].MimeType)
+ }
+ })
+ }
+}
+
+func TestSlackMediaResolver_ReconcilerOwnedKeySkips(t *testing.T) {
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F1": []byte("data")}, "")
+ env.ledger.refuse = true
+ inst, chatMessageID, msg := slackMediaFixture(t, slackRawFile{
+ ID: "F1", Name: "x.bin", DownloadURL: env.fileURL("F1"),
+ })
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 0 || len(env.store.uploads) != 0 {
+ t.Fatal("a reconciler-owned key must not be re-uploaded")
+ }
+}
+
+func TestSlackMediaResolver_OneFailureDoesNotStopTheRest(t *testing.T) {
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F2": []byte("second file")}, "")
+ inst, chatMessageID, msg := slackMediaFixture(t,
+ slackRawFile{ID: "F1", Name: "missing.bin", DownloadURL: env.fileURL("F1")},
+ slackRawFile{ID: "F2", Name: "there.txt", Mimetype: "text/plain", DownloadURL: env.fileURL("F2")},
+ )
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 1 || got.MediaRefs[0].Filename != "there.txt" {
+ t.Fatalf("MediaRefs = %+v, want only the second file", got.MediaRefs)
+ }
+}
+
+func TestSlackFileName_Fallbacks(t *testing.T) {
+ if got := slackFileName(slackRawFile{ID: "F123", Name: "../../etc/passwd"}, 0, "text/plain"); got != "passwd" {
+ t.Errorf("traversal name = %q", got)
+ }
+ if got := slackFileName(slackRawFile{ID: "F123", Name: ".."}, 1, "image/png"); got != "slack-file-F123-2.png" {
+ t.Errorf("dot name fallback = %q", got)
+ }
+ if got := slackFileName(slackRawFile{ID: "F123"}, 0, "application/pdf"); got != "slack-file-F123-1.pdf" {
+ t.Errorf("empty name fallback = %q", got)
+ }
+}
+
+// The redirect policy is the credential boundary: net/http hands the bot token
+// to every hop this returns nil for, so each destination shape is pinned here.
+func TestSlackMediaResolver_RedirectPolicy(t *testing.T) {
+ r := NewMediaResolver(nil, newFakeMediaStorage(), &fakeMediaLedger{}, nil).(*slackMediaResolver)
+ initial := mustParseURL(t, "https://files.slack.com/files-pri/T1-F1/report.pdf")
+ for _, tt := range []struct {
+ name string
+ hop string
+ wantErr bool
+ }{
+ {name: "same Slack host", hop: "https://files.slack.com/files-pri/T1-F1/report.pdf?t=2", wantErr: false},
+ {name: "sibling Slack subdomain", hop: "https://files-origin.slack.com/report.pdf", wantErr: false},
+ {name: "Slack apex", hop: "https://slack.com/report.pdf", wantErr: false},
+ {name: "off-domain CDN", hop: "https://slack-files2.s3.amazonaws.com/report.pdf?X-Amz-Signature=z", wantErr: true},
+ {name: "attacker host", hop: "https://evil.com/report.pdf", wantErr: true},
+ {name: "lookalike host", hop: "https://files.slack.com.evil.com/report.pdf", wantErr: true},
+ {name: "downgrade to http", hop: "http://files.slack.com/report.pdf", wantErr: true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ via := []*http.Request{{URL: initial, Header: http.Header{"Authorization": {"Bearer xoxb-test-token"}}}}
+ next := &http.Request{URL: mustParseURL(t, tt.hop), Header: http.Header{}}
+ err := r.fetch.CheckRedirect(next, via)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("CheckRedirect(%q) err = %v, wantErr = %v", tt.hop, err, tt.wantErr)
+ }
+ if tt.wantErr {
+ return
+ }
+ // net/http drops Authorization on any hop that is not the same
+ // host or a subdomain of it; the policy restores it because the
+ // host check above already proved the destination is Slack's.
+ if got := next.Header.Get("Authorization"); got != "Bearer xoxb-test-token" {
+ t.Errorf("Authorization on permitted hop = %q, want the bot token restored", got)
+ }
+ })
+ }
+}
+
+func TestSlackMediaResolver_RedirectHonorsHopLimit(t *testing.T) {
+ r := NewMediaResolver(nil, newFakeMediaStorage(), &fakeMediaLedger{}, nil).(*slackMediaResolver)
+ hop := &http.Request{URL: mustParseURL(t, "https://files.slack.com/x"), Header: http.Header{}}
+ via := make([]*http.Request, maxDownloadRedirects)
+ for i := range via {
+ via[i] = &http.Request{URL: mustParseURL(t, "https://files.slack.com/x"), Header: http.Header{}}
+ }
+ if err := r.fetch.CheckRedirect(hop, via); err == nil {
+ t.Fatalf("redirect %d must be refused", maxDownloadRedirects+1)
+ }
+}
+
+// A redirect that stays on the same host must still deliver the file: this is
+// the path a working Slack download takes when it bounces internally.
+func TestSlackMediaResolver_FollowsSameHostRedirect(t *testing.T) {
+ pdf := []byte("%PDF-1.4 redirected body")
+ var hops int
+ var lastAuth string
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hops++
+ lastAuth = r.Header.Get("Authorization")
+ if r.URL.Path == "/first" {
+ http.Redirect(w, r, "/second", http.StatusFound)
+ return
+ }
+ w.Header().Set("Content-Type", "application/pdf")
+ _, _ = w.Write(pdf)
+ }))
+ defer srv.Close()
+
+ env := newSlackMediaTestEnv(t, nil, "")
+ env.resolver.fetch.Transport = srv.Client().Transport
+ inst, chatMessageID, msg := slackMediaFixture(t, slackRawFile{
+ ID: "F1", Name: "report.pdf", Mimetype: "application/pdf", DownloadURL: srv.URL + "/first",
+ })
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("MediaRefs = %d, want 1 across a redirect", len(got.MediaRefs))
+ }
+ if hops != 2 {
+ t.Errorf("server hops = %d, want 2", hops)
+ }
+ if lastAuth != "Bearer xoxb-test-token" {
+ t.Errorf("Authorization after redirect = %q, want the bot token", lastAuth)
+ }
+ if string(env.store.uploads[got.MediaRefs[0].StorageKey]) != string(pdf) {
+ t.Error("uploaded bytes do not match the redirected file")
+ }
+}
+
+func TestSlackMediaResolver_DeclaredSizeLimit(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ size int64
+ wantRefs int
+ wantRequests int
+ }{
+ {name: "at the cap", size: maxInboundFileBytes, wantRefs: 1, wantRequests: 1},
+ {name: "one byte over", size: maxInboundFileBytes + 1, wantRefs: 0, wantRequests: 0},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F1": []byte("small body")}, "text/plain")
+ inst, chatMessageID, msg := slackMediaFixture(t, slackRawFile{
+ ID: "F1", Name: "big.txt", Mimetype: "text/plain", Size: tt.size, DownloadURL: env.fileURL("F1"),
+ })
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != tt.wantRefs {
+ t.Fatalf("MediaRefs = %d, want %d", len(got.MediaRefs), tt.wantRefs)
+ }
+ if env.requests != tt.wantRequests {
+ t.Errorf("download attempts = %d, want %d", env.requests, tt.wantRequests)
+ }
+ // An oversized file must not even reserve a key: no transfer, no
+ // intent row for the reconciler to settle.
+ if tt.wantRefs == 0 && len(env.ledger.records) != 0 {
+ t.Errorf("ledger records = %d, want 0 for a file rejected on declared size", len(env.ledger.records))
+ }
+ })
+ }
+}
+
+// A file that under-reports its size is still caught by the byte cap on the
+// response body.
+func TestSlackMediaResolver_BodyExceedingCapIsRejected(t *testing.T) {
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F1": make([]byte, maxInboundFileBytes+1)}, "application/octet-stream")
+ inst, chatMessageID, msg := slackMediaFixture(t, slackRawFile{
+ ID: "F1", Name: "liar.bin", Mimetype: "application/octet-stream", Size: 10, DownloadURL: env.fileURL("F1"),
+ })
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 0 {
+ t.Fatalf("MediaRefs = %d, want 0", len(got.MediaRefs))
+ }
+ if len(env.store.uploads) != 0 {
+ t.Error("an oversized body must not be stored")
+ }
+}
+
+func TestFileFetchBudget(t *testing.T) {
+ if got := fileFetchBudget(context.Background(), 10); got != fileFetchTimeout {
+ t.Errorf("no deadline: budget = %s, want the flat %s", got, fileFetchTimeout)
+ }
+ // The Router's media deadline shared across a full ten-file message must
+ // land well under the flat per-file timeout.
+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
+ defer cancel()
+ got := fileFetchBudget(ctx, maxFilesPerMessage)
+ if got >= fileFetchTimeout || got < 3*time.Second {
+ t.Errorf("ten files under a 45s deadline: budget = %s, want roughly a tenth of it", got)
+ }
+ // The last file may use whatever is left, capped by the flat timeout.
+ if got := fileFetchBudget(ctx, 1); got != fileFetchTimeout {
+ t.Errorf("last file: budget = %s, want the flat %s", got, fileFetchTimeout)
+ }
+}
+
+// Once the Router's deadline has passed every ref is discarded anyway, so the
+// resolver must stop rather than keep reserving keys and downloading.
+func TestSlackMediaResolver_StopsOnceBudgetIsSpent(t *testing.T) {
+ env := newSlackMediaTestEnv(t, map[string][]byte{"F1": []byte("a"), "F2": []byte("b")}, "text/plain")
+ inst, chatMessageID, msg := slackMediaFixture(t,
+ slackRawFile{ID: "F1", Name: "a.txt", Mimetype: "text/plain", DownloadURL: env.fileURL("F1")},
+ slackRawFile{ID: "F2", Name: "b.txt", Mimetype: "text/plain", DownloadURL: env.fileURL("F2")},
+ )
+ expired, cancel := context.WithCancel(context.Background())
+ cancel()
+ got := env.resolver.ResolveMedia(expired, inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 0 {
+ t.Fatalf("MediaRefs = %d, want 0", len(got.MediaRefs))
+ }
+ if env.requests != 0 || len(env.ledger.records) != 0 {
+ t.Errorf("downloads = %d, ledger records = %d, want 0 and 0", env.requests, len(env.ledger.records))
+ }
+}
+
+func TestIsFetchableSlackFileURL(t *testing.T) {
+ for rawURL, want := range map[string]bool{
+ "https://files.slack.com/files-pri/T1-F1/report.pdf": true,
+ "https://slack.com/files-pri/T1-F1/report.pdf": true,
+ // Remote "external" files: url_private points at the host that owns them.
+ "https://docs.google.com/document/d/abc/edit": false,
+ "https://www.dropbox.com/s/abc/report.pdf": false,
+ "http://files.slack.com/files-pri/T1-F1/x.pdf": false,
+ "https://user:[email protected]/x.pdf": false,
+ "https://files.slack.com.evil.com/x.pdf": false,
+ "": false,
+ "not a url": false,
+ } {
+ if got := isFetchableSlackFileURL(rawURL); got != want {
+ t.Errorf("isFetchableSlackFileURL(%q) = %v, want %v", rawURL, got, want)
+ }
+ }
+}
+
+func mustParseURL(t *testing.T, rawURL string) *url.URL {
+ t.Helper()
+ parsed, err := url.Parse(rawURL)
+ if err != nil {
+ t.Fatalf("parse %q: %v", rawURL, err)
+ }
+ return parsed
+}
+
+func TestIsSlackFileHost(t *testing.T) {
+ for host, want := range map[string]bool{
+ "files.slack.com": true,
+ "slack.com": true,
+ "FILES.SLACK.COM": true,
+ "evil.com": false,
+ "slack.com.evil.com": false,
+ "notslack.com": false,
+ "files.slack.com.br": false,
+ "fakeslack.com": false,
+ "sub.files.slack.com": true,
+ } {
+ if got := isSlackFileHost(host); got != want {
+ t.Errorf("isSlackFileHost(%q) = %v, want %v", host, got, want)
+ }
+ }
+}
diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.go
index ef21ab7605..5f891ccae0 100644
--- a/server/internal/integrations/slack/resolvers.go
+++ b/server/internal/integrations/slack/resolvers.go
@@ -14,24 +14,21 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// This file is the Slack ResolverSet: the platform-specific seams the
-// channel-agnostic engine.Router runs the inbound pipeline through. It mirrors
-// the Feishu ResolverSet but is built entirely on the generic channel_* queries
-// (no new query, no schema change) plus the shared engine.ChatSession — so
-// "adding Slack" stays "implement Channel + register a ResolverSet".
+// Slack resolvers connect the channel-agnostic inbound pipeline to Slack
+// installation routing, identity binding, deduplication, session persistence,
+// auditing, reactions, replies, and attachment ingestion. They store shared
+// channel state through the generic channel tables.
// originSlackChat is the issue.origin_type label for issues created via the
// Slack /issue command.
const originSlackChat = "slack_chat"
-// NewSlackResolverSet assembles the Slack ResolverSet over the generated
-// queries + a tx starter (for the shared session service). The replier delivers
-// the outbound binding-prompt / status / issue-created notices; pass a nil
-// engine.OutboundReplier to disable them (the inbound pipeline — route,
-// identity, dedup, session, /issue, run trigger — is fully functional without
-// it). typing shows the "processing" reaction on ingest; pass nil to disable it
-// (MUL-3874). (MUL-3666 wired the replier; stage 3 had both nil.)
-func NewSlackResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, typing *TypingIndicatorManager) engine.ResolverSet {
+// NewSlackResolverSet assembles the Slack implementation of each inbound
+// pipeline stage. The replier sends binding and status notices, typing manages
+// the processing reaction, and media stores inbound attachments. Each optional
+// dependency may be nil to disable only that capability while preserving normal
+// Slack message ingestion.
+func NewSlackResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, typing *TypingIndicatorManager, media engine.MediaResolver) engine.ResolverSet {
set := engine.ResolverSet{
Installation: &installationResolver{q: q},
Identity: &identityResolver{q: q},
@@ -42,11 +39,12 @@ func NewSlackResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.Outb
Fallback: "Slack chat",
})},
Audit: &auditor{q: q},
+ Media: media,
Replier: replier,
OriginType: originSlackChat,
}
- // Guard against assigning a nil *TypingIndicatorManager into the interface
- // field (which would make set.Typing a non-nil typed-nil); mirrors Feishu.
+ // Assign the interface only for a concrete manager. A typed nil would make
+ // the interface compare non-nil and fail when the pipeline invokes it.
if typing != nil {
set.Typing = &slackTypingNotifier{mgr: typing}
}
diff --git a/server/internal/integrations/slack/resolvers_test.go b/server/internal/integrations/slack/resolvers_test.go
index c38a08033a..9fb0e06c16 100644
--- a/server/internal/integrations/slack/resolvers_test.go
+++ b/server/internal/integrations/slack/resolvers_test.go
@@ -93,10 +93,13 @@ func TestSlackThreadIsolation(t *testing.T) {
}
func TestNewSlackResolverSet(t *testing.T) {
- set := NewSlackResolverSet(nil, nil, nil, nil)
+ set := NewSlackResolverSet(nil, nil, nil, nil, nil)
if set.Installation == nil || set.Identity == nil || set.Dedup == nil || set.Session == nil || set.Audit == nil {
t.Error("resolver set must populate all required resolvers")
}
+ if set.Media != nil {
+ t.Error("a nil media arg must leave Media nil")
+ }
if set.OriginType != "slack_chat" {
t.Errorf("OriginType = %q, want slack_chat", set.OriginType)
}
@@ -108,7 +111,7 @@ func TestNewSlackResolverSet(t *testing.T) {
}
// A real replier + typing manager thread through.
- set = NewSlackResolverSet(nil, nil, NewOutboundReplier(OutboundReplierConfig{}), NewTypingIndicatorManager(nil, nil, nil))
+ set = NewSlackResolverSet(nil, nil, NewOutboundReplier(OutboundReplierConfig{}), NewTypingIndicatorManager(nil, nil, nil), NewMediaResolver(nil, nil, nil, nil))
if set.Replier == nil {
t.Error("a non-nil replier must populate ResolverSet.Replier")
}