import { mcpPolicyPreviewRequestSchema, type McpPolicyDecision, type McpPolicyPreviewRequest, type McpPolicyReasonCode, type McpConnectionPolicy, } from "@mmapp/contracts/mcp" import { hasPermission } from "../../lib/permissions.js" import { findMcpOperation } from "./registry.js" export function hasUnattendedPlanAuthority(policy: McpConnectionPolicy) { return policy.authority === "service" && policy.mode === "autonomous" && policy.allowUnattendedPlans === true } export function hasUnlimitedMcpRates(policy: McpConnectionPolicy) { return policy.authority === "service" && policy.unlimitedRates === true } export function operationApprovalRequirement(policy: McpConnectionPolicy, operationId: string, target: McpPolicyPreviewRequest["target"], requiresHuman?: boolean): Pick { if (!requiresHuman || hasUnattendedPlanAuthority(policy)) return { objects: [], protections: [] } const objects = target.scope === "servers" ? [] : [{ kind: "mcp-operation", id: operationId }] const protectedObjects = target.scope === "servers" ? target.serverIds.map(serverId => ({ kind: "server", id: String(serverId), serverId })) : objects return { objects, protections: protectedObjects.map(object => ({ ...object, protection: "human-approval-required" })) } } /** Pure policy simulation. Does not grant authority, reserve budgets or execute handlers. */ export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Date()): McpPolicyDecision { const input = mcpPolicyPreviewRequestSchema.parse(payload) if (!Number.isFinite(now.getTime())) throw new Error("Некорректное время проверки MCP") const { policy, target, usage } = input const unlimitedRates = hasUnlimitedMcpRates(policy) const denied: McpPolicyDecision["reasons"] = [] const approvals: McpPolicyDecision["reasons"] = [] const deny = (code: McpPolicyReasonCode, message: string) => { denied.push({ code, message }) } const approve = (message: string) => { approvals.push({ code: "APPROVAL_REQUIRED", message }) } const result = (): McpPolicyDecision => ({ decision: denied.length ? "denied" : approvals.length ? "approval-required" : "allowed", reasons: [...denied, ...approvals], limits: policy.limits, ...(unlimitedRates && { unlimitedRates: true }), }) const operation = findMcpOperation(input.operationId) if (!operation) { deny("UNKNOWN_OPERATION", "Операция отсутствует в реестре MCP") return result() } if (policy.status !== "active") deny("CONNECTION_INACTIVE", "Подключение приостановлено или отозвано") if (Date.parse(policy.expiresAt) <= now.getTime()) deny("CONNECTION_EXPIRED", "Срок подключения истёк") if (!policy.scope.operationIds.includes(operation.id)) deny("OPERATION_DENIED", "Операция не выдана подключению") for (const permission of operation.requiredPermissions) { if (!hasPermission(input.ownerPermissions, permission)) deny("OWNER_PERMISSION_MISSING", `У владельца нет права ${permission}`) if (!hasPermission(policy.permissions, permission)) deny("CONNECTION_PERMISSION_MISSING", `Подключению не выдано право ${permission}`) } if (operation.scope !== target.scope) deny("TARGET_SCOPE_MISMATCH", "Область операции не совпадает с областью запроса") if (target.scope === "servers" && target.serverIds.some(id => !policy.scope.serverIds.includes(id))) { deny("SERVER_DENIED", "Запрос затрагивает неразрешённый сервер") } if (target.scope === "global" && !policy.scope.allowGlobal) deny("GLOBAL_DENIED", "Глобальные операции не разрешены") const grant = input.temporaryGrant if (grant) { if (Date.parse(grant.startsAt) > now.getTime() || Date.parse(grant.expiresAt) <= now.getTime()) deny("GRANT_INACTIVE", "Временный доступ ещё не начался или истёк") if (!grant.scope.operationIds.includes(operation.id) || target.scope === "servers" && target.serverIds.some(id => !grant.scope.serverIds.includes(id)) || target.scope === "global" && !grant.scope.allowGlobal || input.objects.some(object => object.serverId !== undefined && !grant.scope.serverIds.includes(object.serverId))) { deny("GRANT_SCOPE_DENIED", "Запрос выходит за пределы временного доступа") } } const invalidObjectScope = input.objects.some(object => { if (object.kind === "server" && (object.serverId === undefined || object.id !== String(object.serverId))) return true if (target.scope === "servers") return object.serverId === undefined || !target.serverIds.includes(object.serverId) if (target.scope === "connection") return true return object.serverId !== undefined && !policy.scope.serverIds.includes(object.serverId) }) if (invalidObjectScope) { deny("INVALID_OBJECT_SCOPE", "Объект или зависимость находится вне области запроса") } if (!unlimitedRates && usage.callsInMinute >= policy.limits.callsPerMinute) deny("RATE_LIMITED", "Исчерпан минутный лимит вызовов") if (operation.effect === "read") { if (!unlimitedRates && usage.concurrentReads >= policy.limits.concurrentReads) deny("RATE_LIMITED", "Исчерпан лимит одновременного чтения") return result() } if (policy.mode === "observer") deny("OBSERVER_WRITE_DENIED", "Наблюдателю запрещены изменения и нагрузочные проверки") if (!input.auditAvailable) deny("AUDIT_UNAVAILABLE", "До начала изменений требуется доступный аудит") if (!unlimitedRates && (usage.mutationsInHour >= policy.limits.mutationsPerHour || usage.mutationsInHour + input.objectCount > policy.limits.mutationsPerHour)) deny("BUDGET_EXCEEDED", "Недостаточно часового бюджета для всех изменений плана") const affectedServers = new Set([ ...(target.scope === "servers" ? target.serverIds : []), ...input.objects.flatMap(object => object.serverId === undefined ? [] : [object.serverId]), ]) if (affectedServers.size > policy.limits.serversPerPlan) deny("PLAN_LIMIT_EXCEEDED", "Превышено число серверов на план") if (Math.max(input.objectCount, input.objects.length) > policy.limits.objectsPerPlan) deny("PLAN_LIMIT_EXCEEDED", "Превышено число изменяемых объектов") for (const protection of input.protections) { const matchesServer = protection.kind === "server" && [...affectedServers].some(id => String(id) === protection.id && (protection.serverId === undefined || protection.serverId === id)) // Probe IDs are global primary keys even in a server-scoped plan. Existing // catalog protections may omit serverId; native RouterOS IDs are not global. const matchesObject = input.objects.some(object => object.kind === protection.kind && object.id === protection.id && (object.serverId === protection.serverId || protection.serverId === undefined && ["ping-probe", "speed-probe"].includes(object.kind))) if (!matchesServer && !matchesObject) continue if (protection.protection === "deny") deny("PROTECTED_OBJECT", "Защищённый объект запрещает изменение") else approve("Защищённый объект требует подтверждения человеком") } if (policy.mode === "approval") approve("Режим подключения требует подтверждения человеком") if (operation.risk === "dangerous" && !hasUnattendedPlanAuthority(policy) && !(policy.dangerousPolicy === "explicit-allow" && policy.autonomousDangerousOperationIds.includes(operation.id))) { approve("Опасная операция не разрешена для автономного выполнения") } return result() }