diff --git a/src/lib/commands/cp.ts b/src/lib/commands/cp.ts index e4589c04..03095d41 100644 --- a/src/lib/commands/cp.ts +++ b/src/lib/commands/cp.ts @@ -36,7 +36,7 @@ export class CpCommand implements ShellCommand { // Check write permissions for destination (sources can be read from anywhere) try { - validateWritePath(destination, this.name); + validateWritePath(destination, this.name, cwd); } catch (error) { return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } diff --git a/src/lib/commands/curl.ts b/src/lib/commands/curl.ts index 51b0d33f..7f19ea81 100644 --- a/src/lib/commands/curl.ts +++ b/src/lib/commands/curl.ts @@ -366,7 +366,7 @@ export class CurlCommand implements ShellCommand { private async writeToFile(filename: string, content: string, cwd: string): Promise { try { // Validate write permissions for absolute paths - validateWritePath(filename, 'curl'); + validateWritePath(filename, 'curl', cwd); // Handle both absolute and relative paths let absolutePath: string; diff --git a/src/lib/commands/mkdir.ts b/src/lib/commands/mkdir.ts index c0646216..b6666df3 100644 --- a/src/lib/commands/mkdir.ts +++ b/src/lib/commands/mkdir.ts @@ -35,7 +35,7 @@ export class MkdirCommand implements ShellCommand { try { // Validate write permissions for absolute paths try { - validateWritePath(dirPath, this.name); + validateWritePath(dirPath, this.name, cwd); } catch (error) { return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } diff --git a/src/lib/commands/mv.ts b/src/lib/commands/mv.ts index 66d7e69f..d4f84184 100644 --- a/src/lib/commands/mv.ts +++ b/src/lib/commands/mv.ts @@ -32,7 +32,7 @@ export class MvCommand implements ShellCommand { const pathsToValidate = [destination, ...sources]; for (const path of pathsToValidate) { try { - validateWritePath(path, this.name); + validateWritePath(path, this.name, cwd); } catch (error) { return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } diff --git a/src/lib/commands/rm.ts b/src/lib/commands/rm.ts index 83dade02..1a17f741 100644 --- a/src/lib/commands/rm.ts +++ b/src/lib/commands/rm.ts @@ -33,9 +33,14 @@ export class RmCommand implements ShellCommand { for (const path of paths) { try { + // Check for special cases first + if (path === '.' || path === '..') { + return createErrorResult(`${this.name}: cannot remove '${path}': Invalid argument`); + } + // Validate write permissions for absolute paths try { - validateWritePath(path, this.name); + validateWritePath(path, this.name, cwd); } catch (error) { return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } diff --git a/src/lib/commands/touch.ts b/src/lib/commands/touch.ts index 7bb11b8d..d3564b50 100644 --- a/src/lib/commands/touch.ts +++ b/src/lib/commands/touch.ts @@ -29,7 +29,7 @@ export class TouchCommand implements ShellCommand { try { // Validate write permissions for absolute paths try { - validateWritePath(filePath, this.name); + validateWritePath(filePath, this.name, cwd); } catch (error) { return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } diff --git a/src/lib/security.test.ts b/src/lib/security.test.ts index 90bc3068..975b0ec3 100644 --- a/src/lib/security.test.ts +++ b/src/lib/security.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect } from 'vitest'; -import { - isAbsolutePath, - isWriteAllowed, - validateWritePath, - createWriteAccessDeniedError +import { + isAbsolutePath, + isWriteAllowed, + validateWritePath, + createWriteAccessDeniedError } from './security'; describe('security', () => { @@ -36,12 +36,41 @@ describe('security', () => { expect(isWriteAllowed('/tmp/subdir/file.txt')).toBe(true); }); + it('should allow writes to /projects/', () => { + expect(isWriteAllowed('/projects')).toBe(true); + expect(isWriteAllowed('/projects/')).toBe(true); + expect(isWriteAllowed('/projects/my-project/file.txt')).toBe(true); + expect(isWriteAllowed('/projects/my-project/src/index.ts')).toBe(true); + }); + + it('should allow writes within current working directory', () => { + const cwd = '/project'; + expect(isWriteAllowed('/project', cwd)).toBe(true); + expect(isWriteAllowed('/project/file.txt', cwd)).toBe(true); + expect(isWriteAllowed('/project/src/index.ts', cwd)).toBe(true); + expect(isWriteAllowed('/project/deep/nested/file.txt', cwd)).toBe(true); + }); + + it('should allow relative paths with cwd', () => { + const cwd = '/project'; + expect(isWriteAllowed('file.txt', cwd)).toBe(true); + expect(isWriteAllowed('src/index.ts', cwd)).toBe(true); + expect(isWriteAllowed('./file.txt', cwd)).toBe(true); + expect(isWriteAllowed('../parent/file.txt', cwd)).toBe(true); + }); + it('should deny writes to other absolute paths', () => { expect(isWriteAllowed('/home/user/file.txt')).toBe(false); expect(isWriteAllowed('/var/log/file.txt')).toBe(false); expect(isWriteAllowed('/absolute/path')).toBe(false); expect(isWriteAllowed('/etc/passwd')).toBe(false); }); + + it('should deny writes outside current working directory', () => { + const cwd = '/project'; + expect(isWriteAllowed('/other/path/file.txt', cwd)).toBe(false); + expect(isWriteAllowed('/home/user/file.txt', cwd)).toBe(false); + }); }); describe('validateWritePath', () => { @@ -75,8 +104,9 @@ describe('security', () => { const error = createWriteAccessDeniedError('/absolute/path'); expect(error).toContain('Write access denied to /absolute/path'); expect(error).toContain('Write operations are only allowed in:'); - expect(error).toContain('- Current project directory (relative paths)'); - expect(error).toContain('- /tmp/ directory and its subdirectories'); + expect(error).toContain('- Current working directory and subdirectories'); + expect(error).toContain('- Project directories (/projects/ and subdirectories)'); + expect(error).toContain('- Temporary directory (/tmp/ and subdirectories)'); expect(error).toContain('💡 Examples of allowed paths:'); }); diff --git a/src/lib/security.ts b/src/lib/security.ts index e0041f9a..bc1a07e0 100644 --- a/src/lib/security.ts +++ b/src/lib/security.ts @@ -2,6 +2,8 @@ * Security utilities for path validation and access control */ +import { normalize } from "@std/path"; + /** * Check if the given path is an absolute path */ @@ -10,43 +12,66 @@ export function isAbsolutePath(path: string): boolean { } /** - * Check if write operations are allowed for the given absolute path - * + * Check if write operations are allowed for the given path + * * Write operations are only allowed in: * - /tmp/ directory and its subdirectories - * - Current project directory (handled via relative paths) + * - /projects/ directory and its subdirectories (project directories) + * - Relative paths (always allowed, regardless of where they resolve to) + * - Absolute paths that resolve to within the current working directory */ -export function isWriteAllowed(absolutePath: string): boolean { +export function isWriteAllowed(path: string, cwd?: string): boolean { + // Always allow relative paths (this follows traditional Unix security model) + if (!isAbsolutePath(path)) { + return true; + } + + // For absolute paths, apply restrictions + const absolutePath = normalize(path); + // Allow writes to /tmp/ and its subdirectories if (absolutePath.startsWith('/tmp/') || absolutePath === '/tmp') { return true; } - - // For other absolute paths, deny write access + + // Allow writes to /projects/ and its subdirectories (project directories) + if (absolutePath.startsWith('/projects/') || absolutePath === '/projects') { + return true; + } + + // If we have a current working directory, allow writes within that directory tree + if (cwd) { + const normalizedCwd = normalize(cwd); + if (absolutePath.startsWith(normalizedCwd + '/') || absolutePath === normalizedCwd) { + return true; + } + } + + // Deny all other absolute paths return false; } /** * Validate a path for write operations and throw descriptive errors - * + * * @param path - The path to validate (can be absolute or relative) * @param operationName - Name of the operation for error messages (e.g., 'touch', 'mkdir') * @param cwd - Current working directory for context in error messages * @throws Error if the path is not allowed for write operations */ export function validateWritePath(path: string, operationName: string, cwd?: string): void { - if (isAbsolutePath(path) && !isWriteAllowed(path)) { + if (!isWriteAllowed(path, cwd)) { const cwdInfo = cwd ? `\n\nCurrent working directory: ${cwd}` : ''; throw new Error( `${operationName}: write access denied to ${path}. ` + - `Write operations are only allowed in project directory and /tmp/${cwdInfo}` + `Write operations are only allowed in project directories and /tmp/${cwdInfo}` ); } } /** * Create a standardized error message for write access denial - * + * * @param path - The path that was denied * @param toolName - Name of the tool/command for context * @param cwd - Current working directory for context @@ -55,14 +80,17 @@ export function validateWritePath(path: string, operationName: string, cwd?: str export function createWriteAccessDeniedError(path: string, toolName?: string, cwd?: string): string { const prefix = toolName ? `❌ Write access denied to "${path}".` : `Write access denied to ${path}.`; const cwdInfo = cwd ? `\n\nCurrent working directory: ${cwd}` : ''; - + return ( `${prefix}\n\n` + `Write operations are only allowed in:\n` + - `- Current project directory (relative paths)\n` + - `- /tmp/ directory and its subdirectories\n\n` + + `- Current working directory and subdirectories\n` + + `- Project directories (/projects/ and subdirectories)\n` + + `- Temporary directory (/tmp/ and subdirectories)\n` + + `- Relative paths (resolved relative to current directory)\n\n` + `💡 Examples of allowed paths:\n` + `- "src/index.ts" (relative to current directory)\n` + + `- "/projects/my-project/src/file.js" (absolute project path)\n` + `- "/tmp/temp-file.txt" (temporary files)\n` + `- "/tmp/workspace/file.js" (temporary workspace)${cwdInfo}` ); diff --git a/src/lib/tools/TextEditorStrReplaceTool.ts b/src/lib/tools/TextEditorStrReplaceTool.ts index fe33c6f7..cbcaa828 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import type { Tool } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; -import { isAbsolutePath, createWriteAccessDeniedError } from "../security"; +import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security"; interface TextEditorStrReplaceParams { path: string; @@ -32,27 +32,12 @@ export class TextEditorStrReplaceTool implements Tool { const { path, old_str, new_str, normalize_whitespace = true } = args; - // Check for absolute paths and validate write permissions - if (isAbsolutePath(path)) { - if (!this.isWriteAllowed(path)) { - throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd)); - } + // Check write permissions + if (!isWriteAllowed(path, this.cwd)) { + throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd)); } // Ban editing dependencies in package.json diff --git a/src/lib/tools/TextEditorWriteTool.ts b/src/lib/tools/TextEditorWriteTool.ts index d09bec2d..0c861d82 100644 --- a/src/lib/tools/TextEditorWriteTool.ts +++ b/src/lib/tools/TextEditorWriteTool.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import type { Tool } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; -import { isAbsolutePath, createWriteAccessDeniedError } from "../security"; +import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security"; interface TextEditorWriteParams { path: string; @@ -28,27 +28,12 @@ export class TextEditorWriteTool implements Tool { this.cwd = cwd; } - /** - * Check if write operations are allowed for the given absolute path - */ - private isWriteAllowed(absolutePath: string): boolean { - // Allow writes to /tmp/ and its subdirectories - if (absolutePath.startsWith('/tmp/') || absolutePath === '/tmp') { - return true; - } - - // For other absolute paths, deny write access - return false; - } - async execute(args: TextEditorWriteParams): Promise { const { path, file_text } = args; - // Check for absolute paths and validate write permissions - if (isAbsolutePath(path)) { - if (!this.isWriteAllowed(path)) { - throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd)); - } + // Check write permissions + if (!isWriteAllowed(path, this.cwd)) { + throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd)); } if (