From e9e096ac9e8e3a05ca9261b5d83823c6582d408d Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 15 Jun 2026 09:28:11 +0800 Subject: [PATCH] feat(sandbox): reject blocked request on bash tool result --- packages/agent/src/activities/agent.ts | 46 +----- .../src/database-session-storage.test.ts | 1 + packages/agent/src/index.test.ts | 131 +++++++++++++++++- packages/agent/src/index.ts | 16 ++- packages/agent/src/tools/sandboxed-bash.ts | 15 ++ 5 files changed, 161 insertions(+), 48 deletions(-) diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 1c198997..fad670bd 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -97,8 +97,6 @@ If you need to create files in the local filesystem (for example, a temporary fi systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.` } - let blockedHost = '' - const { session, harness } = await createAgentSession({ teamId: params.teamId, agentId: params.agentId, @@ -124,9 +122,6 @@ If you need to create files in the local filesystem (for example, a temporary fi config: m.config, })), })), - onNetworkBlocked: (host) => { - blockedHost = host - }, }) const imagesToPass: ImageContent[] = [] @@ -148,24 +143,6 @@ If you need to create files in the local filesystem (for example, a temporary fi try { const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass }) - const storage = session.getStorage() - let sessionId = '' - if (storage instanceof DatabaseSessionStorage) { - sessionId = storage.sessionId - } - - if (blockedHost) { - return { - text: `Network request to ${blockedHost} is blocked, please ask admin to allow it in sandbox settings.`, - usage: { - model: modelId, - inputTokens: assistantMessage.usage?.input || 0, - outputTokens: assistantMessage.usage?.output || 0, - }, - sessionId, - } - } - const sessionEntries = await session.getEntries() sessionEntries.forEach((entry) => { if (entry.type === 'message') { @@ -202,25 +179,12 @@ If you need to create files in the local filesystem (for example, a temporary fi outputTokens: assistantMessage.usage?.output || 0, } - return { text, usage, sessionId } - } catch (err) { - if (blockedHost) { - const storage = session.getStorage() - let sessionId = '' - if (storage instanceof DatabaseSessionStorage) { - sessionId = storage.sessionId - } - return { - text: `Network request to ${blockedHost} is blocked, please ask admin to allow it in sandbox settings.`, - usage: { - model: modelId, - inputTokens: 0, - outputTokens: 0, - }, - sessionId, - } + const storage = session.getStorage() + let sessionId = '' + if (storage instanceof DatabaseSessionStorage) { + sessionId = storage.sessionId } - throw err + return { text, usage, sessionId } } finally { // Cleanup handled by agent session if needed } diff --git a/packages/agent/src/database-session-storage.test.ts b/packages/agent/src/database-session-storage.test.ts index 3f58d2f9..2b3a4fe2 100644 --- a/packages/agent/src/database-session-storage.test.ts +++ b/packages/agent/src/database-session-storage.test.ts @@ -335,6 +335,7 @@ describe('DatabaseSessionStorage', () => { expect.objectContaining({ MOCK_ENV_VAR: 'mocked-value', }), + expect.any(Object), ) }) diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index 8bf07085..36789d87 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -1,6 +1,27 @@ -import { describe, it, expect } from 'vitest' -import { formatSkillsForPrompt } from './index' +import { describe, it, expect, vi } from 'vitest' +import { formatSkillsForPrompt, createAgentSession } from './index' +import { createSandboxedBashTool } from './tools/sandboxed-bash' +import { SandboxManager } from '@anthropic-ai/sandbox-runtime' +import { prisma } from '@shumai/db' +import { setupTestDbHooks } from '@shumai/db/test' import * as path from 'path' +import * as childProcess from 'node:child_process' + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let mockSpawn: any = null + +vi.mock('node:child_process', async () => { + const actual = (await vi.importActual('node:child_process')) as typeof childProcess + return { + ...actual, + spawn: (...args: Parameters) => { + if (mockSpawn) { + return mockSpawn(...args) + } + return actual.spawn(...args) + }, + } +}) describe('formatSkillsForPrompt', () => { it('should return empty string if skills array is empty', () => { @@ -31,3 +52,109 @@ describe('formatSkillsForPrompt', () => { expect(result).toContain('') }) }) + +describe('Sandbox Network isolation integration', () => { + setupTestDbHooks() + + it('should register callback that pushes blocked hosts to database and propagates to bash tool', async () => { + // 1. Create a team + const team = await prisma.team.create({ + data: { name: 'Test Sandbox Team' }, + }) + + // Ensure agent user and agent exist in database to avoid foreign key violation + await prisma.user.create({ + data: { + id: 'test-agent', + name: 'Ai Agent', + email: 'test-agent@shumai.ai', + type: 'agent', + }, + }) + await prisma.agent.create({ + data: { + id: 'test-agent', + teamId: team.id, + type: 'chat', + config: { + provider: 'openai', + model: 'gpt-4', + }, + }, + }) + + // 2. Mock / spy SandboxManager + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + const wrapSpy = vi + .spyOn(SandboxManager, 'wrapWithSandbox') + .mockImplementation(async (cmd) => cmd) + + // 3. Call createAgentSession + await createAgentSession({ + teamId: team.id, + agentId: 'test-agent', + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + allowedDomains: [], + providers: [], + }) + + // 4. Verify SandboxManager.initialize was called and extract the callback + expect(initializeSpy).toHaveBeenCalled() + const callback = initializeSpy.mock.calls[0][1] + expect(callback).toBeDefined() + + // 5. Trigger the callback with a blocked host + const result = await callback!({ host: 'blocked-api.com', port: 443 }) + expect(result).toBe(false) // should always return false to block + + // 6. Verify it was pushed to database + const sandbox = await prisma.sandbox.findUnique({ + where: { teamId: team.id }, + }) + expect(sandbox?.pendingDomains).toContain('blocked-api.com:443') + + // 7. Verify that if the bash tool is run while a domain is blocked, it rejects with correct error + const sandboxState = { blockedHost: '' } + const bashTool = createSandboxedBashTool( + process.cwd(), + {}, + { + getBlockedHost: () => sandboxState.blockedHost, + clearBlockedHost: () => { + sandboxState.blockedHost = '' + }, + }, + ) + + // Mock spawn to simulate process exit and trigger network block + mockSpawn = () => { + sandboxState.blockedHost = 'blocked-api.com:443' + const mockChild = { + pid: 123, + stdout: { on: vi.fn() }, + stderr: { on: vi.fn() }, + on: vi.fn((event: string, cb: (code: number) => void) => { + if (event === 'close') { + setTimeout(() => cb(1), 10) + } + }), + } as unknown as childProcess.ChildProcess + return mockChild + } + + const bashPromise = bashTool.execute('1', { command: 'curl blocked-api.com' }) + + try { + await expect(bashPromise).rejects.toThrow( + 'Network request to blocked-api.com:443 is blocked, please ask admin to allow it in sandbox settings.', + ) + } finally { + mockSpawn = null + initializeSpy.mockRestore() + wrapSpy.mockRestore() + } + }) +}) diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index b166636d..fbe4fcd7 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -38,7 +38,6 @@ export interface CreateAgentSessionParams { config: PrismaJson.ModelConfig }> }> - onNetworkBlocked?: (host: string) => void } export async function createAgentSession(params: CreateAgentSessionParams) { @@ -119,6 +118,10 @@ export async function createAgentSession(params: CreateAgentSessionParams) { const allowWrite = [piDir] + const sandboxState = { + blockedHost: '', + } + const sandboxAskCallback = async ({ host, port }: { host: string; port?: number }) => { const hostPort = port ? `${host}:${port}` : host @@ -145,9 +148,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { console.error('Failed to update sandbox pending domains:', err) } - if (params.onNetworkBlocked) { - params.onNetworkBlocked(hostPort) - } + sandboxState.blockedHost = hostPort return false } @@ -209,7 +210,12 @@ export async function createAgentSession(params: CreateAgentSessionParams) { ) } - const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs) + const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, { + getBlockedHost: () => sandboxState.blockedHost, + clearBlockedHost: () => { + sandboxState.blockedHost = '' + }, + }) const readSkill = createReadSkillTool(onEnvsAdded) const systemTools: AgentTool[] = [] diff --git a/packages/agent/src/tools/sandboxed-bash.ts b/packages/agent/src/tools/sandboxed-bash.ts index e9c6445e..f471ad09 100644 --- a/packages/agent/src/tools/sandboxed-bash.ts +++ b/packages/agent/src/tools/sandboxed-bash.ts @@ -15,9 +15,15 @@ type BashDetails = { stderr: string } +export interface SandboxedBashOptions { + getBlockedHost?: () => string + clearBlockedHost?: () => void +} + export const createSandboxedBashTool = ( cwd: string, skillEnvs: Record = {}, + options?: SandboxedBashOptions, ): AgentTool => { return { name: 'bash', @@ -29,6 +35,7 @@ export const createSandboxedBashTool = ( { command, timeout }, signal, ): Promise> => { + options?.clearBlockedHost?.() const wrappedCommand = await SandboxManager.wrapWithSandbox(command) return new Promise((resolve, reject) => { @@ -94,12 +101,20 @@ export const createSandboxedBashTool = ( if (timeoutHandle) clearTimeout(timeoutHandle) signal?.removeEventListener('abort', onAbort) + const blocked = options?.getBlockedHost?.() + if (signal?.aborted) { logger.error({ command, stdout, stderr }, 'Sandboxed bash command aborted') reject(new Error('aborted')) } else if (timedOut) { logger.error({ timeout, command, stdout, stderr }, 'Sandboxed bash command timed out') reject(new Error(`bash command timed out after ${timeout} seconds`)) + } else if (blocked) { + reject( + new Error( + `Network request to ${blocked} is blocked, please ask admin to allow it in sandbox settings.`, + ), + ) } else if (code !== 0 && code !== null) { logger.error( { exitCode: code, command, stdout, stderr },