Files
MikrotikManager/backend/src/modules/mcp/policy.ts
T

95 lines
6.8 KiB
TypeScript

import {
mcpPolicyPreviewRequestSchema,
type McpPolicyDecision,
type McpPolicyPreviewRequest,
type McpPolicyReasonCode,
} from "@mmapp/contracts/mcp"
import { hasPermission } from "../../lib/permissions.js"
import { findMcpOperation } from "./registry.js"
/** 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 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,
})
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 (usage.callsInMinute >= policy.limits.callsPerMinute) deny("RATE_LIMITED", "Исчерпан минутный лимит вызовов")
if (operation.effect === "read") {
if (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 (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" && !(policy.dangerousPolicy === "explicit-allow" && policy.autonomousDangerousOperationIds.includes(operation.id))) {
approve("Опасная операция не разрешена для автономного выполнения")
}
return result()
}