Compare commits
3 Commits
main
...
galzahavi/
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73f9085cad | ||
|
|
296be23bd6 | ||
|
|
0b591f39dc |
@ -1007,6 +1007,7 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
this.fileSystemService = new SandboxedFileSystemService(
|
||||
this._sandboxManager,
|
||||
params.targetDir,
|
||||
this.workspaceContext,
|
||||
);
|
||||
} else {
|
||||
this.fileSystemService = new StandardFileSystemService();
|
||||
@ -1397,14 +1398,13 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
// Add plans directory to workspace context for plan file storage
|
||||
if (this.planEnabled) {
|
||||
const plansDir = this.storage.getPlansDir();
|
||||
this.workspaceContext.addWritablePath(plansDir);
|
||||
try {
|
||||
await fs.promises.access(plansDir);
|
||||
this.workspaceContext.addDirectory(plansDir);
|
||||
} catch {
|
||||
// Directory does not exist yet, so we don't add it to the workspace context.
|
||||
// It will be created when the first plan is written. Since custom plan
|
||||
// directories must be within the project root, they are automatically
|
||||
// covered by the project-wide file discovery once created.
|
||||
// Directory does not exist yet, so we only add it as a writable path
|
||||
// for validation, but not as a workspace directory for discovery.
|
||||
}
|
||||
}
|
||||
|
||||
@ -1708,6 +1708,11 @@ export class Config implements McpContext, AgentLoopContext {
|
||||
this.getApprovalMode(),
|
||||
);
|
||||
this.shellExecutionConfig.sandboxManager = this._sandboxManager;
|
||||
|
||||
// Update FileSystemService if using SandboxedFileSystemService
|
||||
if (this.fileSystemService instanceof SandboxedFileSystemService) {
|
||||
this.fileSystemService.updateSandboxManager(this._sandboxManager);
|
||||
}
|
||||
}
|
||||
|
||||
get sandboxPolicyManager() {
|
||||
|
||||
@ -256,6 +256,7 @@ export class LinuxSandboxManager implements SandboxManager {
|
||||
includeDirectories: this.options.includeDirectories || [],
|
||||
maskFilePath: this.getMaskFilePath(),
|
||||
isWriteCommand: req.command === '__write',
|
||||
geminiTmpPath: join(os.homedir(), '.gemini', 'tmp'),
|
||||
});
|
||||
|
||||
const bpfPath = getSeccompBpfPath();
|
||||
|
||||
@ -33,6 +33,7 @@ export interface BwrapArgsOptions {
|
||||
includeDirectories: string[];
|
||||
maskFilePath: string;
|
||||
isWriteCommand: boolean;
|
||||
geminiTmpPath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -63,6 +64,15 @@ export async function buildBwrapArgs(
|
||||
'/tmp',
|
||||
);
|
||||
|
||||
// Allow read/write access to the Gemini temporary directory if provided
|
||||
if (options.geminiTmpPath) {
|
||||
const geminiTmp = tryRealpath(options.geminiTmpPath);
|
||||
bwrapArgs.push('--bind-try', options.geminiTmpPath, options.geminiTmpPath);
|
||||
if (geminiTmp !== options.geminiTmpPath) {
|
||||
bwrapArgs.push('--bind-try', geminiTmp, geminiTmp);
|
||||
}
|
||||
}
|
||||
|
||||
const workspacePath = tryRealpath(options.workspace);
|
||||
|
||||
const bindFlag = options.workspaceWrite ? '--bind-try' : '--ro-bind-try';
|
||||
@ -91,7 +101,7 @@ export async function buildBwrapArgs(
|
||||
for (const includeDir of includeDirs) {
|
||||
try {
|
||||
const resolved = tryRealpath(includeDir);
|
||||
bwrapArgs.push('--ro-bind-try', resolved, resolved);
|
||||
bwrapArgs.push(bindFlag, resolved, resolved);
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
@ -117,7 +127,7 @@ export async function buildBwrapArgs(
|
||||
}
|
||||
const normalizedAllowedPath = normalize(resolved).replace(/\/$/, '');
|
||||
if (normalizedAllowedPath !== normalizedWorkspace) {
|
||||
bwrapArgs.push('--bind-try', resolved, resolved);
|
||||
bwrapArgs.push(bindFlag, resolved, resolved);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -144,6 +144,7 @@ export class MacOsSandboxManager implements SandboxManager {
|
||||
networkAccess: mergedAdditional.network,
|
||||
workspaceWrite,
|
||||
additionalPermissions: mergedAdditional,
|
||||
geminiTmpPath: path.join(os.homedir(), '.gemini', 'tmp'),
|
||||
});
|
||||
|
||||
const tempFile = this.writeProfileToTempFile(sandboxArgs);
|
||||
|
||||
@ -34,6 +34,8 @@ export interface SeatbeltArgsOptions {
|
||||
additionalPermissions?: SandboxPermissions;
|
||||
/** Whether to allow write access to the workspace. */
|
||||
workspaceWrite?: boolean;
|
||||
/** The path to the Gemini temporary directory (~/.gemini/tmp). */
|
||||
geminiTmpPath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -61,6 +63,15 @@ export function buildSeatbeltProfile(options: SeatbeltArgsOptions): string {
|
||||
const tmpPath = tryRealpath(os.tmpdir());
|
||||
profile += `(allow file-read* file-write* (subpath "${escapeSchemeString(tmpPath)}"))\n`;
|
||||
|
||||
// Allow read/write access to the Gemini temporary directory if provided
|
||||
if (options.geminiTmpPath) {
|
||||
const geminiTmp = tryRealpath(options.geminiTmpPath);
|
||||
profile += `(allow file-read* file-write* (subpath "${escapeSchemeString(options.geminiTmpPath)}"))\n`;
|
||||
if (geminiTmp !== options.geminiTmpPath) {
|
||||
profile += `(allow file-read* file-write* (subpath "${escapeSchemeString(geminiTmp)}"))\n`;
|
||||
}
|
||||
}
|
||||
|
||||
// Add explicit deny rules for governance files in the workspace.
|
||||
// These are added after the workspace allow rule to ensure they take precedence
|
||||
// (Seatbelt evaluates rules in order, later rules win for same path).
|
||||
@ -158,7 +169,11 @@ export function buildSeatbeltProfile(options: SeatbeltArgsOptions): string {
|
||||
const allowedPaths = options.allowedPaths;
|
||||
for (let i = 0; i < allowedPaths.length; i++) {
|
||||
const allowedPath = tryRealpath(allowedPaths[i]);
|
||||
profile += `(allow file-read* file-write* (subpath "${escapeSchemeString(allowedPath)}"))\n`;
|
||||
if (options.workspaceWrite) {
|
||||
profile += `(allow file-read* file-write* (subpath "${escapeSchemeString(allowedPath)}"))\n`;
|
||||
} else {
|
||||
profile += `(allow file-read* (subpath "${escapeSchemeString(allowedPath)}"))\n`;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle granular additional permissions
|
||||
|
||||
@ -222,7 +222,25 @@ export class WindowsSandboxManager implements SandboxManager {
|
||||
|
||||
// Native commands __read and __write are passed directly to GeminiSandbox.exe
|
||||
|
||||
const isApproved = allowOverrides
|
||||
? await isStrictlyApproved(
|
||||
command,
|
||||
args,
|
||||
this.options.modeConfig?.approvedTools,
|
||||
)
|
||||
: false;
|
||||
|
||||
const isYolo = this.options.modeConfig?.yolo ?? false;
|
||||
const workspaceWrite = !isReadonlyMode || isApproved || isYolo;
|
||||
|
||||
if (workspaceWrite) {
|
||||
await this.grantLowIntegrityAccess(this.options.workspace);
|
||||
}
|
||||
|
||||
// Grant write access to the Gemini temporary directory
|
||||
await this.grantLowIntegrityAccess(
|
||||
path.join(os.homedir(), '.gemini', 'tmp'),
|
||||
);
|
||||
|
||||
// Fetch persistent approvals for this command
|
||||
const commandName = await getCommandName(command, args);
|
||||
@ -259,31 +277,19 @@ export class WindowsSandboxManager implements SandboxManager {
|
||||
this.options.modeConfig?.network ?? req.policy?.networkAccess ?? false;
|
||||
const networkAccess = defaultNetwork || mergedAdditional.network;
|
||||
|
||||
// 1. Handle filesystem permissions for Low Integrity
|
||||
// Grant "Low Mandatory Level" write access to the workspace.
|
||||
// If not in readonly mode OR it's a strictly approved pipeline, allow workspace writes
|
||||
const isApproved = allowOverrides
|
||||
? await isStrictlyApproved(
|
||||
command,
|
||||
args,
|
||||
this.options.modeConfig?.approvedTools,
|
||||
)
|
||||
: false;
|
||||
|
||||
if (!isReadonlyMode || isApproved) {
|
||||
await this.grantLowIntegrityAccess(this.options.workspace);
|
||||
}
|
||||
|
||||
const { allowed: allowedPaths, forbidden: forbiddenPaths } =
|
||||
await resolveSandboxPaths(this.options, req);
|
||||
|
||||
// Grant "Low Mandatory Level" access to includeDirectories.
|
||||
// Grant "Low Mandatory Level" access to includeDirectories only if workspaceWrite is enabled.
|
||||
const includeDirs = sanitizePaths(this.options.includeDirectories);
|
||||
for (const includeDir of includeDirs) {
|
||||
await this.grantLowIntegrityAccess(includeDir);
|
||||
if (workspaceWrite) {
|
||||
await this.grantLowIntegrityAccess(includeDir);
|
||||
}
|
||||
}
|
||||
|
||||
// Grant "Low Mandatory Level" read/write access to allowedPaths.
|
||||
// Grant "Low Mandatory Level" read/write access to allowedPaths only if workspaceWrite is enabled.
|
||||
// If not enabled, they remain at Medium integrity (default), which means a Low integrity process cannot write to them.
|
||||
for (const allowedPath of allowedPaths) {
|
||||
const resolved = await tryRealpath(allowedPath);
|
||||
try {
|
||||
@ -294,10 +300,12 @@ export class WindowsSandboxManager implements SandboxManager {
|
||||
'On Windows, granular sandbox access can only be granted to existing paths to avoid broad parent directory permissions.',
|
||||
);
|
||||
}
|
||||
await this.grantLowIntegrityAccess(resolved);
|
||||
if (workspaceWrite) {
|
||||
await this.grantLowIntegrityAccess(resolved);
|
||||
}
|
||||
}
|
||||
|
||||
// Grant "Low Mandatory Level" write access to additional permissions write paths.
|
||||
// Granular permissions: Grant write access to specifically requested paths
|
||||
const additionalWritePaths = sanitizePaths(
|
||||
mergedAdditional.fileSystem?.write,
|
||||
);
|
||||
|
||||
@ -94,7 +94,11 @@ describe('SandboxedFileSystemService', () => {
|
||||
command: '__read',
|
||||
args: [testFile],
|
||||
policy: {
|
||||
allowedPaths: [testFile],
|
||||
additionalPermissions: {
|
||||
fileSystem: {
|
||||
read: [testFile],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
@ -136,7 +140,6 @@ describe('SandboxedFileSystemService', () => {
|
||||
command: '__write',
|
||||
args: [testFile],
|
||||
policy: {
|
||||
allowedPaths: [testFile],
|
||||
additionalPermissions: {
|
||||
fileSystem: {
|
||||
write: [testFile],
|
||||
|
||||
@ -10,6 +10,7 @@ import { type SandboxManager } from './sandboxManager.js';
|
||||
import { debugLogger } from '../utils/debugLogger.js';
|
||||
import { isNodeError } from '../utils/errors.js';
|
||||
import { resolveToRealPath, isSubpath } from '../utils/paths.js';
|
||||
import type { WorkspaceContext } from '../utils/workspaceContext.js';
|
||||
|
||||
/**
|
||||
* A FileSystemService implementation that performs operations through a sandbox.
|
||||
@ -18,27 +19,61 @@ export class SandboxedFileSystemService implements FileSystemService {
|
||||
constructor(
|
||||
private sandboxManager: SandboxManager,
|
||||
private cwd: string,
|
||||
private workspaceContext?: WorkspaceContext,
|
||||
) {}
|
||||
|
||||
private sanitizeAndValidatePath(filePath: string): string {
|
||||
/**
|
||||
* Updates the sandbox manager used by the service.
|
||||
* This is called when the global approval mode changes.
|
||||
*/
|
||||
updateSandboxManager(sandboxManager: SandboxManager): void {
|
||||
this.sandboxManager = sandboxManager;
|
||||
}
|
||||
|
||||
private sanitizeAndValidatePath(
|
||||
filePath: string,
|
||||
checkType: 'read' | 'write' = 'write',
|
||||
): string {
|
||||
const resolvedPath = resolveToRealPath(filePath);
|
||||
if (!isSubpath(this.cwd, resolvedPath) && this.cwd !== resolvedPath) {
|
||||
throw new Error(
|
||||
`Access denied: Path '${filePath}' is outside the workspace.`,
|
||||
);
|
||||
|
||||
if (this.workspaceContext) {
|
||||
const isAllowed =
|
||||
checkType === 'read'
|
||||
? this.workspaceContext.isPathReadable(resolvedPath)
|
||||
: this.workspaceContext.isPathWritable(resolvedPath);
|
||||
|
||||
if (!isAllowed) {
|
||||
throw new Error(
|
||||
`Access denied: Path '${filePath}' is not ${
|
||||
checkType === 'read' ? 'readable' : 'writable'
|
||||
} in the current workspace context.`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Fallback to legacy CWD check if workspaceContext is not provided
|
||||
if (!isSubpath(this.cwd, resolvedPath) && this.cwd !== resolvedPath) {
|
||||
throw new Error(
|
||||
`Access denied: Path '${filePath}' is outside the workspace.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
async readTextFile(filePath: string): Promise<string> {
|
||||
const safePath = this.sanitizeAndValidatePath(filePath);
|
||||
const safePath = this.sanitizeAndValidatePath(filePath, 'read');
|
||||
const prepared = await this.sandboxManager.prepareCommand({
|
||||
command: '__read',
|
||||
args: [safePath],
|
||||
cwd: this.cwd,
|
||||
env: process.env,
|
||||
policy: {
|
||||
allowedPaths: [safePath],
|
||||
additionalPermissions: {
|
||||
fileSystem: {
|
||||
read: [safePath],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@ -91,14 +126,13 @@ export class SandboxedFileSystemService implements FileSystemService {
|
||||
}
|
||||
|
||||
async writeTextFile(filePath: string, content: string): Promise<void> {
|
||||
const safePath = this.sanitizeAndValidatePath(filePath);
|
||||
const safePath = this.sanitizeAndValidatePath(filePath, 'write');
|
||||
const prepared = await this.sandboxManager.prepareCommand({
|
||||
command: '__write',
|
||||
args: [safePath],
|
||||
cwd: this.cwd,
|
||||
env: process.env,
|
||||
policy: {
|
||||
allowedPaths: [safePath],
|
||||
additionalPermissions: {
|
||||
fileSystem: {
|
||||
write: [safePath],
|
||||
|
||||
@ -128,6 +128,7 @@ export class EnterPlanModeInvocation extends BaseToolInvocation<
|
||||
// In sandboxed environments, the plans directory must exist on the host
|
||||
// before it can be bound/allowed in the sandbox.
|
||||
const plansDir = this.config.storage.getPlansDir();
|
||||
this.config.getWorkspaceContext().addWritablePath(plansDir);
|
||||
if (!fs.existsSync(plansDir)) {
|
||||
try {
|
||||
fs.mkdirSync(plansDir, { recursive: true });
|
||||
|
||||
@ -162,6 +162,47 @@ describe('WorkspaceContext with real filesystem', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should support granular writable paths that do not exist yet', () => {
|
||||
const workspaceContext = new WorkspaceContext(cwd);
|
||||
const plansDir = path.join(tempDir, 'plans');
|
||||
const planFile = path.join(plansDir, 'my-plan.md');
|
||||
|
||||
// Initially rejected
|
||||
expect(workspaceContext.isPathWritable(planFile)).toBe(false);
|
||||
|
||||
// Register as writable
|
||||
workspaceContext.addWritablePath(plansDir);
|
||||
|
||||
// Now accepted even though plansDir does not exist on disk yet
|
||||
expect(workspaceContext.isPathWritable(planFile)).toBe(true);
|
||||
expect(workspaceContext.isPathWritable(plansDir)).toBe(true);
|
||||
|
||||
// Other paths still rejected
|
||||
const otherFile = path.join(tempDir, 'other', 'file.txt');
|
||||
expect(workspaceContext.isPathWritable(otherFile)).toBe(false);
|
||||
});
|
||||
|
||||
it('should support workspace paths in isPathWritable', () => {
|
||||
const workspaceContext = new WorkspaceContext(cwd);
|
||||
const projectFile = path.join(cwd, 'src', 'index.ts');
|
||||
|
||||
expect(workspaceContext.isPathWritable(projectFile)).toBe(true);
|
||||
});
|
||||
|
||||
it('should support read-only paths in isPathReadable', () => {
|
||||
const workspaceContext = new WorkspaceContext(cwd);
|
||||
const readOnlyDir = path.join(tempDir, 'readonly');
|
||||
const readOnlyFile = path.join(readOnlyDir, 'data.json');
|
||||
|
||||
fs.mkdirSync(readOnlyDir);
|
||||
fs.writeFileSync(readOnlyFile, '{}');
|
||||
|
||||
workspaceContext.addReadOnlyPath(readOnlyDir);
|
||||
|
||||
expect(workspaceContext.isPathReadable(readOnlyFile)).toBe(true);
|
||||
expect(workspaceContext.isPathWritable(readOnlyFile)).toBe(false);
|
||||
});
|
||||
|
||||
describe.skipIf(os.platform() === 'win32')('with symbolic link', () => {
|
||||
describe('in the workspace', () => {
|
||||
let realDir: string;
|
||||
|
||||
@ -25,6 +25,7 @@ export class WorkspaceContext {
|
||||
private directories = new Set<string>();
|
||||
private initialDirectories: Set<string>;
|
||||
private readOnlyPaths = new Set<string>();
|
||||
private writablePaths = new Set<string>();
|
||||
private onDirectoriesChangedListeners = new Set<() => void>();
|
||||
|
||||
/**
|
||||
@ -132,6 +133,18 @@ export class WorkspaceContext {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a path that is allowed to be written to, even if it's not within the workspace.
|
||||
* This is useful for temporary directories or specific files that need to be
|
||||
* writable even in restricted modes. Unlike addDirectory, this does not
|
||||
* require the path to exist.
|
||||
*/
|
||||
addWritablePath(pathToAdd: string): void {
|
||||
// Resolve to absolute path, but don't use realpath as it might not exist
|
||||
const resolved = path.resolve(this.targetDir, pathToAdd);
|
||||
this.writablePaths.add(resolved);
|
||||
}
|
||||
|
||||
private resolveAndValidateDir(directory: string): string {
|
||||
const absolutePath = path.resolve(this.targetDir, directory);
|
||||
|
||||
@ -221,6 +234,34 @@ export class WorkspaceContext {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a path is allowed to be written to.
|
||||
* This includes workspace paths and explicitly added writable paths.
|
||||
* @param pathToCheck The path to validate
|
||||
* @returns True if the path is writable, false otherwise
|
||||
*/
|
||||
isPathWritable(pathToCheck: string): boolean {
|
||||
if (this.isPathWithinWorkspace(pathToCheck)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const fullyResolvedPath = this.fullyResolvedPath(pathToCheck);
|
||||
|
||||
for (const allowedPath of this.writablePaths) {
|
||||
// Allow exact matches or subpaths (if allowedPath is a directory)
|
||||
if (
|
||||
fullyResolvedPath === allowedPath ||
|
||||
this.isPathWithinRoot(fullyResolvedPath, allowedPath)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully resolves a path, including symbolic links.
|
||||
* If the path does not exist, it returns the fully resolved path as it would be
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user