diff --git a/apps/sim/app/api/files/authorization.test.ts b/apps/sim/app/api/files/authorization.test.ts index b25b679b1be..4607466efaa 100644 --- a/apps/sim/app/api/files/authorization.test.ts +++ b/apps/sim/app/api/files/authorization.test.ts @@ -161,6 +161,12 @@ describe('public-context access (profile-pictures / og-images / workspace-logos) expect(mockGetUserEntityPermissions).not.toHaveBeenCalled() }) + it('denies a dot-segment key that only looks like it sits under a public prefix', async () => { + const key = 'og-images/../workspace/victim-ws/123-report.pdf' + await expect(verifyFileAccess(key, USER_ID, undefined, 'og-images')).resolves.toBe(false) + await expect(verifyFileAccess(key, USER_ID)).resolves.toBe(false) + }) + it('denies a cross-tenant delete that names a workspace key under a public context', async () => { await expect(write('workspace/victim-ws/123-report.pdf', 'og-images')).resolves.toBe(false) expect(mockGetUserEntityPermissions).not.toHaveBeenCalled() diff --git a/apps/sim/app/api/files/authorization.ts b/apps/sim/app/api/files/authorization.ts index f3cb17a9143..b95515fa035 100644 --- a/apps/sim/app/api/files/authorization.ts +++ b/apps/sim/app/api/files/authorization.ts @@ -17,7 +17,7 @@ import { findWorkspaceFileVersionKeys } from '@/lib/uploads/contexts/workspace/f import type { StorageConfig } from '@/lib/uploads/core/storage-client' import { getFileMetadataByKey } from '@/lib/uploads/server/metadata' import { isWorkspaceScopedContext } from '@/lib/uploads/shared/types' -import { inferContextFromKey } from '@/lib/uploads/utils/file' +import { hasDotSegment, inferContextFromKey } from '@/lib/uploads/utils/file' import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' const logger = createLogger('FileAuthorization') @@ -118,6 +118,8 @@ export async function verifyFileAccess( context?: StorageContext | 'general', options?: { requireWrite?: boolean; knowledgeAccess?: KnowledgeFileAccess } ): Promise { + /** Prefix-based context checks below would read `og-images/../workspace/...` as public. */ + if (hasDotSegment(cloudKey)) return false /** Organization images require the Principal-aware Assistant application resolver. */ if ( cloudKey.startsWith('assistant/') || diff --git a/apps/sim/app/api/files/delete/route.test.ts b/apps/sim/app/api/files/delete/route.test.ts index 6c331f9cd06..a27c328bb0c 100644 --- a/apps/sim/app/api/files/delete/route.test.ts +++ b/apps/sim/app/api/files/delete/route.test.ts @@ -32,7 +32,7 @@ vi.mock('fs/promises', () => ({ stat: vi.fn().mockResolvedValue({ isFile: () => true }), })) -import { createMockRequest } from '@sim/testing' +import { createMockRequest, createRouteContext } from '@sim/testing' import { POST } from '@/app/api/files/delete/route' idMockFns.mockGenerateId.mockReturnValue('test-uuid') @@ -71,4 +71,15 @@ describe('File Delete API Route', () => { expect(filesAuthorizationMockFns.mockVerifyFileAccess).not.toHaveBeenCalled() expect(storageServiceMockFns.mockDeleteFile).not.toHaveBeenCalled() }) + it('answers not found for a dot-segment key without checking access or deleting', async () => { + const req = createMockRequest('POST', { + filePath: '/api/files/serve/og-images/..%2Fworkspace%2Fvictim-ws%2F1234-report.pdf', + }) + + const response = await POST(req, createRouteContext({})) + + expect(response.status).toBe(404) + expect(filesAuthorizationMockFns.mockVerifyFileAccess).not.toHaveBeenCalled() + expect(storageServiceMockFns.mockDeleteFile).not.toHaveBeenCalled() + }) }) diff --git a/apps/sim/app/api/files/delete/route.ts b/apps/sim/app/api/files/delete/route.ts index 72ae7640c8c..eaa3ceafd29 100644 --- a/apps/sim/app/api/files/delete/route.ts +++ b/apps/sim/app/api/files/delete/route.ts @@ -5,10 +5,9 @@ import { fileDeleteContract } from '@/lib/api/contracts/storage-transfer' import { getValidationErrorMessage, parseRequest } from '@/lib/api/server' import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import type { StorageContext } from '@/lib/uploads/config' import { deleteFile } from '@/lib/uploads/core/storage-service' import { deleteFileMetadata } from '@/lib/uploads/server/metadata' -import { extractStorageKey, inferContextFromKey } from '@/lib/uploads/utils/file' +import { extractStorageKey, tryInferContextFromKey } from '@/lib/uploads/utils/file' import { verifyFileAccess, verifyKBFileWriteAccess } from '@/app/api/files/authorization' import { createFileErrorResponse, @@ -63,7 +62,8 @@ export const POST = withRouteHandler(async (request: NextRequest) => { const key = extractStorageKeyFromPath(filePath) // Derive context from the trusted key prefix, never the client-supplied value; a supplied context must agree with the key. - const storageContext: StorageContext = inferContextFromKey(key) + const storageContext = tryInferContextFromKey(key) + if (!storageContext) throw new FileNotFoundError(`File not found: ${key}`) if (context && context !== storageContext) { logger.warn('File delete context mismatch', { key, context, inferred: storageContext }) throw new InvalidRequestError(`Provided context "${context}" does not match the file key`) diff --git a/apps/sim/lib/uploads/providers/blob/client.test.ts b/apps/sim/lib/uploads/providers/blob/client.test.ts index 5e41f9a5225..05ba698e74d 100644 --- a/apps/sim/lib/uploads/providers/blob/client.test.ts +++ b/apps/sim/lib/uploads/providers/blob/client.test.ts @@ -194,6 +194,16 @@ describe('Azure Blob Storage Client', () => { }) }) + describe('dot-segment keys', () => { + it('refuses a key the SDK would collapse into another blob or container', async () => { + for (const key of ['og-images/../workspace/ws/secret.txt', 'og-images/../../kb/doc.pdf']) { + await expect(downloadFromBlob(key)).rejects.toThrow('Path traversal detected') + await expect(headBlobObject(key)).rejects.toThrow('Path traversal detected') + } + expect(mockGetBlockBlobClient).not.toHaveBeenCalled() + }) + }) + describe('headBlobObject', () => { it('reports an absent blob as null rather than raising', async () => { /** Azure names the class in `name` and the reason in `code`. */ diff --git a/apps/sim/lib/uploads/providers/blob/client.ts b/apps/sim/lib/uploads/providers/blob/client.ts index 9fa37766b0c..801433e93b3 100644 --- a/apps/sim/lib/uploads/providers/blob/client.ts +++ b/apps/sim/lib/uploads/providers/blob/client.ts @@ -1,5 +1,8 @@ import type { Readable } from 'node:stream' -import type { BlobServiceClient as BlobServiceClientType } from '@azure/storage-blob' +import type { + BlobServiceClient as BlobServiceClientType, + ContainerClient, +} from '@azure/storage-blob' import { createLogger } from '@sim/logger' import { generateId } from '@sim/utils/id' import { @@ -20,7 +23,7 @@ import type { MultipartCompletionPolicy, StoredObjectInfo, } from '@/lib/uploads/shared/types' -import { sanitizeStorageMetadata } from '@/lib/uploads/utils/file' +import { hasDotSegment, sanitizeStorageMetadata } from '@/lib/uploads/utils/file' import { sanitizeFileName } from '@/executor/constants' const logger = createLogger('BlobClient') @@ -45,6 +48,18 @@ function isBlobCreateConflict(error: unknown): boolean { ) } +/** + * The SDK writes the blob name into the URL path, whose parser collapses `.`/`..` segments, so + * `og-images/../workspace/x` would address `workspace/x` (or a sibling container). Every blob + * client is built here so no such key reaches Azure. + */ +function blockBlobClientIn(containerClient: ContainerClient, key: string) { + if (hasDotSegment(key)) { + throw new Error('Path traversal detected in blob key') + } + return containerClient.getBlockBlobClient(key) +} + /** * Extract account name and key from an Azure connection string. * Connection strings have the format: DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...;EndpointSuffix=... @@ -157,7 +172,7 @@ export async function uploadToBlob( const blobServiceClient = await getBlobServiceClient() const containerClient = blobServiceClient.getContainerClient(config.containerName) - const blockBlobClient = containerClient.getBlockBlobClient(uniqueKey) + const blockBlobClient = blockBlobClientIn(containerClient, uniqueKey) const blobMetadata: Record = { originalName: encodeURIComponent(fileName), // Encode filename to prevent invalid characters in HTTP headers @@ -235,7 +250,7 @@ export async function getPresignedUrlWithConfig( } const containerClient = tempBlobServiceClient.getContainerClient(customConfig.containerName) - const blockBlobClient = containerClient.getBlockBlobClient(key) + const blockBlobClient = blockBlobClientIn(containerClient, key) const sasOptions = { containerName: customConfig.containerName, @@ -369,7 +384,7 @@ export async function downloadFromBlob( } const containerClient = blobServiceClient.getContainerClient(containerName) - const blockBlobClient = containerClient.getBlockBlobClient(key) + const blockBlobClient = blockBlobClientIn(containerClient, key) const downloadBlockBlobResponse = await blockBlobClient.download(0, undefined, { abortSignal: signal, @@ -440,7 +455,7 @@ export async function downloadFromBlobStream( } const containerClient = blobServiceClient.getContainerClient(containerName) - const blockBlobClient = containerClient.getBlockBlobClient(key) + const blockBlobClient = blockBlobClientIn(containerClient, key) const downloadBlockBlobResponse = range ? await blockBlobClient.download(range.start, range.end - range.start + 1) @@ -485,7 +500,7 @@ export async function headBlobObject( } const containerClient = blobServiceClient.getContainerClient(containerName) - const blockBlobClient = containerClient.getBlockBlobClient(key) + const blockBlobClient = blockBlobClientIn(containerClient, key) try { const properties = await blockBlobClient.getProperties() @@ -568,7 +583,7 @@ export async function deleteFromBlob( } const containerClient = blobServiceClient.getContainerClient(containerName) - const blockBlobClient = containerClient.getBlockBlobClient(key) + const blockBlobClient = blockBlobClientIn(containerClient, key) signal?.throwIfAborted() await blockBlobClient.deleteIfExists(...(signal ? [{ abortSignal: signal }] : [])) @@ -667,7 +682,7 @@ export async function getMultipartPartUrls( } const containerClient = blobServiceClient.getContainerClient(containerName) - const blockBlobClient = containerClient.getBlockBlobClient(key) + const blockBlobClient = blockBlobClientIn(containerClient, key) return partNumbers.map((partNumber) => { const blockId = deriveBlobBlockId(partNumber) @@ -736,7 +751,7 @@ async function getBlockBlobClientFor(key: string, customConfig?: BlobConfig) { containerName = BLOB_CONFIG.containerName } - return blobServiceClient.getContainerClient(containerName).getBlockBlobClient(key) + return blockBlobClientIn(blobServiceClient.getContainerClient(containerName), key) } /** @@ -828,7 +843,7 @@ export async function completeMultipartUpload( } const containerClient = blobServiceClient.getContainerClient(containerName) - const blockBlobClient = containerClient.getBlockBlobClient(key) + const blockBlobClient = blockBlobClientIn(containerClient, key) const sortedBlockIds = parts .sort((a, b) => a.partNumber - b.partNumber) @@ -922,7 +937,7 @@ export async function abortMultipartUpload( } const containerClient = blobServiceClient.getContainerClient(containerName) - const blockBlobClient = containerClient.getBlockBlobClient(key) + const blockBlobClient = blockBlobClientIn(containerClient, key) try { const properties = await blockBlobClient.getProperties() diff --git a/apps/sim/lib/uploads/utils/context-prefix.test.ts b/apps/sim/lib/uploads/utils/context-prefix.test.ts index d0aa54f26ce..967eb6aebdc 100644 --- a/apps/sim/lib/uploads/utils/context-prefix.test.ts +++ b/apps/sim/lib/uploads/utils/context-prefix.test.ts @@ -20,4 +20,15 @@ describe('tryInferContextFromKey', () => { expect(() => inferContextFromKey(key)).toThrow() } }) + + it('does not classify a dot-segment key by a prefix it escapes', () => { + for (const key of [ + 'og-images/../workspace/ws/a.pdf', + 'og-images/..\\workspace\\ws/a.pdf', + 'profile-pictures/./x', + 'kb/..', + ]) { + expect(tryInferContextFromKey(key)).toBeNull() + } + }) }) diff --git a/apps/sim/lib/uploads/utils/file.ts b/apps/sim/lib/uploads/utils/file.ts index d4470d06f35..f78746b280b 100644 --- a/apps/sim/lib/uploads/utils/file.ts +++ b/apps/sim/lib/uploads/utils/file.ts @@ -776,7 +776,7 @@ export function inferContextFromKey(key: string): StorageContext { * half of them. */ export function tryInferContextFromKey(key: string): StorageContext | null { - if (!key) return null + if (!key || hasDotSegment(key)) return null if (key.startsWith('kb/') || key.startsWith('knowledge-base/')) return 'knowledge-base' if (key.startsWith('chat/')) return 'chat' @@ -1091,6 +1091,16 @@ export function sanitizeStorageMetadata( return sanitized } +/** + * Whether a storage key has a `.` or `..` path segment, splitting on `\` as well as `/`. Such a + * key is never one the platform builds, and URL-based providers (Azure Blob) collapse the + * segments into a different object, so it must not reach a provider or pass a prefix-based + * authorization check. + */ +export function hasDotSegment(key: string): boolean { + return key.split(/[/\\]/).some((segment) => segment === '.' || segment === '..') +} + /** * Sanitize a file key/path for local storage * Removes dangerous characters and prevents path traversal @@ -1103,14 +1113,13 @@ export function sanitizeFileKey(key: string): string { if (!key.includes('/')) { throw new Error('File key must include a context prefix (e.g., kb/, workspace/, execution/)') } + if (hasDotSegment(key)) { + throw new Error('Path traversal detected in file key') + } const segments = key.split('/') const sanitizedSegments = segments.map((segment, index) => { - if (segment === '..' || segment === '.') { - throw new Error('Path traversal detected in file key') - } - if (index === segments.length - 1) { return segment.replace(/[^a-zA-Z0-9.-]/g, '_') } diff --git a/packages/testing/src/mocks/file-utils.mock.ts b/packages/testing/src/mocks/file-utils.mock.ts index 5304bd52f50..05d76ac0be3 100644 --- a/packages/testing/src/mocks/file-utils.mock.ts +++ b/packages/testing/src/mocks/file-utils.mock.ts @@ -393,8 +393,12 @@ function isInternalFileUrl(fileUrl: string): boolean { return path.startsWith('/api/files/serve/') } +function hasDotSegment(key: string): boolean { + return key.split(/[/\\]/).some((segment) => segment === '.' || segment === '..') +} + function tryInferContextFromKey(key: string): MockStorageContext | null { - if (!key) return null + if (!key || hasDotSegment(key)) return null if (key.startsWith('kb/') || key.startsWith('knowledge-base/')) return 'knowledge-base' if (key.startsWith('chat/')) return 'chat' if (key.startsWith('copilot/')) return 'copilot' @@ -662,6 +666,7 @@ export const fileUtilsMockFns = { } return sanitized }), + mockHasDotSegment: vi.fn(hasDotSegment), mockSanitizeFileKey: vi.fn((key: string) => { if (!key.includes('/')) { throw new Error('File key must include a context prefix (e.g., kb/, workspace/, execution/)') @@ -756,6 +761,7 @@ export const fileUtilsMock = { processFilesToUserFiles: fileUtilsMockFns.mockProcessFilesToUserFiles, sanitizeFilenameForMetadata: fileUtilsMockFns.mockSanitizeFilenameForMetadata, sanitizeStorageMetadata: fileUtilsMockFns.mockSanitizeStorageMetadata, + hasDotSegment: fileUtilsMockFns.mockHasDotSegment, sanitizeFileKey: fileUtilsMockFns.mockSanitizeFileKey, extractCleanFilename: fileUtilsMockFns.mockExtractCleanFilename, extractWorkspaceIdFromExecutionKey: fileUtilsMockFns.mockExtractWorkspaceIdFromExecutionKey,