From 1c62611351d757664117140fe751cdf05da08f0c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 16 Nov 2026 09:00:37 -0800 Subject: [PATCH 1/2] fix(slack): download files from Slack's download URL and never send the token off its file host --- .../lib/internal/slack/file-download.test.ts | 40 +++++++++++++ apps/sim/lib/internal/slack/file-download.ts | 28 +++++++++ .../sim/lib/internal/slack/operations.test.ts | 24 +++++++- apps/sim/lib/internal/slack/operations.ts | 9 +-- apps/sim/lib/sim-search/live/README.md | 2 +- apps/sim/lib/sim-search/live/slack.test.ts | 13 +++- apps/sim/lib/sim-search/live/slack.ts | 14 ++--- apps/sim/lib/webhooks/providers/slack.test.ts | 60 +++++++++++++++++++ apps/sim/lib/webhooks/providers/slack.ts | 46 +++++--------- 9 files changed, 192 insertions(+), 44 deletions(-) create mode 100644 apps/sim/lib/internal/slack/file-download.test.ts create mode 100644 apps/sim/lib/internal/slack/file-download.ts diff --git a/apps/sim/lib/internal/slack/file-download.test.ts b/apps/sim/lib/internal/slack/file-download.test.ts new file mode 100644 index 00000000000..3605618231f --- /dev/null +++ b/apps/sim/lib/internal/slack/file-download.test.ts @@ -0,0 +1,40 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { assertSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download' + +const PRIVATE = 'https://files.slack.com/files-pri/T1-F1/report.pdf' +const DOWNLOAD = 'https://files.slack.com/files-pri/T1-F1/download/report.pdf' + +describe('Slack file download URL', () => { + it('prefers the download URL, which serves bytes where the private URL may redirect', () => { + expect( + slackFileDownloadUrl({ url_private: PRIVATE, url_private_download: DOWNLOAD })?.href + ).toBe(DOWNLOAD) + expect(slackFileDownloadUrl({ url_private: PRIVATE })?.href).toBe(PRIVATE) + }) + it('never returns a URL for a file hosted outside Slack', () => { + for (const file of [ + { is_external: true, url_private: PRIVATE }, + { mode: 'external', url_private: PRIVATE }, + { filetype: 'remote', url_private: PRIVATE }, + { url_private: 'https://files.example.com/report.pdf' }, + { url_private: 'https://files.slack.com.example.com/report.pdf' }, + { url_private: 'http://files.slack.com/files-pri/T1-F1/report.pdf' }, + { url_private_download: 'https://files.example.com/report.pdf', url_private: PRIVATE }, + { url_private: 'not a url' }, + {}, + ]) + expect(slackFileDownloadUrl(file)).toBeUndefined() + }) + it('keeps a redirect on the Slack file host', () => { + expect(() => assertSlackFileHost(DOWNLOAD)).not.toThrow() + for (const target of [ + 'https://slack-files.com/files-pri-safe/T1-F1/report.pdf', + 'https://team.slack.com/?redir=%2Ffiles-pri%2FT1-F1', + 'http://files.slack.com/files-pri/T1-F1/report.pdf', + ]) + expect(() => assertSlackFileHost(target)).toThrow() + }) +}) diff --git a/apps/sim/lib/internal/slack/file-download.ts b/apps/sim/lib/internal/slack/file-download.ts new file mode 100644 index 00000000000..e89c9a9dd8f --- /dev/null +++ b/apps/sim/lib/internal/slack/file-download.ts @@ -0,0 +1,28 @@ +/** The only host a Slack token is sent to when downloading a file's contents. */ +const SLACK_FILE_ORIGIN = 'https://files.slack.com' + +/** + * Where to download a Slack-hosted file's bytes with a Slack token, or undefined when Slack does + * not host it. `url_private_download` comes first: Slack answers a PDF's `url_private` with a + * redirect to a sandboxed viewer on another domain, while the download URL serves the bytes from + * its file host. A remote file's URL is whatever the app that shared it chose, so a file marked + * external, or any URL off Slack's file host, never receives a token. + */ +export function slackFileDownloadUrl(file: Record): URL | undefined { + if (file.is_external === true || file.mode === 'external' || file.filetype === 'remote') + return undefined + const candidate = [file.url_private_download, file.url_private].find( + (value): value is string => typeof value === 'string' && value.length > 0 + ) + const url = candidate ? URL.parse(candidate) : null + return url?.origin === SLACK_FILE_ORIGIN ? url : undefined +} + +/** + * Redirect guard for a Slack file download: a hop off the file host, such as the workspace + * sign-in page Slack sends a token it will not serve, is refused rather than read as the file. + */ +export function assertSlackFileHost(target: string): void { + if (URL.parse(target)?.origin !== SLACK_FILE_ORIGIN) + throw new Error('Slack redirected the file download away from its file host') +} diff --git a/apps/sim/lib/internal/slack/operations.test.ts b/apps/sim/lib/internal/slack/operations.test.ts index fcb64190b3c..12fdff32218 100644 --- a/apps/sim/lib/internal/slack/operations.test.ts +++ b/apps/sim/lib/internal/slack/operations.test.ts @@ -18,6 +18,7 @@ vi.mock('@/lib/internal/slack/file-input', () => ({ vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) +import { assertSlackFileHost } from '@/lib/internal/slack/file-download' import { executeSlackDownload } from '@/lib/internal/slack/operations' import { executeSlackGetChannelHistoryOperation } from '@/lib/internal/slack/operations/get-channel-history' import { MAX_FILE_SIZE } from '@/lib/uploads/utils/validation' @@ -55,6 +56,7 @@ describe('Slack operations', () => { name: 'report.pdf', mimetype: 'application/pdf', url_private: 'https://files.slack.com/report.pdf', + url_private_download: 'https://files.slack.com/download/report.pdf', }, }) ) @@ -66,13 +68,14 @@ describe('Slack operations', () => { ) expect(mockSecureFetchWithPinnedIP).toHaveBeenCalledWith( - 'https://files.slack.com/report.pdf', + 'https://files.slack.com/download/report.pdf', '93.184.216.34', { headers: { Authorization: 'Bearer token' }, profile: 'contentFetch', maxResponseBytes: MAX_FILE_SIZE, signal: controller.signal, + assertRedirectTarget: assertSlackFileHost, } ) assert(isInternalToolFileResult(result)) @@ -92,6 +95,25 @@ describe('Slack operations', () => { expect(result.present([storedFile])).toEqual({ success: true, output: { file: storedFile } }) }) + it('never sends the token to a file hosted outside Slack', async () => { + vi.mocked(global.fetch).mockResolvedValueOnce( + slackResponse({ + ok: true, + file: { + name: 'plan.pdf', + is_external: true, + url_private: 'https://files.example.com/plan.pdf', + }, + }) + ) + + await expect(executeSlackDownload({ accessToken: 'token', fileId: 'F1' })).rejects.toThrow( + 'File has no Slack-hosted download URL' + ) + expect(mockValidateUrlWithDNS).not.toHaveBeenCalled() + expect(mockSecureFetchWithPinnedIP).not.toHaveBeenCalled() + }) + it('stops following history cursors at the page ceiling whatever maxPages asks for', async () => { vi.mocked(global.fetch).mockImplementation(async () => slackResponse({ diff --git a/apps/sim/lib/internal/slack/operations.ts b/apps/sim/lib/internal/slack/operations.ts index a275e8da08e..54e4fcdb3a7 100644 --- a/apps/sim/lib/internal/slack/operations.ts +++ b/apps/sim/lib/internal/slack/operations.ts @@ -25,6 +25,7 @@ import { slackString, } from '@/lib/internal/slack/client' import { SlackOperationError } from '@/lib/internal/slack/errors' +import { assertSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download' import { forEachSlackAttachmentFile } from '@/lib/internal/slack/file-input' import { createInternalToolFileResult, @@ -447,10 +448,9 @@ export async function executeSlackDownload(input: SlackDownloadBody, signal?: Ab const file = slackObject(data, 'file') ?? {} const name = input.fileName || slackString(file, 'name') || 'download' const mimeType = slackString(file, 'mimetype') || 'application/octet-stream' - const urlPrivate = slackString(file, 'url_private') - if (!urlPrivate) failure(400, 'File does not have a download URL') - const downloadUrl = urlPrivate - const validation = await validateUrlWithDNS(downloadUrl, 'urlPrivate', 'contentFetch') + const downloadUrl = slackFileDownloadUrl(file)?.href + if (!downloadUrl) failure(400, 'File has no Slack-hosted download URL') + const validation = await validateUrlWithDNS(downloadUrl, 'downloadUrl', 'contentFetch') signal?.throwIfAborted() if (!validation.isValid) failure(400, validation.error || 'Invalid Slack file URL') const response = await secureFetchWithPinnedIP(downloadUrl, validation.resolvedIP, { @@ -458,6 +458,7 @@ export async function executeSlackDownload(input: SlackDownloadBody, signal?: Ab headers: { Authorization: `Bearer ${input.accessToken}` }, maxResponseBytes: MAX_FILE_SIZE, signal, + assertRedirectTarget: assertSlackFileHost, }) signal?.throwIfAborted() if (!response.ok) failure(400, 'Failed to download file content') diff --git a/apps/sim/lib/sim-search/live/README.md b/apps/sim/lib/sim-search/live/README.md index 19b052ffa8a..c91e5f7d98a 100644 --- a/apps/sim/lib/sim-search/live/README.md +++ b/apps/sim/lib/sim-search/live/README.md @@ -58,7 +58,7 @@ Each event must exist under the source's delegated token, be in an allowed calen ### Slack -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. +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. ### GitHub diff --git a/apps/sim/lib/sim-search/live/slack.test.ts b/apps/sim/lib/sim-search/live/slack.test.ts index cb68346ce73..cf6041f3b8d 100644 --- a/apps/sim/lib/sim-search/live/slack.test.ts +++ b/apps/sim/lib/sim-search/live/slack.test.ts @@ -51,6 +51,18 @@ describe('Slack file reads', () => { expect.objectContaining({ service: 'slackFiles' }) ) }) + it('downloads from the Slack download URL when the file has one', async () => { + const api = fileClient({ + mimetype: 'text/plain', + url_private_download: 'https://files.slack.com/files-pri/T1-F123/download/plan', + }) + expect((await readSlack(api, 'F123', undefined, 'file')).content).toBe('Full text') + expect(api.bytes).toHaveBeenCalledWith( + '/files-pri/T1-F123/download/plan', + {}, + expect.objectContaining({ service: 'slackFiles' }) + ) + }) it('reads the full text of a text snippet', async () => { const api = fileClient( { filetype: 'text', mimetype: 'text/plain' }, @@ -75,7 +87,6 @@ describe('Slack file reads', () => { it('never sends the token to a file host other than Slack', async () => { for (const file of [ { mimetype: 'text/plain', url_private: 'https://files.example.com/plan.txt' }, - { mimetype: 'text/plain', url_private: 'http://files.slack.com/files-pri/T1-F123/plan' }, { mimetype: 'text/plain', is_external: true }, ]) { const api = fileClient(file) diff --git a/apps/sim/lib/sim-search/live/slack.ts b/apps/sim/lib/sim-search/live/slack.ts index 70255d60beb..44a99ca314b 100644 --- a/apps/sim/lib/sim-search/live/slack.ts +++ b/apps/sim/lib/sim-search/live/slack.ts @@ -1,3 +1,4 @@ +import { slackFileDownloadUrl } from '@/lib/internal/slack/file-download' import { recordSearchProviderSignal } from '@/lib/knowledge/search/diagnostics' import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates' import { @@ -389,9 +390,9 @@ function decodeFileText(bytes: Buffer, mimetype: string): string | undefined { /** * The full text of a file Slack hosts: canvases as HTML, snippets and text files as text, PDF and - * DOCX extracted. The token only goes to Slack's file host, never a remote file's own URL. Short of - * the caller aborting, any failure (denial, redirect, size limit, unreadable bytes, slow download) - * leaves the read with its preview, plus the provider's reason when it gave one. + * DOCX extracted, from Slack's download URL when it has one. The token only goes to Slack's file + * host. Short of the caller aborting, any failure (denial, redirect, size limit, unreadable bytes, + * slow download) leaves the read with its preview, plus the provider's reason when it gave one. */ async function slackFileText( client: NativeClient, @@ -399,10 +400,9 @@ async function slackFileText( signal?: AbortSignal ): Promise<{ text: string } | { unavailable?: string }> { const format = slackFileFormat(file) - if (!format || file.is_external === true || Number(file.size) > MAX_FILE_DOWNLOAD_BYTES[format]) - return {} - const source = URL.parse(string(file.url_private)) - if (source?.origin !== 'https://files.slack.com') return {} + if (!format || Number(file.size) > MAX_FILE_DOWNLOAD_BYTES[format]) return {} + const source = slackFileDownloadUrl(file) + if (!source) return {} const timeout = AbortSignal.timeout(FILE_DOWNLOAD_TIMEOUT_MS) const download = signal ? AbortSignal.any([signal, timeout]) : timeout const request = { service: 'slackFiles', signal: download } as const diff --git a/apps/sim/lib/webhooks/providers/slack.test.ts b/apps/sim/lib/webhooks/providers/slack.test.ts index 5f7f7047ac0..53154037766 100644 --- a/apps/sim/lib/webhooks/providers/slack.test.ts +++ b/apps/sim/lib/webhooks/providers/slack.test.ts @@ -1,9 +1,14 @@ import { createHmac } from 'node:crypto' import { authOAuthUtilsMock, authOAuthUtilsMockFns } from '@sim/testing/mocks/auth-oauth-utils.mock' import { queueTableRows } from '@sim/testing/mocks/database.mock' +import { + inputValidationMock, + inputValidationMockFns, +} from '@sim/testing/mocks/input-validation.mock' import { schemaMock } from '@sim/testing/mocks/schema.mock' import { describe, expect, it, vi } from 'vitest' import { OutboundRoutingError } from '@/lib/core/network/routing' +import { assertSlackFileHost } from '@/lib/internal/slack/file-download' import { handleSlackChallenge, resolveSlackEventKey, @@ -12,6 +17,7 @@ import { } from '@/lib/webhooks/providers/slack' vi.mock('@/lib/oauth/credential-service', () => authOAuthUtilsMock) +vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) const ctx = (body: unknown) => ({ webhook: {}, @@ -197,6 +203,60 @@ describe('slackHandler formatInput - native app bot token', () => { }) }) +describe('slackHandler formatInput - file downloads', () => { + async function formatWithFiles(files: Record[]) { + const formatInput = slackHandler.formatInput + if (!formatInput) throw new Error('Slack handler has no formatInput') + return formatInput({ + ...ctx({ event: { type: 'message', channel: 'C1', user: 'U1', text: 'see file', files } }), + webhook: { providerConfig: { botToken: 'xoxb-test', includeFiles: true } }, + query: {}, + method: 'POST', + }) + } + + it('downloads from the Slack download URL and keeps redirects on the file host', async () => { + inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({ + isValid: true, + resolvedIP: '93.184.216.34', + originalHostname: 'files.slack.com', + }) + inputValidationMockFns.mockSecureFetchWithPinnedIP.mockResolvedValue( + new Response(Buffer.from('%PDF'), { status: 200 }) + ) + + const { input } = await formatWithFiles([ + { + id: 'F1', + name: 'report.pdf', + mimetype: 'application/pdf', + size: 4, + 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', + }, + ]) + + const [url, , options] = inputValidationMockFns.mockSecureFetchWithPinnedIP.mock.lastCall ?? [] + expect(url).toBe('https://files.slack.com/files-pri/T1-F1/download/report.pdf') + expect(options).toMatchObject({ assertRedirectTarget: assertSlackFileHost }) + expect(eventOf(input).files).toHaveLength(1) + }) + + it('never sends the bot token to a file hosted outside Slack', async () => { + const { input } = await formatWithFiles([ + { + id: 'F2', + name: 'plan.pdf', + is_external: true, + url_private: 'https://files.example.com/plan.pdf', + }, + ]) + + expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled() + expect(eventOf(input).files).toEqual([]) + }) +}) + describe('slackHandler formatInput - interactivity (block_actions)', () => { it('carries the full view (state.values + private_metadata) through for a view_submission', async () => { const { input } = await slackHandler.formatInput!( diff --git a/apps/sim/lib/webhooks/providers/slack.ts b/apps/sim/lib/webhooks/providers/slack.ts index 2f0cc3b884f..d87c5fbf131 100644 --- a/apps/sim/lib/webhooks/providers/slack.ts +++ b/apps/sim/lib/webhooks/providers/slack.ts @@ -15,6 +15,7 @@ import { secureFetchWithPinnedIP, validateUrlWithDNS, } from '@/lib/core/security/input-validation.server' +import { assertSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download' import { getSlackBotCredential, refreshAccessTokenIfNeeded, @@ -287,7 +288,7 @@ function formatSlackInteractive(b: Record): SlackTriggerEvent { async function resolveSlackFileInfo( fileId: string, botToken: string -): Promise<{ url_private?: string; name?: string; mimetype?: string; size?: number } | null> { +): Promise | null> { try { const response = await outboundFetch( `https://slack.com/api/files.info?file=${encodeURIComponent(fileId)}`, @@ -302,12 +303,7 @@ async function resolveSlackFileInfo( logger.warn('Slack files.info failed', { fileId, error: data.error }) return null } - return { - url_private: data.file.url_private as string | undefined, - name: data.file.name as string | undefined, - mimetype: data.file.mimetype as string | undefined, - size: data.file.size as number | undefined, - } + return data.file } catch (error) { logger.error('Error calling Slack files.info', { fileId, @@ -325,30 +321,19 @@ async function downloadSlackFiles( const downloaded: Array<{ name: string; data: string; mimeType: string; size: number }> = [] for (const file of filesToProcess) { - const f = file as Record - let urlPrivate = f.url_private as string | undefined - let fileName = f.name as string | undefined - let fileMimeType = f.mimetype as string | undefined - let fileSize = f.size as number | undefined - - if (!urlPrivate && f.id) { + let f = file as Record + if (!f.url_private && !f.url_private_download && f.id) { const resolved = await resolveSlackFileInfo(f.id as string, botToken) - if (resolved?.url_private) { - urlPrivate = resolved.url_private - fileName = fileName || resolved.name - fileMimeType = fileMimeType || resolved.mimetype - fileSize = fileSize ?? resolved.size - } + if (resolved) f = { ...f, ...resolved } } - if (!urlPrivate) { - logger.warn('Slack file has no url_private and could not be resolved, skipping', { - fileId: f.id, - }) + const downloadUrl = slackFileDownloadUrl(f)?.href + if (!downloadUrl) { + logger.warn('Slack file has no Slack-hosted download URL, skipping', { fileId: f.id }) continue } - const reportedSize = Number(fileSize) || 0 + const reportedSize = Number(f.size) || 0 if (reportedSize > SLACK_MAX_FILE_SIZE) { logger.warn('Slack file exceeds size limit, skipping', { fileId: f.id, @@ -359,18 +344,19 @@ async function downloadSlackFiles( } try { - const urlValidation = await validateUrlWithDNS(urlPrivate, 'url_private', 'contentFetch') + const urlValidation = await validateUrlWithDNS(downloadUrl, 'downloadUrl', 'contentFetch') if (!urlValidation.isValid) { - logger.warn('Slack file url_private failed DNS validation, skipping', { + logger.warn('Slack file download URL failed DNS validation, skipping', { fileId: f.id, error: urlValidation.error, }) continue } - const response = await secureFetchWithPinnedIP(urlPrivate, urlValidation.resolvedIP, { + const response = await secureFetchWithPinnedIP(downloadUrl, urlValidation.resolvedIP, { profile: 'contentFetch', headers: { Authorization: `Bearer ${botToken}` }, + assertRedirectTarget: assertSlackFileHost, }) if (!response.ok) { @@ -394,9 +380,9 @@ async function downloadSlackFiles( } downloaded.push({ - name: fileName || 'download', + name: (f.name as string | undefined) || 'download', data: buffer.toString('base64'), - mimeType: fileMimeType || 'application/octet-stream', + mimeType: (f.mimetype as string | undefined) || 'application/octet-stream', size: buffer.length, }) } catch (error) { From d0f0f2300ba13d2533b5fda8b7494c7274ccfe77 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 16 Nov 2026 09:34:28 -0800 Subject: [PATCH 2/2] fix(slack): report an off-host file redirect as a 400 from the download tool --- apps/sim/lib/internal/slack/file-download.ts | 11 ++++++++--- apps/sim/lib/internal/slack/operations.test.ts | 10 ++++++++-- apps/sim/lib/internal/slack/operations.ts | 7 +++++-- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/apps/sim/lib/internal/slack/file-download.ts b/apps/sim/lib/internal/slack/file-download.ts index e89c9a9dd8f..8dceb28a280 100644 --- a/apps/sim/lib/internal/slack/file-download.ts +++ b/apps/sim/lib/internal/slack/file-download.ts @@ -19,10 +19,15 @@ export function slackFileDownloadUrl(file: Record): URL | undef } /** - * Redirect guard for a Slack file download: a hop off the file host, such as the workspace - * sign-in page Slack sends a token it will not serve, is refused rather than read as the file. + * Whether a redirect stays on Slack's file host. A hop elsewhere, such as the workspace sign-in + * page Slack sends a token it will not serve, must be refused rather than read as the file. */ +export function isSlackFileHost(target: string): boolean { + return URL.parse(target)?.origin === SLACK_FILE_ORIGIN +} + +/** Redirect guard for a Slack file download; see {@link isSlackFileHost}. */ export function assertSlackFileHost(target: string): void { - if (URL.parse(target)?.origin !== SLACK_FILE_ORIGIN) + if (!isSlackFileHost(target)) throw new Error('Slack redirected the file download away from its file host') } diff --git a/apps/sim/lib/internal/slack/operations.test.ts b/apps/sim/lib/internal/slack/operations.test.ts index 12fdff32218..b50a739257f 100644 --- a/apps/sim/lib/internal/slack/operations.test.ts +++ b/apps/sim/lib/internal/slack/operations.test.ts @@ -18,7 +18,6 @@ vi.mock('@/lib/internal/slack/file-input', () => ({ vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) -import { assertSlackFileHost } from '@/lib/internal/slack/file-download' import { executeSlackDownload } from '@/lib/internal/slack/operations' import { executeSlackGetChannelHistoryOperation } from '@/lib/internal/slack/operations/get-channel-history' import { MAX_FILE_SIZE } from '@/lib/uploads/utils/validation' @@ -75,9 +74,16 @@ describe('Slack operations', () => { profile: 'contentFetch', maxResponseBytes: MAX_FILE_SIZE, signal: controller.signal, - assertRedirectTarget: assertSlackFileHost, + assertRedirectTarget: expect.any(Function), } ) + const guard = mockSecureFetchWithPinnedIP.mock.lastCall?.[2]?.assertRedirectTarget + expect(() => + guard?.('https://files.slack.com/files-pri/T1-F1/download/report.pdf') + ).not.toThrow() + expect(() => guard?.('https://slack-files.com/files-pri-safe/T1-F1/report.pdf')).toThrow( + expect.objectContaining({ status: 400 }) + ) assert(isInternalToolFileResult(result)) expect(result.files).toEqual([ { name: 'report.pdf', mimeType: 'application/pdf', buffer: Buffer.from('pdf') }, diff --git a/apps/sim/lib/internal/slack/operations.ts b/apps/sim/lib/internal/slack/operations.ts index 54e4fcdb3a7..19f8abb6b6b 100644 --- a/apps/sim/lib/internal/slack/operations.ts +++ b/apps/sim/lib/internal/slack/operations.ts @@ -25,7 +25,7 @@ import { slackString, } from '@/lib/internal/slack/client' import { SlackOperationError } from '@/lib/internal/slack/errors' -import { assertSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download' +import { isSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download' import { forEachSlackAttachmentFile } from '@/lib/internal/slack/file-input' import { createInternalToolFileResult, @@ -458,7 +458,10 @@ export async function executeSlackDownload(input: SlackDownloadBody, signal?: Ab headers: { Authorization: `Bearer ${input.accessToken}` }, maxResponseBytes: MAX_FILE_SIZE, signal, - assertRedirectTarget: assertSlackFileHost, + assertRedirectTarget: (target) => { + if (!isSlackFileHost(target)) + failure(400, 'Slack redirected the file download away from its file host') + }, }) signal?.throwIfAborted() if (!response.ok) failure(400, 'Failed to download file content')