Update tools to allow reading any VFS path, writing to /tmp

This commit is contained in:
Alex Gleason committed 2025-09-14 12:31:23 -05:00
1 parent f23b92c79f
commit be8309b503
17 files changed
+356 -60

No files matched your search

+3 -3
View File
@@ -118,11 +118,11 @@ describe('CpCommand', () => {
expect(result.stderr).toContain('No such file or directory');
});
it('should reject absolute paths', async () => {
const result = await cpCommand.execute(['/absolute/source', 'dest'], testCwd);
it('should reject absolute destination paths outside allowed directories', async () => {
const result = await cpCommand.execute(['src/test.txt', '/absolute/dest'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
expect(result.stderr).toContain('write access denied');
});
it('should return error when missing operands', async () => {
+20 -7
View File
@@ -2,6 +2,7 @@ import { join, dirname, basename } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath, validateWritePath } from "../security";
/**
* Implementation of the 'cp' command
@@ -33,14 +34,20 @@ export class CpCommand implements ShellCommand {
const sources = paths.slice(0, -1);
const destination = paths[paths.length - 1];
// Check for absolute paths
for (const path of [...sources, destination]) {
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${path}`);
}
// Check write permissions for destination (sources can be read from anywhere)
try {
validateWritePath(destination, this.name);
} catch (error) {
return createErrorResult(error instanceof Error ? error.message : 'Unknown error');
}
const destAbsolutePath = join(cwd, destination);
// Handle both absolute and relative paths for destination
let destAbsolutePath: string;
if (isAbsolutePath(destination)) {
destAbsolutePath = destination;
} else {
destAbsolutePath = join(cwd, destination);
}
// Check if destination exists and is a directory
let destIsDir = false;
@@ -58,7 +65,13 @@ export class CpCommand implements ShellCommand {
for (const source of sources) {
try {
const sourceAbsolutePath = join(cwd, source);
// Handle both absolute and relative paths for source
let sourceAbsolutePath: string;
if (isAbsolutePath(source)) {
sourceAbsolutePath = source;
} else {
sourceAbsolutePath = join(cwd, source);
}
const sourceStats = await this.fs.stat(sourceAbsolutePath);
let targetPath: string;
+10 -5
View File
@@ -2,6 +2,7 @@ import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath, validateWritePath } from "../security";
/**
* Parsed curl options
@@ -364,12 +365,16 @@ export class CurlCommand implements ShellCommand {
*/
private async writeToFile(filename: string, content: string, cwd: string): Promise<void> {
try {
// Handle absolute paths
if (filename.startsWith('/') || filename.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filename)) {
throw new Error('absolute paths are not supported');
}
// Validate write permissions for absolute paths
validateWritePath(filename, 'curl');
const absolutePath = join(cwd, filename);
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(filename)) {
absolutePath = filename;
} else {
absolutePath = join(cwd, filename);
}
await this.fs.writeFile(absolutePath, content, 'utf8');
} catch (error) {
+10 -10
View File
@@ -39,56 +39,56 @@ describe('MkdirCommand', () => {
it('should create new directory', async () => {
const result = await command.execute(['newdir'], '/project');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
});
it('should handle existing directory error', async () => {
const result = await command.execute(['existing'], '/project');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('File exists');
});
it('should handle existing file error', async () => {
const result = await command.execute(['file.txt'], '/project');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('File exists');
});
it('should create parent directories with -p', async () => {
const result = await command.execute(['-p', 'deep/nested'], '/project');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
});
it('should handle missing parent directory without -p', async () => {
const result = await command.execute(['nonexistent/newdir'], '/project');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
});
it('should require directory operand', async () => {
const result = await command.execute([], '/project');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('missing operand');
});
it('should reject absolute paths', async () => {
it('should reject absolute paths outside allowed directories', async () => {
const result = await command.execute(['/absolute/path'], '/project');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
expect(result.stderr).toContain('write access denied');
});
it('should handle multiple directories', async () => {
const result = await command.execute(['newdir', 'deep'], '/project');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
});
+13 -4
View File
@@ -2,6 +2,7 @@ import { join, dirname } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath, validateWritePath } from "../security";
/**
* Implementation of the 'mkdir' command
@@ -32,12 +33,20 @@ export class MkdirCommand implements ShellCommand {
try {
for (const dirPath of directories) {
try {
// Handle absolute paths
if (dirPath.startsWith('/') || dirPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(dirPath)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${dirPath}`);
// Validate write permissions for absolute paths
try {
validateWritePath(dirPath, this.name);
} catch (error) {
return createErrorResult(error instanceof Error ? error.message : 'Unknown error');
}
const absolutePath = join(cwd, dirPath);
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(dirPath)) {
absolutePath = dirPath;
} else {
absolutePath = join(cwd, dirPath);
}
if (options.parents) {
// Create parent directories as needed (-p option)
+2 -2
View File
@@ -104,11 +104,11 @@ describe('MvCommand', () => {
expect(result.stderr).toContain('File exists');
});
it('should reject absolute paths', async () => {
it('should reject absolute paths outside allowed directories', async () => {
const result = await mvCommand.execute(['/absolute/source', 'dest'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
expect(result.stderr).toContain('write access denied');
});
it('should return error when missing operands', async () => {
+22 -6
View File
@@ -2,6 +2,7 @@ import { join, dirname, basename } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath, validateWritePath } from "../security";
/**
* Implementation of the 'mv' command
@@ -27,14 +28,23 @@ export class MvCommand implements ShellCommand {
const sources = args.slice(0, -1);
const destination = args[args.length - 1];
// Check for absolute paths
for (const path of [...sources, destination]) {
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${path}`);
// Check write permissions for destination and sources (since mv deletes the source)
const pathsToValidate = [destination, ...sources];
for (const path of pathsToValidate) {
try {
validateWritePath(path, this.name);
} catch (error) {
return createErrorResult(error instanceof Error ? error.message : 'Unknown error');
}
}
const destAbsolutePath = join(cwd, destination);
// Handle both absolute and relative paths for destination
let destAbsolutePath: string;
if (isAbsolutePath(destination)) {
destAbsolutePath = destination;
} else {
destAbsolutePath = join(cwd, destination);
}
// Check if destination exists and is a directory
let destIsDir = false;
@@ -52,7 +62,13 @@ export class MvCommand implements ShellCommand {
for (const source of sources) {
try {
const sourceAbsolutePath = join(cwd, source);
// Handle both absolute and relative paths for source
let sourceAbsolutePath: string;
if (isAbsolutePath(source)) {
sourceAbsolutePath = source;
} else {
sourceAbsolutePath = join(cwd, source);
}
// Check if source exists
await this.fs.stat(sourceAbsolutePath);
+2 -2
View File
@@ -89,11 +89,11 @@ describe('RmCommand', () => {
expect(result.exitCode).toBe(0);
});
it('should reject absolute paths', async () => {
it('should reject absolute paths outside allowed directories', async () => {
const result = await rmCommand.execute(['/absolute/path'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
expect(result.stderr).toContain('write access denied');
});
it('should reject removing current or parent directory', async () => {
+15 -4
View File
@@ -2,6 +2,7 @@ import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath, validateWritePath } from "../security";
/**
* Implementation of the 'rm' command
@@ -32,9 +33,19 @@ export class RmCommand implements ShellCommand {
for (const path of paths) {
try {
// Handle absolute paths
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${path}`);
// Validate write permissions for absolute paths
try {
validateWritePath(path, this.name);
} catch (error) {
return createErrorResult(error instanceof Error ? error.message : 'Unknown error');
}
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(path)) {
absolutePath = path;
} else {
absolutePath = join(cwd, path);
}
// Prevent removing current directory or parent directory
@@ -42,7 +53,7 @@ export class RmCommand implements ShellCommand {
return createErrorResult(`${this.name}: cannot remove '${path}': Invalid argument`);
}
const absolutePath = join(cwd, path);
try {
const stats = await this.fs.stat(absolutePath);
+2 -2
View File
@@ -65,11 +65,11 @@ describe('TouchCommand', () => {
expect(result.stderr).toContain('missing file operand');
});
it('should reject absolute paths', async () => {
it('should reject absolute paths outside allowed directories', async () => {
const result = await command.execute(['/absolute/path'], '/project');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
expect(result.stderr).toContain('write access denied');
});
it('should handle missing parent directory', async () => {
+13 -4
View File
@@ -2,6 +2,7 @@ import { join, dirname } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath, validateWritePath } from "../security";
/**
* Implementation of the 'touch' command
@@ -26,12 +27,20 @@ export class TouchCommand implements ShellCommand {
try {
for (const filePath of args) {
try {
// Handle absolute paths
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${filePath}`);
// Validate write permissions for absolute paths
try {
validateWritePath(filePath, this.name);
} catch (error) {
return createErrorResult(error instanceof Error ? error.message : 'Unknown error');
}
const absolutePath = join(cwd, filePath);
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(filePath)) {
absolutePath = filePath;
} else {
absolutePath = join(cwd, filePath);
}
try {
// Check if file exists
+93
View File
@@ -0,0 +1,93 @@
import { describe, it, expect } from 'vitest';
import {
isAbsolutePath,
isWriteAllowed,
validateWritePath,
createWriteAccessDeniedError
} from './security';
describe('security', () => {
describe('isAbsolutePath', () => {
it('should detect Unix absolute paths', () => {
expect(isAbsolutePath('/tmp/file.txt')).toBe(true);
expect(isAbsolutePath('/home/user/file.txt')).toBe(true);
expect(isAbsolutePath('/absolute/path')).toBe(true);
});
it('should detect Windows absolute paths', () => {
expect(isAbsolutePath('C:\\temp\\file.txt')).toBe(true);
expect(isAbsolutePath('D:/folder/file.txt')).toBe(true);
expect(isAbsolutePath('\\\\server\\share')).toBe(true);
});
it('should detect relative paths', () => {
expect(isAbsolutePath('src/index.ts')).toBe(false);
expect(isAbsolutePath('./src/index.ts')).toBe(false);
expect(isAbsolutePath('../parent/file.txt')).toBe(false);
expect(isAbsolutePath('file.txt')).toBe(false);
});
});
describe('isWriteAllowed', () => {
it('should allow writes to /tmp/', () => {
expect(isWriteAllowed('/tmp')).toBe(true);
expect(isWriteAllowed('/tmp/')).toBe(true);
expect(isWriteAllowed('/tmp/file.txt')).toBe(true);
expect(isWriteAllowed('/tmp/subdir/file.txt')).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);
});
});
describe('validateWritePath', () => {
it('should allow relative paths', () => {
expect(() => validateWritePath('src/index.ts', 'test')).not.toThrow();
expect(() => validateWritePath('./file.txt', 'test')).not.toThrow();
expect(() => validateWritePath('../parent/file.txt', 'test')).not.toThrow();
});
it('should allow /tmp/ absolute paths', () => {
expect(() => validateWritePath('/tmp/file.txt', 'test')).not.toThrow();
expect(() => validateWritePath('/tmp/subdir/file.txt', 'test')).not.toThrow();
});
it('should reject other absolute paths', () => {
expect(() => validateWritePath('/absolute/path', 'test')).toThrow('write access denied');
expect(() => validateWritePath('/home/user/file.txt', 'test')).toThrow('write access denied');
});
it('should include operation name in error message', () => {
expect(() => validateWritePath('/absolute/path', 'mkdir')).toThrow('mkdir: write access denied');
});
it('should include current working directory in error message', () => {
expect(() => validateWritePath('/absolute/path', 'test', '/project')).toThrow('/project');
});
});
describe('createWriteAccessDeniedError', () => {
it('should create formatted error message without tool name', () => {
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('💡 Examples of allowed paths:');
});
it('should create formatted error message with tool name', () => {
const error = createWriteAccessDeniedError('/absolute/path', 'TextEditor');
expect(error).toContain('❌ Write access denied to "/absolute/path"');
});
it('should include current working directory when provided', () => {
const error = createWriteAccessDeniedError('/absolute/path', undefined, '/project');
expect(error).toContain('Current working directory: /project');
});
});
});
+69
View File
@@ -0,0 +1,69 @@
/**
* Security utilities for path validation and access control
*/
/**
* Check if the given path is an absolute path
*/
export function isAbsolutePath(path: string): boolean {
return path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path);
}
/**
* Check if write operations are allowed for the given absolute path
*
* Write operations are only allowed in:
* - /tmp/ directory and its subdirectories
* - Current project directory (handled via relative paths)
*/
export function 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;
}
/**
* 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)) {
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}`
);
}
}
/**
* 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
* @returns Formatted error message
*/
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` +
`💡 Examples of allowed paths:\n` +
`- "src/index.ts" (relative to current directory)\n` +
`- "/tmp/temp-file.txt" (temporary files)\n` +
`- "/tmp/workspace/file.js" (temporary workspace)${cwdInfo}`
);
}
+15 -1
View File
@@ -134,7 +134,21 @@ describe('TextEditorStrReplaceTool', () => {
path: '/absolute/path/test.ts',
old_str: 'old',
new_str: 'new'
})).rejects.toThrow('❌ Absolute paths are not supported');
})).rejects.toThrow('Write access denied');
});
it('should allow writes to /tmp/ directory', async () => {
// First create the file in /tmp/
await mockFS.writeFile('/tmp/temp-file.txt', 'original content');
const result = await tool.execute({
path: '/tmp/temp-file.txt',
old_str: 'original',
new_str: 'modified'
});
expect(result).toContain('String successfully replaced');
expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('modified content');
});
it('should handle whitespace normalization', async () => {
+27 -4
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import type { Tool } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, createWriteAccessDeniedError } from "../security";
interface TextEditorStrReplaceParams {
path: string;
@@ -31,12 +32,27 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
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: TextEditorStrReplaceParams): Promise<string> {
const { path, old_str, new_str, normalize_whitespace = true } = args;
// Check for absolute paths and provide helpful error
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
throw new Error(`❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`);
// Check for absolute paths and validate write permissions
if (isAbsolutePath(path)) {
if (!this.isWriteAllowed(path)) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd));
}
}
// Ban editing dependencies in package.json
@@ -60,7 +76,14 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
}
try {
const absolutePath = join(this.cwd, path);
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(path)) {
absolutePath = path;
} else {
absolutePath = join(this.cwd, path);
}
const content = await this.fs.readFile(absolutePath, "utf8");
// Helper function to normalize whitespace
+13 -2
View File
@@ -124,11 +124,22 @@ describe('TextEditorWriteTool', () => {
expect(mockFS.getFileContent('/project/src/test.ts')).toBe('console.log("test");');
});
it('should reject absolute paths with helpful error message', async () => {
it('should reject absolute paths outside allowed directories', async () => {
await expect(tool.execute({
path: '/absolute/path/test.ts',
file_text: 'test content'
})).rejects.toThrow('❌ Absolute paths are not supported');
})).rejects.toThrow('Write access denied');
});
it('should allow writes to /tmp/ directory', async () => {
const result = await tool.execute({
path: '/tmp/temp-file.txt',
file_text: 'temporary content'
});
expect(result).toContain('File successfully written to /tmp/temp-file.txt');
expect(mockFS.hasFile('/tmp/temp-file.txt')).toBe(true);
expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('temporary content');
});
it('should reject package.json writes', async () => {
+27 -4
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import type { Tool } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, createWriteAccessDeniedError } from "../security";
interface TextEditorWriteParams {
path: string;
@@ -27,12 +28,27 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
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<string> {
const { path, file_text } = args;
// Check for absolute paths and provide helpful error
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
throw new Error(`❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`);
// Check for absolute paths and validate write permissions
if (isAbsolutePath(path)) {
if (!this.isWriteAllowed(path)) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd));
}
}
if (
@@ -43,7 +59,14 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
}
try {
const absolutePath = join(this.cwd, path);
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(path)) {
absolutePath = path;
} else {
absolutePath = join(this.cwd, path);
}
await this.fs.mkdir(dirname(absolutePath), { recursive: true });
await this.fs.writeFile(absolutePath, file_text, "utf8");
return `File successfully written to ${path}`;