Files
MikrotikManager/backend/src/modules/mcp/server-connection-actions.ts
T

106 lines
10 KiB
TypeScript

import { lookup } from "node:dns/promises"
import { isIP } from "node:net"
import { z } from "zod"
import { pool } from "../../db/index.js"
import { hasPermission } from "../../lib/permissions.js"
import { performServerConnectionTest } from "../../services/server-connection-test.js"
import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
import { effectiveMcpConnection } from "./store.js"
import { decryptSecret, fingerprint, privateSecretFingerprint, McpError } from "./security.js"
import { registerMcpService } from "./service-registry.js"
import type { add } from "./actions.js"
import { isAllowedServerConnectionAddress, serverConnectionHostSchema } from "./server-connection-destination-policy.js"
export { isAllowedServerConnectionAddress } from "./server-connection-destination-policy.js"
const fail = (message: string, code = "STATE_CONFLICT") => new McpError(code, message, 409)
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string() }).strict()
export const serverConnectionActionSchema = z.object({
host: serverConnectionHostSchema,
port: z.number().int().min(1).max(65535).default(443), useSsl: z.boolean().default(true), verifySsl: z.boolean().default(false),
apiPath: z.string().max(256).regex(/^\/(?:[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*)?$/).default("/rest"),
username: z.string().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f:]/.test(value)).default("admin"), passwordRef: z.string().uuid(),
}).strict()
/** Issuance UI must bind all destination and authentication parameters, including
* TLS verification; an old host:port-only server-login reference is insufficient. */
export function serverConnectionSecretPurpose(value: Omit<z.input<typeof serverConnectionActionSchema>, "passwordRef">) {
const { passwordRef: _reference, ...endpoint } = serverConnectionActionSchema.parse({ ...value, passwordRef: "00000000-0000-4000-8000-000000000001" })
return `server-connection-test:${fingerprint(endpoint)}`
}
async function resolveDestination(host: string) {
if (isIP(host)) {
if (!isAllowedServerConnectionAddress(host)) throw fail("Назначение RouterOS запрещено", "DESTINATION_DENIED")
return [{ address: host, family: isIP(host) }]
}
let timer: ReturnType<typeof setTimeout> | undefined
try {
const rows = await Promise.race([lookup(host, { all: true, verbatim: true }), new Promise<never>((_resolve,reject) => { timer = setTimeout(() => reject(fail("Истекло время разрешения адреса", "STATE_UNAVAILABLE")), 2000) })])
if (!rows.length || rows.length > 16 || rows.some(row => !isAllowedServerConnectionAddress(row.address))) throw fail("Не подтверждено безопасное назначение RouterOS", "DESTINATION_DENIED")
return rows.sort((a,b) => a.family - b.family || a.address.localeCompare(b.address))
} catch (error) { if (error instanceof McpError) throw error; throw fail("Адрес RouterOS не разрешён", "STATE_UNAVAILABLE") }
finally { if (timer) clearTimeout(timer) }
}
export async function readServerConnectionSource(input: Record<string, unknown>, signal?: AbortSignal) {
const request = serverConnectionActionSchema.parse(Object.fromEntries(Object.keys(serverConnectionActionSchema.shape).map(key => [key,input[key]])))
const authorize = async () => {
if (signal?.aborted) throw fail("Проверка отменена", "READ_CANCELLED")
const connection = await effectiveMcpConnection(principalSchema.parse(input.principal))
if (connection.owner_id !== input.ownerId || !connection.policy.scope.allowGlobal || !connection.policy.scope.operationIds.includes("servers.test-connection") || !hasPermission(connection.policy.permissions,"mm:servers:write") || !hasPermission(connection.owner_permissions,"mm:servers:write")) throw fail("Право проверки подключения отозвано", "PERMISSION_DENIED")
if (fingerprint(connection.policy) !== input.policyProof) throw fail("Допуск изменился", "RESET_REQUIRED")
const ids = (await pool.query<{id:number}>("SELECT id FROM servers ORDER BY id LIMIT 1001")).rows.map(row => row.id)
if (ids.length > 1000 || ids.some(id => !connection.policy.scope.serverIds.includes(id))) throw fail("Требуется полный каталог серверов", "SERVER_DENIED")
return ids
}
const ids = await authorize()
const reference = (await pool.query("SELECT CASE WHEN octet_length(purpose)<=512 THEN purpose ELSE NULL END AS purpose,server_id,created_by,xmin::text AS revision,CASE WHEN octet_length(ciphertext)<=16384 THEN ciphertext ELSE NULL END AS ciphertext FROM mcp_secrets WHERE id=$1 AND created_by=$2", [request.passwordRef,input.ownerId])).rows[0]
if (!reference || reference.server_id !== null || reference.purpose !== serverConnectionSecretPurpose(request) || typeof reference.ciphertext !== "string") throw fail("Ссылка на пароль не выдана этому назначению", "SECRET_UNAVAILABLE")
let password: string
try { password = await decryptSecret(reference.ciphertext) } catch { throw fail("Ссылка на пароль недоступна", "SECRET_UNAVAILABLE") }
if (Buffer.byteLength(password) > 4096 || /[\u0000\r\n]/.test(password)) throw fail("Пароль не соответствует допустимому формату", "SECRET_UNAVAILABLE")
const destinations = await resolveDestination(request.host)
if (fingerprint(ids) !== fingerprint(await authorize())) throw fail("Каталог изменился")
const { passwordRef: _reference, ...endpoint } = request
return { ids, endpoint, password, destinations, publicState: { endpoint, destinations, passwordConfigured: true, proof: await privateSecretFingerprint(fingerprint({ reference, ids, destinations }),"server-connection-test-v1") } }
}
export function registerServerConnectionActions(register: typeof add) {
const current = async (input: Record<string, unknown>) => (await readServerConnectionSource(input)).publicState
registerMcpService("servers.test-connection", {
current,
execute: async input => {
const source = await readServerConnectionSource(input)
const fence = async () => {
await assertVerifiedConfigurationAccess()
if (fingerprint(await current(input)) !== input.beforeFingerprint) throw fail("Назначение, допуск или ссылка изменились после подтверждения")
}
await fence()
const pinned = source.destinations[0]
const result = await performServerConnectionTest({ ...source.endpoint, password: source.password,
lookup: ((_host: string, options: unknown, callback: (...args: unknown[]) => void) => {
if ((options as {all?:boolean})?.all) callback(null,[pinned]); else callback(null,pinned.address,pinned.family)
}) as typeof import("node:dns").lookup,
servername: isIP(source.endpoint.host) ? undefined : source.endpoint.host,
}, { beforeDispatch: fence, afterDispatch: fence })
if (result.outcome === "unknown") throw new McpError("MUTATION_OUTCOME_UNKNOWN","Результат проверки подключения не подтверждён; автоматический повтор запрещён",502)
return { ...result, attempts: 1, requests: 2, configurationChanged: false, forwardingVerified: false }
},
verify: async (input,result) => {
if (fingerprint(await current(input)) !== input.beforeFingerprint) throw fail("Источник или допуск изменились перед подтверждением результата")
return (result as {success?:boolean}|null)?.success === true
},
reconcile: async (_input,authorize) => { await authorize(); return {matchesDesiredState:false,matchesOriginalState:false} },
})
register("servers.test-connection","mm_server_test_connection_plan","Проверить подключение RouterOS до сохранения","servers","mm:servers:write","write","global",serverConnectionActionSchema, {
prepare: async (input,context) => {
const request = {...input,principal:context.principal,ownerId:context.connection.owner_id,policyProof:fingerprint(context.connection.policy)}
const source = await readServerConnectionSource(request,context.signal)
const objects = [{kind:"server-connection-test",id:"global"},...source.ids.map(serverId => ({kind:"server",id:String(serverId),serverId}))]
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) OR (object_ref->>'kind'='server' AND object_ref->>'id'=ANY($1::text[])) OR object_ref->>'kind'='server-connection-test' LIMIT 1001",[source.ids.map(String)])
if (protections.rows.length > 1000) throw fail("Превышен предел защит", "STATE_UNAVAILABLE")
for (const row of protections.rows) objects.push(row.object_ref)
if (fingerprint(await current(request)) !== fingerprint(source.publicState)) throw fail("Источник изменился при подготовке")
return {target:{scope:"global"},objects,snapshots:[],before:source.publicState,requiresHuman:true,mutationCost:1,verificationScope:"acknowledgement",
steps:[{kind:"service",service:"servers.test-connection",input:{...request,beforeFingerprint:fingerprint(source.publicState)}}],
warnings:["Два ограниченных GET /system/identity и /system/resource с указанными параметрами. Настройки и сохранённые серверы не изменяются; сетевой запрос расходует один допуск операции.","Пароль принимается только через owner/purpose ссылку без server scope, связанную с полным назначением. DNS ограничен, адрес закрепляется без redirect; изменение DNS блокирует результат.","Проверка требует человеческого подтверждения. Ответ не доказывает forwarding. Неопределённый результат не повторяется и не сверяется новым сетевым запросом."]}
},
})
}