Skip to content

Commit 1c62611

Browse files
committed
fix(slack): download files from Slack's download URL and never send the token off its file host
1 parent 748ee49 commit 1c62611

9 files changed

Lines changed: 192 additions & 44 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @vitest-environment node
3+
*/
4+
import { describe, expect, it } from 'vitest'
5+
import { assertSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download'
6+
7+
const PRIVATE = 'https://files.slack.com/files-pri/T1-F1/report.pdf'
8+
const DOWNLOAD = 'https://files.slack.com/files-pri/T1-F1/download/report.pdf'
9+
10+
describe('Slack file download URL', () => {
11+
it('prefers the download URL, which serves bytes where the private URL may redirect', () => {
12+
expect(
13+
slackFileDownloadUrl({ url_private: PRIVATE, url_private_download: DOWNLOAD })?.href
14+
).toBe(DOWNLOAD)
15+
expect(slackFileDownloadUrl({ url_private: PRIVATE })?.href).toBe(PRIVATE)
16+
})
17+
it('never returns a URL for a file hosted outside Slack', () => {
18+
for (const file of [
19+
{ is_external: true, url_private: PRIVATE },
20+
{ mode: 'external', url_private: PRIVATE },
21+
{ filetype: 'remote', url_private: PRIVATE },
22+
{ url_private: 'https://files.example.com/report.pdf' },
23+
{ url_private: 'https://files.slack.com.example.com/report.pdf' },
24+
{ url_private: 'http://files.slack.com/files-pri/T1-F1/report.pdf' },
25+
{ url_private_download: 'https://files.example.com/report.pdf', url_private: PRIVATE },
26+
{ url_private: 'not a url' },
27+
{},
28+
])
29+
expect(slackFileDownloadUrl(file)).toBeUndefined()
30+
})
31+
it('keeps a redirect on the Slack file host', () => {
32+
expect(() => assertSlackFileHost(DOWNLOAD)).not.toThrow()
33+
for (const target of [
34+
'https://slack-files.com/files-pri-safe/T1-F1/report.pdf',
35+
'https://team.slack.com/?redir=%2Ffiles-pri%2FT1-F1',
36+
'http://files.slack.com/files-pri/T1-F1/report.pdf',
37+
])
38+
expect(() => assertSlackFileHost(target)).toThrow()
39+
})
40+
})
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/** The only host a Slack token is sent to when downloading a file's contents. */
2+
const SLACK_FILE_ORIGIN = 'https://files.slack.com'
3+
4+
/**
5+
* Where to download a Slack-hosted file's bytes with a Slack token, or undefined when Slack does
6+
* not host it. `url_private_download` comes first: Slack answers a PDF's `url_private` with a
7+
* redirect to a sandboxed viewer on another domain, while the download URL serves the bytes from
8+
* its file host. A remote file's URL is whatever the app that shared it chose, so a file marked
9+
* external, or any URL off Slack's file host, never receives a token.
10+
*/
11+
export function slackFileDownloadUrl(file: Record<string, unknown>): URL | undefined {
12+
if (file.is_external === true || file.mode === 'external' || file.filetype === 'remote')
13+
return undefined
14+
const candidate = [file.url_private_download, file.url_private].find(
15+
(value): value is string => typeof value === 'string' && value.length > 0
16+
)
17+
const url = candidate ? URL.parse(candidate) : null
18+
return url?.origin === SLACK_FILE_ORIGIN ? url : undefined
19+
}
20+
21+
/**
22+
* Redirect guard for a Slack file download: a hop off the file host, such as the workspace
23+
* sign-in page Slack sends a token it will not serve, is refused rather than read as the file.
24+
*/
25+
export function assertSlackFileHost(target: string): void {
26+
if (URL.parse(target)?.origin !== SLACK_FILE_ORIGIN)
27+
throw new Error('Slack redirected the file download away from its file host')
28+
}

‎apps/sim/lib/internal/slack/operations.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ vi.mock('@/lib/internal/slack/file-input', () => ({
1818

1919
vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock)
2020

21+
import { assertSlackFileHost } from '@/lib/internal/slack/file-download'
2122
import { executeSlackDownload } from '@/lib/internal/slack/operations'
2223
import { executeSlackGetChannelHistoryOperation } from '@/lib/internal/slack/operations/get-channel-history'
2324
import { MAX_FILE_SIZE } from '@/lib/uploads/utils/validation'
@@ -55,6 +56,7 @@ describe('Slack operations', () => {
5556
name: 'report.pdf',
5657
mimetype: 'application/pdf',
5758
url_private: 'https://files.slack.com/report.pdf',
59+
url_private_download: 'https://files.slack.com/download/report.pdf',
5860
},
5961
})
6062
)
@@ -66,13 +68,14 @@ describe('Slack operations', () => {
6668
)
6769

6870
expect(mockSecureFetchWithPinnedIP).toHaveBeenCalledWith(
69-
'https://files.slack.com/report.pdf',
71+
'https://files.slack.com/download/report.pdf',
7072
'93.184.216.34',
7173
{
7274
headers: { Authorization: 'Bearer token' },
7375
profile: 'contentFetch',
7476
maxResponseBytes: MAX_FILE_SIZE,
7577
signal: controller.signal,
78+
assertRedirectTarget: assertSlackFileHost,
7679
}
7780
)
7881
assert(isInternalToolFileResult(result))
@@ -92,6 +95,25 @@ describe('Slack operations', () => {
9295
expect(result.present([storedFile])).toEqual({ success: true, output: { file: storedFile } })
9396
})
9497

98+
it('never sends the token to a file hosted outside Slack', async () => {
99+
vi.mocked(global.fetch).mockResolvedValueOnce(
100+
slackResponse({
101+
ok: true,
102+
file: {
103+
name: 'plan.pdf',
104+
is_external: true,
105+
url_private: 'https://files.example.com/plan.pdf',
106+
},
107+
})
108+
)
109+
110+
await expect(executeSlackDownload({ accessToken: 'token', fileId: 'F1' })).rejects.toThrow(
111+
'File has no Slack-hosted download URL'
112+
)
113+
expect(mockValidateUrlWithDNS).not.toHaveBeenCalled()
114+
expect(mockSecureFetchWithPinnedIP).not.toHaveBeenCalled()
115+
})
116+
95117
it('stops following history cursors at the page ceiling whatever maxPages asks for', async () => {
96118
vi.mocked(global.fetch).mockImplementation(async () =>
97119
slackResponse({

‎apps/sim/lib/internal/slack/operations.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
slackString,
2626
} from '@/lib/internal/slack/client'
2727
import { SlackOperationError } from '@/lib/internal/slack/errors'
28+
import { assertSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download'
2829
import { forEachSlackAttachmentFile } from '@/lib/internal/slack/file-input'
2930
import {
3031
createInternalToolFileResult,
@@ -447,17 +448,17 @@ export async function executeSlackDownload(input: SlackDownloadBody, signal?: Ab
447448
const file = slackObject(data, 'file') ?? {}
448449
const name = input.fileName || slackString(file, 'name') || 'download'
449450
const mimeType = slackString(file, 'mimetype') || 'application/octet-stream'
450-
const urlPrivate = slackString(file, 'url_private')
451-
if (!urlPrivate) failure(400, 'File does not have a download URL')
452-
const downloadUrl = urlPrivate
453-
const validation = await validateUrlWithDNS(downloadUrl, 'urlPrivate', 'contentFetch')
451+
const downloadUrl = slackFileDownloadUrl(file)?.href
452+
if (!downloadUrl) failure(400, 'File has no Slack-hosted download URL')
453+
const validation = await validateUrlWithDNS(downloadUrl, 'downloadUrl', 'contentFetch')
454454
signal?.throwIfAborted()
455455
if (!validation.isValid) failure(400, validation.error || 'Invalid Slack file URL')
456456
const response = await secureFetchWithPinnedIP(downloadUrl, validation.resolvedIP, {
457457
profile: 'contentFetch',
458458
headers: { Authorization: `Bearer ${input.accessToken}` },
459459
maxResponseBytes: MAX_FILE_SIZE,
460460
signal,
461+
assertRedirectTarget: assertSlackFileHost,
461462
})
462463
signal?.throwIfAborted()
463464
if (!response.ok) failure(400, 'Failed to download file content')

‎apps/sim/lib/sim-search/live/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ Each event must exist under the source's delegated token, be in an allowed calen
5858

5959
### Slack
6060

61-
Member mode only. Search uses the connected user's Slack real-time search grant and provider search syntax. Date bounds are sent as numeric provider timestamps; date ordering selects keyword retrieval and timestamp sort, because Slack semantic retrieval uses relevance ordering. Channels, messages, direct messages, and files are limited by that grant and provider scopes; there is no admin channel filter in member mode. Missing required search scopes produce a reconnect status. Thread/file reads use the same connected identity. A file read downloads the full text of a canvas (HTML), text snippet, PDF or DOCX from `files.slack.com` only, never a remote file's own URL (redirects are followed only within that host; a hop elsewhere, such as a sign-in page, keeps the preview), within the shared response-size limit; when Slack will not serve it, the read returns the `files.info` preview. Real-time Search returns at most 20 results a call and counts every page against the member's rate limit, so a search across every source reads one page; a Slack-scoped or native Slack search follows the cursor for up to three pages to fill its limit, and a later page that fails keeps the earlier pages and returns the unread cursor.
61+
Member mode only. Search uses the connected user's Slack real-time search grant and provider search syntax. Date bounds are sent as numeric provider timestamps; date ordering selects keyword retrieval and timestamp sort, because Slack semantic retrieval uses relevance ordering. Channels, messages, direct messages, and files are limited by that grant and provider scopes; there is no admin channel filter in member mode. Missing required search scopes produce a reconnect status. Thread/file reads use the same connected identity. A file read downloads the full text of a canvas (HTML), text snippet, PDF or DOCX from `files.slack.com` only, using `url_private_download` when present (Slack redirects a PDF's `url_private` to a viewer on another domain), never a remote file's own URL (redirects are followed only within that host; a hop elsewhere, such as a sign-in page, keeps the preview), within the shared response-size limit; when Slack will not serve it, the read returns the `files.info` preview. Real-time Search returns at most 20 results a call and counts every page against the member's rate limit, so a search across every source reads one page; a Slack-scoped or native Slack search follows the cursor for up to three pages to fill its limit, and a later page that fails keeps the earlier pages and returns the unread cursor.
6262

6363
### GitHub
6464

‎apps/sim/lib/sim-search/live/slack.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,18 @@ describe('Slack file reads', () => {
5151
expect.objectContaining({ service: 'slackFiles' })
5252
)
5353
})
54+
it('downloads from the Slack download URL when the file has one', async () => {
55+
const api = fileClient({
56+
mimetype: 'text/plain',
57+
url_private_download: 'https://files.slack.com/files-pri/T1-F123/download/plan',
58+
})
59+
expect((await readSlack(api, 'F123', undefined, 'file')).content).toBe('Full text')
60+
expect(api.bytes).toHaveBeenCalledWith(
61+
'/files-pri/T1-F123/download/plan',
62+
{},
63+
expect.objectContaining({ service: 'slackFiles' })
64+
)
65+
})
5466
it('reads the full text of a text snippet', async () => {
5567
const api = fileClient(
5668
{ filetype: 'text', mimetype: 'text/plain' },
@@ -75,7 +87,6 @@ describe('Slack file reads', () => {
7587
it('never sends the token to a file host other than Slack', async () => {
7688
for (const file of [
7789
{ mimetype: 'text/plain', url_private: 'https://files.example.com/plan.txt' },
78-
{ mimetype: 'text/plain', url_private: 'http://files.slack.com/files-pri/T1-F123/plan' },
7990
{ mimetype: 'text/plain', is_external: true },
8091
]) {
8192
const api = fileClient(file)

‎apps/sim/lib/sim-search/live/slack.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { slackFileDownloadUrl } from '@/lib/internal/slack/file-download'
12
import { recordSearchProviderSignal } from '@/lib/knowledge/search/diagnostics'
23
import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates'
34
import {
@@ -389,20 +390,19 @@ function decodeFileText(bytes: Buffer, mimetype: string): string | undefined {
389390

390391
/**
391392
* The full text of a file Slack hosts: canvases as HTML, snippets and text files as text, PDF and
392-
* DOCX extracted. The token only goes to Slack's file host, never a remote file's own URL. Short of
393-
* the caller aborting, any failure (denial, redirect, size limit, unreadable bytes, slow download)
394-
* leaves the read with its preview, plus the provider's reason when it gave one.
393+
* DOCX extracted, from Slack's download URL when it has one. The token only goes to Slack's file
394+
* host. Short of the caller aborting, any failure (denial, redirect, size limit, unreadable bytes,
395+
* slow download) leaves the read with its preview, plus the provider's reason when it gave one.
395396
*/
396397
async function slackFileText(
397398
client: NativeClient,
398399
file: Record<string, unknown>,
399400
signal?: AbortSignal
400401
): Promise<{ text: string } | { unavailable?: string }> {
401402
const format = slackFileFormat(file)
402-
if (!format || file.is_external === true || Number(file.size) > MAX_FILE_DOWNLOAD_BYTES[format])
403-
return {}
404-
const source = URL.parse(string(file.url_private))
405-
if (source?.origin !== 'https://files.slack.com') return {}
403+
if (!format || Number(file.size) > MAX_FILE_DOWNLOAD_BYTES[format]) return {}
404+
const source = slackFileDownloadUrl(file)
405+
if (!source) return {}
406406
const timeout = AbortSignal.timeout(FILE_DOWNLOAD_TIMEOUT_MS)
407407
const download = signal ? AbortSignal.any([signal, timeout]) : timeout
408408
const request = { service: 'slackFiles', signal: download } as const

‎apps/sim/lib/webhooks/providers/slack.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
import { createHmac } from 'node:crypto'
22
import { authOAuthUtilsMock, authOAuthUtilsMockFns } from '@sim/testing/mocks/auth-oauth-utils.mock'
33
import { queueTableRows } from '@sim/testing/mocks/database.mock'
4+
import {
5+
inputValidationMock,
6+
inputValidationMockFns,
7+
} from '@sim/testing/mocks/input-validation.mock'
48
import { schemaMock } from '@sim/testing/mocks/schema.mock'
59
import { describe, expect, it, vi } from 'vitest'
610
import { OutboundRoutingError } from '@/lib/core/network/routing'
11+
import { assertSlackFileHost } from '@/lib/internal/slack/file-download'
712
import {
813
handleSlackChallenge,
914
resolveSlackEventKey,
@@ -12,6 +17,7 @@ import {
1217
} from '@/lib/webhooks/providers/slack'
1318

1419
vi.mock('@/lib/oauth/credential-service', () => authOAuthUtilsMock)
20+
vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock)
1521

1622
const ctx = (body: unknown) => ({
1723
webhook: {},
@@ -197,6 +203,60 @@ describe('slackHandler formatInput - native app bot token', () => {
197203
})
198204
})
199205

206+
describe('slackHandler formatInput - file downloads', () => {
207+
async function formatWithFiles(files: Record<string, unknown>[]) {
208+
const formatInput = slackHandler.formatInput
209+
if (!formatInput) throw new Error('Slack handler has no formatInput')
210+
return formatInput({
211+
...ctx({ event: { type: 'message', channel: 'C1', user: 'U1', text: 'see file', files } }),
212+
webhook: { providerConfig: { botToken: 'xoxb-test', includeFiles: true } },
213+
query: {},
214+
method: 'POST',
215+
})
216+
}
217+
218+
it('downloads from the Slack download URL and keeps redirects on the file host', async () => {
219+
inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({
220+
isValid: true,
221+
resolvedIP: '93.184.216.34',
222+
originalHostname: 'files.slack.com',
223+
})
224+
inputValidationMockFns.mockSecureFetchWithPinnedIP.mockResolvedValue(
225+
new Response(Buffer.from('%PDF'), { status: 200 })
226+
)
227+
228+
const { input } = await formatWithFiles([
229+
{
230+
id: 'F1',
231+
name: 'report.pdf',
232+
mimetype: 'application/pdf',
233+
size: 4,
234+
url_private: 'https://files.slack.com/files-pri/T1-F1/report.pdf',
235+
url_private_download: 'https://files.slack.com/files-pri/T1-F1/download/report.pdf',
236+
},
237+
])
238+
239+
const [url, , options] = inputValidationMockFns.mockSecureFetchWithPinnedIP.mock.lastCall ?? []
240+
expect(url).toBe('https://files.slack.com/files-pri/T1-F1/download/report.pdf')
241+
expect(options).toMatchObject({ assertRedirectTarget: assertSlackFileHost })
242+
expect(eventOf(input).files).toHaveLength(1)
243+
})
244+
245+
it('never sends the bot token to a file hosted outside Slack', async () => {
246+
const { input } = await formatWithFiles([
247+
{
248+
id: 'F2',
249+
name: 'plan.pdf',
250+
is_external: true,
251+
url_private: 'https://files.example.com/plan.pdf',
252+
},
253+
])
254+
255+
expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled()
256+
expect(eventOf(input).files).toEqual([])
257+
})
258+
})
259+
200260
describe('slackHandler formatInput - interactivity (block_actions)', () => {
201261
it('carries the full view (state.values + private_metadata) through for a view_submission', async () => {
202262
const { input } = await slackHandler.formatInput!(

0 commit comments

Comments
 (0)