Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion apps/sim/app/api/mothership/local-files/stage/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ import {
} from '@/lib/copilot/request/http'
import { encodeVfsSegment } from '@/lib/copilot/vfs/path-utils'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { trackChatUpload } from '@/lib/uploads/contexts/workspace/workspace-file-manager'
import {
trackChatUpload,
WorkspaceFileKeyOwnershipError,
} from '@/lib/uploads/contexts/workspace/workspace-file-manager'
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'

const logger = createLogger('StageLocalFileUploadAPI')
Expand Down Expand Up @@ -95,6 +98,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
uploadPath: `uploads/${encodeVfsSegment(displayName)}`,
})
} catch (error) {
if (error instanceof WorkspaceFileKeyOwnershipError) {
// The caller supplied a key they may not bind — a client error, not ours.
logger.warn('Rejected chat upload staging for an unowned storage key', {
error: error.message,
})
return NextResponse.json({ error: 'Storage key is not available' }, { status: 403 })
}
logger.error('Failed to stage local file upload', error)
return createInternalServerErrorResponse('Failed to stage local file upload')
}
Expand Down
61 changes: 57 additions & 4 deletions apps/sim/lib/copilot/chat/payload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
import { workflowsUtilsMock } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { mockCreateUserToolSchema, mockGetHighestPrioritySubscription } = vi.hoisted(() => ({
mockCreateUserToolSchema: vi.fn(() => ({ type: 'object', properties: {} })),
mockGetHighestPrioritySubscription: vi.fn(),
}))
const { mockCreateUserToolSchema, mockGetHighestPrioritySubscription, mockTrackChatUpload } =
vi.hoisted(() => ({
mockCreateUserToolSchema: vi.fn(() => ({ type: 'object', properties: {} })),
mockGetHighestPrioritySubscription: vi.fn(),
mockTrackChatUpload: vi.fn(),
}))

vi.mock('@/lib/billing/core/subscription', () => ({
getHighestPrioritySubscription: mockGetHighestPrioritySubscription,
Expand Down Expand Up @@ -104,6 +106,10 @@ vi.mock('@/tools/params', () => ({
createUserToolSchema: mockCreateUserToolSchema,
}))

vi.mock('@/lib/uploads/contexts/workspace/workspace-file-manager', () => ({
trackChatUpload: mockTrackChatUpload,
}))

import {
buildCopilotRequestPayload,
buildIntegrationToolSchemas,
Expand Down Expand Up @@ -209,6 +215,53 @@ describe('buildIntegrationToolSchemas', () => {
describe('buildCopilotRequestPayload', () => {
beforeEach(() => {
vi.clearAllMocks()
mockTrackChatUpload.mockResolvedValue({ displayName: 'payroll.xlsx' })
})

describe('file attachment tracking', () => {
const attachmentParams = {
message: 'hi',
userId: 'mallory',
userMessageId: 'msg-1',
mode: 'agent',
model: 'claude-opus-4-8',
workspaceId: 'ws-1',
chatId: 'chat-1',
fileAttachments: [
{ id: 'a1', key: 'workspace/ws-1/1731000000000-ab12cd34-payroll.xlsx', size: 1 },
],
}

/**
* Tracking writes `workspace_files` rows. A read-only member reaching the
* chat endpoint must not gain that write through an attachment.
*/
it.each(['read', undefined])('does not track attachments for permission %s', async (perm) => {
await buildCopilotRequestPayload(
{ ...attachmentParams, userPermission: perm },
{ selectedModel: 'claude-opus-4-8' }
)

expect(mockTrackChatUpload).not.toHaveBeenCalled()
})

it.each(['write', 'admin'])('tracks attachments for permission %s', async (perm) => {
await buildCopilotRequestPayload(
{ ...attachmentParams, userPermission: perm },
{ selectedModel: 'claude-opus-4-8' }
)

expect(mockTrackChatUpload).toHaveBeenCalledWith(
'ws-1',
'mallory',
'chat-1',
'workspace/ws-1/1731000000000-ab12cd34-payroll.xlsx',
expect.anything(),
expect.anything(),
1,
'msg-1'
)
})
})

it('passes workspaceContext through to the Go request payload', async () => {
Expand Down
20 changes: 18 additions & 2 deletions apps/sim/lib/copilot/chat/payload.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { BrowserKnownSession } from '@sim/browser-protocol'
import { createLogger } from '@sim/logger'
import { isPermissionType, permissionSatisfies } from '@sim/platform-authz/predicates'
import { toError } from '@sim/utils/errors'
import { LRUCache } from 'lru-cache'
import { getHighestPrioritySubscription } from '@/lib/billing/core/subscription'
Expand Down Expand Up @@ -333,10 +334,25 @@ export async function buildCopilotRequestPayload(
const effectiveMode = mode === 'agent' ? 'build' : mode
const transportMode = effectiveMode === 'build' ? 'agent' : effectiveMode

// Track uploaded files in the DB and build context tags instead of base64 inlining
// Track uploaded files in the DB and build context tags instead of base64 inlining.
// Tracking writes `workspace_files` rows, so it needs the same write grant the
// upload routes that issue these keys already require — reaching the chat
// endpoint with `read` must not confer a file-write capability.
const uploadContexts: Array<{ type: string; content: string; tag?: string; path?: string }> = []
// `userPermission` is typed `string` for legacy reasons, so narrow it before
// comparing — an unrecognized value must fail the gate, not rank below it.
const canWriteWorkspaceFiles =
isPermissionType(params.userPermission) && permissionSatisfies(params.userPermission, 'write')
if (chatId && params.workspaceId && fileAttachments && fileAttachments.length > 0) {
for (const f of fileAttachments) {
if (!canWriteWorkspaceFiles) {
logger.warn('Dropping chat file attachments without workspace write access', {
chatId,
workspaceId: params.workspaceId,
attachmentCount: fileAttachments.length,
})
}
const trackableAttachments = canWriteWorkspaceFiles ? fileAttachments : []
for (const f of trackableAttachments) {
const filename = (f.filename ?? f.name ?? 'file') as string
const mediaType = (f.media_type ?? f.mimeType ?? 'application/octet-stream') as string
try {
Expand Down
Loading
Loading