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
4 changes: 2 additions & 2 deletions apps/sim/app/api/files/serve/[...path]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ async function handleLocalFile(filename: string, userId: string): Promise<NextRe
throw new FileNotFoundError(`File not found: ${filename}`)
}

const filePath = findLocalFile(filename)
const filePath = await findLocalFile(filename)

if (!filePath) {
throw new FileNotFoundError(`File not found: ${filename}`)
Expand Down Expand Up @@ -228,7 +228,7 @@ async function handleCloudProxyPublic(

async function handleLocalFilePublic(filename: string): Promise<NextResponse> {
try {
const filePath = findLocalFile(filename)
const filePath = await findLocalFile(filename)

if (!filePath) {
throw new FileNotFoundError(`File not found: ${filename}`)
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/api/files/upload/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export async function POST(request: NextRequest) {
const uploadResults = []

for (const file of files) {
const originalName = file.name || 'untitled'
const originalName = file.name || 'untitled.md'

if (!validateFileExtension(originalName)) {
const extension = originalName.split('.').pop()?.toLowerCase() || 'unknown'
Expand Down
80 changes: 41 additions & 39 deletions apps/sim/app/api/files/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ describe('extractFilename', () => {

describe('findLocalFile - Path Traversal Security Tests', () => {
describe('path traversal attack prevention', () => {
it.concurrent('should reject classic path traversal attacks', () => {
it.concurrent('should reject classic path traversal attacks', async () => {
const maliciousInputs = [
'../../../etc/passwd',
'..\\..\\..\\windows\\system32\\config\\sam',
Expand All @@ -340,79 +340,81 @@ describe('findLocalFile - Path Traversal Security Tests', () => {
'..\\config.ini',
]

maliciousInputs.forEach((input) => {
const result = findLocalFile(input)
for (const input of maliciousInputs) {
const result = await findLocalFile(input)
expect(result).toBeNull()
})
}
})

it.concurrent('should reject encoded path traversal attempts', () => {
it.concurrent('should reject encoded path traversal attempts', async () => {
const encodedInputs = [
'%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64', // ../../../etc/passwd
'..%2f..%2fetc%2fpasswd',
'..%5c..%5cconfig.ini',
]

encodedInputs.forEach((input) => {
const result = findLocalFile(input)
for (const input of encodedInputs) {
const result = await findLocalFile(input)
expect(result).toBeNull()
})
}
})

it.concurrent('should reject mixed path separators', () => {
it.concurrent('should reject mixed path separators', async () => {
const mixedInputs = ['../..\\config.txt', '..\\../secret.ini', '/..\\..\\system32']

mixedInputs.forEach((input) => {
const result = findLocalFile(input)
for (const input of mixedInputs) {
const result = await findLocalFile(input)
expect(result).toBeNull()
})
}
})

it.concurrent('should reject filenames with dangerous characters', () => {
it.concurrent('should reject filenames with dangerous characters', async () => {
const dangerousInputs = [
'file:with:colons.txt',
'file|with|pipes.txt',
'file?with?questions.txt',
'file*with*asterisks.txt',
]

dangerousInputs.forEach((input) => {
const result = findLocalFile(input)
for (const input of dangerousInputs) {
const result = await findLocalFile(input)
expect(result).toBeNull()
})
}
})

it.concurrent('should reject null and empty inputs', () => {
expect(findLocalFile('')).toBeNull()
expect(findLocalFile(' ')).toBeNull()
expect(findLocalFile('\t\n')).toBeNull()
it.concurrent('should reject null and empty inputs', async () => {
expect(await findLocalFile('')).toBeNull()
expect(await findLocalFile(' ')).toBeNull()
expect(await findLocalFile('\t\n')).toBeNull()
})

it.concurrent('should reject filenames that become empty after sanitization', () => {
it.concurrent('should reject filenames that become empty after sanitization', async () => {
const emptyAfterSanitization = ['../..', '..\\..\\', '////', '....', '..']

emptyAfterSanitization.forEach((input) => {
const result = findLocalFile(input)
for (const input of emptyAfterSanitization) {
const result = await findLocalFile(input)
expect(result).toBeNull()
})
}
})
})

describe('security validation passes for legitimate files', () => {
it.concurrent('should accept properly formatted filenames without throwing errors', () => {
const legitimateInputs = [
'document.pdf',
'image.png',
'data.csv',
'report-2024.doc',
'file_with_underscores.txt',
'file-with-dashes.json',
]

legitimateInputs.forEach((input) => {
// Should not throw security errors for legitimate filenames
expect(() => findLocalFile(input)).not.toThrow()
})
})
it.concurrent(
'should accept properly formatted filenames without throwing errors',
async () => {
const legitimateInputs = [
'document.pdf',
'image.png',
'data.csv',
'report-2024.doc',
'file_with_underscores.txt',
'file-with-dashes.json',
]

for (const input of legitimateInputs) {
await expect(findLocalFile(input)).resolves.toBeDefined()
}
}
)
})
})
76 changes: 13 additions & 63 deletions apps/sim/app/api/files/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { existsSync } from 'fs'
import path from 'path'
import { createLogger } from '@sim/logger'
import { NextResponse } from 'next/server'
import { UPLOAD_DIR } from '@/lib/uploads/config'
import { sanitizeFileKey } from '@/lib/uploads/utils/file-utils'

const logger = createLogger('FilesUtils')
Expand Down Expand Up @@ -123,76 +120,29 @@ export function extractFilename(path: string): string {
return filename
}

function sanitizeFilename(filename: string): string {
if (!filename || typeof filename !== 'string') {
throw new Error('Invalid filename provided')
}

if (!filename.includes('/')) {
throw new Error('File key must include a context prefix (e.g., kb/, workspace/, execution/)')
}

const segments = filename.split('/')

const sanitizedSegments = segments.map((segment) => {
if (segment === '..' || segment === '.') {
throw new Error('Path traversal detected')
}

const sanitized = segment.replace(/\.\./g, '').replace(/[\\]/g, '').replace(/^\./g, '').trim()

if (!sanitized) {
throw new Error('Invalid or empty path segment after sanitization')
}

if (
sanitized.includes(':') ||
sanitized.includes('|') ||
sanitized.includes('?') ||
sanitized.includes('*') ||
sanitized.includes('\x00') ||
/[\x00-\x1F\x7F]/.test(sanitized)
) {
throw new Error('Path segment contains invalid characters')
}

return sanitized
})

return sanitizedSegments.join(path.sep)
}

export function findLocalFile(filename: string): string | null {
export async function findLocalFile(filename: string): Promise<string | null> {
try {
const sanitizedFilename = sanitizeFileKey(filename)

// Reject if sanitized filename is empty or only contains path separators/dots
if (!sanitizedFilename || !sanitizedFilename.trim() || /^[/\\.\s]+$/.test(sanitizedFilename)) {
return null
}

const possiblePaths = [
path.join(UPLOAD_DIR, sanitizedFilename),
path.join(process.cwd(), 'uploads', sanitizedFilename),
]
const { existsSync } = await import('fs')
const path = await import('path')
const { UPLOAD_DIR_SERVER } = await import('@/lib/uploads/core/setup.server')

for (const filePath of possiblePaths) {
const resolvedPath = path.resolve(filePath)
const allowedDirs = [path.resolve(UPLOAD_DIR), path.resolve(process.cwd(), 'uploads')]
const resolvedPath = path.join(UPLOAD_DIR_SERVER, sanitizedFilename)

// Must be within allowed directory but NOT the directory itself
const isWithinAllowedDir = allowedDirs.some(
(allowedDir) =>
resolvedPath.startsWith(allowedDir + path.sep) && resolvedPath !== allowedDir
)

if (!isWithinAllowedDir) {
continue
}
if (
!resolvedPath.startsWith(UPLOAD_DIR_SERVER + path.sep) ||
resolvedPath === UPLOAD_DIR_SERVER
) {
return null
}

if (existsSync(resolvedPath)) {
return resolvedPath
}
if (existsSync(resolvedPath)) {
return resolvedPath
}

return null
Expand Down
67 changes: 67 additions & 0 deletions apps/sim/app/api/tools/workday/assign-onboarding/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { generateRequestId } from '@/lib/core/utils/request'
import { createWorkdaySoapClient, extractRefId, wdRef } from '@/tools/workday/soap'

export const dynamic = 'force-dynamic'

const logger = createLogger('WorkdayAssignOnboardingAPI')

const RequestSchema = z.object({
tenantUrl: z.string().min(1),
tenant: z.string().min(1),
username: z.string().min(1),
password: z.string().min(1),
workerId: z.string().min(1),
onboardingPlanId: z.string().min(1),
actionEventId: z.string().min(1),
})

export async function POST(request: NextRequest) {
const requestId = generateRequestId()

try {
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
if (!authResult.success) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}

const body = await request.json()
const data = RequestSchema.parse(body)

const client = await createWorkdaySoapClient(
data.tenantUrl,
data.tenant,
'humanResources',
data.username,
data.password
)

const [result] = await client.Put_Onboarding_Plan_AssignmentAsync({
Onboarding_Plan_Assignment_Data: {
Onboarding_Plan_Reference: wdRef('Onboarding_Plan_ID', data.onboardingPlanId),
Person_Reference: wdRef('WID', data.workerId),
Action_Event_Reference: wdRef('Background_Check_ID', data.actionEventId),
Assignment_Effective_Moment: new Date().toISOString(),
Active: true,
},
})

return NextResponse.json({
success: true,
output: {
assignmentId: extractRefId(result?.Onboarding_Plan_Assignment_Reference),
workerId: data.workerId,
planId: data.onboardingPlanId,
},
})
} catch (error) {
logger.error(`[${requestId}] Workday assign onboarding failed`, { error })
return NextResponse.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
{ status: 500 }
)
}
}
Loading
Loading