From c938e84ccc7629486a9a84e9eeef5d2051643fb0 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 4 Aug 2026 16:08:04 +0800 Subject: [PATCH 1/3] feat(agent): restrict bash access for non-owner users Editor/reviewer users can no longer ask the agent to run arbitrary bash commands. Bash execution for them is gated behind approved team skills: - Add required source param (enum user/skill) to the bash tool; commands with source=user are blocked when the user is not a team owner. - Append a Restricted User Context instruction to the system prompt for non-owner users: never run user-requested bash, only skill-required commands with source=skill. - Delay bash tool injection for editor/reviewer: it is only added after a skill is successfully loaded via read_skill (or restored when a skill was loaded earlier in the session). Team owners are unaffected. --- packages/agent/src/index.test.ts | 242 +++++++++++++++++- packages/agent/src/index.ts | 72 +++++- packages/agent/src/tools/read-skill.test.ts | 55 ++++ packages/agent/src/tools/read-skill.ts | 4 + .../agent/src/tools/sandboxed-bash.test.ts | 84 +++++- packages/agent/src/tools/sandboxed-bash.ts | 25 +- 6 files changed, 461 insertions(+), 21 deletions(-) diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index 1abf30c5..54e94f7e 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -1,8 +1,9 @@ -import { describe, it, expect, vi } from 'vitest' +import { describe, it, expect, vi, afterEach } from 'vitest' import { formatSkillsForPrompt, createAgentSession, getModelFromDb, + buildRestrictedUserInstructions, type DbProviderInfo, } from './index' import { createSandboxedBashTool } from './tools/sandboxed-bash' @@ -11,6 +12,7 @@ import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import * as path from 'path' import * as childProcess from 'node:child_process' +import * as fs from 'fs' // eslint-disable-next-line @typescript-eslint/no-explicit-any let mockSpawn: any = null @@ -28,6 +30,9 @@ vi.mock('node:child_process', async () => { } }) +// Mock fs so tests can stub skill content loading (matching read-skill.test.ts) +vi.mock('fs') + const mockProviders: DbProviderInfo[] = [ { name: 'google', @@ -172,7 +177,7 @@ describe('Sandbox Network isolation integration', () => { return mockChild } - const bashPromise = bashTool.execute('1', { command: 'curl blocked-api.com' }) + const bashPromise = bashTool.execute('1', { command: 'curl blocked-api.com', source: 'user' }) try { await expect(bashPromise).rejects.toThrow( @@ -556,3 +561,236 @@ describe('createAgentSession sandbox options', () => { initializeSpy.mockRestore() }) }) + +describe('buildRestrictedUserInstructions', () => { + it('should describe the restricted user bash rules', () => { + const instructions = buildRestrictedUserInstructions() + expect(instructions).toContain('# Restricted User Context') + expect(instructions).toContain( + 'NEVER execute a bash command that the user asks you to run directly', + ) + expect(instructions).toContain('loaded via the `read_skill` tool') + expect(instructions).toContain('parameter to "skill"') + expect(instructions).toContain('source="user" will be rejected') + }) +}) + +describe('createAgentSession bash restriction for non-owner users', () => { + setupTestDbHooks() + + afterEach(() => { + vi.restoreAllMocks() + }) + + type TestHarness = Awaited>['harness'] + + async function setupSession(opts: { + role: 'owner' | 'editor' | 'reviewer' | 'none' + deniedTools?: string[] + sessionId?: string + }): Promise<{ team: { id: string }; userId?: string; harness: TestHarness }> { + const team = await prisma.team.create({ data: { name: 'Bash Restriction Team' } }) + + await prisma.user.create({ + data: { + id: 'bash-agent', + name: 'Ai Agent Bash', + email: 'bash-agent@shumai.ai', + type: 'agent', + }, + }) + await prisma.agent.create({ + data: { + id: 'bash-agent', + teamId: team.id, + type: 'chat', + config: { + provider: 'google', + model: 'gemini', + ...(opts.deniedTools ? { deniedTools: opts.deniedTools } : {}), + }, + }, + }) + + let userId: string | undefined + if (opts.role !== 'none') { + const user = await prisma.user.create({ + data: { name: 'Bash User', email: 'bash-user@shumai.ai' }, + }) + await prisma.teamMember.create({ + data: { teamId: team.id, userId: user.id, role: opts.role }, + }) + userId = user.id + } + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + agentId: 'bash-agent', + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + allowedDomains: [], + providers: mockProviders, + userId, + sessionId: opts.sessionId, + }) + return { team, userId, harness } + } finally { + initializeSpy.mockRestore() + } + } + + it('should include the bash tool from the start for team owners', async () => { + const { harness } = await setupSession({ role: 'owner' }) + expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true) + }) + + it('should include the bash tool from the start when there is no user context', async () => { + const { harness } = await setupSession({ role: 'none' }) + expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true) + }) + + it.each(['editor', 'reviewer'] as const)( + 'should exclude the bash tool initially for %s users', + async (role) => { + const { harness } = await setupSession({ role }) + const tools = harness.getTools() + expect(tools.some((t) => t.name === 'bash')).toBe(false) + expect(tools.some((t) => t.name === 'read_skill')).toBe(true) + }, + ) + + it('should include the bash tool from the start when a skill was already loaded earlier in the session', async () => { + const team = await prisma.team.create({ data: { name: 'Restore Team' } }) + const user = await prisma.user.create({ + data: { name: 'Restore User', email: 'restore@shumai.ai' }, + }) + await prisma.teamMember.create({ + data: { teamId: team.id, userId: user.id, role: 'reviewer' }, + }) + await prisma.user.create({ + data: { + id: 'bash-agent-restore', + name: 'Ai Agent Restore', + email: 'bash-agent-restore@shumai.ai', + type: 'agent', + }, + }) + await prisma.agent.create({ + data: { + id: 'bash-agent-restore', + teamId: team.id, + type: 'chat', + config: { provider: 'google', model: 'gemini' }, + }, + }) + + const session = await prisma.agentSession.create({ + data: { + agentId: 'bash-agent-restore', + userId: user.id, + cwd: process.cwd(), + type: 'chat', + }, + }) + await prisma.agentSessionEntry.create({ + data: { + id: 'restore-entry-1', + sessionId: session.id, + type: 'message', + data: { + message: { + role: 'toolResult', + content: [{ type: 'text', text: 'skill content restored' }], + toolName: 'read_skill', + isError: false, + details: { skillId: 'previously-loaded-skill' }, + timestamp: Date.now(), + }, + }, + }, + }) + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + agentId: 'bash-agent-restore', + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + allowedDomains: [], + providers: mockProviders, + userId: user.id, + sessionId: session.id, + }) + expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true) + } finally { + initializeSpy.mockRestore() + } + }) + + it('should inject the bash tool after a skill is loaded via read_skill for restricted users', async () => { + const { team, harness } = await setupSession({ role: 'reviewer' }) + const skill = await prisma.skill.create({ + data: { name: 'Inject Skill', assetId: 'asset1', hash: 'inject-hash', teamId: team.id }, + }) + + vi.spyOn(fs, 'existsSync').mockReturnValue(true) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures + vi.spyOn(fs, 'readFileSync').mockImplementation((p: any) => { + if (p.toString().endsWith('.hash')) return 'inject-hash' + if (p.toString().endsWith('SKILL.md')) return '# Inject Skill' + return '' + }) + + const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill') + expect(readSkillTool).toBeDefined() + expect(harness.getTools().some((t) => t.name === 'bash')).toBe(false) + + await readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined) + + expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true) + }) + + it('should not inject the bash tool for restricted users when bash is in deniedTools', async () => { + const { team, harness } = await setupSession({ role: 'editor', deniedTools: ['bash'] }) + const skill = await prisma.skill.create({ + data: { name: 'Denied Skill', assetId: 'asset1', hash: 'denied-hash', teamId: team.id }, + }) + + vi.spyOn(fs, 'existsSync').mockReturnValue(true) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures + vi.spyOn(fs, 'readFileSync').mockImplementation((p: any) => { + if (p.toString().endsWith('.hash')) return 'denied-hash' + if (p.toString().endsWith('SKILL.md')) return '# Denied Skill' + return '' + }) + + const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill') + expect(readSkillTool).toBeDefined() + + await readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined) + + expect(harness.getTools().some((t) => t.name === 'bash')).toBe(false) + }) + + it('should include restricted user instructions in the system prompt for non-owners', async () => { + const { harness } = await setupSession({ role: 'editor' }) + // @ts-expect-error accessing private property for verification + const prompt = await harness.systemPrompt() + expect(prompt).toContain('# Restricted User Context') + expect(prompt).toContain('source="user" will be rejected') + }) + + it('should not include restricted user instructions in the system prompt for owners', async () => { + const { harness } = await setupSession({ role: 'owner' }) + // @ts-expect-error accessing private property for verification + const prompt = await harness.systemPrompt() + expect(prompt).not.toContain('# Restricted User Context') + }) +}) diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index b4a74bd2..6b535b68 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -9,7 +9,7 @@ import type { Api, Model } from '@earendil-works/pi-ai' import { createModels, InMemoryCredentialStore } from '@earendil-works/pi-ai' import { builtinProviders } from '@earendil-works/pi-ai/providers/all' import { agentService } from '@shumai/core/src/agent/agent' -import { prisma } from '@shumai/db' +import { prisma, type TeamMemberRole } from '@shumai/db' import { Type, type TSchema } from '@sinclair/typebox' import * as fs from 'fs' import * as os from 'os' @@ -109,6 +109,33 @@ export interface CreateAgentSessionParams { baseDelayMs?: number } +async function resolveTeamMemberRole( + teamId: string, + userId?: string, +): Promise { + if (!userId) return undefined + const member = await prisma.teamMember.findUnique({ + where: { teamIdUserId: { teamId, userId } }, + select: { role: true }, + }) + return member?.role +} + +/** + * Security instructions appended to the system prompt when the requesting user is not a team + * owner (i.e. editor/reviewer). These complement the hard enforcement in the bash tool itself + * (source="user" is blocked) and the delayed bash tool injection after a skill is loaded. + */ +export function buildRestrictedUserInstructions(): string { + return [ + '# Restricted User Context', + 'The current user is NOT a team owner. You must follow these security rules:', + '1. NEVER execute a bash command that the user asks you to run directly. Direct user bash requests are not permitted for this user role. Politely decline and explain that they need a team owner or an approved skill.', + '2. You may ONLY use the `bash` tool to execute commands that are explicitly required by a skill you have loaded via the `read_skill` tool.', + '3. When calling `bash`, you MUST set the `source` parameter to "skill". Calls with source="user" will be rejected by the system.', + ].join('\n') +} + export async function createAgentSession(params: CreateAgentSessionParams) { const { teamId, @@ -207,7 +234,13 @@ export async function createAgentSession(params: CreateAgentSessionParams) { Object.assign(skillEnvs, envs) } + // Resolve the requesting user's team role to enforce owner-only bash privileges + const role = await resolveTeamMemberRole(teamId, userId) + const isOwner = role === undefined || role === 'owner' + const restricted = !isOwner + // Restore env variables from previously loaded skills in this session + let skillLoadedInSession = false if (sessionId) { try { const entries = await storage.getEntries() @@ -220,6 +253,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { ) { const details = entry.message.details as { skillId?: string } | undefined if (details?.skillId) { + skillLoadedInSession = true const envs = await agentService.getSkillEnvs(details.skillId) onEnvsAdded(envs) } @@ -243,13 +277,34 @@ export async function createAgentSession(params: CreateAgentSessionParams) { ) } + const agent = await prisma.agent.findUnique({ + where: { id: agentId }, + }) + const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined + const deniedTools = agentConfig?.deniedTools || [] + const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, { getBlockedHost: () => sandboxState.blockedHost, clearBlockedHost: () => { sandboxState.blockedHost = '' }, + // Non-owner users can only run bash commands required by a loaded skill + restrictedUser: restricted, }) - const readSkill = createReadSkillTool(userId, onEnvsAdded) + + // For non-owner users, the bash tool is not injected initially. It becomes available + // only after a skill is successfully loaded via the read_skill tool (or immediately when + // a skill was already loaded earlier in this session). + let harness: AgentHarness | undefined = undefined + const bashIncludedFromStart = isOwner || skillLoadedInSession + let bashInjected = bashIncludedFromStart + const onSkillLoaded = async () => { + if (!harness || bashInjected || deniedTools.includes('bash')) return + if (harness.getTools().some((t) => t.name === 'bash')) return + bashInjected = true + await harness.setTools([...harness.getTools(), sandboxedBash]) + } + const readSkill = createReadSkillTool(userId, onEnvsAdded, restricted ? onSkillLoaded : undefined) const systemTools: AgentTool[] = [] if (userId) { @@ -262,17 +317,12 @@ export async function createAgentSession(params: CreateAgentSessionParams) { ) } - const agent = await prisma.agent.findUnique({ - where: { id: agentId }, - }) - const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined - const deniedTools = agentConfig?.deniedTools || [] const readThread = createReadThreadTool() const allTools = [ ...mediaTools, readSkill, readThread, - sandboxedBash, + ...(bashIncludedFromStart ? [sandboxedBash] : []), ...systemTools, ...customTools, ] @@ -293,7 +343,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { modelsStore.setProvider(provider) } - const harness = new AgentHarness({ + harness = new AgentHarness({ session, models: modelsStore, model, @@ -309,6 +359,10 @@ export async function createAgentSession(params: CreateAgentSessionParams) { return prompt } + if (restricted) { + prompt += `\n\n${buildRestrictedUserInstructions()}` + } + // Sandbox environment restrictions prompt += '\n\n' + diff --git a/packages/agent/src/tools/read-skill.test.ts b/packages/agent/src/tools/read-skill.test.ts index 4f60f1b9..0963a473 100644 --- a/packages/agent/src/tools/read-skill.test.ts +++ b/packages/agent/src/tools/read-skill.test.ts @@ -308,4 +308,59 @@ describe('readSkillTool', () => { ).rejects.toThrow('Permission denied') }) }) + + describe('onSkillLoaded callback', () => { + it('should invoke onSkillLoaded after a successful skill load', async () => { + const team = await prisma.team.create({ data: { name: 'Callback Team' } }) + const skill = await prisma.skill.create({ + data: { + name: 'Callback Skill', + assetId: 'asset1', + hash: 'cb-hash', + teamId: team.id, + }, + }) + + vi.spyOn(fs, 'existsSync').mockReturnValue(true) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures + vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => { + if (path.toString().endsWith('.hash')) return 'cb-hash' + if (path.toString().endsWith('SKILL.md')) return '# Callback Skill' + return '' + }) + + const onSkillLoaded = vi.fn() + const readSkillTool = createReadSkillTool(undefined, () => {}, onSkillLoaded) + await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined) + + expect(onSkillLoaded).toHaveBeenCalledTimes(1) + }) + + it('should not invoke onSkillLoaded when loading is denied', async () => { + const team = await prisma.team.create({ data: { name: 'Callback Deny Team' } }) + const reviewerUser = await prisma.user.create({ + data: { name: 'Reviewer Callback', email: 'callback-reviewer@test.com' }, + }) + await prisma.teamMember.create({ + data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' }, + }) + const ownerSkill = await prisma.skill.create({ + data: { + name: 'Owner Callback Skill', + assetId: 'asset1', + hash: 'cb-owner-hash', + teamId: team.id, + permission: 'owner', + }, + }) + + const onSkillLoaded = vi.fn() + const reviewerTool = createReadSkillTool(reviewerUser.id, () => {}, onSkillLoaded) + await expect( + reviewerTool.execute('1', { skillId: ownerSkill.id }, undefined, undefined), + ).rejects.toThrow('Permission denied') + + expect(onSkillLoaded).not.toHaveBeenCalled() + }) + }) }) diff --git a/packages/agent/src/tools/read-skill.ts b/packages/agent/src/tools/read-skill.ts index 3b431c61..7063d708 100644 --- a/packages/agent/src/tools/read-skill.ts +++ b/packages/agent/src/tools/read-skill.ts @@ -16,6 +16,7 @@ const ROLE_HIERARCHY: Record = { export const createReadSkillTool = ( userId: string | undefined, onEnvsAdded: (envs: Record) => void, + onSkillLoaded?: () => Promise | void, ): AgentTool => ({ name: 'read_skill', label: 'Read Agent Skill', @@ -60,6 +61,9 @@ export const createReadSkillTool = ( // Retrieve skill content using agentService const skillMdContent = await agentService.getSkillContent(params.skillId) + // Notify that a skill was successfully loaded (e.g. to enable restricted tools) + await onSkillLoaded?.() + return { content: [{ type: 'text', text: skillMdContent }], details: { skillId: params.skillId }, diff --git a/packages/agent/src/tools/sandboxed-bash.test.ts b/packages/agent/src/tools/sandboxed-bash.test.ts index aff79006..b6d0f335 100644 --- a/packages/agent/src/tools/sandboxed-bash.test.ts +++ b/packages/agent/src/tools/sandboxed-bash.test.ts @@ -57,7 +57,12 @@ describe('createSandboxedBashTool', () => { const signal = createMockSignal() // pi-coding-agent AgentTool.execute signature: (toolCallId, params, signal?, onUpdate?) - const executePromise = tool.execute('1', { command: 'echo hello' }, signal, onUpdate) + const executePromise = tool.execute( + '1', + { command: 'echo hello', source: 'user' }, + signal, + onUpdate, + ) await vi.waitFor(() => expect(spawn).toHaveBeenCalled()) @@ -81,6 +86,46 @@ describe('createSandboxedBashTool', () => { expect((result as any).content[0].text).toContain('hello output') }) + it('should block user-requested commands when restrictedUser is enabled', async () => { + const tool = createSandboxedBashTool(mockCwd, {}, { restrictedUser: true }) + + const signal = createMockSignal() + await expect( + tool.execute('1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()), + ).rejects.toThrow(/not permitted for your role/) + + expect(spawn).not.toHaveBeenCalled() + expect(SandboxManager.wrapWithSandbox).not.toHaveBeenCalled() + }) + + it('should allow skill-requested commands when restrictedUser is enabled', async () => { + const tool = createSandboxedBashTool(mockCwd, {}, { restrictedUser: true }) + + const mockStdout = new EventEmitter() + const mockStderr = new EventEmitter() + const mockChild = Object.assign(new EventEmitter(), { + stdout: mockStdout, + stderr: mockStderr, + pid: 124, + kill: vi.fn(), + }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn is mocked to return a partial ChildProcess + ;(spawn as any).mockReturnValue(mockChild) + + const signal = createMockSignal() + const executePromise = tool.execute('1', { command: 'echo skill', source: 'skill' }, signal) + + await vi.waitFor(() => expect(spawn).toHaveBeenCalled()) + expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith('echo skill') + + mockStdout.emit('data', Buffer.from('skill output')) + mockChild.emit('close', 0) + + const result = await executePromise + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks + expect((result as any).content[0].text).toContain('skill output') + }) + it('should handle process errors', async () => { const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs()) const mockChild = new EventEmitter() @@ -88,7 +133,12 @@ describe('createSandboxedBashTool', () => { ;(spawn as any).mockReturnValue(mockChild) const signal = createMockSignal() - const executePromise = tool.execute('1', { command: 'fail' }, signal, createMockOnUpdate()) + const executePromise = tool.execute( + '1', + { command: 'fail', source: 'user' }, + signal, + createMockOnUpdate(), + ) await vi.waitFor(() => expect(spawn).toHaveBeenCalled()) mockChild.emit('error', new Error('spawn failed')) @@ -107,7 +157,12 @@ describe('createSandboxedBashTool', () => { ;(spawn as any).mockReturnValue(mockChild) const signal = createMockSignal() - const executePromise = tool.execute('1', { command: 'exit 1' }, signal, createMockOnUpdate()) + const executePromise = tool.execute( + '1', + { command: 'exit 1', source: 'user' }, + signal, + createMockOnUpdate(), + ) await vi.waitFor(() => expect(spawn).toHaveBeenCalled()) mockChild.emit('close', 1) @@ -133,7 +188,7 @@ describe('createSandboxedBashTool', () => { const signal = createMockSignal() const executePromise = tool.execute( '1', - { command: 'sleep 10', timeout: 2 }, + { command: 'sleep 10', timeout: 2, source: 'user' }, signal, createMockOnUpdate(), ) @@ -165,7 +220,12 @@ describe('createSandboxedBashTool', () => { const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any) const signal = createMockSignal() - const executePromise = tool.execute('1', { command: 'long-run' }, signal, createMockOnUpdate()) + const executePromise = tool.execute( + '1', + { command: 'long-run', source: 'user' }, + signal, + createMockOnUpdate(), + ) await vi.waitFor(() => expect(spawn).toHaveBeenCalled()) @@ -194,7 +254,7 @@ describe('createSandboxedBashTool', () => { ;(spawn as any).mockReturnValue(mockChild) const signal = createMockSignal() - const executePromise = tool.execute('1', { command: 'generate lines' }, signal) + const executePromise = tool.execute('1', { command: 'generate lines', source: 'user' }, signal) await vi.waitFor(() => expect(spawn).toHaveBeenCalled()) @@ -236,7 +296,11 @@ describe('createSandboxedBashTool', () => { ;(spawn as any).mockReturnValue(mockChild) const signal = createMockSignal() - const executePromise = tool.execute('1', { command: 'long single line' }, signal) + const executePromise = tool.execute( + '1', + { command: 'long single line', source: 'user' }, + signal, + ) await vi.waitFor(() => expect(spawn).toHaveBeenCalled()) @@ -266,7 +330,11 @@ describe('createSandboxedBashTool', () => { const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any) const signal = createMockSignal() - const executePromise = tool.execute('1', { command: 'slow', timeout: 1 }, signal) + const executePromise = tool.execute( + '1', + { command: 'slow', timeout: 1, source: 'user' }, + signal, + ) await vi.waitFor(() => expect(spawn).toHaveBeenCalled()) diff --git a/packages/agent/src/tools/sandboxed-bash.ts b/packages/agent/src/tools/sandboxed-bash.ts index c7127d01..30357b4e 100644 --- a/packages/agent/src/tools/sandboxed-bash.ts +++ b/packages/agent/src/tools/sandboxed-bash.ts @@ -11,9 +11,19 @@ import { type TruncationResult, } from '../utils/truncate' +const BashSource = Type.String({ + enum: ['user', 'skill'], + description: + 'Indicates who requested this bash command. Set to "user" when the end user directly ' + + 'requested the command. Set to "skill" when the command is required by a skill you loaded ' + + 'via the read_skill tool. Users without the owner role can only execute commands with ' + + 'source="skill"; source="user" will be blocked.', +}) + const BashParameters = Type.Object({ command: Type.String({ description: 'The bash command to execute.' }), timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })), + source: BashSource, }) export interface BashDetails { @@ -25,6 +35,11 @@ export interface BashDetails { export interface SandboxedBashOptions { getBlockedHost?: () => string clearBlockedHost?: () => void + /** + * When true, the tool only allows commands requested by a loaded skill (source="skill"). + * Commands requested directly by the end user (source="user") are blocked. + */ + restrictedUser?: boolean } const BASH_UPDATE_THROTTLE_MS = 100 @@ -36,15 +51,21 @@ export const createSandboxedBashTool = ( ): AgentTool => { return { name: 'bash', - description: `Execute a bash command in a sandboxed environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`, + description: `Execute a bash command in a sandboxed environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds. When in a restricted (non-owner) user context, only commands required by a skill loaded via the read_skill tool are allowed, and you must set source="skill".`, label: 'Executing bash command', parameters: BashParameters, execute: async ( toolCallId, - { command, timeout }, + { command, timeout, source }, signal, onUpdate, ): Promise> => { + if (options?.restrictedUser && source !== 'skill') { + throw new Error( + 'Bash commands requested directly by the user (source="user") are not permitted for your role. ' + + 'Only commands required by a loaded skill (source="skill") can be executed.', + ) + } options?.clearBlockedHost?.() const wrappedCommand = await SandboxManager.wrapWithSandbox(command) From dd2f8e68d9f2c2fd0a04d385c636698a89d5f1a8 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 4 Aug 2026 16:26:16 +0800 Subject: [PATCH 2/3] fix(agent): fail closed when user role cannot be resolved A userId that is not a team member previously resolved to isOwner=true (role === undefined || role === 'owner'), bypassing bash restrictions. Treat only flows without a user context (autofill etc.) and explicit owner memberships as unrestricted; unknown users are now restricted. --- packages/agent/src/index.test.ts | 19 +++++++++++++++++-- packages/agent/src/index.ts | 6 ++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index 54e94f7e..365b3a6e 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -585,7 +585,7 @@ describe('createAgentSession bash restriction for non-owner users', () => { type TestHarness = Awaited>['harness'] async function setupSession(opts: { - role: 'owner' | 'editor' | 'reviewer' | 'none' + role: 'owner' | 'editor' | 'reviewer' | 'none' | 'non-member' deniedTools?: string[] sessionId?: string }): Promise<{ team: { id: string }; userId?: string; harness: TestHarness }> { @@ -613,7 +613,12 @@ describe('createAgentSession bash restriction for non-owner users', () => { }) let userId: string | undefined - if (opts.role !== 'none') { + if (opts.role === 'non-member') { + const user = await prisma.user.create({ + data: { name: 'Non Member', email: 'non-member@shumai.ai' }, + }) + userId = user.id // no teamMember record created + } else if (opts.role !== 'none') { const user = await prisma.user.create({ data: { name: 'Bash User', email: 'bash-user@shumai.ai' }, }) @@ -653,6 +658,16 @@ describe('createAgentSession bash restriction for non-owner users', () => { expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true) }) + it('should treat a user who is not a team member as restricted (fail-closed)', async () => { + const { harness } = await setupSession({ role: 'non-member' }) + const tools = harness.getTools() + expect(tools.some((t) => t.name === 'bash')).toBe(false) + expect(tools.some((t) => t.name === 'read_skill')).toBe(true) + // @ts-expect-error accessing private property for verification + const prompt = await harness.systemPrompt() + expect(prompt).toContain('# Restricted User Context') + }) + it.each(['editor', 'reviewer'] as const)( 'should exclude the bash tool initially for %s users', async (role) => { diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index 6b535b68..b5e40f4a 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -234,9 +234,11 @@ export async function createAgentSession(params: CreateAgentSessionParams) { Object.assign(skillEnvs, envs) } - // Resolve the requesting user's team role to enforce owner-only bash privileges + // Resolve the requesting user's team role to enforce owner-only bash privileges. + // A user who is not a member of the team is treated as restricted (fail-closed), + // while flows without a user context (e.g. autofill) remain unrestricted. const role = await resolveTeamMemberRole(teamId, userId) - const isOwner = role === undefined || role === 'owner' + const isOwner = !userId || role === 'owner' const restricted = !isOwner // Restore env variables from previously loaded skills in this session From e6fde254468fdaf3b55572008e7105d8a884f881 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 4 Aug 2026 17:01:47 +0800 Subject: [PATCH 3/3] fix(agent): activate bash tool after skill load and fix chat stream Two bugs found while testing skill loading as a non-owner: 1. The injected bash tool was never actually usable: AgentHarness.setTools only updates the tool registry unless activeToolNames is passed, so bash was missing from the active tool set sent to the model on the next turn. Pass the full post-update tool list as activeToolNames. 2. The active_tools_change session entry (written by setTools) has no chat representation, so mapEntryToMessage fell back to fabricating an empty user message that appeared as a stray empty bubble in the chat stream. Render active_tools_change as a typed custom message and skip entry types that have no chat representation instead of emitting empty text. --- packages/agent/src/index.test.ts | 4 ++++ packages/agent/src/index.ts | 8 ++++++- packages/core/src/chat/chat.test.ts | 33 +++++++++++++++++++++++++++++ packages/core/src/chat/chat.ts | 18 ++++++++++------ 4 files changed, 56 insertions(+), 7 deletions(-) diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index 365b3a6e..eb6634fd 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -766,10 +766,14 @@ describe('createAgentSession bash restriction for non-owner users', () => { const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill') expect(readSkillTool).toBeDefined() expect(harness.getTools().some((t) => t.name === 'bash')).toBe(false) + expect(harness.getActiveTools().some((t) => t.name === 'bash')).toBe(false) await readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined) expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true) + // bash must be part of the ACTIVE tool set, not just the registry, or the model + // would never receive it on the next turn + expect(harness.getActiveTools().some((t) => t.name === 'bash')).toBe(true) }) it('should not inject the bash tool for restricted users when bash is in deniedTools', async () => { diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index b5e40f4a..36c28db3 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -304,7 +304,13 @@ export async function createAgentSession(params: CreateAgentSessionParams) { if (!harness || bashInjected || deniedTools.includes('bash')) return if (harness.getTools().some((t) => t.name === 'bash')) return bashInjected = true - await harness.setTools([...harness.getTools(), sandboxedBash]) + // Pass the full post-update tool list as activeToolNames: setTools only updates the + // registry otherwise, and the model would never see the bash tool on the next turn. + const next = [...harness.getTools(), sandboxedBash] + await harness.setTools( + next, + next.map((t) => t.name), + ) } const readSkill = createReadSkillTool(userId, onEnvsAdded, restricted ? onSkillLoaded : undefined) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index 7e56035d..1ca32072 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -525,6 +525,39 @@ describe('ChatService', () => { expect((msg3.details as Record).fromId).toBe('entry-old') }) + it('should render active_tools_change entries as custom messages', () => { + const pathEntries = [ + { + id: 'entry-tools', + type: 'active_tools_change', + timestamp: '2026-07-07T00:05:00.000Z', + activeToolNames: ['read_skill', 'bash'], + }, + ] + + const messages = buildSessionMessages(pathEntries as unknown as PathEntry[]) + expect(messages).toHaveLength(1) + // Casting to any to access properties of union in test assertions + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const msg = messages[0] as any + expect(msg.role).toBe('custom') + expect(msg.customType).toBe('active-tools-change') + expect(msg.content).toBe('Active tools: read_skill, bash') + expect(msg.details).toEqual({ activeToolNames: ['read_skill', 'bash'] }) + }) + + it('should return null for entry types without a chat representation instead of an empty message', () => { + const leafRecord = { + id: 'entry-leaf', + type: 'leaf', + parentId: null, + createdAt: new Date('2026-07-07T00:05:00.000Z'), + data: { targetId: 'some-entry' }, + } as unknown as Parameters[0] + + expect(mapEntryToMessage(leafRecord)).toBeNull() + }) + describe('getNewSessionMessages', () => { it('returns new messages and lastEntryId', async () => { const { user, team, project } = await setupBasicData() diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 896673e7..2e13f7a1 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -64,6 +64,15 @@ export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] { content: `Thinking level changed to ${entry.thinkingLevel}`, timestamp: timestampMs, } as unknown as ChatMessage) + } else if (entry.type === 'active_tools_change') { + messages.push({ + id: entry.id, + role: 'custom', + customType: 'active-tools-change', + content: `Active tools: ${entry.activeToolNames.join(', ')}`, + details: { activeToolNames: entry.activeToolNames }, + timestamp: timestampMs, + } as unknown as ChatMessage) } } @@ -121,12 +130,9 @@ export function mapEntryToMessage( if (messages.length > 0) { return messages[0] } - return { - id: entryRecord.id, - role: 'user', - content: '', - timestamp: entryRecord.createdAt.getTime(), - } as unknown as ChatMessage + // Entry types that have no chat representation (e.g. leaf, label, model_change, + // or any unknown/unsupported type) are skipped rather than rendered as an empty message. + return null } export class ChatService {