Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
645045a5d5 |
No files matched your search
@@ -7,7 +7,7 @@
|
||||
"test:mcp:module-completion": "tsx src/services/ipsec-server-init-model.test.ts && tsx src/modules/mcp/ipsec-server-init-actions.test.ts && tsx src/services/wireguard-revision-restore.test.ts && tsx src/modules/mcp/vrf-ticket-runtime.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-pool-dependencies.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx src/services/vrf-production-action-binding.test.ts && tsx src/services/ipsec-revision-restore-model.test.ts && tsx src/modules/mcp/ipsec-revision-actions.test.ts && tsx src/modules/mcp/service-native-progress.test.ts && tsx src/services/ipsec-revision-restore.test.ts && tsx src/services/ipsec-revision-secret.test.ts",
|
||||
"test:mcp:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
||||
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
||||
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts",
|
||||
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts src/modules/mcp/gre-ipsec-pair-actions.test.ts",
|
||||
"test:mcp:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics",
|
||||
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
||||
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
||||
|
||||
@@ -80,6 +80,7 @@ import { prepareWireguardPeerDeletion, registerWireguardPeerDeleteActions } from
|
||||
import { registerFirewallActions } from "./firewall-actions.js"
|
||||
import { registerBfdMoveActions } from "./bfd-move-actions.js"
|
||||
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
||||
import { registerGreIpsecPairActions } from "./gre-ipsec-pair-actions.js"
|
||||
import { registerIxActions } from "./internet-exchange-actions.js"
|
||||
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
||||
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
||||
@@ -707,6 +708,7 @@ registerWireguardInterfaceDeleteActions(add)
|
||||
registerFirewallActions(add)
|
||||
registerBfdMoveActions(add)
|
||||
registerGreMutationActions(add)
|
||||
registerGreIpsecPairActions(add)
|
||||
registerIxActions(add)
|
||||
registerGreRevisionActions(add)
|
||||
registerGreNativeServices()
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test, { mock } from "node:test"
|
||||
import type { add } from "./actions.js"
|
||||
import type { McpAction } from "./action-types.js"
|
||||
import type { GreMutation } from "../../services/gre-mutation-input.js"
|
||||
|
||||
const routerStates = new Map([
|
||||
[3, { ipv4: [{ address: "192.0.2.3/24" }], gre: new Array<Record<string, string>>() }],
|
||||
[6, { ipv4: [{ address: "198.51.100.6/24" }], gre: new Array<Record<string, string>>() }],
|
||||
])
|
||||
const writes: Array<{ id: number; mutation: GreMutation }> = []
|
||||
mock.module("./resources.js", { namedExports: { async routerClient(id: number) { return { server: { id } } } } })
|
||||
mock.module("./gre-mutation-actions.js", { namedExports: { async greMutationProtectionObjects(serverId: number) {
|
||||
return [{ kind: "server", id: String(serverId), serverId }]
|
||||
} } })
|
||||
mock.module("../../services/gre-mutation-state.js", { namedExports: {
|
||||
greMutationProof: (state: unknown) => state,
|
||||
async readGreMutationState(server: { id: number }) { return structuredClone(routerStates.get(server.id)) },
|
||||
} })
|
||||
const { fingerprint, redact } = await import("./security.js")
|
||||
mock.module("../../services/gre-mutation.js", { namedExports: {
|
||||
planGreMutation: () => [{}],
|
||||
async mutateGreTunnel(server: { id: number }, mutation: GreMutation, beforeFingerprint: string) {
|
||||
const state = routerStates.get(server.id)!
|
||||
assert.equal(beforeFingerprint, fingerprint(state))
|
||||
assert.equal(mutation.operation, "create")
|
||||
if (mutation.operation !== "create") throw new Error("expected create")
|
||||
writes.push({ id: server.id, mutation })
|
||||
state.gre.push({ name: mutation.fields.name, "remote-address": mutation.fields.remoteAddress })
|
||||
return { verified: true, afterFingerprint: fingerprint(state), tunnel: { ipsecSecret: mutation.fields.ipsecSecret } }
|
||||
},
|
||||
} })
|
||||
const { registerGreIpsecPairActions } = await import("./gre-ipsec-pair-actions.js")
|
||||
const { findMcpService } = await import("./service-registry.js")
|
||||
let action: Pick<McpAction, "prepare" | "target"> | undefined
|
||||
let definition: { id: string; toolName: string } | undefined
|
||||
const register: typeof add = (id, toolName, _title, _section, _permission, _effect, _scope, _schema, handlers) => {
|
||||
definition = { id, toolName }
|
||||
if (handlers.target) action = { prepare: handlers.prepare, target: handlers.target }
|
||||
}
|
||||
registerGreIpsecPairActions(register)
|
||||
|
||||
const input = { endpoints: [
|
||||
{ serverId: 3, endpoint: "192.0.2.3", name: "gre-test-home", localInnerIp: "10.253.0.1/30" },
|
||||
{ serverId: 6, endpoint: "198.51.100.6", name: "gre-test-nov", localInnerIp: "10.253.0.2/30" },
|
||||
] }
|
||||
const context = {} as Parameters<NonNullable<McpAction["prepare"]>>[1]
|
||||
|
||||
test("GRE/IPsec pair creates two disabled endpoints using one private key", async () => {
|
||||
assert.equal(definition?.toolName, "mm_gre_ipsec_pair_create_plan")
|
||||
const prepare = action!.prepare!, service = findMcpService(definition!.id)!
|
||||
const evidence = await prepare(input, context), another = await prepare(input, context)
|
||||
assert.deepEqual(await action!.target(input, context), { scope: "servers", serverIds: [3, 6] })
|
||||
assert.deepEqual(evidence.objects.map(object => object.serverId), [3, 6])
|
||||
assert.equal(writes.length, 0)
|
||||
const [first, second] = evidence.steps.map(step => { assert.equal(step.kind, "service"); return step.kind === "service" ? step.input : {} })
|
||||
const [other] = another.steps
|
||||
assert.ok(other.kind === "service" && first.ipsecSecret !== other.input.ipsecSecret)
|
||||
assert.match(String(first.ipsecSecret), /^[a-f0-9]{64}$/)
|
||||
assert.equal(first.ipsecSecret, second.ipsecSecret)
|
||||
assert.ok(!JSON.stringify(redact(evidence)).includes(String(first.ipsecSecret)))
|
||||
await assert.rejects(prepare({ ...input, ipsecSecret: "caller-supplied" }, context))
|
||||
await assert.rejects(prepare({ endpoints: input.endpoints.slice(0, 1) }, context))
|
||||
await assert.rejects(prepare({ endpoints: [input.endpoints[0], input.endpoints[0]] }, context), /два разных сервера/)
|
||||
await assert.rejects(prepare({ endpoints: [input.endpoints[0], { ...input.endpoints[1], endpoint: "203.0.113.6" }] }, context), /Внешний адрес GRE не найден/)
|
||||
assert.deepEqual(await service.current(first), evidence.before)
|
||||
for (const step of [first, second]) {
|
||||
const receipt = await service.execute(step)
|
||||
assert.ok(await service.verify!(step, receipt))
|
||||
assert.ok(!JSON.stringify(receipt).includes(String(first.ipsecSecret)))
|
||||
}
|
||||
assert.deepEqual(writes.map(({ id, mutation }) => mutation.operation === "create" ?
|
||||
[id, mutation.fields.localAddress, mutation.fields.remoteAddress, mutation.fields.enabled, mutation.fields.allowFastPath] : []), [
|
||||
[3, "192.0.2.3", "198.51.100.6", false, false],
|
||||
[6, "198.51.100.6", "192.0.2.3", false, false],
|
||||
])
|
||||
await assert.rejects(prepare(input, context), /уже есть GRE/)
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { z } from "zod"
|
||||
import { greCreateFieldsSchema, type GreMutation } from "../../services/gre-mutation-input.js"
|
||||
import { greMutationProof, readGreMutationState } from "../../services/gre-mutation-state.js"
|
||||
import { mutateGreTunnel, planGreMutation } from "../../services/gre-mutation.js"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import type { ChangeEvidence } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { greMutationProtectionObjects } from "./gre-mutation-actions.js"
|
||||
import { routerClient } from "./resources.js"
|
||||
import { fingerprint, McpError } from "./security.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
|
||||
const operation = "network.gre.ipsec_pair.create"
|
||||
const endpointSchema = greCreateFieldsSchema.pick({ name: true, localInnerIp: true, comment: true }).extend({
|
||||
serverId: z.number().int().positive().safe(), endpoint: greCreateFieldsSchema.shape.remoteAddress,
|
||||
})
|
||||
const schema = z.object({
|
||||
endpoints: z.array(endpointSchema).length(2),
|
||||
mtu: greCreateFieldsSchema.shape.mtu,
|
||||
}).strict()
|
||||
const stepSchema = schema.extend({
|
||||
side: z.union([z.literal(0), z.literal(1)]),
|
||||
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
beforeFingerprint: z.string(),
|
||||
})
|
||||
type Pair = z.infer<typeof schema>
|
||||
type Side = 0 | 1
|
||||
const sides = [0, 1] as const
|
||||
|
||||
function target(input: Pair): ChangeEvidence["target"] {
|
||||
const [first, second] = input.endpoints
|
||||
if (first.serverId === second.serverId || first.endpoint === second.endpoint) {
|
||||
throw new McpError("INVALID_INPUT", "Нужны два разных сервера и два разных внешних IPv4")
|
||||
}
|
||||
return { scope: "servers", serverIds: [first.serverId, second.serverId] }
|
||||
}
|
||||
|
||||
function mutationFor(input: Pair, side: Side, ipsecSecret: string): GreMutation {
|
||||
const local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
|
||||
return { operation: "create", fields: {
|
||||
name: local.name, localAddress: local.endpoint, remoteAddress: remote.endpoint,
|
||||
localInnerIp: local.localInnerIp, comment: local.comment, mtu: input.mtu ?? "auto",
|
||||
enabled: false, allowFastPath: false, ipsecSecret,
|
||||
} }
|
||||
}
|
||||
|
||||
async function readSide(input: Pair, side: Side, ipsecSecret: string) {
|
||||
const { server } = await routerClient(input.endpoints[side].serverId)
|
||||
const mutation = mutationFor(input, side, ipsecSecret)
|
||||
const state = await readGreMutationState(server, mutation)
|
||||
return { server, mutation, state, proof: fingerprint(greMutationProof(state)) }
|
||||
}
|
||||
|
||||
export function registerGreIpsecPairActions(register: typeof add) {
|
||||
registerMcpService(operation, {
|
||||
current: async raw => {
|
||||
const input = stepSchema.parse(raw)
|
||||
const before = await Promise.all(sides.map(side => readSide(input, side, input.ipsecSecret)))
|
||||
return before.map(item => item.proof)
|
||||
},
|
||||
execute: async raw => {
|
||||
const input = stepSchema.parse(raw)
|
||||
const { server } = await routerClient(input.endpoints[input.side].serverId)
|
||||
const { tunnel: _tunnel, ...receipt } = await mutateGreTunnel(server, mutationFor(input, input.side, input.ipsecSecret), input.beforeFingerprint)
|
||||
return receipt
|
||||
},
|
||||
verify: async (raw, result) => {
|
||||
const input = stepSchema.parse(raw)
|
||||
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
|
||||
return receipt?.verified === true && receipt.afterFingerprint === (await readSide(input, input.side, input.ipsecSecret)).proof
|
||||
},
|
||||
})
|
||||
register(operation, "mm_gre_ipsec_pair_create_plan", "План создания пары GRE/IPsec с автоматическим PSK",
|
||||
"network", "mm:network:write", "write", "servers", schema, {
|
||||
target: raw => target(schema.parse(raw)),
|
||||
prepare: async raw => {
|
||||
const input = schema.parse(raw), scope = target(input)
|
||||
const ipsecSecret = randomBytes(32).toString("hex")
|
||||
const before = await Promise.all(sides.map(side => readSide(input, side, ipsecSecret)))
|
||||
const mutationCost = sides.reduce<number>((cost, side) => {
|
||||
const item = before[side]!, local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
|
||||
if (!item.state.ipv4.some(row => row.address.split("/")[0] === local.endpoint &&
|
||||
observedBoolean(row.disabled) !== true && observedBoolean(row.invalid) !== true)) {
|
||||
throw new McpError("STATE_CONFLICT", `Внешний адрес GRE не найден на сервере ${local.serverId}`, 409)
|
||||
}
|
||||
if (item.state.gre.some(row => [row["remote-address"], row["current-remote-address"]].includes(remote.endpoint))) {
|
||||
throw new McpError("STATE_CONFLICT", `На сервере ${local.serverId} уже есть GRE с этим удалённым адресом`, 409)
|
||||
}
|
||||
return cost + planGreMutation(item.server, item.mutation, item.state).length + 1
|
||||
}, 0)
|
||||
return {
|
||||
target: scope, objects: (await Promise.all(before.map(item => greMutationProtectionObjects(Number(item.server.id), item.state)))).flat(),
|
||||
snapshots: [], before: before.map(item => item.proof), mutationCost, requiresHuman: true,
|
||||
steps: sides.map(side => ({ kind: "service" as const, service: operation, input: {
|
||||
...input, side, ipsecSecret, beforeFingerprint: before[side]!.proof,
|
||||
} })),
|
||||
warnings: [
|
||||
"Создаются только два новых отключённых GRE. Стороны получают один автоматически сгенерированный PSK; FastPath отключён.",
|
||||
"Стороны применяются и проверяются последовательно. При отказе второй стороны первая может остаться созданной и отключённой.",
|
||||
"Установка IPsec SA и передача трафика проверяются после отдельного включения обоих интерфейсов.",
|
||||
],
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -131,6 +131,12 @@ npm --prefix backend run mcp:stdio
|
||||
|
||||
Наличие инструмента не означает, что каждый сценарий раздела проверен на стенде. Статусы — в [манифесте](mcp-final-manifest.md).
|
||||
|
||||
### Прямой GRE/IPsec между двумя CHR
|
||||
|
||||
`mm_gre_ipsec_pair_create_plan` требует разрешение `network.gre.ipsec_pair.create` и допуск к обоим серверам. Передайте в `endpoints` два объекта с `serverId`, `name` и локальным внешним IPv4 в `endpoint`. При необходимости укажите `localInnerIp` на каждой стороне и общий `mtu`. Manager генерирует единый PSK для обеих сторон. Ключ скрыт в плане и квитанции, ручная регистрация `secretRef` не нужна.
|
||||
|
||||
Применение создаёт две отключённые стороны. Сверьте обе через `mm_gre_state_get`, затем включите их через `mm_gre_tunnel_update_plan` и проверьте IPsec и связность. При ошибке сверяйте обе стороны перед следующей операцией. Первая сторона может остаться созданной и отключённой.
|
||||
|
||||
### Разбор отказа и проверка резерва
|
||||
|
||||
1. Зафиксируйте источник, назначение, ожидаемый выход и максимальный допустимый перерыв. Проверьте доступ через `mm_capabilities_get` и давность наблюдений через `mm_telemetry_health_get`. Обрыв экспорта NetFlow оставляет пробел в наблюдениях.
|
||||
|
||||
Reference in new issue
Block a user