From 1daeaf51ef83e4c0317b5cbda04f3918ee7bad82 Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Mon, 10 Aug 2026 17:33:40 +0800 Subject: [PATCH] fix(agent): prevent agents from accessing disabled skills (#292) Disabling a skill in the agent config dialog only removed it from the agent_skills join table, but the chat flow still advertised ALL team skills to the model in the system prompt section and the read_skill tool never checked per-agent enablement. - getAgentChatContextActivity / getAgentAutofillContextActivity now only return skills explicitly enabled for the agent (agent_skills), and expose enabledSkillIds in the execution context. - createReadSkillTool accepts enabledSkillIds and rejects read_skill calls for skills not enabled for the agent, even if the model knows the skill id from earlier conversation history. - Added unit tests for context filtering (chat + autofill), tool-level enforcement, and the zero-enabled-skills case. --- packages/agent/src/activities/agent.test.ts | 99 +++++++++++++ packages/agent/src/activities/agent.ts | 41 ++++-- packages/agent/src/index.test.ts | 146 ++++++++++++++++++++ packages/agent/src/index.ts | 9 +- packages/agent/src/tools/read-skill.test.ts | 71 ++++++++++ packages/agent/src/tools/read-skill.ts | 7 + 6 files changed, 361 insertions(+), 12 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index 39a30b56..b28f12ee 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -1089,6 +1089,24 @@ describe('Agent Database Activities Integration', () => { }, }) + // Create two team skills, only one of which is enabled for the agent + const enabledSkill = await prisma.skill.create({ + data: { + name: 'Enabled Chat Skill', + assetId: 'asset-enabled', + hash: 'enabled-hash', + teamId: team.id, + }, + }) + const disabledSkill = await prisma.skill.create({ + data: { + name: 'Disabled Chat Skill', + assetId: 'asset-disabled', + hash: 'disabled-hash', + teamId: team.id, + }, + }) + const agent = await prisma.agent.create({ data: { id: agentUser.id, @@ -1100,6 +1118,9 @@ describe('Agent Database Activities Integration', () => { provider: 'openai', model: 'gpt-4', }, + skills: { + create: [{ skillId: enabledSkill.id }], + }, }, }) @@ -1110,6 +1131,10 @@ describe('Agent Database Activities Integration', () => { expect(chatCtx.agent.id).toBe(agent.id) expect(chatCtx.dbProviders[0].name).toBe('openai') + // Only the enabled skill must be advertised, and disabled team skills excluded + expect(chatCtx.teamSkills.map((s) => s.id)).toEqual([enabledSkill.id]) + expect(chatCtx.enabledSkillIds).toEqual([enabledSkill.id]) + expect(chatCtx.teamSkills.map((s) => s.id)).not.toContain(disabledSkill.id) // Create User for autofill agent const autofillUser = await prisma.user.create({ @@ -1132,6 +1157,9 @@ describe('Agent Database Activities Integration', () => { provider: 'openai', model: 'gpt-4', }, + skills: { + create: [{ skillId: enabledSkill.id }], + }, }, }) @@ -1140,6 +1168,77 @@ describe('Agent Database Activities Integration', () => { }) expect(autofillCtx.agent.id).toBe(autofillAgent.id) + // Only the enabled skill must be advertised for the autofill agent as well + expect(autofillCtx.teamSkills.map((s) => s.id)).toEqual([enabledSkill.id]) + expect(autofillCtx.enabledSkillIds).toEqual([enabledSkill.id]) + expect(autofillCtx.teamSkills.map((s) => s.id)).not.toContain(disabledSkill.id) + }) + + it('should return an empty enabled skill list when the agent has no skills enabled', async () => { + const provider = await prisma.provider.create({ + data: { + teamId: team.id, + name: 'openai-noskill', + config: { + api: 'openai-completions', + apiKey: 'mock-key', + }, + }, + }) + + const model = await prisma.model.create({ + data: { + providerId: provider.id, + modelId: 'gpt-4', + name: 'GPT 4', + config: { + reasoning: false, + input: ['text'], + contextWindow: 8192, + maxTokens: 2048, + cost: { input: 0.01, output: 0.03, cacheRead: 0, cacheWrite: 0 }, + }, + }, + }) + + await prisma.skill.create({ + data: { + name: 'Team Wide Skill', + assetId: 'asset-team', + hash: 'team-hash', + teamId: team.id, + }, + }) + + const agentUser = await prisma.user.create({ + data: { + name: 'No Skill Agent User', + email: 'noskillagent@shumai.ai', + type: 'agent', + }, + }) + const agent = await prisma.agent.create({ + data: { + id: agentUser.id, + teamId: team.id, + type: 'chat', + providerId: provider.id, + modelId: model.id, + config: { + provider: 'openai-noskill', + model: 'gpt-4', + }, + }, + }) + + const chatCtx = await getAgentChatContextActivity({ + teamId: team.id, + agentId: agent.id, + }) + + // Team-wide skill exists but is not enabled for this agent + expect(chatCtx.teamSkills).toEqual([]) + expect(chatCtx.enabledSkillIds).toEqual([]) }) }) diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index eb3bb829..94aef423 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -41,6 +41,11 @@ export type AgentWithProviderAndModel = Prisma.AgentGetPayload<{ include: { provider: true modelRef: true + skills: { + include: { + skill: true + } + } } }> @@ -54,6 +59,7 @@ export interface AgentExecutionContext { agent: AgentWithProviderAndModel dbProviders: DbProviderWithModels[] teamSkills: Skill[] + enabledSkillIds: string[] allowedDomains: string[] } @@ -71,7 +77,7 @@ async function executeAgentPrompt(params: { context: AgentExecutionContext attachedAssets?: Array<{ id: string; name: string; type: string }> }): Promise<{ text: string; usage: Usage; sessionId: string }> { - const { agent, dbProviders, teamSkills, allowedDomains } = params.context + const { agent, dbProviders, teamSkills, enabledSkillIds, allowedDomains } = params.context if (!agent.provider) { throw ApplicationFailure.create({ @@ -125,6 +131,7 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the name: s.name, description: s.description, })), + enabledSkillIds, allowedDomains, sessionId: params.sessionId, userId: params.userId, @@ -834,6 +841,11 @@ export async function getAgentChatContextActivity(params: { include: { provider: true, modelRef: true, + skills: { + include: { + skill: true, + }, + }, }, }) if (!agent) { @@ -864,10 +876,10 @@ export async function getAgentChatContextActivity(params: { include: { models: true }, }) - // Fetch team skills - const teamSkills = await prisma.skill.findMany({ - where: { teamId: params.teamId }, - }) + // Only advertise skills that are explicitly enabled for this agent (agent_skills). + // Disabled skills must not be listed in the system prompt nor loadable via read_skill. + const enabledSkills = (agent.skills ?? []).map((as) => as.skill) + const enabledSkillIds = enabledSkills.map((s) => s.id) const sandbox = await prisma.sandbox.findUnique({ where: { teamId: params.teamId }, @@ -877,7 +889,8 @@ export async function getAgentChatContextActivity(params: { return { agent, dbProviders, - teamSkills, + teamSkills: enabledSkills, + enabledSkillIds, allowedDomains, } } @@ -912,6 +925,11 @@ export async function getAgentAutofillContextActivity(params: { include: { provider: true, modelRef: true, + skills: { + include: { + skill: true, + }, + }, }, }) if (!agentWithDetails) { @@ -938,10 +956,10 @@ export async function getAgentAutofillContextActivity(params: { include: { models: true }, }) - // Fetch team skills - const teamSkills = await prisma.skill.findMany({ - where: { teamId: params.teamId }, - }) + // Only advertise skills that are explicitly enabled for this agent (agent_skills). + // Disabled skills must not be listed in the system prompt nor loadable via read_skill. + const enabledSkills = (agentWithDetails.skills ?? []).map((as) => as.skill) + const enabledSkillIds = enabledSkills.map((s) => s.id) const sandbox = await prisma.sandbox.findUnique({ where: { teamId: params.teamId }, @@ -951,7 +969,8 @@ export async function getAgentAutofillContextActivity(params: { return { agent: agentWithDetails, dbProviders, - teamSkills, + teamSkills: enabledSkills, + enabledSkillIds, allowedDomains, } } diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index eb6634fd..fb8f66fa 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -813,3 +813,149 @@ describe('createAgentSession bash restriction for non-owner users', () => { expect(prompt).not.toContain('# Restricted User Context') }) }) + +describe('createAgentSession enabled skill filtering', () => { + setupTestDbHooks() + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('should only advertise and allow reading skills enabled for the agent', async () => { + const team = await prisma.team.create({ data: { name: 'Skill Filter Team' } }) + + const enabledSkill = await prisma.skill.create({ + data: { + name: 'Enabled Skill', + assetId: 'asset-enabled', + hash: 'enabled-hash', + teamId: team.id, + }, + }) + const disabledSkill = await prisma.skill.create({ + data: { + name: 'Disabled Skill', + assetId: 'asset-disabled', + hash: 'disabled-hash', + teamId: team.id, + }, + }) + + await prisma.user.create({ + data: { + id: 'skill-filter-agent', + name: 'Ai Agent Skill Filter', + email: 'skill-filter-agent@shumai.ai', + type: 'agent', + }, + }) + await prisma.agent.create({ + data: { + id: 'skill-filter-agent', + teamId: team.id, + type: 'chat', + config: { provider: 'google', model: 'gemini' }, + skills: { + create: [{ skillId: enabledSkill.id }], + }, + }, + }) + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + agentId: 'skill-filter-agent', + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [{ id: enabledSkill.id, name: enabledSkill.name }], + enabledSkillIds: [enabledSkill.id], + allowedDomains: [], + providers: mockProviders, + }) + + // The disabled skill must not be advertised in the available skills list + // @ts-expect-error accessing private property for verification + const prompt = await harness.systemPrompt() + expect(prompt).toContain(enabledSkill.id) + expect(prompt).not.toContain(disabledSkill.id) + + // read_skill must reject the disabled skill id + const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill') + expect(readSkillTool).toBeDefined() + + 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 'enabled-hash' + if (p.toString().endsWith('SKILL.md')) return '# Enabled Skill' + return '' + }) + + await expect( + readSkillTool!.execute('1', { skillId: disabledSkill.id }, undefined, undefined, undefined), + ).rejects.toThrow('not enabled for this agent') + + const result = await readSkillTool!.execute( + '1', + { skillId: enabledSkill.id }, + undefined, + undefined, + undefined, + ) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect((result.content[0] as any).text).toBe('# Enabled Skill') + } finally { + initializeSpy.mockRestore() + } + }) + + it('should reject all read_skill calls when no skills are enabled for the agent', async () => { + const team = await prisma.team.create({ data: { name: 'Skill None Team' } }) + const skill = await prisma.skill.create({ + data: { name: 'Unassigned Skill', assetId: 'asset-none', hash: 'none-hash', teamId: team.id }, + }) + + await prisma.user.create({ + data: { + id: 'skill-none-agent', + name: 'Ai Agent Skill None', + email: 'skill-none-agent@shumai.ai', + type: 'agent', + }, + }) + await prisma.agent.create({ + data: { + id: 'skill-none-agent', + teamId: team.id, + type: 'chat', + config: { provider: 'google', model: 'gemini' }, + }, + }) + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + agentId: 'skill-none-agent', + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + enabledSkillIds: [], + allowedDomains: [], + providers: mockProviders, + }) + + const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill') + expect(readSkillTool).toBeDefined() + + await expect( + readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined), + ).rejects.toThrow('not enabled for this agent') + } finally { + initializeSpy.mockRestore() + } + }) +}) diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index a8554085..7067573a 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -98,6 +98,7 @@ export interface CreateAgentSessionParams { modelId: string systemPrompt: string teamSkills: Array<{ id: string; name: string; description?: string | null }> + enabledSkillIds?: string[] allowedDomains: string[] sessionId?: string userId?: string @@ -145,6 +146,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { modelId, systemPrompt, teamSkills, + enabledSkillIds, allowedDomains, sessionId, userId, @@ -313,7 +315,12 @@ export async function createAgentSession(params: CreateAgentSessionParams) { next.map((t) => t.name), ) } - const readSkill = createReadSkillTool(userId, onEnvsAdded, restricted ? onSkillLoaded : undefined) + const readSkill = createReadSkillTool( + userId, + onEnvsAdded, + restricted ? onSkillLoaded : undefined, + enabledSkillIds, + ) const systemTools: AgentTool[] = [] if (userId) { diff --git a/packages/agent/src/tools/read-skill.test.ts b/packages/agent/src/tools/read-skill.test.ts index 0963a473..3c9b6fe6 100644 --- a/packages/agent/src/tools/read-skill.test.ts +++ b/packages/agent/src/tools/read-skill.test.ts @@ -363,4 +363,75 @@ describe('readSkillTool', () => { expect(onSkillLoaded).not.toHaveBeenCalled() }) }) + + describe('enabled skills enforcement', () => { + it('should reject loading a skill that is not enabled for the agent', async () => { + const team = await prisma.team.create({ data: { name: 'Enabled Filter Team' } }) + const skill = await prisma.skill.create({ + data: { + name: 'Disabled For Agent Skill', + assetId: 'asset1', + hash: 'disabled-agent-hash', + teamId: team.id, + }, + }) + + const readSkillTool = createReadSkillTool(undefined, () => {}, undefined, [ + 'some-other-enabled-skill', + ]) + await expect( + readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined), + ).rejects.toThrow('not enabled for this agent') + }) + + it('should allow loading a skill that is enabled for the agent', async () => { + const team = await prisma.team.create({ data: { name: 'Enabled Allow Team' } }) + const skill = await prisma.skill.create({ + data: { + name: 'Enabled For Agent Skill', + assetId: 'asset1', + hash: 'enabled-agent-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 'enabled-agent-hash' + if (path.toString().endsWith('SKILL.md')) return '# Enabled For Agent Skill' + return '' + }) + + const readSkillTool = createReadSkillTool(undefined, () => {}, undefined, [skill.id]) + const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect((result.content[0] as any).text).toBe('# Enabled For Agent Skill') + }) + + it('should allow loading any skill when enabledSkillIds is not provided (backward compatibility)', async () => { + const team = await prisma.team.create({ data: { name: 'No Filter Team' } }) + const skill = await prisma.skill.create({ + data: { + name: 'No Filter Skill', + assetId: 'asset1', + hash: 'no-filter-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 'no-filter-hash' + if (path.toString().endsWith('SKILL.md')) return '# No Filter Skill' + return '' + }) + + const readSkillTool = createReadSkillTool(undefined, () => {}) + const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect((result.content[0] as any).text).toBe('# No Filter Skill') + }) + }) }) diff --git a/packages/agent/src/tools/read-skill.ts b/packages/agent/src/tools/read-skill.ts index 7063d708..381300e7 100644 --- a/packages/agent/src/tools/read-skill.ts +++ b/packages/agent/src/tools/read-skill.ts @@ -17,6 +17,7 @@ export const createReadSkillTool = ( userId: string | undefined, onEnvsAdded: (envs: Record) => void, onSkillLoaded?: () => Promise | void, + enabledSkillIds?: string[], ): AgentTool => ({ name: 'read_skill', label: 'Read Agent Skill', @@ -31,6 +32,12 @@ export const createReadSkillTool = ( throw new Error(`Skill with ID ${params.skillId} not found.`) } + // Skills disabled for this agent must not be loadable, even if the model + // somehow knows their ID (e.g. from earlier conversation history). + if (enabledSkillIds && !enabledSkillIds.includes(params.skillId)) { + throw new Error(`Skill with ID ${params.skillId} is not enabled for this agent.`) + } + const requiredLevel = ROLE_HIERARCHY[skill.permission] || 1 if (userId) {