Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
misc: added rbac checks for mcp server and activity logs
Sheen Capadnganf2cbb22bc111
diff --git a/backend/src/ee/routes/v1/ai-mcp-activity-log-router.ts b/backend/src/ee/routes/v1/ai-mcp-activity-log-router.tsindex 63647a9832..a8eed9566b 100644--- a/backend/src/ee/routes/v1/ai-mcp-activity-log-router.ts+++ b/backend/src/ee/routes/v1/ai-mcp-activity-log-router.ts@@ -22,7 +22,13 @@ export const registerAiMcpActivityLogRouter = async (server: FastifyZodProvider)},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const activityLogs = await server.services.aiMcpActivityLog.listActivityLogs(req.query.projectId);+ const activityLogs = await server.services.aiMcpActivityLog.listActivityLogs({+ projectId: req.query.projectId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });return activityLogs;}diff --git a/backend/src/ee/routes/v1/ai-mcp-server-router.ts b/backend/src/ee/routes/v1/ai-mcp-server-router.tsindex 6f43beed47..ada724c89a 100644--- a/backend/src/ee/routes/v1/ai-mcp-server-router.ts+++ b/backend/src/ee/routes/v1/ai-mcp-server-router.ts@@ -71,7 +71,10 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {url: req.body.url,clientId: req.body.clientId,clientSecret: req.body.clientSecret,- actorId: req.permission.id+ actorId: req.permission.id,+ actor: req.permission.type,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId});return result;@@ -149,7 +152,10 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {handler: async (req) => {const result = await server.services.aiMcpServer.getOAuthStatus({sessionId: req.params.sessionId,- actorId: req.permission.id+ actorId: req.permission.id,+ actor: req.permission.type,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId});return result;@@ -174,11 +180,11 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const mcpServer = await server.services.aiMcpServer.createMcpServer({- ...req.body,- actorId: req.permission.id,actor: req.permission.type,- actorAuthMethod: req.permission.authMethod!,- actorOrgId: req.permission.orgId+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ ...req.body});return { server: mcpServer };@@ -207,7 +213,11 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const mcpServers = await server.services.aiMcpServer.listMcpServers({- projectId: req.query.projectId+ projectId: req.query.projectId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId});return {@@ -236,7 +246,11 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const mcpServer = await server.services.aiMcpServer.getMcpServerById({- serverId: req.params.serverId+ serverId: req.params.serverId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId});return { server: mcpServer };@@ -267,7 +281,11 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {handler: async (req) => {const mcpServer = await server.services.aiMcpServer.updateMcpServer({serverId: req.params.serverId,- ...req.body+ ...req.body,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId});return { server: mcpServer };@@ -293,7 +311,11 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const tools = await server.services.aiMcpServer.listMcpServerTools({- serverId: req.params.serverId+ serverId: req.params.serverId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId});return { tools };@@ -319,7 +341,11 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const tools = await server.services.aiMcpServer.syncMcpServerTools({- serverId: req.params.serverId+ serverId: req.params.serverId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId});return { tools };@@ -345,7 +371,11 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const mcpServer = await server.services.aiMcpServer.deleteMcpServer({- serverId: req.params.serverId+ serverId: req.params.serverId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId});return { server: mcpServer };diff --git a/backend/src/ee/services/ai-mcp-activity-log/ai-mcp-activity-log-service.ts b/backend/src/ee/services/ai-mcp-activity-log/ai-mcp-activity-log-service.tsindex cfdf9162c5..046c6c1f2e 100644--- a/backend/src/ee/services/ai-mcp-activity-log/ai-mcp-activity-log-service.ts+++ b/backend/src/ee/services/ai-mcp-activity-log/ai-mcp-activity-log-service.ts@@ -1,19 +1,41 @@-import { TAiMcpActivityLogsInsert } from "@app/db/schemas";+import { ForbiddenError } from "@casl/ability";+import { ActionProjectType, TAiMcpActivityLogsInsert } from "@app/db/schemas";+import { TProjectPermission } from "@app/lib/types";++import { TPermissionServiceFactory } from "../permission/permission-service-types";+import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";import { TAiMcpActivityLogDALFactory } from "./ai-mcp-activity-log-dal";export type TAiMcpActivityLogServiceFactory = ReturnType<typeof aiMcpActivityLogServiceFactory>;export type TAiMcpActivityLogServiceFactoryDep = {aiMcpActivityLogDAL: TAiMcpActivityLogDALFactory;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;};-export const aiMcpActivityLogServiceFactory = ({ aiMcpActivityLogDAL }: TAiMcpActivityLogServiceFactoryDep) => {+export type TListActivityLogsDTO = TProjectPermission;++export const aiMcpActivityLogServiceFactory = ({+ aiMcpActivityLogDAL,+ permissionService+}: TAiMcpActivityLogServiceFactoryDep) => {const createActivityLog = async (activityLog: TAiMcpActivityLogsInsert) => {return aiMcpActivityLogDAL.create(activityLog);};- const listActivityLogs = async (projectId: string) => {+ const listActivityLogs = async ({ projectId, actor, actorId, actorAuthMethod, actorOrgId }: TListActivityLogsDTO) => {+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.McpActivityLogs);+return aiMcpActivityLogDAL.find({ projectId });};diff --git a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.tsindex 58d04987d1..e9f22c8bec 100644--- a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts+++ b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts@@ -1,5 +1,6 @@import crypto from "node:crypto";+import { ForbiddenError } from "@casl/ability";// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignore - MCP SDK uses ESM with .js extensions which don't resolve types with moduleResolution: "Node"import { Client } from "@modelcontextprotocol/sdk/client/index.js";@@ -8,28 +9,37 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";import axios, { AxiosError } from "axios";+import { ActionProjectType } from "@app/db/schemas";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";+import { TPermissionServiceFactory } from "../permission/permission-service-types";+import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";import { TAiMcpServerDALFactory } from "./ai-mcp-server-dal";import { AiMcpServerCredentialMode, AiMcpServerStatus } from "./ai-mcp-server-enum";import { TAiMcpServerToolDALFactory } from "./ai-mcp-server-tool-dal";import {TAiMcpServerCredentials,TCreateAiMcpServerDTO,+ TDeleteMcpServerDTO,+ TGetMcpServerByIdDTO,TGetOAuthStatusDTO,THandleOAuthCallbackDTO,TInitiateOAuthDTO,+ TListMcpServersDTO,+ TListMcpServerToolsDTO,TOAuthAuthorizationServerMetadata,TOAuthDynamicClientMetadata,TOAuthProtectedResourceMetadata,TOAuthSession,TOAuthTokenResponse,+ TSyncMcpServerToolsDTO,TUpdateAiMcpServerDTO} from "./ai-mcp-server-types";import { TAiMcpServerUserCredentialDALFactory } from "./ai-mcp-server-user-credential-dal";@@ -40,6 +50,7 @@ type TAiMcpServerServiceFactoryDep = {aiMcpServerUserCredentialDAL: TAiMcpServerUserCredentialDALFactory;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;};export type TAiMcpServerServiceFactory = ReturnType<typeof aiMcpServerServiceFactory>;@@ -115,7 +126,8 @@ export const aiMcpServerServiceFactory = ({aiMcpServerToolDAL,aiMcpServerUserCredentialDAL,kmsService,- keyStore+ keyStore,+ permissionService}: TAiMcpServerServiceFactoryDep) => {/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-redundant-type-constituents */const fetchMcpTools = async (serverUrl: string, accessToken: string): Promise<TMcpTool[]> => {@@ -258,14 +270,35 @@ export const aiMcpServerServiceFactory = ({* Returns the authorization URL and session ID* Supports both DCR (Dynamic Client Registration) and hardcoded client credentials*/- const initiateOAuth = async ({ projectId, url, actorId, clientId, clientSecret }: TInitiateOAuthDTO) => {+ const initiateOAuth = async ({+ projectId,+ url,+ actorId,+ clientId,+ clientSecret,+ actor,+ actorAuthMethod,+ actorOrgId+ }: TInitiateOAuthDTO) => {const appCfg = getConfig();+ // Check permissions only when actor context is provided (called from router)+ if (actor && actorAuthMethod && actorOrgId) {+ const { permission } = await permissionService.getProjectPermission({+ actor: actor as ActorType,+ actorId,+ projectId,+ actorAuthMethod: actorAuthMethod as AuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.McpServers);+ }+// 1. Discover OAuth metadata following RFC 9728 flowconst { protectedResource, authServer } = await discoverOAuthMetadata(url);- logger.info({ protectedResource, authServer }, "Discovered OAuth metadata for MCP server");-// 2. Generate session IDconst sessionId = crypto.randomUUID();@@ -420,7 +453,7 @@ export const aiMcpServerServiceFactory = ({/*** Get OAuth status for a session*/- const getOAuthStatus = async ({ sessionId, actorId }: TGetOAuthStatusDTO) => {+ const getOAuthStatus = async ({ sessionId, actorId, actor, actorAuthMethod, actorOrgId }: TGetOAuthStatusDTO) => {const sessionDataStr = await keyStore.getItem(KeyStorePrefixes.AiMcpServerOAuth(sessionId));if (!sessionDataStr) {return { authorized: false };@@ -433,6 +466,17 @@ export const aiMcpServerServiceFactory = ({throw new BadRequestError({ message: "Unauthorized to access this OAuth session" });}+ const { permission } = await permissionService.getProjectPermission({+ actor: actor as ActorType,+ actorId,+ projectId: sessionData.projectId,+ actorAuthMethod: actorAuthMethod as AuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.McpServers);+if (!sessionData.authorized) {return { authorized: false };}@@ -455,8 +499,23 @@ export const aiMcpServerServiceFactory = ({authMethod,credentials,oauthClientId,- oauthClientSecret+ oauthClientSecret,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId}: TCreateAiMcpServerDTO) => {+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.McpServers);+const encryptedCredentials = await encryptCredentials({projectId,credentials,@@ -514,27 +573,61 @@ export const aiMcpServerServiceFactory = ({return server;};- const listMcpServers = async ({ projectId }: { projectId: string }) => {+ const listMcpServers = async ({ projectId, actor, actorId, actorAuthMethod, actorOrgId }: TListMcpServersDTO) => {+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.McpServers);+const servers = await aiMcpServerDAL.find({ projectId });return servers;};- const getMcpServerById = async ({ serverId }: { serverId: string }) => {+ const getMcpServerById = async ({ serverId, actor, actorId, actorAuthMethod, actorOrgId }: TGetMcpServerByIdDTO) => {const server = await aiMcpServerDAL.findById(serverId);if (!server) {throw new NotFoundError({ message: `MCP server with ID '${serverId}' not found` });}++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: server.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.McpServers);+return server;};const updateMcpServer = async (dto: TUpdateAiMcpServerDTO) => {- const { serverId, name, description } = dto;+ const { serverId, name, description, actor, actorId, actorAuthMethod, actorOrgId } = dto;const server = await aiMcpServerDAL.findById(serverId);if (!server) {throw new NotFoundError({ message: `MCP server with ID '${serverId}' not found` });}+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: server.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.McpServers);+const updateData: { name?: string; description?: string } = {};if (name !== undefined) updateData.name = name;if (description !== undefined) updateData.description = description;@@ -544,32 +637,77 @@ export const aiMcpServerServiceFactory = ({return updatedServer;};- const deleteMcpServer = async ({ serverId }: { serverId: string }) => {+ const deleteMcpServer = async ({ serverId, actor, actorId, actorAuthMethod, actorOrgId }: TDeleteMcpServerDTO) => {const server = await aiMcpServerDAL.findById(serverId);if (!server) {throw new NotFoundError({ message: `MCP server with ID '${serverId}' not found` });}+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: server.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.McpServers);+await aiMcpServerDAL.deleteById(serverId);return server;};- const listMcpServerTools = async ({ serverId }: { serverId: string }) => {+ const listMcpServerTools = async ({+ serverId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TListMcpServerToolsDTO) => {const server = await aiMcpServerDAL.findById(serverId);if (!server) {throw new NotFoundError({ message: `MCP server with ID '${serverId}' not found` });}+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: server.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.McpServers);+const tools = await aiMcpServerToolDAL.find({ aiMcpServerId: serverId });return tools;};- const syncMcpServerTools = async ({ serverId }: { serverId: string }) => {+ const syncMcpServerTools = async ({+ serverId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TSyncMcpServerToolsDTO) => {const server = await aiMcpServerDAL.findById(serverId);if (!server) {throw new NotFoundError({ message: `MCP server with ID '${serverId}' not found` });}+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: server.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.AI+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.McpServers);+if (!server.encryptedCredentials) {throw new BadRequestError({ message: "Server credentials not found" });}diff --git a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-types.ts b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-types.tsindex 38a107001f..6007d56d38 100644--- a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-types.ts+++ b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-types.ts@@ -1,3 +1,6 @@+import { TProjectPermission } from "@app/lib/types";+import { ActorAuthMethod } from "@app/services/auth/auth-type";+import { AiMcpServerAuthMethod, AiMcpServerCredentialMode } from "./ai-mcp-server-enum";// OAuth types from MCP server@@ -87,6 +90,9 @@ export type TInitiateOAuthDTO = {actorId: string;clientId?: string;clientSecret?: string;+ actor?: string;+ actorAuthMethod?: ActorAuthMethod;+ actorOrgId?: string;};export type THandleOAuthCallbackDTO = {@@ -96,11 +102,9 @@ export type THandleOAuthCallbackDTO = {export type TGetOAuthStatusDTO = {sessionId: string;- actorId: string;-};+} & Omit<TProjectPermission, "projectId">;export type TCreateAiMcpServerDTO = {- projectId: string;name: string;url: string;description?: string;@@ -109,14 +113,28 @@ export type TCreateAiMcpServerDTO = {credentials: TBasicCredentials | TBearerCredentials | TOAuthCredentials;oauthClientId?: string;oauthClientSecret?: string;- actorId: string;- actor: string;- actorAuthMethod: string;- actorOrgId: string;-};+} & TProjectPermission;++export type TListMcpServersDTO = TProjectPermission;++export type TGetMcpServerByIdDTO = {+ serverId: string;+} & Omit<TProjectPermission, "projectId">;export type TUpdateAiMcpServerDTO = {serverId: string;name?: string;description?: string;-};+} & Omit<TProjectPermission, "projectId">;++export type TDeleteMcpServerDTO = {+ serverId: string;+} & Omit<TProjectPermission, "projectId">;++export type TListMcpServerToolsDTO = {+ serverId: string;+} & Omit<TProjectPermission, "projectId">;++export type TSyncMcpServerToolsDTO = {+ serverId: string;+} & Omit<TProjectPermission, "projectId">;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 6966043fc3..3df42032e2 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2498,11 +2498,13 @@ export const registerRoutes = async (aiMcpServerToolDAL,aiMcpServerUserCredentialDAL,kmsService,- keyStore+ keyStore,+ permissionService});const aiMcpActivityLogService = aiMcpActivityLogServiceFactory({- aiMcpActivityLogDAL+ aiMcpActivityLogDAL,+ permissionService});const aiMcpEndpointService = aiMcpEndpointServiceFactory({diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsxindex 496566da1d..ec087d8d65 100644--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx@@ -370,6 +370,7 @@ export const AuthenticationStep = ({ onOAuthSuccess }: Props) => {value={field.value || ""}placeholder="Optional client ID"isDisabled={isOAuthPending || !!isOAuthAuthorized}+ autoComplete="one-time-code"/></FormControl>)}@@ -390,6 +391,7 @@ export const AuthenticationStep = ({ onOAuthSuccess }: Props) => {type="password"placeholder="Optional client secret"isDisabled={isOAuthPending || !!isOAuthAuthorized}+ autoComplete="new-password"/></FormControl>)}