diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 87b041e5..85cf1253 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -361,6 +361,83 @@ describe('ProjectsManager', () => { expect(project.name).toBe('new-project'); expect(project.id).toBe('new-project'); }); + + it('should prevent zip slip attacks during import', async () => { + await projectsManager.init(); + + // Mock the git methods + const mockGit = { + init: vi.fn(), + clone: vi.fn(), + add: vi.fn(), + commit: vi.fn(), + getConfig: vi.fn(), + getAllFiles: vi.fn().mockResolvedValue([]), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Create a mock ZIP file that would try to escape the project directory + const zipFile = new File(['malicious content'], 'malicious.zip', { type: 'application/zip' }); + + // Mock JSZip to simulate a malicious ZIP with path traversal + const JSZip = await import('jszip'); + + const mockLoadAsync = vi.fn().mockResolvedValue({ + files: { + '../../../etc/passwd': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])) + }, + '../../outside.txt': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])) + }, + 'safe-file.txt': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])) + } + } + }); + + vi.spyOn(JSZip.default, 'loadAsync').mockImplementation(mockLoadAsync); + + // Mock arrayBuffer method + Object.defineProperty(zipFile, 'arrayBuffer', { + value: () => Promise.resolve(new ArrayBuffer(0)), + writable: false + }); + + // Spy on console.warn to check for security warnings + const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + try { + // Import the malicious ZIP + const project = await projectsManager.importProjectFromZip(zipFile, undefined, false); + + // Should have completed successfully (safe files extracted) + expect(project).toBeDefined(); + + // Should have logged a security warning about skipped files + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining('Skipped 2 files due to security concerns'), + ['../../../etc/passwd', '../../outside.txt'] + ); + + // Verify that only safe files would be written (check writeFile calls) + const writeFileCalls = (fs.writeFile as unknown as { mock?: { calls: [string, unknown][] } }).mock?.calls || []; + const maliciousPaths = writeFileCalls.filter((call: [string, unknown]) => + call[0].includes('../') || call[0].includes('etc/passwd') || call[0].includes('outside.txt') + ); + expect(maliciousPaths).toHaveLength(0); + + } finally { + // Restore mocks + consoleSpy.mockRestore(); + vi.restoreAllMocks(); + } + }); }); describe('renameProject', () => { diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index f6faa22b..2bc8bd3d 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -154,32 +154,41 @@ export class ProjectsManager { const arrayBuffer = await zipFile.arrayBuffer(); const zip = await JSZip.loadAsync(arrayBuffer); - // Extract all files from the zip - const files = Object.keys(zip.files); + // Extract all files from the zip with security validation + const extractedFiles: string[] = []; + const skippedFiles: string[] = []; - for (const filePath of files) { - const zipEntry = zip.files[filePath]; + for (const [relativePath, zipEntry] of Object.entries(zip.files)) { + // Validate the extraction path is within the project directory + const extractPath = this.join(projectPath, relativePath); + + if (!this.isPathWithinProject(extractPath, projectPath)) { + skippedFiles.push(relativePath); + continue; + } - // Skip directories (they end with / in JSZip) if (zipEntry.dir) { // Create the directory structure - const dirPath = `${projectPath}/${filePath}`; - await this.fs.mkdir(dirPath, { recursive: true }); + await this.fs.mkdir(extractPath, { recursive: true }); continue; } // Extract file content const content = await zipEntry.async('uint8array'); - const fullPath = `${projectPath}/${filePath}`; // Ensure parent directory exists - const dirPath = fullPath.split('/').slice(0, -1).join('/'); + const dirPath = extractPath.split('/').slice(0, -1).join('/'); if (dirPath) { await this.fs.mkdir(dirPath, { recursive: true }); } // Write the file (this will overwrite existing files) - await this.fs.writeFile(fullPath, content); + await this.fs.writeFile(extractPath, content); + extractedFiles.push(relativePath); + } + + if (skippedFiles.length > 0) { + console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project direcotry:`, skippedFiles); } // Get filesystem stats for timestamps @@ -580,4 +589,57 @@ export class ProjectsManager { return files; } + + /** + * Safe path join that normalizes the result to prevent directory traversal + */ + private join(...paths: string[]): string { + // Simple path joining with normalization + const joined = paths.join('/').replace(/\/+/g, '/'); + + // Normalize path separators and resolve .. and . components + const parts = joined.split('/').filter(part => part !== ''); + const normalized: string[] = []; + + for (const part of parts) { + if (part === '..') { + normalized.pop(); + } else if (part !== '.') { + normalized.push(part); + } + } + + return '/' + normalized.join('/'); + } + + /** + * Check if a path is within the project directory + */ + private isPathWithinProject(extractPath: string, projectPath: string): boolean { + // Normalize both paths + const normalizedExtractPath = this.normalize(extractPath); + const normalizedProjectPath = this.normalize(projectPath); + + // Check if the extract path starts with the project path + return normalizedExtractPath.startsWith(normalizedProjectPath + '/') || + normalizedExtractPath === normalizedProjectPath; + } + + /** + * Normalize a path by resolving . and .. components + */ + private normalize(path: string): string { + const parts = path.split('/').filter(part => part !== ''); + const normalized: string[] = []; + + for (const part of parts) { + if (part === '..') { + normalized.pop(); + } else if (part !== '.') { + normalized.push(part); + } + } + + return '/' + normalized.join('/'); + } } \ No newline at end of file diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 85c8e8ac..a0c39678 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -261,12 +261,13 @@ export default function Index() { navigate(`/project/${project.id}?${searchParams.toString()}`); } catch (error) { console.error('Failed to create project:', error); - checkForKeyFailure(error) || + if (!checkForKeyFailure(error)) { toast({ title: "Project Creation Failed", description: error instanceof Error ? error.message : "An unexpected error occurred", variant: "destructive", }); + } } finally { setIsCreating(false); }