Skip to content

Commit 3305d31

Browse files
committed
fix(search): keep oversized Slack files off the full-text promise and fail GitLab source filtering open
1 parent ee4a060 commit 3305d31

7 files changed

Lines changed: 105 additions & 22 deletions

File tree

‎apps/sim/lib/knowledge/__integration__/gitlab-group.integration.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ describe('GitLab group Search permission boundary', () => {
5555
let moved = false
5656
let failedDiscovery = false
5757
let added = false
58+
let aliceLegacyResult: { documentId: string } | undefined
5859
let confidential = false
5960
let providerState = 'healthy'
6061
const checks: string[] = []
@@ -433,9 +434,8 @@ describe('GitLab group Search permission boundary', () => {
433434
input: { organizationId: ids.organizationId, sourceId: legacyId },
434435
})
435436
expect(legacyRevision).toEqual({ revision: 1 })
436-
expect(
437-
(await search(ids.aliceId, '11', undefined, 20, legacyId)).results.length
438-
).toBeGreaterThan(0)
437+
aliceLegacyResult = (await search(ids.aliceId, '11', undefined, 20, legacyId)).results[0]
438+
expect(aliceLegacyResult).toBeDefined()
439439
await replaceSearchSourcePermissions.execute({
440440
principal: principal(ids.aliceId),
441441
input: {
@@ -481,6 +481,10 @@ describe('GitLab group Search permission boundary', () => {
481481
expect(new Set((await accounts(ids.bobId)).map((account) => account.accountId))).toEqual(
482482
new Set([`gitlab-source:${sourceId}`, `gitlab-source:${legacyId}`])
483483
)
484+
if (!aliceLegacyResult) throw new Error('Missing result found before revocation')
485+
await expect(read(ids.aliceId, aliceLegacyResult.documentId)).rejects.toThrow(
486+
'This GitLab source is not available to your account.'
487+
)
484488
checks.push('Sources granting the reader nothing are left out of their searches')
485489
})
486490

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const hoisted = vi.hoisted(() => ({
2222
}))
2323
vi.mock('@/lib/knowledge/search/integration-policy', () => knowledgeSearchIntegrationPolicyMock)
2424
vi.mock('@/lib/sim-search/live/gitlab-admin', () => ({
25+
isAdminGitLabAccountId: (accountId: string) => accountId.startsWith('gitlab-source:'),
2526
listAdminGitLabAccounts: hoisted.admin,
2627
resolveAdminGitLabAccount: hoisted.resolveAdmin,
2728
}))

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { resolveKnowledgeWorkspaceContext } from '@/lib/knowledge/application/co
2020
import { listOrganizationSearchApprovals } from '@/lib/knowledge/search/integration-policy'
2121
import { resolveCredentialTokenBundle } from '@/lib/oauth/credential-service'
2222
import {
23+
isAdminGitLabAccountId,
2324
listAdminGitLabAccounts,
2425
resolveAdminGitLabAccount,
2526
} from '@/lib/sim-search/live/gitlab-admin'
@@ -162,7 +163,9 @@ export async function resolveLiveAccount(
162163
) {
163164
const current = (await listLiveAccounts(owner, userId)).find((row) => row.id === accountId)
164165
if (!current)
165-
throw new NativeSearchError('reconnect', 'This search connection is no longer available.')
166+
throw isAdminGitLabAccountId(accountId)
167+
? new NativeSearchError('unavailable', 'This GitLab source is not available to your account.')
168+
: new NativeSearchError('reconnect', 'This search connection is no longer available.')
166169
return resolveListedLiveAccount(owner, userId, current, signal)
167170
}
168171

‎apps/sim/lib/sim-search/live/gitlab-admin.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1+
import { queueTableRows, schemaMock } from '@sim/testing'
12
import {
23
knowledgeAccessScopeMock,
34
knowledgeAccessScopeMockFns,
45
} from '@sim/testing/mocks/knowledge-access-scope.mock'
56
import { beforeEach, describe, expect, it, vi } from 'vitest'
67
import { groupToken } from '@/lib/knowledge/access/tokens'
7-
import { createAdminGitLabSession } from '@/lib/sim-search/live/gitlab-admin'
8+
import {
9+
createAdminGitLabSession,
10+
listAdminGitLabAccounts,
11+
} from '@/lib/sim-search/live/gitlab-admin'
812
import {
913
gitLabCsvGroupToken,
1014
setGitLabCsvContext,
@@ -19,13 +23,15 @@ const mocks = vi.hoisted(() => ({
1923
search: vi.fn(),
2024
read: vi.fn(),
2125
grant: vi.fn(),
26+
metadata: vi.fn(),
2227
}))
2328
vi.mock('@/lib/knowledge/access/scope', () => knowledgeAccessScopeMock)
2429
vi.mock('@/connectors/gitlab/permission-config/repository', () => ({
2530
seedGitLabPermissionContext: mocks.seed,
2631
}))
2732
vi.mock('@/lib/knowledge/connectors/permission-store', () => ({
2833
hasConnectorPermissionGrant: mocks.grant,
34+
readConnectorPermissionMetadata: mocks.metadata,
2935
}))
3036
vi.mock('@/connectors/gitlab/permissions', () => ({
3137
openGitLabDirectory: mocks.directory,
@@ -236,3 +242,16 @@ describe('non-admin token and CSV permissions', () => {
236242
await expect(session()).rejects.toThrow('not available')
237243
})
238244
})
245+
246+
describe('administrator-managed GitLab source listing', () => {
247+
it('lists every source when its grants cannot be checked, leaving the session to refuse it', async () => {
248+
queueTableRows(schemaMock.knowledgeConnector, [
249+
{ id: 'source-a', config: source.config, encryptedApiKey: 'sealed' },
250+
])
251+
mocks.metadata.mockRejectedValue(new Error('connection reset'))
252+
253+
const accounts = await listAdminGitLabAccounts({ organizationId: 'org' }, 'reader')
254+
255+
expect(accounts.map((account) => account.id)).toEqual(['gitlab-source:source-a'])
256+
})
257+
})

‎apps/sim/lib/sim-search/live/gitlab-admin.ts‎

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { db } from '@sim/db'
22
import { knowledgeBase, knowledgeConnector } from '@sim/db/schema'
3+
import { createLogger } from '@sim/logger'
4+
import { getErrorMessage } from '@sim/utils/errors'
35
import { and, eq, inArray, isNull } from 'drizzle-orm'
46
import { decryptApiKey } from '@/lib/api-key/crypto'
57
import { type ResourceOwner, resourceScopeFromOwner } from '@/lib/core/resource-scope'
@@ -45,6 +47,7 @@ import {
4547
} from '@/connectors/gitlab/permissions'
4648
import { normalizeGitLabHost } from '@/tools/gitlab/utils'
4749

50+
const logger = createLogger('SimSearchGitLabSources')
4851
const PREFIX = 'gitlab-source:'
4952

5053
/** Canonical admin-managed sources only. Neither credentials nor indexed documents leave this module. */
@@ -90,26 +93,45 @@ function hasCsvPermissions(metadata: unknown): boolean {
9093
}
9194
}
9295

96+
/** The IDs of CSV-permission sources that grant the viewer no project. */
97+
async function ungrantedSources(
98+
owner: ResourceOwner,
99+
userId: string,
100+
ids: string[]
101+
): Promise<Set<string>> {
102+
const csv = (await readConnectorPermissionMetadata(ids))
103+
.filter((row) => hasCsvPermissions(row.metadata))
104+
.map((row) => row.connectorId)
105+
const own = csv.length ? await viewerToken(owner, userId) : undefined
106+
if (!own) return new Set()
107+
const granted = await connectorsGrantingSubject(csv, own)
108+
return new Set(csv.filter((id) => !granted.has(id)))
109+
}
110+
93111
/**
94112
* A source whose uploaded permissions grant the viewer nothing could never return a result, so it
95113
* is left out rather than reported unavailable on every search. Sources that check permissions
96-
* with GitLab, and any whose stored permissions cannot be read, stay listed: their session decides.
114+
* with GitLab, any whose stored permissions cannot be read, and every source when this check
115+
* itself fails stay listed: their session decides.
97116
*/
98117
export async function listAdminGitLabAccounts(
99118
owner: ResourceOwner,
100119
userId: string
101120
): Promise<LiveAccount[]> {
102121
const rows = await sources(owner)
103122
if (!rows.length) return []
104-
const metadata = await readConnectorPermissionMetadata(rows.map((source) => source.id))
105-
const csv = new Set(
106-
metadata.filter((row) => hasCsvPermissions(row.metadata)).map((row) => row.connectorId)
107-
)
108-
// Listing is only a filter: a failed identity lookup lists every source for its session to refuse.
109-
const own = csv.size ? await viewerToken(owner, userId).catch(() => null) : null
110-
const granted = own ? await connectorsGrantingSubject([...csv], own) : null
123+
const hidden = await ungrantedSources(
124+
owner,
125+
userId,
126+
rows.map((source) => source.id)
127+
).catch((error: unknown) => {
128+
logger.warn('GitLab source grants could not be checked; listing every source', {
129+
error: getErrorMessage(error),
130+
})
131+
return new Set<string>()
132+
})
111133
return rows
112-
.filter((source) => !granted || !csv.has(source.id) || granted.has(source.id))
134+
.filter((source) => !hidden.has(source.id))
113135
.map((source) => ({
114136
id: `${PREFIX}${source.id}`,
115137
provider: 'gitlab',
@@ -120,9 +142,14 @@ export async function listAdminGitLabAccounts(
120142
}))
121143
}
122144

145+
/** Whether a live account ID names an administrator-managed GitLab source. */
146+
export function isAdminGitLabAccountId(accountId: string): boolean {
147+
return accountId.startsWith(PREFIX)
148+
}
149+
123150
export async function resolveAdminGitLabAccount(owner: ResourceOwner, account: LiveAccount) {
124151
const [source] = await sources(owner, account.id.slice(PREFIX.length))
125-
if (!account.id.startsWith(PREFIX) || !source?.encryptedApiKey)
152+
if (!isAdminGitLabAccountId(account.id) || !source?.encryptedApiKey)
126153
throw new NativeSearchError(
127154
'unavailable',
128155
'Ask an organization admin to check the GitLab connection.'

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,10 +236,24 @@ describe('Slack file hits', () => {
236236
await fileHits([
237237
hit({ file_type: 'application/pdf', content: 'Revenue grew 12% in Q3' }),
238238
hit({ content: '' }),
239+
hit({ file_type: 'application/x-unknown', title: 'Plan v2.1 final', content: '' }),
239240
])
240241
).toEqual([
241242
'PDF. Reading it returns its full text.\nRevenue grew 12% in Q3',
242243
'File. Its contents cannot be read here; open the source.',
244+
'File. Its contents cannot be read here; open the source.',
245+
])
246+
})
247+
248+
it('does not offer the full text of a file above the read limit, and reports a zero-byte size', async () => {
249+
expect(
250+
await fileHits([
251+
hit({ file_type: 'application/pdf', size: 5 * 1024 * 1024 }),
252+
hit({ file_type: 'text/plain', size: 0 }),
253+
])
254+
).toEqual([
255+
'PDF, 5 MB. Too large to read in full here; open the source.',
256+
'Text, 0 Bytes. Reading it returns its full text.',
243257
])
244258
})
245259
})

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

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -366,27 +366,42 @@ function slackFileFormat(file: Record<string, unknown>): SlackFileFormat | undef
366366
return documentExtension(mimetype)
367367
}
368368

369+
/** Whether a read downloads a file of this size; an unreported size is tried and capped while reading. */
370+
function withinDownloadLimit(format: SlackFileFormat, size: unknown): boolean {
371+
return !(Number(size) > MAX_FILE_DOWNLOAD_BYTES[format])
372+
}
373+
369374
const SLACK_FILE_LABELS: Readonly<Record<string, string>> = {
370375
'application/vnd.slack-docs': 'Canvas',
371376
'application/vnd.slack-list': 'List',
372377
}
373378

379+
/** The shared label for a known type; a title is not a filename, so it never supplies one. */
380+
function knownFileLabel(mimetype: string): string {
381+
const label = fileBrowserTypeLabel(mimetype, '')
382+
return label && label !== mimetype ? label : 'File'
383+
}
384+
374385
/**
375386
* Slack search returns only a file's title, repeated as its content. A hit says what the file is
376387
* and whether reading it returns its text, so a reader can tell which files to open.
377388
*/
378389
function slackFileHitContent(file: Record<string, unknown>, users: Map<string, string>): string {
379390
const mimetype = normalizeMimeType(string(file.file_type))
380-
const size = Number(file.size)
381391
const summary = [
382-
SLACK_FILE_LABELS[mimetype] ?? (fileBrowserTypeLabel(mimetype, string(file.title)) || 'File'),
383-
size > 0 ? formatFileSize(size, { includeBytes: true }) : '',
392+
SLACK_FILE_LABELS[mimetype] ?? knownFileLabel(mimetype),
393+
typeof file.size === 'number' && file.size >= 0
394+
? formatFileSize(file.size, { includeBytes: true })
395+
: '',
384396
]
385397
.filter(Boolean)
386398
.join(', ')
387-
const reading = slackFileFormat({ mimetype })
388-
? 'Reading it returns its full text.'
389-
: 'Its contents cannot be read here; open the source.'
399+
const format = slackFileFormat({ mimetype })
400+
const reading = !format
401+
? 'Its contents cannot be read here; open the source.'
402+
: withinDownloadLimit(format, file.size)
403+
? 'Reading it returns its full text.'
404+
: 'Too large to read in full here; open the source.'
390405
const text = slackPlainText(string(file.content), users)
391406
return [`${summary}. ${reading}`, text === string(file.title) ? '' : text]
392407
.filter(Boolean)
@@ -430,7 +445,7 @@ async function slackFileText(
430445
signal?: AbortSignal
431446
): Promise<{ text: string } | { unavailable?: string }> {
432447
const format = slackFileFormat(file)
433-
if (!format || Number(file.size) > MAX_FILE_DOWNLOAD_BYTES[format]) return {}
448+
if (!format || !withinDownloadLimit(format, file.size)) return {}
434449
const source = slackFileDownloadUrl(file)
435450
if (!source) return {}
436451
const timeout = AbortSignal.timeout(FILE_DOWNLOAD_TIMEOUT_MS)

0 commit comments

Comments
 (0)