Skip to content

Commit fc4966a

Browse files
committed
fix(uploads): reject dot-segment storage keys before authorization and Azure Blob
A caller-authored serve URL could decode to a key like og-images/../workspace/<id>/<file>. Prefix-based checks classified it as a public context and skipped authorization, and the Azure Blob SDK collapses dot segments when it builds the request URL, so the read landed on another workspace's blob or a sibling container. - tryInferContextFromKey answers null for a key with a . or .. segment, so no prefix check (serve route, verifyFileAccess, classifiers) trusts an escaped prefix - verifyFileAccess denies such keys up front - every Azure block blob client is built through one guard that refuses them
1 parent 507953c commit fc4966a

7 files changed

Lines changed: 69 additions & 18 deletions

File tree

‎apps/sim/app/api/files/authorization.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,12 @@ describe('public-context access (profile-pictures / og-images / workspace-logos)
161161
expect(mockGetUserEntityPermissions).not.toHaveBeenCalled()
162162
})
163163

164+
it('denies a dot-segment key that only looks like it sits under a public prefix', async () => {
165+
const key = 'og-images/../workspace/victim-ws/123-report.pdf'
166+
await expect(verifyFileAccess(key, USER_ID, undefined, 'og-images')).resolves.toBe(false)
167+
await expect(verifyFileAccess(key, USER_ID)).resolves.toBe(false)
168+
})
169+
164170
it('denies a cross-tenant delete that names a workspace key under a public context', async () => {
165171
await expect(write('workspace/victim-ws/123-report.pdf', 'og-images')).resolves.toBe(false)
166172
expect(mockGetUserEntityPermissions).not.toHaveBeenCalled()

‎apps/sim/app/api/files/authorization.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { findWorkspaceFileVersionKeys } from '@/lib/uploads/contexts/workspace/f
1717
import type { StorageConfig } from '@/lib/uploads/core/storage-client'
1818
import { getFileMetadataByKey } from '@/lib/uploads/server/metadata'
1919
import { isWorkspaceScopedContext } from '@/lib/uploads/shared/types'
20-
import { inferContextFromKey } from '@/lib/uploads/utils/file'
20+
import { hasDotSegment, inferContextFromKey } from '@/lib/uploads/utils/file'
2121
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
2222

2323
const logger = createLogger('FileAuthorization')
@@ -118,6 +118,8 @@ export async function verifyFileAccess(
118118
context?: StorageContext | 'general',
119119
options?: { requireWrite?: boolean; knowledgeAccess?: KnowledgeFileAccess }
120120
): Promise<boolean> {
121+
/** Prefix-based context checks below would read `og-images/../workspace/...` as public. */
122+
if (hasDotSegment(cloudKey)) return false
121123
/** Organization images require the Principal-aware Assistant application resolver. */
122124
if (
123125
cloudKey.startsWith('assistant/') ||

‎apps/sim/lib/uploads/providers/blob/client.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,16 @@ describe('Azure Blob Storage Client', () => {
194194
})
195195
})
196196

197+
describe('dot-segment keys', () => {
198+
it('refuses a key the SDK would collapse into another blob or container', async () => {
199+
for (const key of ['og-images/../workspace/ws/secret.txt', 'og-images/../../kb/doc.pdf']) {
200+
await expect(downloadFromBlob(key)).rejects.toThrow('Path traversal detected')
201+
await expect(headBlobObject(key)).rejects.toThrow('Path traversal detected')
202+
}
203+
expect(mockGetBlockBlobClient).not.toHaveBeenCalled()
204+
})
205+
})
206+
197207
describe('headBlobObject', () => {
198208
it('reports an absent blob as null rather than raising', async () => {
199209
/** Azure names the class in `name` and the reason in `code`. */

‎apps/sim/lib/uploads/providers/blob/client.ts‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import type { Readable } from 'node:stream'
2-
import type { BlobServiceClient as BlobServiceClientType } from '@azure/storage-blob'
2+
import type {
3+
BlobServiceClient as BlobServiceClientType,
4+
ContainerClient,
5+
} from '@azure/storage-blob'
36
import { createLogger } from '@sim/logger'
47
import { generateId } from '@sim/utils/id'
58
import {
@@ -20,7 +23,7 @@ import type {
2023
MultipartCompletionPolicy,
2124
StoredObjectInfo,
2225
} from '@/lib/uploads/shared/types'
23-
import { sanitizeStorageMetadata } from '@/lib/uploads/utils/file'
26+
import { hasDotSegment, sanitizeStorageMetadata } from '@/lib/uploads/utils/file'
2427
import { sanitizeFileName } from '@/executor/constants'
2528

2629
const logger = createLogger('BlobClient')
@@ -45,6 +48,18 @@ function isBlobCreateConflict(error: unknown): boolean {
4548
)
4649
}
4750

51+
/**
52+
* The SDK writes the blob name into the URL path, whose parser collapses `.`/`..` segments, so
53+
* `og-images/../workspace/x` would address `workspace/x` (or a sibling container). Every blob
54+
* client is built here so no such key reaches Azure.
55+
*/
56+
function blockBlobClientIn(containerClient: ContainerClient, key: string) {
57+
if (hasDotSegment(key)) {
58+
throw new Error('Path traversal detected in blob key')
59+
}
60+
return containerClient.getBlockBlobClient(key)
61+
}
62+
4863
/**
4964
* Extract account name and key from an Azure connection string.
5065
* Connection strings have the format: DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...;EndpointSuffix=...
@@ -157,7 +172,7 @@ export async function uploadToBlob(
157172

158173
const blobServiceClient = await getBlobServiceClient()
159174
const containerClient = blobServiceClient.getContainerClient(config.containerName)
160-
const blockBlobClient = containerClient.getBlockBlobClient(uniqueKey)
175+
const blockBlobClient = blockBlobClientIn(containerClient, uniqueKey)
161176

162177
const blobMetadata: Record<string, string> = {
163178
originalName: encodeURIComponent(fileName), // Encode filename to prevent invalid characters in HTTP headers
@@ -235,7 +250,7 @@ export async function getPresignedUrlWithConfig(
235250
}
236251

237252
const containerClient = tempBlobServiceClient.getContainerClient(customConfig.containerName)
238-
const blockBlobClient = containerClient.getBlockBlobClient(key)
253+
const blockBlobClient = blockBlobClientIn(containerClient, key)
239254

240255
const sasOptions = {
241256
containerName: customConfig.containerName,
@@ -369,7 +384,7 @@ export async function downloadFromBlob(
369384
}
370385

371386
const containerClient = blobServiceClient.getContainerClient(containerName)
372-
const blockBlobClient = containerClient.getBlockBlobClient(key)
387+
const blockBlobClient = blockBlobClientIn(containerClient, key)
373388

374389
const downloadBlockBlobResponse = await blockBlobClient.download(0, undefined, {
375390
abortSignal: signal,
@@ -440,7 +455,7 @@ export async function downloadFromBlobStream(
440455
}
441456

442457
const containerClient = blobServiceClient.getContainerClient(containerName)
443-
const blockBlobClient = containerClient.getBlockBlobClient(key)
458+
const blockBlobClient = blockBlobClientIn(containerClient, key)
444459

445460
const downloadBlockBlobResponse = range
446461
? await blockBlobClient.download(range.start, range.end - range.start + 1)
@@ -485,7 +500,7 @@ export async function headBlobObject(
485500
}
486501

487502
const containerClient = blobServiceClient.getContainerClient(containerName)
488-
const blockBlobClient = containerClient.getBlockBlobClient(key)
503+
const blockBlobClient = blockBlobClientIn(containerClient, key)
489504

490505
try {
491506
const properties = await blockBlobClient.getProperties()
@@ -568,7 +583,7 @@ export async function deleteFromBlob(
568583
}
569584

570585
const containerClient = blobServiceClient.getContainerClient(containerName)
571-
const blockBlobClient = containerClient.getBlockBlobClient(key)
586+
const blockBlobClient = blockBlobClientIn(containerClient, key)
572587

573588
signal?.throwIfAborted()
574589
await blockBlobClient.deleteIfExists(...(signal ? [{ abortSignal: signal }] : []))
@@ -667,7 +682,7 @@ export async function getMultipartPartUrls(
667682
}
668683

669684
const containerClient = blobServiceClient.getContainerClient(containerName)
670-
const blockBlobClient = containerClient.getBlockBlobClient(key)
685+
const blockBlobClient = blockBlobClientIn(containerClient, key)
671686

672687
return partNumbers.map((partNumber) => {
673688
const blockId = deriveBlobBlockId(partNumber)
@@ -736,7 +751,7 @@ async function getBlockBlobClientFor(key: string, customConfig?: BlobConfig) {
736751
containerName = BLOB_CONFIG.containerName
737752
}
738753

739-
return blobServiceClient.getContainerClient(containerName).getBlockBlobClient(key)
754+
return blockBlobClientIn(blobServiceClient.getContainerClient(containerName), key)
740755
}
741756

742757
/**
@@ -828,7 +843,7 @@ export async function completeMultipartUpload(
828843
}
829844

830845
const containerClient = blobServiceClient.getContainerClient(containerName)
831-
const blockBlobClient = containerClient.getBlockBlobClient(key)
846+
const blockBlobClient = blockBlobClientIn(containerClient, key)
832847

833848
const sortedBlockIds = parts
834849
.sort((a, b) => a.partNumber - b.partNumber)
@@ -922,7 +937,7 @@ export async function abortMultipartUpload(
922937
}
923938

924939
const containerClient = blobServiceClient.getContainerClient(containerName)
925-
const blockBlobClient = containerClient.getBlockBlobClient(key)
940+
const blockBlobClient = blockBlobClientIn(containerClient, key)
926941

927942
try {
928943
const properties = await blockBlobClient.getProperties()

‎apps/sim/lib/uploads/utils/context-prefix.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,10 @@ describe('tryInferContextFromKey', () => {
2020
expect(() => inferContextFromKey(key)).toThrow()
2121
}
2222
})
23+
24+
it('does not classify a dot-segment key by a prefix it escapes', () => {
25+
for (const key of ['og-images/../workspace/ws/a.pdf', 'profile-pictures/./x', 'kb/..']) {
26+
expect(tryInferContextFromKey(key)).toBeNull()
27+
}
28+
})
2329
})

‎apps/sim/lib/uploads/utils/file.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -776,7 +776,7 @@ export function inferContextFromKey(key: string): StorageContext {
776776
* half of them.
777777
*/
778778
export function tryInferContextFromKey(key: string): StorageContext | null {
779-
if (!key) return null
779+
if (!key || hasDotSegment(key)) return null
780780

781781
if (key.startsWith('kb/') || key.startsWith('knowledge-base/')) return 'knowledge-base'
782782
if (key.startsWith('chat/')) return 'chat'
@@ -1091,6 +1091,15 @@ export function sanitizeStorageMetadata(
10911091
return sanitized
10921092
}
10931093

1094+
/**
1095+
* Whether a storage key has a `.` or `..` path segment. Such a key is never one the platform
1096+
* builds, and URL-based providers (Azure Blob) collapse the segments into a different object,
1097+
* so it must not reach a provider or pass a prefix-based authorization check.
1098+
*/
1099+
export function hasDotSegment(key: string): boolean {
1100+
return key.split('/').some((segment) => segment === '.' || segment === '..')
1101+
}
1102+
10941103
/**
10951104
* Sanitize a file key/path for local storage
10961105
* Removes dangerous characters and prevents path traversal
@@ -1103,14 +1112,13 @@ export function sanitizeFileKey(key: string): string {
11031112
if (!key.includes('/')) {
11041113
throw new Error('File key must include a context prefix (e.g., kb/, workspace/, execution/)')
11051114
}
1115+
if (hasDotSegment(key)) {
1116+
throw new Error('Path traversal detected in file key')
1117+
}
11061118

11071119
const segments = key.split('/')
11081120

11091121
const sanitizedSegments = segments.map((segment, index) => {
1110-
if (segment === '..' || segment === '.') {
1111-
throw new Error('Path traversal detected in file key')
1112-
}
1113-
11141122
if (index === segments.length - 1) {
11151123
return segment.replace(/[^a-zA-Z0-9.-]/g, '_')
11161124
}

‎packages/testing/src/mocks/file-utils.mock.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,9 @@ export const fileUtilsMockFns = {
662662
}
663663
return sanitized
664664
}),
665+
mockHasDotSegment: vi.fn((key: string) =>
666+
key.split('/').some((segment) => segment === '.' || segment === '..')
667+
),
665668
mockSanitizeFileKey: vi.fn((key: string) => {
666669
if (!key.includes('/')) {
667670
throw new Error('File key must include a context prefix (e.g., kb/, workspace/, execution/)')
@@ -756,6 +759,7 @@ export const fileUtilsMock = {
756759
processFilesToUserFiles: fileUtilsMockFns.mockProcessFilesToUserFiles,
757760
sanitizeFilenameForMetadata: fileUtilsMockFns.mockSanitizeFilenameForMetadata,
758761
sanitizeStorageMetadata: fileUtilsMockFns.mockSanitizeStorageMetadata,
762+
hasDotSegment: fileUtilsMockFns.mockHasDotSegment,
759763
sanitizeFileKey: fileUtilsMockFns.mockSanitizeFileKey,
760764
extractCleanFilename: fileUtilsMockFns.mockExtractCleanFilename,
761765
extractWorkspaceIdFromExecutionKey: fileUtilsMockFns.mockExtractWorkspaceIdFromExecutionKey,

0 commit comments

Comments
 (0)