Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 2m18s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 2m11s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
214 lines
15 KiB
TypeScript
214 lines
15 KiB
TypeScript
import { z } from "zod"
|
|
import { pool } from "../../db/index.js"
|
|
import { hasPermission } from "../../lib/permissions.js"
|
|
import { listMcpOperations } from "./registry.js"
|
|
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError } from "./security.js"
|
|
import type { ActionContext } from "./action-types.js"
|
|
import type { add } from "./actions.js"
|
|
|
|
const sources = ["routeros-poll", "uptime", "logs", "netflow"] as const
|
|
type Source = typeof sources[number]
|
|
const permissions: Record<Source, string> = {
|
|
"routeros-poll": "mm:servers:read", uptime: "mm:uptime:read", logs: "mm:servers:read", netflow: "mm:traffic:read",
|
|
}
|
|
const selection = {
|
|
serverId: z.number().int().positive().safe(),
|
|
sources: z.array(z.enum(sources)).min(1).max(sources.length).optional(),
|
|
}
|
|
const healthInput = z.object({ ...selection, serverId: selection.serverId.optional(),
|
|
afterServerId: selection.serverId.optional(), limit: z.number().int().min(1).max(20).default(10),
|
|
}).strict().refine(input => input.serverId === undefined || input.afterServerId === undefined, "Курсор доступен для списка серверов")
|
|
const hourMs = 3_600_000
|
|
const timelineSourceNames = [...sources, "uptime-probe", "mcp-request"] as const
|
|
type TimelineSource = typeof timelineSourceNames[number]
|
|
const cursorSchema = z.object({ scope: z.string(), at: z.iso.datetime({ precision: 6 }),
|
|
source: z.enum(timelineSourceNames), key: z.string().max(1000),
|
|
}).strict()
|
|
const timelineInput = z.object({
|
|
...selection, from: z.iso.datetime({ offset: true }), to: z.iso.datetime({ offset: true }),
|
|
limit: z.number().int().min(1).max(200).default(50),
|
|
includeManagerEvents: z.boolean().default(false),
|
|
cursor: z.string().min(1).max(3000).optional(),
|
|
}).strict().refine(({ from, to }) => {
|
|
const duration = Date.parse(to) - Date.parse(from)
|
|
return duration > 0 && duration <= 24 * hourMs
|
|
}, "Требуется положительное окно до 24 часов")
|
|
|
|
function permittedSources(context: ActionContext, requested?: Source[]) {
|
|
const permitted = (source: Source) => [context.connection.policy.permissions, context.connection.owner_permissions]
|
|
.every(granted => hasPermission(granted, permissions[source]))
|
|
if (requested?.some(source => !permitted(source))) throw new McpError("PERMISSION_DENIED", "Чтение выбранного источника запрещено", 403)
|
|
return [...new Set(requested ?? sources.filter(permitted))]
|
|
}
|
|
|
|
type HealthRow = { enabled: boolean | null; intervalSec: number | null; observedAt: Date | null; status: string | null; gapAt?: Date | null }
|
|
type EvidenceRow = { at: string; key: string; id: string; status: string | null; timestampKind: string; receivedAt?: Date; topics?: string[]; message?: string; toolName?: string }
|
|
const healthSources: Record<Source, string> = {
|
|
"routeros-poll": `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",sample.sampled_at AS "observedAt",
|
|
CASE sample.ok WHEN true THEN 'ok' WHEN false THEN 'error' END AS status
|
|
FROM servers_api_ping_settings cfg LEFT JOIN LATERAL (
|
|
SELECT sampled_at,ok FROM servers_rest_ping_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
|
|
ORDER BY sampled_at DESC LIMIT 1
|
|
) sample ON true WHERE cfg.id=1`,
|
|
uptime: `SELECT cfg.enabled AND cfg.resources_enabled AS enabled,cfg.interval_sec AS "intervalSec",
|
|
sample.sampled_at AS "observedAt",sample.status
|
|
FROM uptime_settings cfg LEFT JOIN LATERAL (
|
|
SELECT sampled_at,status FROM uptime_resource_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
|
|
ORDER BY sampled_at DESC LIMIT 1
|
|
) sample ON true WHERE cfg.id=1`,
|
|
logs: `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",
|
|
CASE WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN sample.last_collected_at END AS "observedAt",
|
|
CASE WHEN sample.gap_at BETWEEN $2 AND $3 THEN sample.gap_at END AS "gapAt",
|
|
CASE WHEN sample.last_error IS NOT NULL AND sample.last_error <> '' THEN 'error'
|
|
WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN 'ok' END AS status
|
|
FROM router_log_settings cfg LEFT JOIN router_log_collection_state sample ON sample.server_id=$1 WHERE cfg.id=1`,
|
|
netflow: `SELECT NULL::boolean AS enabled,NULL::integer AS "intervalSec",bucket_at AS "observedAt",'retained-bucket' AS status
|
|
FROM flow_minute_stats WHERE server_id=$1 AND bucket_at BETWEEN $2 AND $3
|
|
ORDER BY bucket_at DESC LIMIT 1`,
|
|
}
|
|
const uptimeProbeHealth = `SELECT cfg.enabled AND cfg.ping_enabled AS enabled,
|
|
COALESCE(NULLIF(sample.interval_sec,0),cfg.probe_interval_sec) AS "intervalSec",
|
|
sample.sampled_at AS "observedAt",sample.status
|
|
FROM uptime_settings cfg LEFT JOIN LATERAL (
|
|
SELECT p.interval_sec,s.sampled_at,s.status FROM uptime_probes p CROSS JOIN LATERAL (
|
|
SELECT sampled_at,status FROM uptime_probe_samples WHERE probe_id=p.id AND sampled_at BETWEEN $2 AND $3 AND sampled_at>=p.updated_at
|
|
ORDER BY sampled_at DESC LIMIT 1
|
|
) s WHERE p.src_server_id=$1 AND p.enabled ORDER BY s.sampled_at DESC,p.id LIMIT 1
|
|
) sample ON true WHERE cfg.id=1`
|
|
const timelineSources: Record<TimelineSource, { time: string; key: string; evidence: string }> = {
|
|
"routeros-poll": { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,CASE ok WHEN true THEN 'ok' ELSE 'error' END AS status,
|
|
'backend-sample' AS "timestampKind" FROM servers_rest_ping_samples WHERE server_id=$1` },
|
|
uptime: { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,status,'backend-sample' AS "timestampKind"
|
|
FROM uptime_resource_samples WHERE server_id=$1` },
|
|
"uptime-probe": { time: "s.sampled_at", key: "p.id", evidence: `p.id,status,'backend-sample' AS "timestampKind",
|
|
s.rtt_ms AS "rttMs",s.loss_pct AS "lossPct" FROM uptime_probes p
|
|
JOIN uptime_probe_samples s ON s.probe_id=p.id WHERE p.src_server_id=$1 AND s.sampled_at>=p.updated_at` },
|
|
logs: { time: "effective_at", key: "lpad(id::text,20,'0')", evidence: `id::text,level AS status,
|
|
CASE WHEN event_at IS NULL THEN 'receipt' ELSE 'router' END AS "timestampKind",
|
|
received_at AS "receivedAt",topics[1:20] AS topics,left(message,500) AS message FROM router_log_entries WHERE server_id=$1` },
|
|
netflow: { time: "bucket_at", key: "''::text", evidence: `bucket_at::text AS id,'retained-bucket' AS status,'bucket' AS "timestampKind"
|
|
FROM flow_minute_stats WHERE server_id=$1` },
|
|
"mcp-request": { time: "created_at", key: "id::text", evidence: `id::text,CASE WHEN finished_at <= $3 THEN status END AS status,
|
|
'request-created' AS "timestampKind",tool AS "toolName" FROM mcp_requests WHERE server_ids=ARRAY[$1]::bigint[]
|
|
AND connection_id=$5 AND actor_id=$6 AND tool=ANY($7::text[])` },
|
|
}
|
|
|
|
function timelineQuery(source: TimelineSource, parameters: unknown[], cursor?: z.infer<typeof cursorSchema>) {
|
|
const { time, key, evidence } = timelineSources[source]
|
|
const tie = `(${key}) COLLATE "C"`
|
|
let clause = ""
|
|
if (cursor) {
|
|
const mark = `$${parameters.push(cursor.at)}::timestamptz`
|
|
if (source === cursor.source) clause = `AND (${time},${tie}) < (${mark},$${parameters.push(cursor.key)}::text COLLATE "C")`
|
|
else clause = `AND ${time} ${source > cursor.source ? "<=" : "<"} ${mark}`
|
|
}
|
|
return `SELECT to_char(${time} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS at,
|
|
${key} AS key,${evidence} AND ${time} BETWEEN $2 AND $3 ${clause}
|
|
ORDER BY ${time} DESC,${tie} DESC LIMIT $4`
|
|
}
|
|
|
|
function managerEventTools(context: ActionContext) {
|
|
const { policy, owner_permissions } = context.connection
|
|
const hasBoth = (permission: string) => hasPermission(policy.permissions, permission) && hasPermission(owner_permissions, permission)
|
|
if (!hasBoth("mm:mcp:read")) throw new McpError("PERMISSION_DENIED", "Чтение аудита MCP запрещено", 403)
|
|
const allowed = new Set(policy.scope.operationIds)
|
|
return listMcpOperations().filter(operation => operation.implementation === "available" && operation.scope === "servers" &&
|
|
allowed.has(operation.id) && operation.requiredPermissions.every(hasBoth)).map(operation => operation.toolName)
|
|
}
|
|
|
|
async function requireServer(serverId: number) {
|
|
const { rows } = await pool.query<{ enabled: boolean }>("SELECT enabled FROM servers WHERE id=$1", [serverId])
|
|
if (!rows.length) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
|
|
return rows[0].enabled
|
|
}
|
|
|
|
export function telemetryFreshness(row: HealthRow | undefined, asOf: number, serverEnabled: boolean) {
|
|
const ageMs = row?.observedAt ? asOf - row.observedAt.getTime() : null
|
|
const staleAfterMs = row?.intervalSec ? row.intervalSec * 3000 : null
|
|
const freshness = !serverEnabled || row?.enabled === false ? "disabled"
|
|
: ageMs === null ? "unobserved" : staleAfterMs === null ? "unknown" : ageMs > staleAfterMs ? "stale" : "fresh"
|
|
return { freshness, observedAt: row?.observedAt?.toISOString() ?? null, ageMs, lastStatus: row?.status ?? null,
|
|
...(row?.gapAt && { gapAt: row.gapAt.toISOString() }) }
|
|
}
|
|
|
|
export function registerIncidentActions(register: typeof add) {
|
|
register("telemetry.health.read", "mm_telemetry_health_get", "Здоровье источников телеметрии сервера", "logs",
|
|
"mm:servers:read", "read", "servers", healthInput, {
|
|
target: (raw, context) => {
|
|
const serverIds = typeof raw.serverId === "number" ? [raw.serverId] : context.connection.policy.scope.serverIds
|
|
if (!serverIds.length) throw new McpError("SERVER_DENIED", "Подключению не выдан доступ к серверам", 403)
|
|
return { scope: "servers", serverIds }
|
|
},
|
|
read: async (raw, context) => {
|
|
const input = healthInput.parse(raw), selected = permittedSources(context, input.sources)
|
|
const asOf = Date.now(), from = new Date(asOf - 24 * hourMs), to = new Date(asOf)
|
|
const healthQueries = selected.map(source => ({ source: source as Source | "uptime-probe", sql: healthSources[source] }))
|
|
if (selected.includes("uptime")) healthQueries.push({ source: "uptime-probe", sql: uptimeProbeHealth })
|
|
const readServer = async (serverId: number, serverEnabled: boolean) => ({
|
|
serverId, serverEnabled, observations: await Promise.all(healthQueries.map(async ({ source, sql }) => {
|
|
const expectsActiveServer = source === "netflow" || serverEnabled
|
|
try {
|
|
const { rows } = await pool.query<HealthRow>(sql, [serverId, from, to])
|
|
return { source, ...telemetryFreshness(rows[0], asOf, expectsActiveServer) }
|
|
} catch {
|
|
context.signal?.throwIfAborted()
|
|
return { source, ...telemetryFreshness(undefined, asOf, expectsActiveServer), freshness: "unavailable" as const }
|
|
}
|
|
})),
|
|
})
|
|
const metadata = { observedAt: to.toISOString(), lookbackFrom: from.toISOString(),
|
|
sourceOmissions: sources.filter(source => !selected.includes(source)).map(source => ({
|
|
source, reason: input.sources ? "not-requested" : "permission-denied",
|
|
})),
|
|
netflowDataQuality: { available: false, reason: "no-server-scoped-collector-quality", exportCoverage: "unverified" } }
|
|
if (input.serverId !== undefined) return { ...await readServer(input.serverId, await requireServer(input.serverId)), ...metadata }
|
|
const { rows } = await pool.query<{ id: number; enabled: boolean }>(
|
|
"SELECT id,enabled FROM servers WHERE id=ANY($1::bigint[]) AND id>$2 ORDER BY id LIMIT $3",
|
|
[context.connection.policy.scope.serverIds, input.afterServerId ?? 0, input.limit + 1])
|
|
const page = rows.slice(0, input.limit)
|
|
const items = await Promise.all(page.map(row => readServer(Number(row.id), row.enabled)))
|
|
return { ...metadata, items, nextAfterServerId: rows.length > input.limit ? Number(page.at(-1)?.id) : null }
|
|
},
|
|
})
|
|
register("incident.timeline.read", "mm_incident_timeline_get", "Хронология наблюдений по серверу", "logs",
|
|
"mm:servers:read", "read", "servers", timelineInput, {
|
|
read: async (raw, context) => {
|
|
const input = timelineInput.parse(raw), selected = permittedSources(context, input.sources)
|
|
const managerTools = input.includeManagerEvents ? managerEventTools(context) : null
|
|
const { cursor: token, limit, ...filters } = input
|
|
const scope = async () => fingerprint({ purpose: "incident-timeline-v1", filters, generation: await accessGeneration(),
|
|
connection: context.connection.id, credential: context.principal?.credentialId,
|
|
policy: context.connection.policy, ownerPermissions: context.connection.owner_permissions })
|
|
let cursor: z.infer<typeof cursorSchema> | undefined
|
|
if (token) {
|
|
try {
|
|
cursor = cursorSchema.parse(JSON.parse(await decryptSecret(token)))
|
|
if (cursor.scope !== await scope()) throw Error("scope")
|
|
} catch { throw new McpError("RESET_REQUIRED", "Курсор устарел или относится к другим фильтрам", 409) }
|
|
}
|
|
await requireServer(input.serverId)
|
|
const parameters = [input.serverId, input.from, input.to, limit + 1]
|
|
const queries: Array<{ source: TimelineSource; parameters: unknown[] }> =
|
|
selected.map(source => ({ source, parameters: [...parameters] }))
|
|
if (selected.includes("uptime")) queries.push({ source: "uptime-probe", parameters: [...parameters] })
|
|
if (managerTools) queries.push({ source: "mcp-request",
|
|
parameters: [...parameters, context.connection.id, context.connection.owner_id, managerTools] })
|
|
const batches = await Promise.all(queries.map(async ({ source, parameters }) => {
|
|
const { rows } = await pool.query<EvidenceRow>(timelineQuery(source, parameters, cursor), parameters)
|
|
return rows.map(row => ({ ...row, source }))
|
|
}))
|
|
const items = batches.flat().sort((a, b) => a.at < b.at ? 1 : a.at > b.at ? -1 : a.source < b.source ? -1 : a.source > b.source ? 1 : 0)
|
|
const page = items.slice(0, limit)
|
|
const last = page.at(-1)
|
|
const nextCursor = last && items.length > limit
|
|
? await encryptSecret(JSON.stringify({ at: last.at, key: last.key, source: last.source, scope: cursor?.scope ?? await scope() }))
|
|
: null
|
|
return { serverId: input.serverId, from: new Date(input.from).toISOString(), to: new Date(input.to).toISOString(),
|
|
observedAt: new Date().toISOString(), order: "newest-first", sources: queries.map(query => query.source),
|
|
items: page.map(({ key: _key, receivedAt, ...row }) => ({
|
|
...row, ...(receivedAt && { receivedAt: receivedAt.toISOString() }),
|
|
})), nextCursor, truncated: nextCursor !== null, coverageVerified: false, managerEventsIncluded: input.includeManagerEvents }
|
|
},
|
|
})
|
|
}
|