feat(authz): enforce project-aware roles for agent/skill/mcp permissions (#314)

* 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).
This commit is contained in:
Yiling-J
2026-08-16 15:44:45 +08:00
committed by GitHub
parent cb1c1c502b
commit 55d9596835
23 changed files with 1088 additions and 210 deletions
+103
View File
@@ -536,6 +536,109 @@ describe('McpService', () => {
expect(allowed.ok).toBe(true)
})
it('uses the effective project role for MCP permission checks', async () => {
const server = await service.createServer(teamId, {
url: srv.url,
permission: 'editor',
})
const project = await prisma.project.create({
data: { name: 'MCP Proj', teamId },
})
// Team editor demoted to project reviewer: denied inside the project
const demoted = await prisma.user.create({
data: { name: 'Demoted MCP', email: `dem-mcp-${Date.now()}@shumai.ai`, type: 'human' },
})
const demotedTm = await prisma.teamMember.create({
data: { teamId, userId: demoted.id, role: 'editor', scope: 'team' },
})
await prisma.projectMember.create({
data: { projectId: project.id, teamMemberId: demotedTm.id, role: 'reviewer' },
})
const denied = await service.callMcpTool(
server.id,
'echo',
{ text: 'x' },
{ teamId, userId: demoted.id, projectId: project.id },
)
expect(denied.ok).toBe(false)
expect((denied.content[0] as { text?: string }).text).toContain('Permission denied')
// Project-scoped member invited as editor: allowed
const projEditor = await prisma.user.create({
data: { name: 'PE MCP', email: `pe-mcp-${Date.now()}@shumai.ai`, type: 'human' },
})
const peTm = await prisma.teamMember.create({
data: { teamId, userId: projEditor.id, role: 'reviewer', scope: 'project' },
})
await prisma.projectMember.create({
data: { projectId: project.id, teamMemberId: peTm.id, role: 'editor' },
})
const allowed = await service.callMcpTool(
server.id,
'echo',
{ text: 'ok' },
{ teamId, userId: projEditor.id, projectId: project.id },
)
expect(allowed.ok).toBe(true)
})
it('filters assigned MCP servers by the user effective role when building agent tools', async () => {
const agent = await seedAgentAndUser(teamId, 'Filtered MCP Agent')
const project = await prisma.project.create({
data: { name: 'MCP Filter Proj', teamId },
})
const reviewerSrv = await startTestMcpServer({
tools: standardTestTools(),
serverInfo: { name: 'reviewer-only-mcp' },
})
const editorSrv = await startTestMcpServer({
tools: standardTestTools(),
serverInfo: { name: 'editor-only-mcp' },
})
const reviewerServer = await service.createServer(teamId, {
url: reviewerSrv.url,
permission: 'reviewer',
})
const editorServer = await service.createServer(teamId, {
url: editorSrv.url,
permission: 'editor',
})
await service.refreshServer(reviewerServer.id)
await service.refreshServer(editorServer.id)
await prisma.agentMcpServer.create({
data: { agentId: agent.id, mcpServerId: reviewerServer.id },
})
await prisma.agentMcpServer.create({
data: { agentId: agent.id, mcpServerId: editorServer.id },
})
// Project-scoped member invited as reviewer: only the reviewer server's
// tools are attached; the editor server's tools are not even registered.
const reviewer = await prisma.user.create({
data: { name: 'Filter Reviewer', email: `fr-${Date.now()}@shumai.ai`, type: 'human' },
})
const reviewerTm = await prisma.teamMember.create({
data: { teamId, userId: reviewer.id, role: 'reviewer', scope: 'project' },
})
await prisma.projectMember.create({
data: { projectId: project.id, teamMemberId: reviewerTm.id, role: 'reviewer' },
})
const tools = await service.buildAgentTools(agent.id, teamId, reviewer.id, project.id)
const descriptions = tools
.map((t) => (t.description ?? '') + (t.name === 'mcp' ? JSON.stringify(t.parameters) : ''))
.join('\n')
expect(descriptions).toContain('reviewer-only-mcp')
expect(descriptions).not.toContain('editor-only-mcp')
await reviewerSrv.stop()
await editorSrv.stop()
})
// --------------------------------------------------------------------------
// Per-agent assignment (D6)
// --------------------------------------------------------------------------
+54 -40
View File
@@ -13,6 +13,7 @@ import type {
UpdateMcpServerRequest,
} from '@shumai/dtos'
import { logger } from '@shumai/core/src/logger'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { mcpDbStore, type PendingAuth } from './mcp-db-store'
import { buildDirectTools, isDirectTool } from './mcp-direct-tools'
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
@@ -34,6 +35,7 @@ const ROLE_HIERARCHY: Record<string, number> = {
export interface McpToolCallContext {
teamId: string
userId?: string
projectId?: string
}
export type McpToolCallContent = AgentToolResult<Record<string, unknown>>['content']
@@ -468,16 +470,10 @@ export class McpService {
const requiredLevel = ROLE_HIERARCHY[server.permission] || 1
if (ctx?.userId) {
const member = await prisma.teamMember.findUnique({
where: {
teamIdUserId: {
teamId: server.teamId,
userId: ctx.userId,
},
},
select: { role: true },
})
const userLevel = member ? ROLE_HIERARCHY[member.role] || 0 : 0
// Resolve the user's effective role for the project context (project
// override wins; project-scoped members without project access are denied).
const effectiveRole = await resolveEffectiveRole(server.teamId, ctx.projectId, ctx.userId)
const userLevel = effectiveRole ? ROLE_HIERARCHY[effectiveRole] || 0 : 0
if (userLevel < requiredLevel) {
return `Permission denied: Insufficient role to use MCP server "${server.name}". Minimum required role is "${server.permission}".`
}
@@ -791,47 +787,65 @@ export class McpService {
* Build the agent's MCP AgentTools: the single `mcp` proxy tool plus direct
* tools for assigned servers in direct-tools mode. Returns [] when the agent
* has no assigned servers (no proxy tool — don't waste LLM context).
*
* When a user context is provided, servers whose `permission` exceeds the
* user's effective project role are filtered out up front, so the model never
* sees tools it is not allowed to call (call-time checks remain as a backstop).
*/
async buildAgentTools(agentId: string, teamId: string, userId?: string): Promise<AgentTool[]> {
async buildAgentTools(
agentId: string,
teamId: string,
userId?: string,
projectId?: string,
): Promise<AgentTool[]> {
const assignments = await prisma.agentMcpServer.findMany({
where: { agentId },
include: { mcpServer: true },
})
if (assignments.length === 0) return []
let assignedServers = assignments.map((a) => a.mcpServer)
if (userId) {
const effectiveRole = await resolveEffectiveRole(teamId, projectId, userId)
if (!effectiveRole) return []
const userLevel = ROLE_HIERARCHY[effectiveRole] || 0
assignedServers = assignedServers.filter(
(s) => (ROLE_HIERARCHY[s.permission] || 1) <= userLevel,
)
}
if (assignedServers.length === 0) return []
// Per-agent tool registry: built fresh for this agent from the persisted
// discovery cache (McpServer.tools). It only ever contains the agent's
// assigned servers, so unassigned/disabled servers can neither be searched
// nor called — no global mutable state to leak through.
const registry = new McpToolRegistry()
const servers = assignments
.map((a) => a.mcpServer)
.map((s) => {
const storedTools = (s.tools ?? []) as PrismaJson.McpToolInfo[]
if (storedTools.length > 0) {
registry.setTools(
s.id,
s.name,
storedTools.map((t) => ({
name: t.name,
description: t.description ?? '',
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
})),
{ excludeTools: s.config?.excludeTools },
)
}
return {
id: s.id,
name: s.name,
instructions: s.instructions ?? null,
url: s.url,
transport: s.transport,
authConfig: (s.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
config: (s.config ?? {}) as PrismaJson.McpServerConfig,
status: s.status,
}
})
const servers = assignedServers.map((s) => {
const storedTools = (s.tools ?? []) as PrismaJson.McpToolInfo[]
if (storedTools.length > 0) {
registry.setTools(
s.id,
s.name,
storedTools.map((t) => ({
name: t.name,
description: t.description ?? '',
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
})),
{ excludeTools: s.config?.excludeTools },
)
}
return {
id: s.id,
name: s.name,
instructions: s.instructions ?? null,
url: s.url,
transport: s.transport,
authConfig: (s.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
config: (s.config ?? {}) as PrismaJson.McpServerConfig,
status: s.status,
}
})
const serverNameById = new Map<string, string>()
const serverIdByName = new Map<string, string>()
@@ -880,7 +894,7 @@ export class McpService {
},
ensureConnected: (serverId) => this.ensureConnected(serverId, registry),
callTool: (serverId, toolName, args) =>
this.callMcpTool(serverId, toolName, args, { teamId, userId }),
this.callMcpTool(serverId, toolName, args, { teamId, userId, projectId }),
authStatus: (serverId) => this.getAuthStatus(serverId),
startAuth: (serverId) => this.startAuth(serverId),
getInstructions: (serverId) => this.getServerInstructions(serverId),
@@ -898,7 +912,7 @@ export class McpService {
serverId: server.id,
serverName: server.name,
callTool: (serverId, toolName, args) =>
this.callMcpTool(serverId, toolName, args, { teamId, userId }),
this.callMcpTool(serverId, toolName, args, { teamId, userId, projectId }),
}),
)
}