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
6 changes: 6 additions & 0 deletions apps/sim/app/api/files/authorization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 3 additions & 1 deletion apps/sim/app/api/files/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -118,6 +118,8 @@ export async function verifyFileAccess(
context?: StorageContext | 'general',
options?: { requireWrite?: boolean; knowledgeAccess?: KnowledgeFileAccess }
): Promise<boolean> {
/** 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/') ||
Expand Down
13 changes: 12 additions & 1 deletion apps/sim/app/api/files/delete/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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()
})
})
6 changes: 3 additions & 3 deletions apps/sim/app/api/files/delete/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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`)
Expand Down
10 changes: 10 additions & 0 deletions apps/sim/lib/uploads/providers/blob/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`. */
Expand Down
39 changes: 27 additions & 12 deletions apps/sim/lib/uploads/providers/blob/client.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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')
Expand All @@ -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=...
Expand Down Expand Up @@ -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<string, string> = {
originalName: encodeURIComponent(fileName), // Encode filename to prevent invalid characters in HTTP headers
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 }] : []))
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}

/**
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
11 changes: 11 additions & 0 deletions apps/sim/lib/uploads/utils/context-prefix.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
})
})
19 changes: 14 additions & 5 deletions apps/sim/lib/uploads/utils/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved

if (key.startsWith('kb/') || key.startsWith('knowledge-base/')) return 'knowledge-base'
if (key.startsWith('chat/')) return 'chat'
Expand Down Expand Up @@ -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
Expand All @@ -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, '_')
}
Expand Down
8 changes: 7 additions & 1 deletion packages/testing/src/mocks/file-utils.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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/)')
Expand Down Expand Up @@ -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,
Expand Down
Loading