feat(mcp): расширить управление сетью и исправить разрезы трафика
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Failing after 10m39s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 3m11s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Failing after 10m39s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 3m11s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Добавить переименование интерфейсов и возможность отключать лимиты частоты для сервисных аккаунтов. Уточнить дедупликацию, учёт интерфейсов и геоданных, фильтрацию сессий и карту потоков.
This commit is contained in:
1 parent
d255694cda
commit
aac425c7b2
31 files changed
+623
-138
No files matched your search
@@ -12,6 +12,7 @@ export const ACCEPTANCE_SHARDS: Record<string, (actor: AuthUser) => Promise<unkn
|
||||
acceptRouteCommunityContextMcp: async actor => (await import("./routing-community-context-acceptance.js")).acceptRouteCommunityContextMcp(actor),
|
||||
acceptWireguardPeerCreation: async actor => (await import("./wireguard-peer-create-acceptance.js")).acceptWireguardPeerCreation(actor),
|
||||
acceptWireguardInterfaceUpdate: async actor => (await import("./wireguard-interface-update-acceptance.js")).acceptWireguardInterfaceUpdate(actor),
|
||||
acceptInterfaceRename: async actor => (await import("./interface-rename-acceptance.js")).acceptInterfaceRename(actor),
|
||||
acceptWireguardImport: async actor => (await import("./wireguard-import-acceptance.js")).acceptWireguardImport(actor),
|
||||
verifyMcpFlowOverlay: async actor => (await import("../../test/mcp-flow-overlay.js")).verifyMcpFlowOverlay(actor),
|
||||
acceptWireguardInterfaceDeletion: async actor => (await import("./wireguard-interface-delete-acceptance.js")).acceptWireguardInterfaceDeletion(actor),
|
||||
|
||||
@@ -91,6 +91,7 @@ import { registerTerminalDiagnosticActions } from "./terminal-diagnostic-actions
|
||||
import { registerEventsBatchActions } from "./events-batch-actions.js"
|
||||
import { registerGlobalReconciliationActions } from "./global-reconciliation-actions.js"
|
||||
import { registerWireguardInterfaceUpdateActions } from "./wireguard-interface-update-actions.js"
|
||||
import { registerInterfaceRenameActions } from "./interface-rename-actions.js"
|
||||
import { registerWireguardImportActions } from "./wireguard-import-actions.js"
|
||||
import { registerWireguardExportActions } from "./wireguard-export-actions.js"
|
||||
import { registerServerConnectionActions } from "./server-connection-actions.js"
|
||||
@@ -710,6 +711,7 @@ registerTerminalDiagnosticActions(add)
|
||||
registerEventsBatchActions(add)
|
||||
registerGlobalReconciliationActions(add)
|
||||
registerWireguardInterfaceUpdateActions(add)
|
||||
registerInterfaceRenameActions(add)
|
||||
registerWireguardImportActions(add)
|
||||
registerServerConnectionActions(add)
|
||||
registerIpsecPeerDeleteActions(add)
|
||||
|
||||
@@ -3028,6 +3028,7 @@ try {
|
||||
await soft("verifyMcpTerminalDiagnostics", async () => (await import("../../test/mcp-terminal-diagnostics.js")).verifyMcpTerminalDiagnostics(actor, app))
|
||||
await soft("verifyMcpEventsBatch", async () => (await import("../../test/mcp-events-batch.js")).verifyMcpEventsBatch(actor, app))
|
||||
await shardable("acceptWireguardInterfaceUpdate")
|
||||
await shardable("acceptInterfaceRename")
|
||||
await shardable("acceptWireguardImport")
|
||||
await soft("acceptWireguardExportMcp", async () => (await import("./wireguard-export-acceptance.js")).acceptWireguardExportMcp(actor, app))
|
||||
await soft("acceptProtectionRegistrationScope", async () => (await import("./protection-scope-acceptance.js")).acceptProtectionRegistrationScope(actor))
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { createServer } from "node:http"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
|
||||
import { pool } from "../../db/index.js"
|
||||
import type { AuthUser } from "../../lib/permissions.js"
|
||||
import { approvePlan, applyPlan, invokeMcpTool } from "./runtime.js"
|
||||
import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js"
|
||||
|
||||
export async function acceptInterfaceRename(actor: AuthUser) {
|
||||
const serverId = 174
|
||||
const initial: Record<string, Record<string, string>[]> = {
|
||||
"/interface": [
|
||||
{ ".id": "*7", name: "wg1", type: "wg", dynamic: "false" },
|
||||
{ ".id": "*8", name: "ether1", "default-name": "ether1", type: "ether" },
|
||||
{ ".id": "*9", name: "radio one", type: "wifi" },
|
||||
{ ".id": "*a", name: "dynamic1", type: "ppp", dynamic: "true" },
|
||||
{ ".id": "*b", name: "wg1-backup", type: "wg" },
|
||||
],
|
||||
"/ip/address": [{ ".id": "*15", interface: "wg1", "actual-interface": "wg1", address: "192.0.2.1/30" }],
|
||||
"/ipv6/address": [{ ".id": "*16", interface: "*7", address: "2001:db8::1/64" }],
|
||||
"/interface/bridge/port": [{ ".id": "*14", bridge: "bridge1", interface: "ether1" }],
|
||||
"/interface/wireguard/peers": [{ ".id": "*11", interface: "wg1", name: "other-site", "public-key": "fixture-public-key", "allowed-address": "192.0.2.2/32", "endpoint-port": "13235" }],
|
||||
"/ip/firewall/filter": [
|
||||
{ ".id": "*20", chain: "input", action: "accept", "in-interface": "wg1", protocol: "udp" },
|
||||
{ ".id": "*21", chain: "forward", action: "drop", "in-interface": "!wg1", "out-interface": "wg1-backup" },
|
||||
],
|
||||
"/ip/route": [{ ".id": "*22", static: "true", gateway: "192.0.2.2%wg1@main", "dst-address": "198.51.100.0/24" }, ...Array.from({ length: 12_608 }, (_, i) => ({ ".id": `*r${i.toString(16)}`, dynamic: "true", gateway: "192.0.2.2%ether1" }))],
|
||||
}
|
||||
let rows = structuredClone(initial), reads = 0, mode: "normal" | "stale" | "lost" = "normal"
|
||||
const writes: { path: string; fields: Record<string, string> }[] = []
|
||||
const router = createServer(async (req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://fixture.invalid"), path = url.pathname.slice(5)
|
||||
res.setHeader("content-type", "application/json")
|
||||
if (req.method === "GET") {
|
||||
let records = rows[path] ?? []
|
||||
if (url.searchParams.get("static") === "true") records = records.filter(row => row.static === "true")
|
||||
const properties = url.searchParams.get(".proplist")?.split(",")
|
||||
if (properties) records = records.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => properties.includes(key))))
|
||||
if (path === "/ip/firewall/filter") records = records.map(row => ({ ...row, packets: String(++reads) }))
|
||||
res.end(JSON.stringify(records)); return
|
||||
}
|
||||
if (req.method !== "PATCH" || !/^\/interface\/\*[a-z0-9]+$/i.test(path)) { res.statusCode = 400; res.end("{}"); return }
|
||||
let body = ""; for await (const chunk of req) body += chunk
|
||||
const fields: Record<string, string> = JSON.parse(body), target = rows["/interface"].find(row => path.endsWith("/" + row[".id"]))!
|
||||
const old = target.name
|
||||
writes.push({ path, fields })
|
||||
Object.assign(target, fields)
|
||||
if (mode !== "stale") {
|
||||
for (const rowsForPath of Object.values(rows)) for (const row of rowsForPath) for (const key of ["interface", "actual-interface", "in-interface", "out-interface"]) {
|
||||
if (row[key] === old) row[key] = target.name
|
||||
if (row[key] === "!" + old) row[key] = "!" + target.name
|
||||
}
|
||||
for (const row of rows["/ip/route"]) if (row.gateway.endsWith(`%${old}@main`)) row.gateway = row.gateway.replace(`%${old}@main`, `%${target.name}@main`)
|
||||
}
|
||||
if (mode === "lost") { req.socket.destroy(); return }
|
||||
res.end(JSON.stringify(target))
|
||||
})
|
||||
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
||||
let connectionId: string | undefined
|
||||
const protection = randomUUID()
|
||||
try {
|
||||
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl) VALUES($1,'interface-rename-fixture','127.0.0.1',$2,false)", [serverId, (router.address() as { port: number }).port])
|
||||
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "interface rename", mode: "approval", expiresAt: new Date(Date.now() + 1_800_000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [serverId], operationIds: ["interfaces.rename"], allowGlobal: false }, limits: { callsPerMinute: 120 } }), actor)
|
||||
connectionId = access.connection.id
|
||||
const principal = await authenticateMcpToken(access.token)
|
||||
const plan = async (iface: string, name: string) => (await invokeMcpTool(principal, "mm_interface_rename_plan", { serverId, interface: iface, name })) as { planId: string }
|
||||
const execute = async (iface: string, name: string) => {
|
||||
const { planId } = await plan(iface, name)
|
||||
await approvePlan(planId, actor, true)
|
||||
const { id } = await applyPlan(principal, planId, randomUUID())
|
||||
for (let i = 0; i < 500; i++) {
|
||||
const result = (await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]
|
||||
if (result && !["pending", "running"].includes(result.state)) return result
|
||||
await delay(20)
|
||||
}
|
||||
throw new Error("Interface rename remains live")
|
||||
}
|
||||
await assert.rejects(plan("dynamic1", "renamed"), { code: "PROTECTED_OBJECT" })
|
||||
await assert.rejects(plan("*7", "ether1"), { code: "STATE_CONFLICT" })
|
||||
assert.equal(writes.length, 0)
|
||||
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,$3)", [protection, JSON.stringify({ kind: "ip_filter", id: "*20", serverId, protection: "deny" }), actor.id])
|
||||
await assert.rejects(plan("*7", "protected-test"), { code: "PROTECTED_OBJECT" })
|
||||
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection])
|
||||
assert.equal((await execute("wg1", "wg-to-msk-gw01")).state, "applied")
|
||||
assert.deepEqual(writes[0], { path: "/interface/*7", fields: { name: "wg-to-msk-gw01" } })
|
||||
assert.deepEqual(rows["/ip/firewall/filter"].map(row => row["in-interface"]), ["wg-to-msk-gw01", "!wg-to-msk-gw01"])
|
||||
assert.equal(rows["/ip/firewall/filter"][1]["out-interface"], "wg1-backup")
|
||||
assert.equal(rows["/interface/wireguard/peers"][0].interface, "wg-to-msk-gw01")
|
||||
assert.equal(rows["/ipv6/address"][0].interface, "*7")
|
||||
assert.equal(rows["/ip/route"][0].gateway, "192.0.2.2%wg-to-msk-gw01@main")
|
||||
assert.equal((await execute("*8", "ether-wan")).state, "applied")
|
||||
assert.equal(rows["/interface/bridge/port"][0].interface, "ether-wan")
|
||||
assert.equal((await execute("radio one", "wifi guest")).state, "applied")
|
||||
assert.equal(writes.length, 3)
|
||||
mode = "stale"
|
||||
assert.equal((await execute("wg-to-msk-gw01", "wg-incomplete")).error_code, "VERIFICATION_FAILED")
|
||||
assert.equal(writes.length, 4)
|
||||
rows = structuredClone(initial); mode = "lost"
|
||||
assert.equal((await execute("wg1", "wg-unknown")).error_code, "MUTATION_OUTCOME_UNKNOWN")
|
||||
assert.equal(writes.length, 5)
|
||||
} finally {
|
||||
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection])
|
||||
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
|
||||
await pool.query("DELETE FROM servers WHERE id=$1", [serverId])
|
||||
router.closeAllConnections()
|
||||
await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js"
|
||||
import { greStableRows, assertGreDeleteDependencies } from "../../services/gre-mutation-state.js"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import { encodeRosId, isRouterOsNativeId } from "../../services/routeros-native-paths.js"
|
||||
import type { add } from "./actions.js"
|
||||
import type { ChangeEvidence } from "./action-types.js"
|
||||
import { rosSnapshotSourceProof, routerClient } from "./resources.js"
|
||||
import { fingerprint, McpError, privateSecretFingerprint } from "./security.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
|
||||
const service = "interfaces.rename"
|
||||
const name = z.string().min(1).max(100).refine(value => value === value.trim() && !/[\u0000-\u001f\u007f]/.test(value))
|
||||
const schema = z.object({ serverId: z.number().int().positive().safe(), interface: name, name }).strict()
|
||||
const recordSchema = z.object({ serverId: schema.shape.serverId, id: z.string().max(200).refine(isRouterOsNativeId), from: name, to: name }).strict()
|
||||
type Rename = z.infer<typeof recordSchema>
|
||||
type Row = Record<string, string>
|
||||
type Reference = "single" | "list" | "gateway" | "negated"
|
||||
|
||||
const inventory = "/interface?.proplist=.id,name,type,default-name,dynamic,builtin,default,disabled,mtu,l2mtu,comment"
|
||||
const firewall = (["ip", "ipv6"] as const).flatMap(family => ["filter", "nat", "mangle", "raw"].map(table => ({
|
||||
kind: `${family}_${table}`, path: `/${family}/firewall/${table}`, fields: { "in-interface": "negated", "out-interface": "negated" } as const, ordered: true,
|
||||
})))
|
||||
const references: { kind: string; path: string; fields: Record<string, Reference>; ordered?: boolean; wireguard?: boolean }[] = [
|
||||
{ kind: "ipv4_address", path: "/ip/address", fields: { interface: "single", "actual-interface": "single" } },
|
||||
{ kind: "ipv6_address", path: "/ipv6/address", fields: { interface: "single", "actual-interface": "single" } },
|
||||
{ kind: "interface_list_member", path: "/interface/list/member", fields: { interface: "single" } },
|
||||
{ kind: "bridge_port", path: "/interface/bridge/port", fields: { interface: "single", bridge: "single" } },
|
||||
{ kind: "bridge_vlan", path: "/interface/bridge/vlan", fields: { bridge: "single", tagged: "list", untagged: "list" } },
|
||||
{ kind: "vlan", path: "/interface/vlan", fields: { interface: "single" } },
|
||||
{ kind: "bonding", path: "/interface/bonding", fields: { slaves: "list" } },
|
||||
{ kind: "vrrp", path: "/interface/vrrp", fields: { interface: "single", "group-authority": "single" } },
|
||||
{ kind: "wireguard_peer", path: "/interface/wireguard/peers?.proplist=.id,interface,name,public-key,allowed-address,endpoint-address,endpoint-port,persistent-keepalive,disabled,dynamic,comment", fields: { interface: "single" }, wireguard: true },
|
||||
{ kind: "ipv4_route", path: "/ip/route?static=true", fields: { gateway: "gateway" } },
|
||||
{ kind: "ipv6_route", path: "/ipv6/route?static=true", fields: { gateway: "gateway" } },
|
||||
{ kind: "routing_rule", path: "/routing/rule", fields: { interface: "single" }, ordered: true },
|
||||
{ kind: "vrf", path: "/ip/vrf", fields: { interfaces: "list" }, ordered: true },
|
||||
{ kind: "ospf_template", path: "/routing/ospf/interface-template", fields: { interfaces: "list" }, ordered: true },
|
||||
{ kind: "bfd_configuration", path: "/routing/bfd/configuration", fields: { interfaces: "list" }, ordered: true },
|
||||
...firewall,
|
||||
]
|
||||
|
||||
const fail = (code: string, message: string, status = 409) => new McpError(code, message, status)
|
||||
const unstable = (path: string) => fail("STATE_UNAVAILABLE", `Не подтверждён каталог RouterOS ${path.split("?")[0]}`, 502)
|
||||
const unsupported = new Set(["all", "none", "dynamic", "slave", "static", "wg-flow", "lo"])
|
||||
|
||||
async function catalogue(client: Awaited<ReturnType<typeof routerClient>>["client"], path: string): Promise<Row[]> {
|
||||
const routes = path.endsWith("?static=true")
|
||||
let raw: unknown
|
||||
try { raw = await client.get<unknown>(path, 10_000, undefined, routes ? 8 * 1024 * 1024 : 1_048_576) }
|
||||
catch (error) { if (error instanceof McpError) throw error; throw unstable(path) }
|
||||
if (!Array.isArray(raw) || raw.length > (routes ? 50_000 : 10_000) || raw.some(row => !row || typeof row !== "object" || Array.isArray(row) || !isRouterOsNativeId(row[".id"]) || Object.values(row).some(value => typeof value !== "string")) || new Set(raw.map(row => row[".id"])).size !== raw.length) throw unstable(path)
|
||||
return raw as Row[]
|
||||
}
|
||||
|
||||
/** RouterOS can render the same typed reference as a name or a native ID. */
|
||||
function interfaceRenameReference(value: string, mode: Reference, aliases: ReadonlySet<string>, replacement: string): string {
|
||||
if (aliases.has(value)) return replacement
|
||||
if (mode === "negated" && value.startsWith("!") && aliases.has(value.slice(1))) return `!${replacement}`
|
||||
if (mode === "list" || mode === "gateway") return value.split(",").map(part => {
|
||||
if (aliases.has(part)) return replacement
|
||||
if (mode === "gateway") {
|
||||
const match = /^([^%@]+%)?([^%@]+)(@[^%@]+)?$/.exec(part)
|
||||
if (match && aliases.has(match[2])) return `${match[1] ?? ""}${replacement}${match[3] ?? ""}`
|
||||
}
|
||||
return part
|
||||
}).join(",")
|
||||
return value
|
||||
}
|
||||
|
||||
function targetFrom(rows: Row[], identity: string) {
|
||||
const target = rows.find(row => row.name === identity || row[".id"] === identity)
|
||||
if (!target) throw fail("NOT_FOUND", "Интерфейс RouterOS не найден", 404)
|
||||
if (!target.type || !target.name || rows.filter(row => row.name === target.name || row[".id"] === identity || row.name === identity).length !== 1) throw unstable(inventory)
|
||||
if (["dynamic", "builtin", "default"].some(key => target[key] !== undefined && observedBoolean(target[key]) !== false) || unsupported.has(target.name.toLowerCase()) || target.comment === "MikrotikManager traffic-flow overlay") throw fail("PROTECTED_OBJECT", "Динамический, системный или управляемый NetFlow интерфейс нельзя переименовать этим планом")
|
||||
return target
|
||||
}
|
||||
|
||||
async function applicationReferences(move: Rename) {
|
||||
const names = [move.id, move.from, move.to]
|
||||
const { rows } = await pool.query<{ bound: boolean }>(`SELECT (
|
||||
EXISTS(SELECT 1 FROM user_interface_bindings WHERE server_id=$1 AND interface_name=ANY($2::text[])) OR
|
||||
EXISTS(SELECT 1 FROM uptime_probes WHERE src_server_id=$1 AND src_interface=ANY($2::text[])) OR
|
||||
EXISTS(SELECT 1 FROM uptime_speed_probes WHERE (src_server_id=$1 AND src_interface=ANY($2::text[])) OR (dst_server_id=$1 AND dst_interface=ANY($2::text[])))
|
||||
) AS bound`, [move.serverId, names])
|
||||
if (rows[0]?.bound !== false) throw fail("DEPENDENCY_CONFLICT", "Имя или ID используется в настройках приложения; требуется согласованное изменение привязки")
|
||||
const { rows: filters } = await pool.query<{ id: number; gateway: string; gatewayTunnelId: string }>('SELECT id, gateway, gateway_tunnel_id AS "gatewayTunnelId" FROM filter_rules WHERE server_id=$1 LIMIT 1001', [move.serverId])
|
||||
if (filters.length > 1000) throw fail("STATE_UNAVAILABLE", "Не подтверждены зависимости фильтров приложения", 502)
|
||||
const aliases = new Set(names)
|
||||
if (filters.some(row => aliases.has(row.gatewayTunnelId) || interfaceRenameReference(row.gateway, "gateway", aliases, "\u0000") !== row.gateway)) throw fail("DEPENDENCY_CONFLICT", "Интерфейс используется BGP-фильтром приложения")
|
||||
}
|
||||
|
||||
async function read(move: Rename, expectedSource: string, authorize: () => Promise<unknown>) {
|
||||
await authorize()
|
||||
const { client, server } = await routerClient(move.serverId)
|
||||
if (await rosSnapshotSourceProof(server) !== expectedSource) throw fail("STATE_CONFLICT", "Источник RouterOS изменился")
|
||||
const interfaces = await catalogue(client, inventory), target = targetFrom(interfaces, move.id)
|
||||
if (![move.from, move.to].includes(target.name) || interfaces.some(row => row[".id"] !== move.id && row.name === move.to)) throw fail("STATE_CONFLICT", "Интерфейс изменился или новое имя уже занято")
|
||||
const aliases = new Set([move.from, move.to, move.id]), current = new Set([target.name, move.id])
|
||||
const marker = `\u0000${move.id}`
|
||||
const affected: ChangeEvidence["objects"] = []
|
||||
const sections: unknown[] = []
|
||||
for (const dependency of references) {
|
||||
if (dependency.wireguard && !["wg", "wireguard"].includes(target.type)) continue
|
||||
await authorize()
|
||||
const rows = await catalogue(client, dependency.path)
|
||||
if (dependency.path.endsWith("?static=true") && rows.some(row => observedBoolean(row.dynamic) === true || observedBoolean(row.static) === false)) throw unstable(dependency.path)
|
||||
const selected: Row[] = []
|
||||
for (const [position, row] of rows.entries()) {
|
||||
if (observedBoolean(row.dynamic) === true) continue
|
||||
const projection = { ...row }
|
||||
let related = false
|
||||
for (const [field, mode] of Object.entries(dependency.fields)) {
|
||||
if (row[field] === undefined || interfaceRenameReference(row[field], mode, aliases, marker) === row[field]) continue
|
||||
if (interfaceRenameReference(row[field], mode, aliases, marker) !== interfaceRenameReference(row[field], mode, current, marker)) throw fail("DEPENDENCY_CONFLICT", `Несогласованная ссылка на интерфейс в ${dependency.path.split("?")[0]}`)
|
||||
projection[field] = interfaceRenameReference(row[field], mode, current, marker)
|
||||
related = true
|
||||
}
|
||||
if (!related) continue
|
||||
affected.push({ kind: dependency.kind, id: row[".id"], serverId: move.serverId })
|
||||
// These bridge VLAN memberships are derived by RouterOS from the configured ports and PVID.
|
||||
if (dependency.kind === "bridge_vlan") { delete projection["current-tagged"]; delete projection["current-untagged"] }
|
||||
if (dependency.ordered) projection.position = String(position)
|
||||
selected.push(projection)
|
||||
}
|
||||
sections.push([dependency.kind, greStableRows(selected, dependency.ordered)])
|
||||
}
|
||||
const policyPath = "/routing/filter/rule?.proplist=.id,rule"
|
||||
await authorize()
|
||||
const routingFilters = await catalogue(client, policyPath)
|
||||
for (const reference of [move.from, move.to]) assertGreDeleteDependencies({ dependencies: { [policyPath]: routingFilters }, bindings: [], filters: [] }, { name: reference, ".id": move.id }, "Имя интерфейса")
|
||||
await applicationReferences(move)
|
||||
await authorize()
|
||||
if (await rosSnapshotSourceProof((await routerClient(move.serverId)).server) !== expectedSource) throw fail("STATE_CONFLICT", "Источник RouterOS изменился во время чтения")
|
||||
const identities = interfaces.filter(row => row[".id"] === move.id || observedBoolean(row.dynamic) !== true)
|
||||
const proof = (targetName: string) => privateSecretFingerprint(fingerprint({ interfaces: greStableRows(identities.map(row => row[".id"] === move.id ? { ...row, name: targetName } : row)), sections }), "mcp-interface-rename-v1")
|
||||
return { target, affected, before: { name: target.name, proof: await proof(target.name) }, afterProof: await proof(move.to) }
|
||||
}
|
||||
|
||||
export function registerInterfaceRenameActions(register: typeof add) {
|
||||
const current = async (input: Record<string, unknown>) => (await read(recordSchema.parse(input.move), String(input.source), async () => {})).before
|
||||
registerMcpService(service, {
|
||||
current,
|
||||
execute: async input => {
|
||||
const move = recordSchema.parse(input.move), source = String(input.source)
|
||||
const { client } = await routerClient(move.serverId)
|
||||
try {
|
||||
await client.patch(`/interface/${encodeRosId(move.id)}`, { name: move.to }, 15_000, async () => {
|
||||
await assertVerifiedConfigurationAccess()
|
||||
if ((await read(move, source, assertVerifiedConfigurationReadAccess)).before.proof !== input.beforeProof) throw fail("STATE_CONFLICT", "Интерфейс или его ссылки изменились перед переименованием")
|
||||
await assertVerifiedConfigurationAccess()
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof McpError) throw error
|
||||
throw fail("MUTATION_OUTCOME_UNKNOWN", "Исход переименования не подтверждён; повтор запрещён", 503)
|
||||
}
|
||||
return { interfaceId: move.id, previousName: move.from, name: move.to }
|
||||
},
|
||||
verify: async input => {
|
||||
try { return (await current(input)).proof === input.afterProof }
|
||||
catch (error) { if (error instanceof McpError && error.code === "DEPENDENCY_CONFLICT") return false; throw error }
|
||||
},
|
||||
reconcile: async (input, authorize) => {
|
||||
const { before } = await read(recordSchema.parse(input.move), String(input.source), authorize)
|
||||
return { matchesOriginalState: before.proof === input.beforeProof, matchesDesiredState: before.proof === input.afterProof }
|
||||
},
|
||||
})
|
||||
register(service, "mm_interface_rename_plan", "Переименовать интерфейс RouterOS по ID или текущему имени и проверить сохранность привязок", "network", "mm:network:write", "write", "servers", schema, {
|
||||
prepare: async (input, context) => {
|
||||
const request = schema.parse(input), { client, server } = await routerClient(request.serverId)
|
||||
const source = await rosSnapshotSourceProof(server)
|
||||
const target = targetFrom(await catalogue(client, inventory), request.interface)
|
||||
if (request.name === target.name || unsupported.has(request.name.toLowerCase()) || isRouterOsNativeId(request.name)) throw fail("INVALID_INPUT", "Укажите новое незарезервированное имя интерфейса", 400)
|
||||
const move = recordSchema.parse({ serverId: request.serverId, id: target[".id"], from: target.name, to: request.name })
|
||||
const state = await read(move, source, async () => { context.signal?.throwIfAborted() })
|
||||
if (state.before.name !== move.from) throw fail("STATE_CONFLICT", "Имя интерфейса изменилось во время подготовки")
|
||||
const kind = ({ wg: "wireguard", ether: "ethernet" } as Record<string, string>)[state.target.type] ?? state.target.type
|
||||
const objects = [{ kind: "server", id: String(move.serverId), serverId: move.serverId }, ...[...new Set(["interface", kind])].flatMap(kind => [move.id, move.from, move.to].map(id => ({ kind, id, serverId: move.serverId }))), ...state.affected]
|
||||
return { target: { scope: "servers", serverIds: [move.serverId] }, objects, snapshots: [], before: state.before, requiresHuman: true, verificationScope: "configuration",
|
||||
steps: [{ kind: "service", service, input: { serverId: move.serverId, move, source, beforeProof: state.before.proof, afterProof: state.afterProof } }],
|
||||
warnings: ["Выполняется один RouterOS PATCH имени по native ID. Передача трафика может кратко прерваться.", "Проверяются идентичность интерфейса и ссылки в наблюдаемых каталогах RouterOS. Пользовательские скрипты и история метрик по имени не переписываются.", "При неясном исходе требуется сверка. Команда не повторяется автоматически."],
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -55,6 +55,24 @@ test("unattended plans require an explicit service policy and retain server prot
|
||||
denied(input, "PROTECTED_OBJECT")
|
||||
})
|
||||
|
||||
test("service rate exemptions keep plan size, server scope and approval checks", () => {
|
||||
const input = request()
|
||||
assert.equal(mcpConnectionPolicySchema.safeParse({ ...input.policy, unlimitedRates: true }).success, false)
|
||||
input.policy = mcpConnectionPolicySchema.parse({ ...input.policy, authority: "service", expiresAt: MCP_SERVICE_EXPIRATION, unlimitedRates: true })
|
||||
input.usage = { callsInMinute: 10_000, concurrentReads: 100, mutationsInHour: 10_000 }
|
||||
const read = { ...input, operationId: "logs.query" }
|
||||
assert.equal(evaluateMcpPolicy(read, now).decision, "allowed")
|
||||
const mutation = mcpPolicyDecisionSchema.parse(evaluateMcpPolicy(input, now))
|
||||
assert.equal(mutation.unlimitedRates, true)
|
||||
assert.equal(mutation.decision, "approval-required")
|
||||
denied({ ...input, objectCount: input.policy.limits.objectsPerPlan + 1 }, "PLAN_LIMIT_EXCEEDED")
|
||||
denied({ ...input, target: { scope: "servers", serverIds: [99] } }, "SERVER_DENIED")
|
||||
denied({ ...input, protections: [{ kind: "server", id: "1", protection: "deny" }] }, "PROTECTED_OBJECT")
|
||||
delete input.policy.unlimitedRates
|
||||
denied(input, "BUDGET_EXCEEDED")
|
||||
denied(read, "RATE_LIMITED")
|
||||
})
|
||||
|
||||
test("observer reads permitted logs, but cannot run bandwidth or create users", () => {
|
||||
const read = request("logs.query"); read.policy.mode = "observer"
|
||||
assert.equal(evaluateMcpPolicy(read, now).decision, "allowed")
|
||||
|
||||
@@ -12,6 +12,10 @@ 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<McpPolicyPreviewRequest, "objects" | "protections"> {
|
||||
if (!requiresHuman || hasUnattendedPlanAuthority(policy)) return { objects: [], protections: [] }
|
||||
const objects = target.scope === "servers" ? [] : [{ kind: "mcp-operation", id: operationId }]
|
||||
@@ -24,6 +28,7 @@ export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Da
|
||||
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 }) }
|
||||
@@ -32,6 +37,7 @@ export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Da
|
||||
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) {
|
||||
@@ -72,15 +78,15 @@ export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Da
|
||||
deny("INVALID_OBJECT_SCOPE", "Объект или зависимость находится вне области запроса")
|
||||
}
|
||||
|
||||
if (usage.callsInMinute >= policy.limits.callsPerMinute) deny("RATE_LIMITED", "Исчерпан минутный лимит вызовов")
|
||||
if (!unlimitedRates && usage.callsInMinute >= policy.limits.callsPerMinute) deny("RATE_LIMITED", "Исчерпан минутный лимит вызовов")
|
||||
if (operation.effect === "read") {
|
||||
if (usage.concurrentReads >= policy.limits.concurrentReads) deny("RATE_LIMITED", "Исчерпан лимит одновременного чтения")
|
||||
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 (usage.mutationsInHour >= policy.limits.mutationsPerHour || usage.mutationsInHour + input.objectCount > policy.limits.mutationsPerHour) deny("BUDGET_EXCEEDED", "Недостаточно часового бюджета для всех изменений плана")
|
||||
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]),
|
||||
|
||||
@@ -20,12 +20,12 @@ const { pool, closePool } = await import("../../db/index.js")
|
||||
const { SYSTEM_DATABASE_OPERATION_LOCK, SYSTEM_DATABASE_REQUEST_LOCK, withOperationLock, withSystemDatabaseOperationLock } = await import("../../db/operation-lock.js")
|
||||
const { applySqlMigrations, applyStandaloneSqlMigrations } = await import("../../db/migrate.js")
|
||||
const { PARTITION_WRITER_ADVISORY_KEY } = await import("../../services/partition-write-transaction.js")
|
||||
const { authenticateMcpToken, createMcpConnection, updateMcpSettings } = await import("./store.js")
|
||||
const { authenticateMcpToken, createMcpConnection, updateMcpConnection, updateMcpSettings } = await import("./store.js")
|
||||
const { recordUnauthorizedProtocol, reserveProtocolEnvelope } = await import("./protocol-limits.js")
|
||||
const { canonicalMcpUrl, encryptSecret, tokenDigest } = await import("./security.js")
|
||||
const { buildApp } = await import("../../index.js")
|
||||
const { sharedDatabaseGate } = await import("../../services/shared-database-gate.js")
|
||||
const { invokeMcpTool } = await import("./runtime.js")
|
||||
const { applyPlan, approvePlan, invokeMcpTool } = await import("./runtime.js")
|
||||
|
||||
const app = await buildApp({ startScheduler: false })
|
||||
try {
|
||||
@@ -177,6 +177,54 @@ try {
|
||||
(SELECT count(*)::int FROM mcp_requests WHERE tool='protocol:unauthorized') AS unauthorized,
|
||||
(SELECT max(attempts)::int FROM mcp_unauthorized_buckets) AS attempts`)
|
||||
assert.deepEqual(counts, { denied: 1, unauthorized: 1, attempts: 8 })
|
||||
|
||||
const serviceOwner = { ...actor, permissions: [...actor.permissions, "mm:mcp:admin", "mm:dashboard:read"] }
|
||||
const settings = mcpConnectionCreateSchema.parse({ name: "Service rate fixture", authority: "service", mode: "autonomous", expiresAt: null,
|
||||
permissions: ["mm:dashboard:read"], scope: { serverIds: [], operationIds: ["capabilities.read", "events.batch.append"], allowGlobal: true },
|
||||
limits: { callsPerMinute: 1, concurrentReads: 1, mutationsPerHour: 1 } })
|
||||
const service = await createMcpConnection(settings, serviceOwner)
|
||||
const servicePrincipal = await authenticateMcpToken(service.token)
|
||||
const serviceId = service.connection.id
|
||||
await pool.query(`INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used)
|
||||
SELECT $1,kind,date_trunc(period,now())+window_shift,10 FROM (VALUES
|
||||
('calls','minute',interval '0'),('protocol','minute',interval '0'),('mutations','hour',interval '0'),
|
||||
('calls','minute',interval '1 minute'),('protocol','minute',interval '1 minute'),('mutations','hour',interval '1 hour')
|
||||
) AS slots(kind,period,window_shift)`, [serviceId])
|
||||
const leaseId = randomUUID()
|
||||
await pool.query("INSERT INTO mcp_read_leases(id,connection_id,expires_at) VALUES($1,$2,now()+interval '2 minutes')", [leaseId, serviceId])
|
||||
const serviceRequest = () => app.inject({ method: "POST", url: "/mcp", headers: {
|
||||
authorization: `Bearer ${service.token}`, accept: "application/json, text/event-stream", "mcp-protocol-version": "2025-06-18",
|
||||
}, payload: { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} } })
|
||||
try {
|
||||
assert.equal((await serviceRequest()).statusCode, 429)
|
||||
await assert.rejects(invokeMcpTool(servicePrincipal, "mm_capabilities_get", {}), { code: "RATE_LIMITED" })
|
||||
const updated = await updateMcpConnection(serviceId, { ...settings, unlimitedRates: true }, serviceOwner)
|
||||
assert.equal(updated.policy.unlimitedRates, true)
|
||||
assert.equal((await authenticateMcpToken(service.token)).credentialId, servicePrincipal.credentialId)
|
||||
assert.equal((await serviceRequest()).statusCode, 200)
|
||||
await invokeMcpTool(servicePrincipal, "mm_capabilities_get", {})
|
||||
const eventType = `service-rate-fixture-${randomUUID()}`
|
||||
const plan = await invokeMcpTool(servicePrincipal, "mm_events_batch_append_plan", { events: [
|
||||
{ level: "info", eventType, sourceModule: "system", title: "Service rate fixture", message: "Synthetic journal entry" },
|
||||
] }) as { planId: string; state: string }
|
||||
assert.equal(plan.state, "awaiting-approval")
|
||||
await approvePlan(plan.planId, serviceOwner, true)
|
||||
const operation = await applyPlan(servicePrincipal, plan.planId, randomUUID())
|
||||
let outcome: string | undefined
|
||||
for (let i = 0; i < 250; i++) {
|
||||
outcome = (await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [operation.id])).rows[0]?.state
|
||||
if (outcome && !["pending", "running"].includes(outcome)) break
|
||||
await delay(20)
|
||||
}
|
||||
assert.equal(outcome, "applied")
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM events WHERE event_type=$1", [eventType])).rows[0].n, 1)
|
||||
const restored = await updateMcpConnection(serviceId, settings, serviceOwner)
|
||||
assert.equal(restored.policy.unlimitedRates, undefined)
|
||||
assert.equal((await serviceRequest()).statusCode, 429)
|
||||
await assert.rejects(invokeMcpTool(servicePrincipal, "mm_capabilities_get", {}), { code: "RATE_LIMITED" })
|
||||
} finally {
|
||||
await pool.query("DELETE FROM mcp_read_leases WHERE id=$1", [leaseId])
|
||||
}
|
||||
console.log("MCP request accounting respects the backup/restore lock independently of the partition lease")
|
||||
} finally {
|
||||
await app.close()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { requestAccountingWrite, validatePrincipal, type McpPrincipal } from "./store.js"
|
||||
import { accessGeneration, tokenDigest } from "./security.js"
|
||||
import { hasUnlimitedMcpRates } from "./policy.js"
|
||||
|
||||
export async function reserveProtocolEnvelope(principal: McpPrincipal) {
|
||||
return requestAccountingWrite(async client => {
|
||||
@@ -9,8 +10,8 @@ export async function reserveProtocolEnvelope(principal: McpPrincipal) {
|
||||
const connection = await validatePrincipal(principal, client)
|
||||
// Protocol negotiation and metadata have their own cap; tools retain their
|
||||
// stricter policy budget. A single metadata endpoint cannot bypass limits.
|
||||
const limit = Math.max(10, Math.min(3000, connection.policy.limits.callsPerMinute * 3))
|
||||
const { rows } = await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'protocol',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+1 WHERE mcp_budget_buckets.used<$2 RETURNING used", [connection.id, limit])
|
||||
const limit = hasUnlimitedMcpRates(connection.policy) ? null : Math.max(10, Math.min(3000, connection.policy.limits.callsPerMinute * 3))
|
||||
const { rows } = await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'protocol',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used::bigint+1,2147483647) WHERE $2::integer IS NULL OR mcp_budget_buckets.used<$2 RETURNING used", [connection.id, limit])
|
||||
if (!rows.length) {
|
||||
const { rows: [denied] } = await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'protocol-denied',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used+1,2147483647) RETURNING used", [connection.id])
|
||||
if (denied.used === 1) await client.query("INSERT INTO mcp_requests(id,connection_id,actor_id,tool,status,input,error_code) VALUES($1,$2,$3,'protocol:rate-limit','denied','{}','RATE_LIMITED')", [randomUUID(), connection.id, connection.owner_id])
|
||||
|
||||
@@ -18,6 +18,7 @@ import { routingReservationDeadline, transitionRoutingReservation, type RoutingR
|
||||
import { routingReservationTransaction, type RoutingReservationConnect } from "./routing-reservation-transaction.js"
|
||||
import { lockRoutingReservationAdmissionSource } from "./routing-reservation-runtime.js"
|
||||
import type { StoredPlan } from "./store.js"
|
||||
import { hasUnlimitedMcpRates } from "./policy.js"
|
||||
|
||||
const uuid = z.string().uuid(), proof = z.string().regex(/^[a-f0-9]{64}$/), stamp = z.string().datetime()
|
||||
const principalSchema = z.object({ connectionId: uuid, credentialId: uuid, credentialExpiresAt: stamp }).strict()
|
||||
@@ -271,7 +272,8 @@ async function reserveWithinOwner(db: PoolClient, operationId: string) {
|
||||
// Legacy overlap stays charged, including allocations predating audit anchors.
|
||||
const charges = await readHistoricalChargesWithinOwner(db, value.authority.packet.profileId, connection, createdAt, deadline)
|
||||
if (charges.totalCharges + 2 > value.profile.maxSwitchesPerHour) throw fail("Insufficient durable profile switch slots")
|
||||
const budget = await db.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) SELECT $1,'mutations',$2,2 WHERE $3::int>=2 ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+2 WHERE mcp_budget_buckets.used<=$3::int-2 RETURNING used", [connection.id, budgetBucket, connection.policy.limits.mutationsPerHour])
|
||||
const limit = hasUnlimitedMcpRates(connection.policy) ? null : connection.policy.limits.mutationsPerHour
|
||||
const budget = await db.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) SELECT $1,'mutations',$2,2 WHERE $3::int IS NULL OR $3::int>=2 ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used::bigint+2,2147483647) WHERE $3::int IS NULL OR mcp_budget_buckets.used<=$3::int-2 RETURNING used", [connection.id, budgetBucket, limit])
|
||||
if (budget.rowCount !== 1) throw fail("Insufficient connection mutation budget for forward and inverse")
|
||||
const binding = bindingSchema.parse({ revision: 1, id: randomUUID(), planId: value.row.plan_id, operationId, stepIndex: 0, sourceReceiptId: value.input.receiptId,
|
||||
inverseReceiptId: randomUUID(), profileId: value.authority.packet.profileId, profileVersion: value.authority.packet.profileVersion, principal: value.principal,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto"
|
||||
import { basename, dirname, join, resolve } from "node:path"
|
||||
import { readFile, writeFile } from "node:fs/promises"
|
||||
import type { PoolClient } from "pg"
|
||||
import { MCP_SERVICE_EXPIRATION } from "@mmapp/contracts/mcp"
|
||||
|
||||
/** Actual SQL/crypto numbered-schema acceptance only; no public tool registration,
|
||||
* native callback, controller tick, reservation refund or fixture DELETE. */
|
||||
@@ -49,11 +50,12 @@ export async function acceptRoutingReservationSql(options: { runtimeAdmission?:
|
||||
ids.push(...(await pool.query("INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) VALUES($1,'127.0.0.1',9,true,'SYNTHETIC','SYNTHETIC',false,true) RETURNING id", ["reservation-synthetic-" + randomUUID()])).rows.map(row => Number(row.id)))
|
||||
await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1")
|
||||
const contextSources = (await createRoutingSourceContext(await readRoutingEndpoints(ids))).expected
|
||||
const fixture = async (mutations = 10, maxSwitches = 3, autoRecovery = true) => {
|
||||
const fixture = async (mutations = 10, maxSwitches = 3, autoRecovery = true, unlimitedRates = false) => {
|
||||
const connectionId = randomUUID(), credentialId = randomUUID(), profileId = randomUUID(), ownerId = "reservation-owner-" + randomUUID()
|
||||
const now = Date.now(), expiresAt = new Date(now + 600000).toISOString(), generation = await security.accessGeneration()
|
||||
const permissions = ["mm:network:read", "mm:network:write", "mm:filters:write"]
|
||||
const policy = mcpConnectionPolicySchema.parse({ id: connectionId, version: 1, status: "active", mode: "approval", permissions, expiresAt,
|
||||
const policy = mcpConnectionPolicySchema.parse({ id: connectionId, version: 1, status: "active", permissions,
|
||||
...(unlimitedRates ? { authority: "service", mode: "autonomous", expiresAt: MCP_SERVICE_EXPIRATION, unlimitedRates: true } : { mode: "approval", expiresAt }),
|
||||
scope: { serverIds: ids, operationIds: ["routing.analyze", "routing.community.switch", "routing.path.verify", "operations.recover"], allowGlobal: false },
|
||||
limits: { callsPerMinute: 100, mutationsPerHour: mutations, concurrentReads: 4, serversPerPlan: 2, objectsPerPlan: 20 } })
|
||||
await pool.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,'synthetic reservation',$2,$3::jsonb,$4::jsonb,$5,$6,$7)", [connectionId, ownerId, JSON.stringify(permissions), JSON.stringify(policy), generation, expiresAt, new Date(now - 1000)])
|
||||
@@ -295,6 +297,13 @@ export async function acceptRoutingReservationSql(options: { runtimeAdmission?:
|
||||
assert.equal(await used(f.connectionId), 2)
|
||||
names.push("short by one rolling-hour profile slot across source operations")
|
||||
}
|
||||
{
|
||||
const f = await fixture(1, 3, true, true), first = await f.makeSource(), second = await f.makeSource()
|
||||
assert.equal((await store.reserve(first.operationId)).created, true)
|
||||
await assert.rejects(store.reserve(second.operationId), /profile switch slots/)
|
||||
assert.equal(await used(f.connectionId), 2)
|
||||
names.push("unlimited service connection still obeys the routing profile switch limit")
|
||||
}
|
||||
{
|
||||
const f = await fixture(10, 3), source = await f.makeSource()
|
||||
await pool.query("UPDATE mcp_routing_profiles SET state=jsonb_build_object('switches',jsonb_build_array(to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'))) WHERE id=$1", [f.profileId])
|
||||
|
||||
@@ -31,7 +31,7 @@ import { readPollRuntimePolicySource, type PollRuntimePolicySource } from "./pol
|
||||
import { withVerifiedConfigurationChange, assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
|
||||
import { beginMcpOperationAdmission, insertMcpOperationAdmission, retireMcpOperationAdmission, withMcpOperationExecutionOrigin, stripMcpOperationExecutionPrivateResult, type McpOperationAdmission } from "./operation-execution-origin.js"
|
||||
import { createOspfOwnerSourceGuard, verifyOspfOwnerGraph, verifyOspfOwnerGraphAtPhase } from "./ospf-owner-graph.js"
|
||||
import { evaluateMcpPolicy, hasUnattendedPlanAuthority, operationApprovalRequirement } from "./policy.js"
|
||||
import { evaluateMcpPolicy, hasUnattendedPlanAuthority, hasUnlimitedMcpRates, operationApprovalRequirement } from "./policy.js"
|
||||
import { findAction, findActionByOperation } from "./actions.js"
|
||||
import { refuseExpiredOperationReplay } from "./operation-replay-tombstones.js"
|
||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, privateSecretFingerprint, McpError, redact } from "./security.js"
|
||||
@@ -138,7 +138,7 @@ async function reserveCall(principal: McpPrincipal, toolName: string, input: Rec
|
||||
const result = evaluateMcpPolicy(evidence)
|
||||
await client.query("INSERT INTO mcp_requests(id,connection_id,actor_id,tool,server_ids,status,input,error_code) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8)", [requestId, connection.id, connection.owner_id, toolName, evidence.target.scope === "servers" ? evidence.target.serverIds : [], result.decision === "denied" ? "denied" : "running", JSON.stringify(redact(input)), result.decision === "denied" ? result.reasons[0]?.code : null])
|
||||
if (result.decision !== "denied") {
|
||||
await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'calls',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+1", [connection.id])
|
||||
await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'calls',date_trunc('minute',now()),1) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used::bigint+1,2147483647)", [connection.id])
|
||||
if (action.operation.effect === "read") await client.query("INSERT INTO mcp_read_leases(id,connection_id,expires_at) VALUES($1,$2,now()+interval '2 minutes')", [requestId, connection.id])
|
||||
await client.query("UPDATE mcp_connections SET last_used_at=now() WHERE id=$1", [connection.id])
|
||||
}
|
||||
@@ -461,8 +461,8 @@ async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey
|
||||
await assertOriginalMcpTemporaryGrant(client,connection.id,principal.credentialId,originalServiceGrant)
|
||||
}
|
||||
const mutationCost = reservedRouting ? 2 : changeMutationCost(evidence) + (evidence.recovery ? 1 : 0)
|
||||
if (input.usage.mutationsInHour + mutationCost > connection.policy.limits.mutationsPerHour) throw new McpError("BUDGET_EXCEEDED", "Недостаточно бюджета для всех шагов плана", 429)
|
||||
if (!reservedRouting) await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'mutations',date_trunc('hour',now()),$2) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+EXCLUDED.used", [connection.id, mutationCost])
|
||||
if (!hasUnlimitedMcpRates(connection.policy) && input.usage.mutationsInHour + mutationCost > connection.policy.limits.mutationsPerHour) throw new McpError("BUDGET_EXCEEDED", "Недостаточно бюджета для всех шагов плана", 429)
|
||||
if (!reservedRouting) await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'mutations',date_trunc('hour',now()),$2) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=LEAST(mcp_budget_buckets.used::bigint+EXCLUDED.used,2147483647)", [connection.id, mutationCost])
|
||||
if (delegated) {
|
||||
// Execution receipts use the delegating owner's ID. Object protections still require a human decision.
|
||||
plan.evidence.approvalSource = "connection-policy"
|
||||
|
||||
Reference in new issue
Block a user