mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 12:24:39 +00:00
* feat(authz): enforce project-aware roles for agent/skill/mcp permissions Introduce a shared resolveEffectiveRole helper that mirrors AuthzService precedence rules (projectMember.role override -> team role for team-scoped members -> restricted), and route all agent/skill/mcp runtime permission checks through it. Previously these checks used the raw teamMember.role, which let project-only members execute team-level agents/skills/MCP tools and ignored per-project role overrides. Changes: - authz: add resolveEffectiveRole(teamId, projectId, userId, db) and refactor hasPermission to use it (behavior-preserving) - chat/asset/agent-activity: gate agent usage by the effective project role - read_skill: enforce skill permission via effective role (projectId threaded from the agent session) - mcp-service: checkPermission and buildAgentTools filter by effective role; un-permitted servers' tools are no longer advertised to the model - agent activity: only advertise skills the user's effective role permits - listProjectMembers: filter included agent bots by the requester's effective project role - new GET /projects/:projectId/chat-agents API returning chat agents scoped to the project and the user's effective role; WebUI chat selector now uses it (settings keeps the team-level API) - tests: effective-role resolver, chat/mention/MCP/skill project-role matrices, listProjectChatAgents, listProjectMembers filter, API route * fix(agent): forward projectId to getAgentChatContextActivity in agentChat workflow The agentChat workflow called getAgentChatContextActivity without passing projectId from the task payload, so project-scoped members (scope: 'project') resolved a null effective role in the activity and were denied with 'Insufficient role to use agent' even though the chat selector and chat.ts both authorized them. Forward payload.projectId so the activity enforces the user's effective project role, and assert the forwarding in the workflow unit test (fails without the fix).
509 lines
19 KiB
TypeScript
509 lines
19 KiB
TypeScript
import { vi } from 'vitest'
|
|
|
|
vi.mock('@shumai/core/src/s3/s3')
|
|
vi.mock('fs')
|
|
|
|
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
|
import { prisma } from '@shumai/db'
|
|
import { setupTestDbHooks } from '@shumai/db/test'
|
|
import { createReadSkillTool } from './read-skill'
|
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
|
import AdmZip from 'adm-zip'
|
|
import * as fs from 'fs'
|
|
|
|
describe('readSkillTool', () => {
|
|
setupTestDbHooks()
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
it('should throw error if skill not found', async () => {
|
|
const readSkillTool = createReadSkillTool(undefined, () => {})
|
|
await expect(
|
|
readSkillTool.execute('1', { skillId: 'non-existent' }, undefined, undefined),
|
|
).rejects.toThrow('not found')
|
|
})
|
|
|
|
it('should read skill from cache if hash matches', async () => {
|
|
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
|
const skill = await prisma.skill.create({
|
|
data: {
|
|
name: 'Test Skill',
|
|
assetId: 'asset1',
|
|
hash: 'match-hash',
|
|
teamId: team.id,
|
|
},
|
|
})
|
|
|
|
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
|
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
|
if (path.toString().endsWith('.hash')) return 'match-hash'
|
|
if (path.toString().endsWith('SKILL.md')) return '# Test Skill Content'
|
|
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('# Test Skill Content')
|
|
expect(s3Service.getObject).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('should download and extract skill if cache missing or hash mismatch', async () => {
|
|
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
|
const skill = await prisma.skill.create({
|
|
data: {
|
|
name: 'New Skill',
|
|
assetId: 'asset1',
|
|
hash: 'new-hash',
|
|
teamId: team.id,
|
|
},
|
|
})
|
|
|
|
await prisma.asset.create({
|
|
data: {
|
|
id: 'asset1',
|
|
name: 'skill.zip',
|
|
storageKey: { create: { key: 'skills/skill.zip' } },
|
|
type: 'file',
|
|
status: 'uploaded',
|
|
},
|
|
})
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
|
vi.spyOn(fs, 'existsSync').mockImplementation((path: any) => {
|
|
if (path.toString().endsWith('.hash')) return false
|
|
if (path.toString().endsWith('SKILL.md')) return true
|
|
return true
|
|
})
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
|
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
|
if (path.toString().endsWith('SKILL.md')) return '# Extracted Content'
|
|
return ''
|
|
})
|
|
|
|
const zip = new AdmZip()
|
|
zip.addFile('SKILL.md', Buffer.from('# Extracted Content'))
|
|
const zipBuffer = zip.toBuffer()
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
|
;(s3Service.getObject as any).mockResolvedValue({
|
|
buffer: zipBuffer,
|
|
contentType: 'application/zip',
|
|
})
|
|
|
|
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('# Extracted Content')
|
|
expect(s3Service.getObject).toHaveBeenCalled()
|
|
expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.hash'), 'new-hash')
|
|
})
|
|
|
|
describe('environment variables', () => {
|
|
let originalEnv: NodeJS.ProcessEnv
|
|
|
|
beforeEach(() => {
|
|
originalEnv = { ...process.env }
|
|
})
|
|
|
|
afterEach(() => {
|
|
process.env = originalEnv
|
|
})
|
|
|
|
it('should use user-configured value if it is non-empty', async () => {
|
|
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
|
const skill = await prisma.skill.create({
|
|
data: {
|
|
name: 'Skill Env Test 1',
|
|
assetId: 'asset1',
|
|
hash: 'hash1',
|
|
teamId: team.id,
|
|
config: {
|
|
environmentVariables: [{ name: 'CONFIGURED_VAR', default: 'user-val' }],
|
|
},
|
|
},
|
|
})
|
|
|
|
delete process.env.CONFIGURED_VAR
|
|
|
|
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 'hash1'
|
|
if (path.toString().endsWith('SKILL.md')) return '# Content'
|
|
return ''
|
|
})
|
|
|
|
let capturedEnvs: Record<string, string> = {}
|
|
const readSkillTool = createReadSkillTool(undefined, (envs) => {
|
|
capturedEnvs = { ...capturedEnvs, ...envs }
|
|
})
|
|
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
|
|
|
|
expect(capturedEnvs).toEqual({
|
|
CONFIGURED_VAR: 'user-val',
|
|
})
|
|
})
|
|
|
|
it('should favor user-configured value even if host environment variable is also defined', async () => {
|
|
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
|
const skill = await prisma.skill.create({
|
|
data: {
|
|
name: 'Skill Env Test 2',
|
|
assetId: 'asset1',
|
|
hash: 'hash2',
|
|
teamId: team.id,
|
|
config: {
|
|
environmentVariables: [{ name: 'OVERRIDDEN_VAR', default: 'user-val' }],
|
|
},
|
|
},
|
|
})
|
|
|
|
process.env.OVERRIDDEN_VAR = 'host-val'
|
|
|
|
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 'hash2'
|
|
if (path.toString().endsWith('SKILL.md')) return '# Content'
|
|
return ''
|
|
})
|
|
|
|
let capturedEnvs: Record<string, string> = {}
|
|
const readSkillTool = createReadSkillTool(undefined, (envs) => {
|
|
capturedEnvs = { ...capturedEnvs, ...envs }
|
|
})
|
|
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
|
|
|
|
expect(capturedEnvs).toEqual({
|
|
OVERRIDDEN_VAR: 'user-val',
|
|
})
|
|
})
|
|
|
|
it('should fall back to host environment variable if user-configured value is empty string', async () => {
|
|
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
|
const skill = await prisma.skill.create({
|
|
data: {
|
|
name: 'Skill Env Test 3',
|
|
assetId: 'asset1',
|
|
hash: 'hash3',
|
|
teamId: team.id,
|
|
config: {
|
|
environmentVariables: [{ name: 'FALLBACK_VAR', default: '' }],
|
|
},
|
|
},
|
|
})
|
|
|
|
process.env.FALLBACK_VAR = 'host-val'
|
|
|
|
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 'hash3'
|
|
if (path.toString().endsWith('SKILL.md')) return '# Content'
|
|
return ''
|
|
})
|
|
|
|
let capturedEnvs: Record<string, string> = {}
|
|
const readSkillTool = createReadSkillTool(undefined, (envs) => {
|
|
capturedEnvs = { ...capturedEnvs, ...envs }
|
|
})
|
|
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
|
|
|
|
expect(capturedEnvs).toEqual({
|
|
FALLBACK_VAR: 'host-val',
|
|
})
|
|
})
|
|
|
|
it('should fall back to host environment variable if user-configured value is undefined', async () => {
|
|
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
|
const skill = await prisma.skill.create({
|
|
data: {
|
|
name: 'Skill Env Test 4',
|
|
assetId: 'asset1',
|
|
hash: 'hash4',
|
|
teamId: team.id,
|
|
config: {
|
|
environmentVariables: [{ name: 'FALLBACK_VAR_UNDEF' }],
|
|
},
|
|
},
|
|
})
|
|
|
|
process.env.FALLBACK_VAR_UNDEF = 'host-val2'
|
|
|
|
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 'hash4'
|
|
if (path.toString().endsWith('SKILL.md')) return '# Content'
|
|
return ''
|
|
})
|
|
|
|
let capturedEnvs: Record<string, string> = {}
|
|
const readSkillTool = createReadSkillTool(undefined, (envs) => {
|
|
capturedEnvs = { ...capturedEnvs, ...envs }
|
|
})
|
|
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
|
|
|
|
expect(capturedEnvs).toEqual({
|
|
FALLBACK_VAR_UNDEF: 'host-val2',
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('permissions', () => {
|
|
it('should allow loading skill matching user role level or lower', async () => {
|
|
const team = await prisma.team.create({ data: { name: 'Permission Team' } })
|
|
const ownerUser = await prisma.user.create({
|
|
data: { name: 'Owner User', email: 'owner@test.com' },
|
|
})
|
|
const reviewerUser = await prisma.user.create({
|
|
data: { name: 'Reviewer User', email: 'reviewer@test.com' },
|
|
})
|
|
|
|
await prisma.teamMember.create({
|
|
data: { teamId: team.id, userId: ownerUser.id, role: 'owner' },
|
|
})
|
|
await prisma.teamMember.create({
|
|
data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' },
|
|
})
|
|
|
|
const ownerSkill = await prisma.skill.create({
|
|
data: {
|
|
name: 'Owner Skill',
|
|
assetId: 'asset1',
|
|
hash: 'hash-owner',
|
|
teamId: team.id,
|
|
permission: 'owner',
|
|
},
|
|
})
|
|
|
|
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
|
if (path.toString().endsWith('.hash')) return 'hash-owner'
|
|
if (path.toString().endsWith('SKILL.md')) return '# Owner Skill'
|
|
return ''
|
|
})
|
|
|
|
const ownerTool = createReadSkillTool(ownerUser.id, () => {})
|
|
const resultOwner = await ownerTool.execute(
|
|
'1',
|
|
{ skillId: ownerSkill.id },
|
|
undefined,
|
|
undefined,
|
|
)
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
expect((resultOwner.content[0] as any).text).toBe('# Owner Skill')
|
|
|
|
const reviewerTool = createReadSkillTool(reviewerUser.id, () => {})
|
|
await expect(
|
|
reviewerTool.execute('1', { skillId: ownerSkill.id }, undefined, undefined),
|
|
).rejects.toThrow('Permission denied')
|
|
})
|
|
|
|
it('uses the effective project role for skill permission checks', async () => {
|
|
const team = await prisma.team.create({ data: { name: 'Project Skill Team' } })
|
|
const project = await prisma.project.create({ data: { name: 'Skill Proj', teamId: team.id } })
|
|
const editorSkill = await prisma.skill.create({
|
|
data: {
|
|
name: 'Editor Project Skill',
|
|
assetId: 'asset1',
|
|
hash: 'proj-editor-hash',
|
|
teamId: team.id,
|
|
permission: 'editor',
|
|
},
|
|
})
|
|
|
|
// Team editor demoted to project reviewer: denied inside the project
|
|
const demoted = await prisma.user.create({
|
|
data: { name: 'Demoted Skill', email: 'dem-skill@test.com' },
|
|
})
|
|
const demotedTm = await prisma.teamMember.create({
|
|
data: { teamId: team.id, userId: demoted.id, role: 'editor', scope: 'team' },
|
|
})
|
|
await prisma.projectMember.create({
|
|
data: { projectId: project.id, teamMemberId: demotedTm.id, role: 'reviewer' },
|
|
})
|
|
|
|
const demotedTool = createReadSkillTool(
|
|
demoted.id,
|
|
() => {},
|
|
undefined,
|
|
undefined,
|
|
project.id,
|
|
)
|
|
await expect(
|
|
demotedTool.execute('1', { skillId: editorSkill.id }, undefined, undefined),
|
|
).rejects.toThrow('Permission denied')
|
|
|
|
// Project-scoped member invited as editor: allowed
|
|
const projEditor = await prisma.user.create({
|
|
data: { name: 'PE Skill', email: 'pe-skill@test.com' },
|
|
})
|
|
const projEditorTm = await prisma.teamMember.create({
|
|
data: { teamId: team.id, userId: projEditor.id, role: 'reviewer', scope: 'project' },
|
|
})
|
|
await prisma.projectMember.create({
|
|
data: { projectId: project.id, teamMemberId: projEditorTm.id, role: 'editor' },
|
|
})
|
|
|
|
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
|
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
|
if (path.toString().endsWith('.hash')) return 'proj-editor-hash'
|
|
if (path.toString().endsWith('SKILL.md')) return '# Editor Project Skill Content'
|
|
return ''
|
|
})
|
|
|
|
const projEditorTool = createReadSkillTool(
|
|
projEditor.id,
|
|
() => {},
|
|
undefined,
|
|
undefined,
|
|
project.id,
|
|
)
|
|
const result = await projEditorTool.execute(
|
|
'1',
|
|
{ skillId: editorSkill.id },
|
|
undefined,
|
|
undefined,
|
|
)
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
expect((result.content[0] as any).text).toBe('# Editor Project Skill Content')
|
|
})
|
|
})
|
|
|
|
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()
|
|
})
|
|
})
|
|
|
|
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')
|
|
})
|
|
})
|
|
})
|