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.
This commit is contained in:
yiling
2026-08-04 16:08:04 +08:00
parent 9745985f57
commit c938e84ccc
6 changed files with 461 additions and 21 deletions
@@ -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()
})
})
})
+4
View File
@@ -16,6 +16,7 @@ const ROLE_HIERARCHY: Record<string, number> = {
export const createReadSkillTool = (
userId: string | undefined,
onEnvsAdded: (envs: Record<string, string>) => void,
onSkillLoaded?: () => Promise<void> | void,
): AgentTool<typeof readSkillSchema, { skillId: string }> => ({
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 },
@@ -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())
+23 -2
View File
@@ -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<typeof BashParameters, BashDetails> => {
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<AgentToolResult<BashDetails>> => {
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)