Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bec8de7c95 | ||
|
|
e9639313c6 | ||
|
|
04c3b1e482 | ||
|
|
776dea6a77 |
No files matched your search
@@ -823,7 +823,7 @@ export default function TrafficPage() {
|
|||||||
const [flowScope, setFlowScope] = useState<FlowScope>("servers")
|
const [flowScope, setFlowScope] = useState<FlowScope>("servers")
|
||||||
const [flowRetry, setFlowRetry] = useState(0)
|
const [flowRetry, setFlowRetry] = useState(0)
|
||||||
const flowKey = JSON.stringify([isLive, groupMode, backendUrl, range, flowScope, flowRetry])
|
const flowKey = JSON.stringify([isLive, groupMode, backendUrl, range, flowScope, flowRetry])
|
||||||
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; error?: string } | null>(null)
|
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; cardWindow?: FlowStatsDto["sourceWindow"]; error?: string } | null>(null)
|
||||||
const currentFlows = flowResult?.key === flowKey ? flowResult : null
|
const currentFlows = flowResult?.key === flowKey ? flowResult : null
|
||||||
const liveBusy = isLive && groupMode === "flows" && !currentFlows
|
const liveBusy = isLive && groupMode === "flows" && !currentFlows
|
||||||
const liveError = currentFlows?.error
|
const liveError = currentFlows?.error
|
||||||
@@ -932,7 +932,8 @@ export default function TrafficPage() {
|
|||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
const clients = await getFlowClients(backendUrl, range)
|
const clients = await getFlowClients(backendUrl, range)
|
||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients })
|
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients,
|
||||||
|
cardWindow: flowScope === "users" ? clients.sourceWindow : exporters.sourceWindow })
|
||||||
setSelectedId(prev => {
|
setSelectedId(prev => {
|
||||||
const list = flowScope === "users" ? clients.clients : exporters.exporters
|
const list = flowScope === "users" ? clients.clients : exporters.exporters
|
||||||
return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "")
|
return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "")
|
||||||
@@ -1250,6 +1251,8 @@ export default function TrafficPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{isLive && <TrafficDataTime label="Получение списка потоков" receivedAt={currentFlows?.receivedAt} source="API" />}
|
{isLive && <TrafficDataTime label="Получение списка потоков" receivedAt={currentFlows?.receivedAt} source="API" />}
|
||||||
|
{flowStats?.sourceWindow && <p role="status" className="text-sm text-muted-foreground">Сводка потоков за последние {flowStats.sourceWindow.effectiveMinutes} мин из запрошенных {flowStats.sourceWindow.requestedMinutes} мин.</p>}
|
||||||
|
{currentFlows?.cardWindow && <p role="status" className="text-sm text-muted-foreground">Данные карточек за последние {currentFlows.cardWindow.effectiveMinutes} мин из запрошенных {currentFlows.cardWindow.requestedMinutes} мин.</p>}
|
||||||
{liveBusy && <p role="status">Загрузка потоков…</p>}
|
{liveBusy && <p role="status">Загрузка потоков…</p>}
|
||||||
{liveError && <Alert variant="destructive" role="alert"><AlertTitle>Потоки недоступны</AlertTitle><AlertDescription>{liveError}<Button size="sm" variant="outline" onClick={() => setFlowRetry(value => value + 1)}>Повторить загрузку потоков</Button></AlertDescription></Alert>}
|
{liveError && <Alert variant="destructive" role="alert"><AlertTitle>Потоки недоступны</AlertTitle><AlertDescription>{liveError}<Button size="sm" variant="outline" onClick={() => setFlowRetry(value => value + 1)}>Повторить загрузку потоков</Button></AlertDescription></Alert>}
|
||||||
{flowError && !liveError && (
|
{flowError && !liveError && (
|
||||||
|
|||||||
@@ -555,6 +555,13 @@
|
|||||||
"operations": [],
|
"operations": [],
|
||||||
"reason": "Управление самим MCP, транспорт или машинная авторизация: отдельного AI-инструмента нет."
|
"reason": "Управление самим MCP, транспорт или машинная авторизация: отдельного AI-инструмента нет."
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/api/mcp/server-choices",
|
||||||
|
"status": "excluded",
|
||||||
|
"operations": [],
|
||||||
|
"reason": "Каталог выбора серверов для выдачи доступа в панели MCP."
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"path": "/api/mcp/connections/:id/grants",
|
"path": "/api/mcp/connections/:id/grants",
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ const RULES: Rule[] = [
|
|||||||
{ methods: ["POST"], match: p => p === "/api/mcp/oauth/consent", permission: "mm:mcp:read" },
|
{ methods: ["POST"], match: p => p === "/api/mcp/oauth/consent", permission: "mm:mcp:read" },
|
||||||
{ methods: ["POST"], match: p => /^\/api\/mcp\/connections\/[^/]+\/revalidate$/.test(p), permission: "mm:mcp:read" },
|
{ methods: ["POST"], match: p => /^\/api\/mcp\/connections\/[^/]+\/revalidate$/.test(p), permission: "mm:mcp:read" },
|
||||||
{ methods: ["GET"], match: p => p === "/api/mcp/catalog", permission: "mm:mcp:read" },
|
{ methods: ["GET"], match: p => p === "/api/mcp/catalog", permission: "mm:mcp:read" },
|
||||||
|
{ methods: ["GET"], match: p => p === "/api/mcp/server-choices", permission: "mm:mcp:read" },
|
||||||
{ methods: ["GET"], match: p => p.startsWith("/api/mcp/devices/"), permission: "mm:mcp:read" },
|
{ methods: ["GET"], match: p => p.startsWith("/api/mcp/devices/"), permission: "mm:mcp:read" },
|
||||||
{ methods: ["GET"], match: p => /^\/api\/mcp\/(?:overview|connections|requests|plans|operations|protections|drift|audit|artifacts|routing-profiles)(?:\/|$)/.test(p), permission: "mm:mcp:read" },
|
{ methods: ["GET"], match: p => /^\/api\/mcp\/(?:overview|connections|requests|plans|operations|protections|drift|audit|artifacts|routing-profiles)(?:\/|$)/.test(p), permission: "mm:mcp:read" },
|
||||||
{ methods: ["POST"], match: p => /^\/api\/mcp\/plans\/(?:[^/]+)\/decision$/.test(p), permission: "mm:mcp:approve" },
|
{ methods: ["POST"], match: p => /^\/api\/mcp\/plans\/(?:[^/]+)\/decision$/.test(p), permission: "mm:mcp:approve" },
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { z } from "zod"
|
|||||||
import { flowAnalyticsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
import { flowAnalyticsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
||||||
import { buildFlowAnalytics } from "../../services/traffic-flow-analytics.js"
|
import { buildFlowAnalytics } from "../../services/traffic-flow-analytics.js"
|
||||||
import { readFlowSourceLimits } from "../../services/traffic-flow-source-limits.js"
|
import { readFlowSourceLimits } from "../../services/traffic-flow-source-limits.js"
|
||||||
|
import { readFlowWindow } from "../../services/traffic-flow-read-window.js"
|
||||||
import { getBoundedFlowServerRowById as getServerRowById } from "../../services/traffic-flow-server-source.js"
|
import { getBoundedFlowServerRowById as getServerRowById } from "../../services/traffic-flow-server-source.js"
|
||||||
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
|
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
|
||||||
import { McpError } from "./security.js"
|
import { McpError } from "./security.js"
|
||||||
@@ -20,10 +21,10 @@ export function registerLegacyFlowAnalyticsAction(register: typeof add) {
|
|||||||
if (!server) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
|
if (!server) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
|
||||||
const authorize = () => assertTrafficHistorySource(context, server)
|
const authorize = () => assertTrafficHistorySource(context, server)
|
||||||
try {
|
try {
|
||||||
const result = await buildFlowAnalytics({ serverId: server.id, minutes: Number(input.minutes), iface: input.interface as string | undefined, skipHeavy: true },
|
const result = await readFlowWindow(Number(input.minutes), minutes => buildFlowAnalytics({ serverId: server.id, minutes, iface: input.interface as string | undefined, skipHeavy: true },
|
||||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize })
|
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
|
||||||
return {
|
return {
|
||||||
serverId: input.serverId, source: "PostgreSQL/flow_buckets", observedAt: new Date().toISOString(),
|
serverId: input.serverId, source: "PostgreSQL/flow_buckets", observedAt: new Date().toISOString(), sourceWindow: result.sourceWindow,
|
||||||
bpsNow: result.bpsNow, bytes: result.bytes, packets: result.packets, conversations: result.conversations,
|
bpsNow: result.bpsNow, bytes: result.bytes, packets: result.packets, conversations: result.conversations,
|
||||||
uniqueSrc: result.uniqueSrc, uniqueDst: result.uniqueDst, rxSeries: result.rxSeries, txSeries: result.txSeries,
|
uniqueSrc: result.uniqueSrc, uniqueDst: result.uniqueDst, rxSeries: result.rxSeries, txSeries: result.txSeries,
|
||||||
applications: result.applications, protocols: result.protocols, countries: result.countries,
|
applications: result.applications, protocols: result.protocols, countries: result.countries,
|
||||||
@@ -57,9 +58,10 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
|||||||
try {
|
try {
|
||||||
const limits = await readFlowSourceLimits()
|
const limits = await readFlowSourceLimits()
|
||||||
await authorize()
|
await authorize()
|
||||||
const result = flowAnalyticsDtoSchema.parse(await buildFlowAnalytics({ serverId: server.id, minutes: Number(input.minutes), userId: input.userId as string | undefined,
|
const { sourceWindow, ...raw } = await readFlowWindow(Number(input.minutes), minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
|
||||||
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
||||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }))
|
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
|
||||||
|
const result = flowAnalyticsDtoSchema.parse(raw)
|
||||||
const offset = Number(input.offset), limit = Number(input.limit), pages: Record<string, { total: number; nextOffset: number | null }> = {}
|
const offset = Number(input.offset), limit = Number(input.limit), pages: Record<string, { total: number; nextOffset: number | null }> = {}
|
||||||
const analytics: Record<string, unknown> = { ...result }
|
const analytics: Record<string, unknown> = { ...result }
|
||||||
for (const [key, value] of Object.entries(result)) if (Array.isArray(value) && !["rxSeries", "txSeries"].includes(key)) {
|
for (const [key, value] of Object.entries(result)) if (Array.isArray(value) && !["rxSeries", "txSeries"].includes(key)) {
|
||||||
@@ -71,7 +73,7 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
|||||||
await authorize()
|
await authorize()
|
||||||
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
|
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
|
||||||
await authorize()
|
await authorize()
|
||||||
const output = { serverId: server.id, minutes: Number(input.minutes), interface: input.interface ?? null, userId: input.userId ?? null,
|
const output = { serverId: server.id, minutes: sourceWindow?.effectiveMinutes ?? Number(input.minutes), sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null,
|
||||||
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
|
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
|
||||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: current server/interface ring with retained-window fallback; wire projection uses current interface snapshots" },
|
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: current server/interface ring with retained-window fallback; wire projection uses current interface snapshots" },
|
||||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
|
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { z } from "zod"
|
|||||||
import { readFlowExporterInputs, readFlowClientInputs, observeFlowExporter, observeFlowClient } from "../../services/traffic-flow-catalog-read.js"
|
import { readFlowExporterInputs, readFlowClientInputs, observeFlowExporter, observeFlowClient } from "../../services/traffic-flow-catalog-read.js"
|
||||||
import { getFlowMonthly } from "../../services/traffic-flow-analytics.js"
|
import { getFlowMonthly } from "../../services/traffic-flow-analytics.js"
|
||||||
import { readFlowCatalogWindow } from "../../services/traffic-flow-catalog-read.js"
|
import { readFlowCatalogWindow } from "../../services/traffic-flow-catalog-read.js"
|
||||||
|
import { readFlowWindow } from "../../services/traffic-flow-read-window.js"
|
||||||
import { projectFlowTalkers } from "../../services/traffic-flow-talkers-model.js"
|
import { projectFlowTalkers } from "../../services/traffic-flow-talkers-model.js"
|
||||||
import { resolveIfaceName } from "../../services/traffic-flow-ifindex.js"
|
import { resolveIfaceName } from "../../services/traffic-flow-ifindex.js"
|
||||||
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
|
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
|
||||||
@@ -21,9 +22,10 @@ export function registerFlowCatalogActions(register: typeof add) {
|
|||||||
await assertTrafficHistoryAccess(context)
|
await assertTrafficHistoryAccess(context)
|
||||||
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
|
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
|
||||||
try {
|
try {
|
||||||
const window = await readFlowCatalogWindow(Number(input.minutes), selected.map(row => row.id))
|
const requestedMinutes = Number(input.minutes)
|
||||||
|
const window = await readFlowWindow(requestedMinutes, minutes => readFlowCatalogWindow(minutes, selected.map(row => row.id)), context.signal)
|
||||||
const topN = window.topConversationsLimit ?? 20
|
const topN = window.topConversationsLimit ?? 20
|
||||||
const projection = projectFlowTalkers(window.rows, Number(input.minutes), topN, new Map(selected.map(row => [row.id, row.name])), resolveIfaceName)
|
const projection = projectFlowTalkers(window.rows, window.sourceWindow?.effectiveMinutes ?? requestedMinutes, topN, new Map(selected.map(row => [row.id, row.name])), resolveIfaceName)
|
||||||
const offset = Number(input.offset), limit = Number(input.limit), items = projection.talkers.slice(offset, offset + limit)
|
const offset = Number(input.offset), limit = Number(input.limit), items = projection.talkers.slice(offset, offset + limit)
|
||||||
for (const server of selected) await assertTrafficHistorySource(context, server)
|
for (const server of selected) await assertTrafficHistorySource(context, server)
|
||||||
if (selected.length && (await getTrafficFlowSettingsRow()).topN !== topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
|
if (selected.length && (await getTrafficFlowSettingsRow()).topN !== topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
|
||||||
@@ -33,7 +35,7 @@ export function registerFlowCatalogActions(register: typeof add) {
|
|||||||
retainedRowsBytes: projection.retainedRowsBytes, observedExporters: projection.observedExporters,
|
retainedRowsBytes: projection.retainedRowsBytes, observedExporters: projection.observedExporters,
|
||||||
uniqueSrc: projection.uniqueSrc, uniqueDst: projection.uniqueDst, topProto: projection.topProto,
|
uniqueSrc: projection.uniqueSrc, uniqueDst: projection.uniqueDst, topProto: projection.topProto,
|
||||||
topConversationsLimit: topN, topRowsPerBucketLimit: window.topRowsPerBucketLimit,
|
topConversationsLimit: topN, topRowsPerBucketLimit: window.topRowsPerBucketLimit,
|
||||||
incomplete: true, from: window.since, to: window.until,
|
incomplete: true, from: window.since, to: window.until, sourceWindow: window.sourceWindow,
|
||||||
source: "flow_buckets plus pending; scope before SQL and retained conversation aggregation",
|
source: "flow_buckets plus pending; scope before SQL and retained conversation aggregation",
|
||||||
bpsMeaning: "retained conversation bytes averaged over the entire requested window",
|
bpsMeaning: "retained conversation bytes averaged over the entire requested window",
|
||||||
...sourceSemantics },context)
|
...sourceSemantics },context)
|
||||||
@@ -47,27 +49,31 @@ export function registerFlowCatalogActions(register: typeof add) {
|
|||||||
register("traffic.flow.exporters.read", "mm_netflow_exporters_get", "NetFlow: экспортёры выбранной области", "traffic", "mm:traffic:read", "read", "servers", schema, {
|
register("traffic.flow.exporters.read", "mm_netflow_exporters_get", "NetFlow: экспортёры выбранной области", "traffic", "mm:traffic:read", "read", "servers", schema, {
|
||||||
read: async (input, context) => {
|
read: async (input, context) => {
|
||||||
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
|
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
|
||||||
const data = await readFlowExporterInputs(Number(input.minutes), selected.map(row => row.id))
|
const requestedMinutes = Number(input.minutes)
|
||||||
|
const data = await readFlowWindow(requestedMinutes, minutes => readFlowExporterInputs(minutes, selected.map(row => row.id)), context.signal)
|
||||||
const present = new Set([...data.window.rows.map(row => row.serverId), ...data.configuredIds])
|
const present = new Set([...data.window.rows.map(row => row.serverId), ...data.configuredIds])
|
||||||
const all = data.catalog.list.filter(row => present.has(row.id)).sort((a, b) => a.id - b.id)
|
const all = data.catalog.list.filter(row => present.has(row.id)).sort((a, b) => a.id - b.id)
|
||||||
const offset = Number(input.offset), limit = Number(input.limit)
|
const offset = Number(input.offset), limit = Number(input.limit)
|
||||||
return withCurrentFlowReadQuality({ ...page, exporters: all.slice(offset, offset + limit).map(row => observeFlowExporter(data, row.id, Number(input.minutes))), total: all.length,
|
for (const server of selected) await assertTrafficHistorySource(context, server)
|
||||||
nextOffset: offset + limit < all.length ? offset + limit : null, incomplete: page.incomplete || all.length > limit || offset > 0 || data.configurationMembershipVerified === false,
|
return withCurrentFlowReadQuality({ ...page, exporters: all.slice(offset, offset + limit).map(row => observeFlowExporter(data, row.id, data.sourceWindow?.effectiveMinutes ?? requestedMinutes)), total: all.length,
|
||||||
|
nextOffset: offset + limit < all.length ? offset + limit : null, incomplete: !!data.sourceWindow || page.incomplete || all.length > limit || offset > 0 || data.configurationMembershipVerified === false,
|
||||||
configurationMembershipVerified: data.configurationMembershipVerified, configurationEvidence: "stored-peer-records; device exporter settings and keys not verified", source: "flow_buckets plus pending; retained top rows per server/bucket",
|
configurationMembershipVerified: data.configurationMembershipVerified, configurationEvidence: "stored-peer-records; device exporter settings and keys not verified", source: "flow_buckets plus pending; retained top rows per server/bucket",
|
||||||
failures: data.configurationMembershipVerified === false ? [{ source: "selected-peer-membership", code: "UNVERIFIED_SCHEMA" }] : [],
|
failures: data.configurationMembershipVerified === false ? [{ source: "selected-peer-membership", code: "UNVERIFIED_SCHEMA" }] : [],
|
||||||
topRowsPerBucketLimit: data.window.topRowsPerBucketLimit, from: data.window.since, to: data.window.until, ...sourceSemantics },context)
|
topRowsPerBucketLimit: data.window.topRowsPerBucketLimit, from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
register("traffic.flow.clients.read", "mm_netflow_clients_get", "NetFlow: клиенты по доступным привязкам", "traffic", "mm:traffic:read", "read", "servers", schema.safeExtend({ limit: z.number().int().min(1).max(50).default(20) }), {
|
register("traffic.flow.clients.read", "mm_netflow_clients_get", "NetFlow: клиенты по доступным привязкам", "traffic", "mm:traffic:read", "read", "servers", schema.safeExtend({ limit: z.number().int().min(1).max(50).default(20) }), {
|
||||||
read: async (input, context) => {
|
read: async (input, context) => {
|
||||||
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
|
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
|
||||||
const offset = Number(input.offset), limit = Number(input.limit)
|
const offset = Number(input.offset), limit = Number(input.limit)
|
||||||
const data = await readFlowClientInputs(Number(input.minutes), { serverIds: selected.map(row => row.id), allowedServerIds: context.connection.policy.scope.serverIds, offset, limit })
|
const requestedMinutes = Number(input.minutes)
|
||||||
const clients = data.users.sort((a, b) => a.id.localeCompare(b.id)).map(user => observeFlowClient(user, data.window.rows, Number(input.minutes)))
|
const data = await readFlowWindow(requestedMinutes, minutes => readFlowClientInputs(minutes, { serverIds: selected.map(row => row.id), allowedServerIds: context.connection.policy.scope.serverIds, offset, limit }), context.signal)
|
||||||
|
const clients = data.users.sort((a, b) => a.id.localeCompare(b.id)).map(user => observeFlowClient(user, data.window.rows, data.sourceWindow?.effectiveMinutes ?? requestedMinutes))
|
||||||
|
for (const server of selected) await assertTrafficHistorySource(context, server)
|
||||||
return withCurrentFlowReadQuality({ ...page, clients, total: data.total, nextOffset: offset + clients.length < data.total ? offset + clients.length : null,
|
return withCurrentFlowReadQuality({ ...page, clients, total: data.total, nextOffset: offset + clients.length < data.total ? offset + clients.length : null,
|
||||||
incomplete: page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
|
incomplete: !!data.sourceWindow || page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
|
||||||
source: "retained ingress rows and current named whole-interface bindings", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
source: "retained ingress rows and current named whole-interface bindings", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||||
from: data.window.since, to: data.window.until, ...sourceSemantics },context)
|
from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
register("traffic.flow.monthly.read", "mm_netflow_monthly_report_get", "NetFlow: месячный отчёт выбранной области", "traffic", "mm:traffic:read", "read", "servers", catalogPaging.safeExtend({ month: z.string().regex(/^(?!0000)\d{4}-(0[1-9]|1[0-2])$/) }), {
|
register("traffic.flow.monthly.read", "mm_netflow_monthly_report_get", "NetFlow: месячный отчёт выбранной области", "traffic", "mm:traffic:read", "read", "servers", catalogPaging.safeExtend({ month: z.string().regex(/^(?!0000)\d{4}-(0[1-9]|1[0-2])$/) }), {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
|||||||
import { isDeepStrictEqual } from "node:util"
|
import { isDeepStrictEqual } from "node:util"
|
||||||
import { buildFlowMapHops } from "../../services/traffic-flow-map-hops.js"
|
import { buildFlowMapHops } from "../../services/traffic-flow-map-hops.js"
|
||||||
import { readFlowMapSourceLimits } from "../../services/traffic-flow-source-limits.js"
|
import { readFlowMapSourceLimits } from "../../services/traffic-flow-source-limits.js"
|
||||||
|
import { readFlowWindow } from "../../services/traffic-flow-read-window.js"
|
||||||
import { getBoundedFlowServerRowById as getServerRowById } from "../../services/traffic-flow-server-source.js"
|
import { getBoundedFlowServerRowById as getServerRowById } from "../../services/traffic-flow-server-source.js"
|
||||||
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
|
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
|
||||||
import { McpError } from "./security.js"
|
import { McpError } from "./security.js"
|
||||||
@@ -27,9 +28,10 @@ export function registerFlowMapActions(register: typeof add) {
|
|||||||
try {
|
try {
|
||||||
const limits = await readFlowMapSourceLimits()
|
const limits = await readFlowMapSourceLimits()
|
||||||
await authorize()
|
await authorize()
|
||||||
const result = flowMapHopsDtoSchema.parse(await buildFlowMapHops({ serverId: server.id, minutes: Number(input.minutes), userId: input.userId as string | undefined,
|
const { sourceWindow, ...raw } = await readFlowWindow(Number(input.minutes), minutes => buildFlowMapHops({ serverId: server.id, minutes, userId: input.userId as string | undefined,
|
||||||
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
||||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }))
|
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
|
||||||
|
const result = flowMapHopsDtoSchema.parse(raw)
|
||||||
const pages: Record<string, { total: number; nextOffset: number | null }> = {}
|
const pages: Record<string, { total: number; nextOffset: number | null }> = {}
|
||||||
const project = (value: unknown, path = "", depth = 0): unknown => {
|
const project = (value: unknown, path = "", depth = 0): unknown => {
|
||||||
if (Array.isArray(value)) {
|
if (Array.isArray(value)) {
|
||||||
@@ -45,7 +47,7 @@ export function registerFlowMapActions(register: typeof add) {
|
|||||||
await authorize()
|
await authorize()
|
||||||
if (!isDeepStrictEqual(limits, await readFlowMapSourceLimits())) throw new McpError("STATE_CONFLICT", "Пределы карты NetFlow изменились во время чтения", 409)
|
if (!isDeepStrictEqual(limits, await readFlowMapSourceLimits())) throw new McpError("STATE_CONFLICT", "Пределы карты NetFlow изменились во время чтения", 409)
|
||||||
await authorize()
|
await authorize()
|
||||||
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages,
|
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
|
||||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
|
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
|
||||||
source: "retained flow_buckets plus pending; same REST map engine with scoped topology",
|
source: "retained flow_buckets plus pending; same REST map engine with scoped topology",
|
||||||
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||||
|
|||||||
@@ -23,8 +23,9 @@ assert.match(basename(dirname(resolve(process.env.MCP_STATE_DIR))), /^mm-mcp-tes
|
|||||||
const { pool, closePool } = await import("../../db/index.js")
|
const { pool, closePool } = await import("../../db/index.js")
|
||||||
const { applySqlMigrations } = await import("../../db/migrate.js")
|
const { applySqlMigrations } = await import("../../db/migrate.js")
|
||||||
const { MIGRATION_MANIFEST } = await import("../../db/migration-manifest.js")
|
const { MIGRATION_MANIFEST } = await import("../../db/migration-manifest.js")
|
||||||
const { mcpConnectionCreateSchema, mcpTemporaryGrantSchema } = await import("@mmapp/contracts/mcp")
|
const { MCP_SERVICE_EXPIRATION, mcpConnectionCreateSchema, mcpTemporaryGrantSchema } = await import("@mmapp/contracts/mcp")
|
||||||
const { createMcpConnection, authenticateMcpToken, getConnection, validatePrincipal, effectiveMcpConnectionSource } = await import("./store.js")
|
const { createMcpConnection, authenticateMcpToken, getConnection, validatePrincipal, effectiveMcpConnectionSource,
|
||||||
|
updateMcpConnection, revalidateMcpOwner, rotateConnectionToken, setConnectionStatus, intersectGrant } = await import("./store.js")
|
||||||
const { acceptPortalRevocation } = await import("./portal-revocation.js")
|
const { acceptPortalRevocation } = await import("./portal-revocation.js")
|
||||||
const { connectProbeStorage } = await import("../../services/server-probe-storage-connection.js")
|
const { connectProbeStorage } = await import("../../services/server-probe-storage-connection.js")
|
||||||
const { principalSourceSql, principalSourceStatementName } = await import("./principal-security-sql.js")
|
const { principalSourceSql, principalSourceStatementName } = await import("./principal-security-sql.js")
|
||||||
@@ -83,6 +84,67 @@ try {
|
|||||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n, MIGRATION_MANIFEST.length)
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n, MIGRATION_MANIFEST.length)
|
||||||
priorEnabled = Boolean((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled)
|
priorEnabled = Boolean((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled)
|
||||||
await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1")
|
await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1")
|
||||||
|
await check("explicit all-server selection stores current IDs and the empty list stays empty", async () => {
|
||||||
|
const { actor, principal } = await fixture()
|
||||||
|
const input = mcpConnectionCreateSchema.parse({ name: "All server scope", expiresAt: new Date(actor.expiresAt!).toISOString(),
|
||||||
|
permissions: ["mm:servers:read"], scope: { serverIds: [], operationIds: ["servers.list"], allowGlobal: false } })
|
||||||
|
const insertServer = async (name: string) => Number((await pool.query("INSERT INTO servers(name,host,enabled) VALUES($1,'127.0.0.1',false) RETURNING id", [name])).rows[0].id)
|
||||||
|
const serverIds: number[] = []
|
||||||
|
try {
|
||||||
|
serverIds.push(await insertServer("Owned all-scope first"))
|
||||||
|
const current = (await pool.query("SELECT id FROM servers ORDER BY id")).rows.map(row => Number(row.id))
|
||||||
|
assert.equal(mcpConnectionCreateSchema.safeParse({ ...input, selectAllServers: true, scope: { ...input.scope, serverIds } }).success, false)
|
||||||
|
const access = await createMcpConnection({ ...input, selectAllServers: true }, actor)
|
||||||
|
connectionIds.push(access.connection.id)
|
||||||
|
const allPrincipal = await authenticateMcpToken(access.token)
|
||||||
|
serverIds.push(await insertServer("Owned all-scope second"))
|
||||||
|
const granted = await validatePrincipal(allPrincipal)
|
||||||
|
assert.deepEqual(granted.policy.scope.serverIds, current)
|
||||||
|
assert.equal(granted.policy.scope.allowGlobal, false)
|
||||||
|
assert.equal(Object.hasOwn(granted.policy, "selectAllServers"), false)
|
||||||
|
const limited = intersectGrant(granted, { id: randomUUID(), startsAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||||
|
scope: { serverIds: [serverIds[0]], operationIds: ["servers.list"], allowGlobal: false } })
|
||||||
|
assert.deepEqual(limited.policy.scope.serverIds, [serverIds[0]])
|
||||||
|
const updated = await updateMcpConnection(principal.connectionId, { ...input, selectAllServers: true }, actor)
|
||||||
|
assert.deepEqual(updated.policy.scope.serverIds, [...current, serverIds[1]])
|
||||||
|
const emptied = await updateMcpConnection(principal.connectionId, input, actor)
|
||||||
|
assert.deepEqual(emptied.policy.scope.serverIds, [])
|
||||||
|
} finally {
|
||||||
|
await pool.query("DELETE FROM servers WHERE id=ANY($1::bigint[])", [serverIds])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await check("service access survives portal expiry and preserves token rotation and revocation", async () => {
|
||||||
|
const { actor, principal: personal } = await fixture()
|
||||||
|
const payload = { authority: "service", name: "Service access", mode: "autonomous", expiresAt: null,
|
||||||
|
permissions: ["mm:servers:read"], scope: { serverIds: [], operationIds: ["capabilities.read"], allowGlobal: false } }
|
||||||
|
const policy = mcpConnectionCreateSchema.parse(payload)
|
||||||
|
assert.equal(mcpConnectionCreateSchema.safeParse({ ...payload, dangerousPolicy: "explicit-allow" }).success, false)
|
||||||
|
assert.equal(mcpConnectionCreateSchema.safeParse({ ...payload, authority: undefined }).success, false)
|
||||||
|
await assert.rejects(createMcpConnection(policy, { ...actor, permissions: policy.permissions }), { code: "PERMISSION_DENIED" })
|
||||||
|
await assert.rejects(updateMcpConnection(personal.connectionId, policy, actor), { code: "INVALID_CONFIGURATION" })
|
||||||
|
const shortSession = { ...actor, expiresAt: Date.now() + 250 }
|
||||||
|
const { connection, token } = await createMcpConnection(policy, shortSession)
|
||||||
|
connectionIds.push(connection.id)
|
||||||
|
await new Promise(resolve => setTimeout(resolve, Math.max(0, shortSession.expiresAt - Date.now() + 1)))
|
||||||
|
const principal = await authenticateMcpToken(token)
|
||||||
|
const current = await validatePrincipal(principal)
|
||||||
|
assert.equal(current.policy.authority, "service")
|
||||||
|
assert.equal(current.owner_valid_until.toISOString(), MCP_SERVICE_EXPIRATION)
|
||||||
|
assert.equal(principal.credentialExpiresAt, MCP_SERVICE_EXPIRATION)
|
||||||
|
assert.deepEqual(current.owner_permissions, policy.permissions)
|
||||||
|
await assert.rejects(revalidateMcpOwner(connection.id, actor), { code: "INVALID_CONFIGURATION" })
|
||||||
|
const edited = await updateMcpConnection(connection.id, { ...policy, name: "Edited service access" }, actor)
|
||||||
|
assert.equal(edited.ownerValidUntil, MCP_SERVICE_EXPIRATION)
|
||||||
|
const rotated = await rotateConnectionToken(connection.id, actor)
|
||||||
|
await assert.rejects(authenticateMcpToken(token), { code: "UNAUTHORIZED" })
|
||||||
|
const replacement = await authenticateMcpToken(rotated.token)
|
||||||
|
await setConnectionStatus(connection.id, "paused", actor)
|
||||||
|
await assert.rejects(validatePrincipal(replacement), { code: "UNAUTHORIZED" })
|
||||||
|
await setConnectionStatus(connection.id, "active", actor)
|
||||||
|
await validatePrincipal(replacement)
|
||||||
|
await setConnectionStatus(connection.id, "revoked", actor)
|
||||||
|
await assert.rejects(authenticateMcpToken(rotated.token), { code: "UNAUTHORIZED" })
|
||||||
|
})
|
||||||
await check("poll current policy tuple: real SQL bounds, clock, backend, scopes and fresh committed updates", async () => {
|
await check("poll current policy tuple: real SQL bounds, clock, backend, scopes and fresh committed updates", async () => {
|
||||||
const f = await fixture()
|
const f = await fixture()
|
||||||
console.log("Owned poll policy tuple SQL:", JSON.stringify(await checkOwnedPollPolicySource(pool, f.principal.connectionId, f.principal.credentialId)))
|
console.log("Owned poll policy tuple SQL:", JSON.stringify(await checkOwnedPollPolicySource(pool, f.principal.connectionId, f.principal.credentialId)))
|
||||||
@@ -132,12 +194,17 @@ try {
|
|||||||
})
|
})
|
||||||
await check("actual HMAC portal revoke and private external cutoff interrupt source capture", async () => {
|
await check("actual HMAC portal revoke and private external cutoff interrupt source capture", async () => {
|
||||||
const f = await fixture(), secret = randomBytes(32).toString("hex")
|
const f = await fixture(), secret = randomBytes(32).toString("hex")
|
||||||
|
const service = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Revocable service", authority: "service", expiresAt: null,
|
||||||
|
mode: "autonomous", permissions: [], scope: { serverIds: [], operationIds: ["capabilities.read"] } }), f.actor)
|
||||||
|
connectionIds.push(service.connection.id)
|
||||||
|
await validatePrincipal(await authenticateMcpToken(service.token))
|
||||||
await refusalBetween(f, async () => {
|
await refusalBetween(f, async () => {
|
||||||
const timestamp = String(Math.floor(Date.now() / 1000)), raw = Buffer.from(JSON.stringify({ eventId: randomUUID(), userId: f.actor.id, type: "sessions.revoked" }))
|
const timestamp = String(Math.floor(Date.now() / 1000)), raw = Buffer.from(JSON.stringify({ eventId: randomUUID(), userId: f.actor.id, type: "sessions.revoked" }))
|
||||||
const signature = "sha256=" + createHmac("sha256", secret).update(timestamp + ".").update(raw).digest("hex")
|
const signature = "sha256=" + createHmac("sha256", secret).update(timestamp + ".").update(raw).digest("hex")
|
||||||
assert.deepEqual(await acceptPortalRevocation(raw, timestamp, signature, secret), { ok: true, duplicate: false })
|
assert.deepEqual(await acceptPortalRevocation(raw, timestamp, signature, secret), { ok: true, duplicate: false })
|
||||||
}, "OWNER_CLAIMS_REVOKED")
|
}, "OWNER_CLAIMS_REVOKED")
|
||||||
await assert.rejects(validatePrincipal(f.principal), { code: "OWNER_CLAIMS_REVOKED" })
|
await assert.rejects(validatePrincipal(f.principal), { code: "OWNER_CLAIMS_REVOKED" })
|
||||||
|
await assert.rejects(authenticateMcpToken(service.token), { code: "UNAUTHORIZED" })
|
||||||
})
|
})
|
||||||
await check("duplicate signed revocation repairs the external cutoff without moving recorded authority", async () => {
|
await check("duplicate signed revocation repairs the external cutoff without moving recorded authority", async () => {
|
||||||
const f = await fixture(), secret = randomBytes(32).toString("hex")
|
const f = await fixture(), secret = randomBytes(32).toString("hex")
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto"
|
|||||||
import type { PoolClient, QueryResultRow } from "pg"
|
import type { PoolClient, QueryResultRow } from "pg"
|
||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
import {
|
import {
|
||||||
mcpConnectionPolicySchema, mcpConnectionSchema, mcpSettingsSchema, mcpTemporaryGrantSchema,
|
MCP_SERVICE_EXPIRATION, mcpConnectionPolicySchema, mcpConnectionSchema, mcpSettingsSchema, mcpTemporaryGrantSchema,
|
||||||
type McpConnection, type McpConnectionCreate, type McpConnectionPolicy,
|
type McpConnection, type McpConnectionCreate, type McpConnectionPolicy,
|
||||||
} from "@mmapp/contracts/mcp"
|
} from "@mmapp/contracts/mcp"
|
||||||
import { pool } from "../../db/index.js"
|
import { pool } from "../../db/index.js"
|
||||||
@@ -19,6 +19,29 @@ export interface ConnectionRow extends QueryResultRow {
|
|||||||
owner_claims_issued_at: Date
|
owner_claims_issued_at: Date
|
||||||
}
|
}
|
||||||
function ownerValidUntil(actor: AuthUser) { return new Date(Math.min(actor.expiresAt ?? Date.now() + 900000, Date.now() + 86400000)) }
|
function ownerValidUntil(actor: AuthUser) { return new Date(Math.min(actor.expiresAt ?? Date.now() + 900000, Date.now() + 86400000)) }
|
||||||
|
function connectionExpiration(input: McpConnectionCreate, actor: AuthUser) {
|
||||||
|
if (input.authority === "service" && input.expiresAt === null) {
|
||||||
|
if (!hasPermission(actor.permissions, "mm:mcp:admin")) throw new McpError("PERMISSION_DENIED", "Сервисный доступ выдаёт администратор MCP", 403)
|
||||||
|
return MCP_SERVICE_EXPIRATION
|
||||||
|
}
|
||||||
|
const expires = Date.parse(input.expiresAt ?? ""), now = Date.now()
|
||||||
|
if (!input.expiresAt || !Number.isFinite(expires) || expires <= now || expires > now + 366 * 86400000)
|
||||||
|
throw new McpError("INVALID_EXPIRATION", "Срок доступа должен быть от текущего времени до одного года", 400)
|
||||||
|
return input.expiresAt
|
||||||
|
}
|
||||||
|
async function resolveConnectionScope(scope: McpConnectionCreate["scope"], selectAllServers: boolean, client: PoolClient) {
|
||||||
|
if (selectAllServers) {
|
||||||
|
if (scope.serverIds.length) throw new McpError("INVALID_CONFIGURATION", "Выберите все серверы или укажите конкретные ID", 400)
|
||||||
|
const { rows } = await client.query<{ id: string }>("SELECT id FROM servers ORDER BY id LIMIT 1001")
|
||||||
|
if (rows.length > 1000) throw new McpError("INVALID_CONFIGURATION", "Подключению можно выдать доступ не более чем к 1000 серверам", 400)
|
||||||
|
return { ...scope, serverIds: rows.map(row => Number(row.id)) }
|
||||||
|
}
|
||||||
|
if (scope.serverIds.length) {
|
||||||
|
const { rows } = await client.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [scope.serverIds])
|
||||||
|
if (rows.length !== scope.serverIds.length) throw new McpError("SERVER_DENIED", "Выбран неизвестный сервер", 400)
|
||||||
|
}
|
||||||
|
return scope
|
||||||
|
}
|
||||||
export interface McpPrincipal { connectionId: string; credentialId: string; credentialExpiresAt: string }
|
export interface McpPrincipal { connectionId: string; credentialId: string; credentialExpiresAt: string }
|
||||||
export function intersectGrant(connection: ConnectionRow, grant?: z.infer<typeof mcpTemporaryGrantSchema>): ConnectionRow {
|
export function intersectGrant(connection: ConnectionRow, grant?: z.infer<typeof mcpTemporaryGrantSchema>): ConnectionRow {
|
||||||
if (!grant) return connection
|
if (!grant) return connection
|
||||||
@@ -113,38 +136,41 @@ export function assertConnectionVisible(row: ConnectionRow, actor: AuthUser): vo
|
|||||||
if (row.owner_id !== actor.id && !hasPermission(actor.permissions, "mm:mcp:admin")) throw new McpError("NOT_FOUND", "Подключение не найдено", 404)
|
if (row.owner_id !== actor.id && !hasPermission(actor.permissions, "mm:mcp:admin")) throw new McpError("NOT_FOUND", "Подключение не найдено", 404)
|
||||||
}
|
}
|
||||||
export async function createMcpConnection(input: McpConnectionCreate, actor: AuthUser) {
|
export async function createMcpConnection(input: McpConnectionCreate, actor: AuthUser) {
|
||||||
const expires = Date.parse(input.expiresAt)
|
const expiresAt = connectionExpiration(input, actor)
|
||||||
if (expires <= Date.now() || expires > Date.now() + 366 * 86400000) throw new McpError("INVALID_EXPIRATION", "Срок доступа должен быть от текущего времени до одного года", 400)
|
|
||||||
if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие у владельца права")
|
if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие у владельца права")
|
||||||
if (input.scope.serverIds.length) {
|
|
||||||
const { rows } = await pool.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [input.scope.serverIds])
|
|
||||||
if (rows.length !== input.scope.serverIds.length) throw new McpError("SERVER_DENIED", "Выбран неизвестный сервер", 400)
|
|
||||||
}
|
|
||||||
const id = randomUUID(), generation = await accessGeneration()
|
const id = randomUUID(), generation = await accessGeneration()
|
||||||
const { name, ...configuration } = input
|
const { name, scope: requestedScope, selectAllServers, ...configuration } = input
|
||||||
const policy = mcpConnectionPolicySchema.parse({ ...configuration, id, version: 1, status: "active" })
|
|
||||||
const token = randomToken("bearer")
|
const token = randomToken("bearer")
|
||||||
return connectionWrite(async client => {
|
return connectionWrite(async client => {
|
||||||
await lockPortalOwner(client, actor.id)
|
await lockPortalOwner(client, actor.id)
|
||||||
await assertPortalClaimsCurrent(actor, client)
|
await assertPortalClaimsCurrent(actor, client)
|
||||||
const { rows: [row] } = await client.query<ConnectionRow>("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,$2,$3,$4::jsonb,$5::jsonb,$6,$7,$8) RETURNING *", [id, name, actor.id, JSON.stringify(actor.permissions), JSON.stringify(policy), generation, ownerValidUntil(actor), new Date(actor.issuedAt ?? 0)])
|
const scope = await resolveConnectionScope(requestedScope, selectAllServers === true, client)
|
||||||
await client.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [randomUUID(), id, tokenDigest(token), input.expiresAt])
|
const policy = mcpConnectionPolicySchema.parse({ ...configuration, scope, expiresAt, id, version: 1, status: "active" })
|
||||||
|
const service = policy.authority === "service"
|
||||||
|
const { rows: [row] } = await client.query<ConnectionRow>("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,$2,$3,$4::jsonb,$5::jsonb,$6,$7,$8) RETURNING *", [id, name, actor.id, JSON.stringify(service ? policy.permissions : actor.permissions), JSON.stringify(policy), generation, service ? expiresAt : ownerValidUntil(actor), new Date(actor.issuedAt ?? 0)])
|
||||||
|
await client.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [randomUUID(), id, tokenDigest(token), expiresAt])
|
||||||
await audit(client, actor.id, "connection.create", id, { name, policy })
|
await audit(client, actor.id, "connection.create", id, { name, policy })
|
||||||
return { connection: publicConnection(row, generation), token }
|
return { connection: publicConnection(row, generation), token }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
export async function updateMcpConnection(id: string, input: McpConnectionCreate, actor: AuthUser) {
|
export async function updateMcpConnection(id: string, input: McpConnectionCreate, actor: AuthUser) {
|
||||||
|
const expiresAt = connectionExpiration(input, actor)
|
||||||
|
const service = input.authority === "service"
|
||||||
if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие права")
|
if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие права")
|
||||||
if (Date.parse(input.expiresAt) > Date.now() + 366 * 86400000) throw new McpError("INVALID_EXPIRATION", "Срок доступа не может превышать год", 400)
|
|
||||||
if (input.scope.serverIds.length && (await pool.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [input.scope.serverIds])).rows.length !== input.scope.serverIds.length) throw new McpError("SERVER_DENIED", "Выбран неизвестный сервер", 400)
|
|
||||||
return connectionWrite(async client => {
|
return connectionWrite(async client => {
|
||||||
|
if (service) {
|
||||||
|
await lockPortalOwner(client, actor.id)
|
||||||
|
await assertPortalClaimsCurrent(actor, client)
|
||||||
|
}
|
||||||
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id])
|
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id])
|
||||||
const before = await getConnection(id, client)
|
const before = await getConnection(id, client)
|
||||||
if (before.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Политику обновляет её владелец после подтверждения своих прав")
|
if (before.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Политику обновляет её владелец после подтверждения своих прав")
|
||||||
if (Date.parse(input.expiresAt) <= Date.now()) throw new McpError("INVALID_EXPIRATION", "Истёк срок доступа", 400)
|
if (before.policy.authority !== input.authority) throw new McpError("INVALID_CONFIGURATION", "Для смены типа доступа создайте новое подключение", 400)
|
||||||
const { name, ...configuration } = input
|
if (Date.parse(expiresAt) <= Date.now()) throw new McpError("INVALID_EXPIRATION", "Истёк срок доступа", 400)
|
||||||
const policy = mcpConnectionPolicySchema.parse({ ...configuration, id, version: before.policy.version + 1, status: before.policy.status })
|
const { name, scope: requestedScope, selectAllServers, ...configuration } = input
|
||||||
const { rows: [row] } = await client.query<ConnectionRow>("UPDATE mcp_connections SET name=$2,policy=$3::jsonb,owner_permissions=$4::jsonb,owner_valid_until=$5,updated_at=now() WHERE id=$1 RETURNING *", [id, name, JSON.stringify(policy), JSON.stringify(actor.permissions), ownerValidUntil(actor)])
|
const scope = await resolveConnectionScope(requestedScope, selectAllServers === true, client)
|
||||||
|
const policy = mcpConnectionPolicySchema.parse({ ...configuration, scope, expiresAt, id, version: before.policy.version + 1, status: before.policy.status })
|
||||||
|
const { rows: [row] } = await client.query<ConnectionRow>("UPDATE mcp_connections SET name=$2,policy=$3::jsonb,owner_permissions=$4::jsonb,owner_valid_until=$5,updated_at=now() WHERE id=$1 RETURNING *", [id, name, JSON.stringify(policy), JSON.stringify(service ? policy.permissions : actor.permissions), service ? before.owner_valid_until : ownerValidUntil(actor)])
|
||||||
await client.query("UPDATE mcp_plans SET state='invalidated' WHERE connection_id=$1 AND state IN ('draft','awaiting-approval','approved')", [id])
|
await client.query("UPDATE mcp_plans SET state='invalidated' WHERE connection_id=$1 AND state IN ('draft','awaiting-approval','approved')", [id])
|
||||||
await audit(client, actor.id, "connection.policy.update", id, { before: before.policy, after: policy })
|
await audit(client, actor.id, "connection.policy.update", id, { before: before.policy, after: policy })
|
||||||
return publicConnection(row, await accessGeneration())
|
return publicConnection(row, await accessGeneration())
|
||||||
@@ -169,6 +195,7 @@ export async function revalidateMcpOwner(id: string, actor: AuthUser) {
|
|||||||
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id])
|
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id])
|
||||||
const connection = await getConnection(id, client)
|
const connection = await getConnection(id, client)
|
||||||
if (connection.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Права подтверждает владелец подключения")
|
if (connection.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Права подтверждает владелец подключения")
|
||||||
|
if (connection.policy.authority === "service") throw new McpError("INVALID_CONFIGURATION", "Сервисное подключение не требует подтверждения прав владельца", 400)
|
||||||
const policy = { ...connection.policy, version: connection.policy.version + 1 }
|
const policy = { ...connection.policy, version: connection.policy.version + 1 }
|
||||||
const until = ownerValidUntil(actor)
|
const until = ownerValidUntil(actor)
|
||||||
const { rows: [row] } = await client.query<ConnectionRow>("UPDATE mcp_connections SET owner_permissions=$2::jsonb,owner_valid_until=$3,policy=$4::jsonb,owner_claims_issued_at=$5,updated_at=now() WHERE id=$1 RETURNING *", [id, JSON.stringify(actor.permissions), until, JSON.stringify(policy), new Date(actor.issuedAt ?? 0)])
|
const { rows: [row] } = await client.query<ConnectionRow>("UPDATE mcp_connections SET owner_permissions=$2::jsonb,owner_valid_until=$3,policy=$4::jsonb,owner_claims_issued_at=$5,updated_at=now() WHERE id=$1 RETURNING *", [id, JSON.stringify(actor.permissions), until, JSON.stringify(policy), new Date(actor.issuedAt ?? 0)])
|
||||||
|
|||||||
@@ -111,6 +111,30 @@ try {
|
|||||||
} finally { pool.query = originalQuery; pool.connect = originalConnect }
|
} finally { pool.query = originalQuery; pool.connect = originalConnect }
|
||||||
// Human JWT authentication stays outside the delegated MCP credential failure.
|
// Human JWT authentication stays outside the delegated MCP credential failure.
|
||||||
const connectionSql = "SELECT * FROM mcp_connections WHERE id=$1"
|
const connectionSql = "SELECT * FROM mcp_connections WHERE id=$1"
|
||||||
|
const serverChoicesUrl = "/api/mcp/server-choices"
|
||||||
|
const scopedChoicesUrl = `${serverChoicesUrl}?connectionId=${createBody.connectionId}`
|
||||||
|
const readMcp = { authorization: "Bearer " + await token(["mm:mcp:read"]) }
|
||||||
|
let catalogOwnerId = "human-admin"
|
||||||
|
const serverScopeQueries: unknown[] = []
|
||||||
|
pool.query = (async (sql: string, values?: unknown[]) => {
|
||||||
|
if (sql === connectionSql) return { rows: [{ id: createBody.connectionId, owner_id: catalogOwnerId, policy: payload.policy }] }
|
||||||
|
assert.match(sql, /^SELECT id,name,host,enabled FROM servers/)
|
||||||
|
serverScopeQueries.push(values?.[0])
|
||||||
|
return { rows: [{ id: "1", name: "CHR test", host: "router.example.test", enabled: true, password: "synthetic-hidden" }] }
|
||||||
|
}) as typeof pool.query
|
||||||
|
try {
|
||||||
|
assert.equal((await app.inject({ url: serverChoicesUrl })).statusCode, 401)
|
||||||
|
assert.equal((await app.inject({ url: serverChoicesUrl, headers: readMcp })).statusCode, 403)
|
||||||
|
const full = await app.inject({ url: serverChoicesUrl, headers: admin })
|
||||||
|
const scoped = await app.inject({ url: scopedChoicesUrl, headers: readMcp })
|
||||||
|
for (const response of [full, scoped]) {
|
||||||
|
assert.equal(response.statusCode, 200)
|
||||||
|
assert.deepEqual(response.json(), { servers: [{ id: 1, name: "CHR test", host: "router.example.test", enabled: true }] })
|
||||||
|
}
|
||||||
|
catalogOwnerId = "another-owner"
|
||||||
|
assert.equal((await app.inject({ url: scopedChoicesUrl, headers: readMcp })).statusCode, 404)
|
||||||
|
assert.deepEqual(serverScopeQueries, [null, [1]])
|
||||||
|
} finally { pool.query = originalQuery }
|
||||||
const credentialSql = `SELECT c.id,c.expires_at FROM mcp_credentials c WHERE c.connection_id=$1 AND c.kind='bearer'
|
const credentialSql = `SELECT c.id,c.expires_at FROM mcp_credentials c WHERE c.connection_id=$1 AND c.kind='bearer'
|
||||||
AND c.revoked_at IS NULL AND c.expires_at>now() AND NOT EXISTS(SELECT 1 FROM mcp_grants g WHERE g.payload->>'credentialId'=c.id::text)
|
AND c.revoked_at IS NULL AND c.expires_at>now() AND NOT EXISTS(SELECT 1 FROM mcp_grants g WHERE g.payload->>'credentialId'=c.id::text)
|
||||||
ORDER BY c.created_at DESC LIMIT 1`
|
ORDER BY c.created_at DESC LIMIT 1`
|
||||||
|
|||||||
@@ -160,6 +160,21 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent =
|
|||||||
})
|
})
|
||||||
|
|
||||||
app.get("/mcp/connections", async request => ({ connections: await listMcpConnections(actorOf(request.authUser)) }))
|
app.get("/mcp/connections", async request => ({ connections: await listMcpConnections(actorOf(request.authUser)) }))
|
||||||
|
app.get("/mcp/server-choices", async request => {
|
||||||
|
const { connectionId } = z.object({ connectionId: uuid.optional() }).strict().parse(request.query)
|
||||||
|
const actor = actorOf(request.authUser)
|
||||||
|
let serverIds: number[] | null = null
|
||||||
|
if (connectionId) {
|
||||||
|
const connection = await getConnection(connectionId)
|
||||||
|
assertConnectionVisible(connection, actor)
|
||||||
|
serverIds = connection.policy.scope.serverIds
|
||||||
|
} else if (!hasPermission(actor.permissions, "mm:mcp:admin")) {
|
||||||
|
throw new McpError("PERMISSION_DENIED", "Полный каталог доступен администратору MCP", 403)
|
||||||
|
}
|
||||||
|
const { rows } = await pool.query<{ id: string; name: string; host: string; enabled: boolean }>(
|
||||||
|
"SELECT id,name,host,enabled FROM servers WHERE $1::bigint[] IS NULL OR id=ANY($1::bigint[]) ORDER BY name,id", [serverIds])
|
||||||
|
return { servers: rows.map(row => ({ id: Number(row.id), name: row.name, host: row.host, enabled: row.enabled })) }
|
||||||
|
})
|
||||||
app.post("/mcp/connections", async request => {
|
app.post("/mcp/connections", async request => {
|
||||||
const input = mcpConnectionCreateSchema.parse(request.body)
|
const input = mcpConnectionCreateSchema.parse(request.body)
|
||||||
const available = new Set(listActions().map(action => action.operation.id))
|
const available = new Set(listActions().map(action => action.operation.id))
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto"
|
|||||||
import { channel } from "node:diagnostics_channel"
|
import { channel } from "node:diagnostics_channel"
|
||||||
import { createFlowReadResponseOwner, writeBoundedFlowSse, withFlowReadSourceWindow } from "../services/traffic-flow-read-budget.js"
|
import { createFlowReadResponseOwner, writeBoundedFlowSse, withFlowReadSourceWindow } from "../services/traffic-flow-read-budget.js"
|
||||||
import { flowReadBudget, flowResponseReadLimits, FLOW_READ_RESERVATION_BYTES, FLOW_SSE_MAX_FRAME_BYTES } from "../services/traffic-flow-read-policy.js"
|
import { flowReadBudget, flowResponseReadLimits, FLOW_READ_RESERVATION_BYTES, FLOW_SSE_MAX_FRAME_BYTES } from "../services/traffic-flow-read-policy.js"
|
||||||
|
import { readFlowWindow } from "../services/traffic-flow-read-window.js"
|
||||||
import { updateTrafficFlowSettingsWithListener } from "../services/traffic-flow-settings-service.js"
|
import { updateTrafficFlowSettingsWithListener } from "../services/traffic-flow-settings-service.js"
|
||||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||||
import { mcpDatabaseRequestSignal, withDatabaseApiRequest } from "../modules/mcp/database-request-lease.js"
|
import { mcpDatabaseRequestSignal, withDatabaseApiRequest } from "../modules/mcp/database-request-lease.js"
|
||||||
@@ -98,7 +99,7 @@ function analyticsQuery(req: FastifyRequest) {
|
|||||||
|
|
||||||
async function sendFlowTalkers(req: FastifyRequest, reply: FastifyReply) {
|
async function sendFlowTalkers(req: FastifyRequest, reply: FastifyReply) {
|
||||||
const q = req.query as { range?: string }
|
const q = req.query as { range?: string }
|
||||||
return reply.send(await listFlowTalkers(rangeToMinutes(q.range)))
|
return reply.send(await readFlowWindow(rangeToMinutes(q.range), listFlowTalkers, mcpDatabaseRequestSignal()))
|
||||||
}
|
}
|
||||||
|
|
||||||
function requestPublicHost(req: FastifyRequest): string {
|
function requestPublicHost(req: FastifyRequest): string {
|
||||||
@@ -200,20 +201,22 @@ const trafficFlowRoutes: FastifyPluginAsyncZod = async (app) => {
|
|||||||
|
|
||||||
app.get("/traffic/flow/exporters", async (req, reply) => {
|
app.get("/traffic/flow/exporters", async (req, reply) => {
|
||||||
const q = req.query as { range?: string }
|
const q = req.query as { range?: string }
|
||||||
return reply.send(await listFlowExporters(rangeToMinutes(q.range)))
|
return reply.send(await readFlowWindow(rangeToMinutes(q.range), listFlowExporters, mcpDatabaseRequestSignal()))
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get("/traffic/flow/clients", async (req, reply) => {
|
app.get("/traffic/flow/clients", async (req, reply) => {
|
||||||
const q = req.query as { range?: string }
|
const q = req.query as { range?: string }
|
||||||
return reply.send(await listFlowClients(rangeToMinutes(q.range)))
|
return reply.send(await readFlowWindow(rangeToMinutes(q.range), listFlowClients, mcpDatabaseRequestSignal()))
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get("/traffic/flow/analytics", async (req, reply) => {
|
app.get("/traffic/flow/analytics", async (req, reply) => {
|
||||||
return reply.send(await buildFlowAnalytics(analyticsQuery(req)))
|
const query = analyticsQuery(req)
|
||||||
|
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowAnalytics({ ...query, minutes }), mcpDatabaseRequestSignal()))
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get("/traffic/flow/map-hops", async (req, reply) => {
|
app.get("/traffic/flow/map-hops", async (req, reply) => {
|
||||||
return reply.send(await buildFlowMapHops(analyticsQuery(req)))
|
const query = analyticsQuery(req)
|
||||||
|
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowMapHops({ ...query, minutes }), mcpDatabaseRequestSignal()))
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get("/traffic/flow/monthly", async (req, reply) => {
|
app.get("/traffic/flow/monthly", async (req, reply) => {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
|
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
|
||||||
|
import { readFlowWindow } from "./traffic-flow-read-window.js"
|
||||||
import { isDeepStrictEqual } from "node:util"
|
import { isDeepStrictEqual } from "node:util"
|
||||||
import { readFlowSourceLimits } from "./traffic-flow-source-limits.js"
|
import { readFlowSourceLimits } from "./traffic-flow-source-limits.js"
|
||||||
import { readFlowExporterInputs, readFlowClientInputs, flowCounter, flowCounterSum } from "./traffic-flow-catalog-read.js"
|
import { readFlowExporterInputs, readFlowClientInputs, flowCounter, flowCounterSum } from "./traffic-flow-catalog-read.js"
|
||||||
@@ -664,7 +665,7 @@ export async function safeBuildLiveFlowSample(q: Omit<FlowAnalyticsQuery, "minut
|
|||||||
}> {
|
}> {
|
||||||
return formatLiveSseFromBuilder(async () => {
|
return formatLiveSseFromBuilder(async () => {
|
||||||
const skipHeavy = isFlowAnalyticsDegraded()
|
const skipHeavy = isFlowAnalyticsDegraded()
|
||||||
return await buildFlowAnalytics({ ...q, minutes: LIVE_ANALYTICS_MINUTES, skipHeavy }, scope)
|
return readFlowWindow(LIVE_ANALYTICS_MINUTES, minutes => buildFlowAnalytics({ ...q, minutes, skipHeavy }, scope))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { getFlowReadResourceProfile } from "./traffic-flow-read-resource-profile.js"
|
import { getFlowReadResourceProfile } from "./traffic-flow-read-resource-profile.js"
|
||||||
import type { QueryResultRow } from "pg"
|
import type { QueryResultRow } from "pg"
|
||||||
import { trackFlowReadSource } from "./traffic-flow-read-budget.js"
|
import { trackFlowReadSource } from "./traffic-flow-read-budget.js"
|
||||||
|
import { FlowSqlSourceTooLarge } from "./traffic-flow-read-window.js"
|
||||||
|
|
||||||
export interface FlowBoundedQueryClient {
|
export interface FlowBoundedQueryClient {
|
||||||
query(sql: string, values: unknown[]): Promise<{ rows: Array<Record<string, unknown>>; fields?:Array<{name:string}> }>
|
query(sql: string, values: unknown[]): Promise<{ rows: Array<Record<string, unknown>>; fields?:Array<{name:string}> }>
|
||||||
@@ -24,7 +25,8 @@ export async function readBoundedFlowSql<T extends QueryResultRow>(client: FlowB
|
|||||||
const preflight=await client.query(`WITH flow_read_source AS MATERIALIZED (${query}) SELECT count(*)::text AS "__flowRowCount",COALESCE(sum(octet_length(row_to_json(s)::text)),0)::text AS "__flowEncodedBytes" FROM flow_read_source s`,values)
|
const preflight=await client.query(`WITH flow_read_source AS MATERIALIZED (${query}) SELECT count(*)::text AS "__flowRowCount",COALESCE(sum(octet_length(row_to_json(s)::text)),0)::text AS "__flowEncodedBytes" FROM flow_read_source s`,values)
|
||||||
const n=String(preflight.rows[0]?.__flowRowCount),b=String(preflight.rows[0]?.__flowEncodedBytes)
|
const n=String(preflight.rows[0]?.__flowRowCount),b=String(preflight.rows[0]?.__flowEncodedBytes)
|
||||||
const measuredBytes=Number(b)+2+Math.max(Number(n)-1,0)
|
const measuredBytes=Number(b)+2+Math.max(Number(n)-1,0)
|
||||||
if(!/^\d{1,15}$/.test(n)||!/^\d{1,15}$/.test(b)||Number(n)>limits.maxRows||measuredBytes>sourceByteLimit)throw Object.assign(Error("Источник NetFlow превышает допустимый объём; сократите область или окно"),{statusCode:409,code:"STATE_UNAVAILABLE"})
|
if(!/^\d{1,15}$/.test(n)||!/^\d{1,15}$/.test(b))throw Error("Invalid bounded NetFlow source size")
|
||||||
|
if(Number(n)>limits.maxRows||measuredBytes>sourceByteLimit)throw new FlowSqlSourceTooLarge()
|
||||||
const reserved=admit(Number(n),measuredBytes)
|
const reserved=admit(Number(n),measuredBytes)
|
||||||
const countIndex = values.length + 1, bytesIndex = values.length + 2
|
const countIndex = values.length + 1, bytesIndex = values.length + 2
|
||||||
const result = await client.query(`WITH flow_read_source AS MATERIALIZED (${query}),
|
const result = await client.query(`WITH flow_read_source AS MATERIALIZED (${query}),
|
||||||
@@ -36,7 +38,8 @@ export async function readBoundedFlowSql<T extends QueryResultRow>(client: FlowB
|
|||||||
if(result.fields && ["__flowRowCount","__flowEncodedBytes","__flowPresent"].some(name=>result.fields!.filter(field=>field.name===name).length!==1))throw Error("Reserved NetFlow source column collision")
|
if(result.fields && ["__flowRowCount","__flowEncodedBytes","__flowPresent"].some(name=>result.fields!.filter(field=>field.name===name).length!==1))throw Error("Reserved NetFlow source column collision")
|
||||||
const row = result.rows[0]
|
const row = result.rows[0]
|
||||||
const count = String(row?.__flowRowCount), bytes = String(row?.__flowEncodedBytes)
|
const count = String(row?.__flowRowCount), bytes = String(row?.__flowEncodedBytes)
|
||||||
if (!row || !/^\d{1,15}$/.test(count) || !/^\d{1,15}$/.test(bytes) || Number(count) > reserved.maxRows || Number(bytes) + 2 + Math.max(Number(count)-1,0) > reserved.maxEncodedBytes) throw Object.assign(Error("Источник NetFlow превышает допустимый объём; сократите область или окно"), { statusCode: 409, code: "STATE_UNAVAILABLE" })
|
if (!row || !/^\d{1,15}$/.test(count) || !/^\d{1,15}$/.test(bytes)) throw Error("Invalid bounded NetFlow source size")
|
||||||
|
if (Number(count) > reserved.maxRows || Number(bytes) + 2 + Math.max(Number(count)-1,0) > reserved.maxEncodedBytes) throw new FlowSqlSourceTooLarge()
|
||||||
if (Number(count) === 0) return []
|
if (Number(count) === 0) return []
|
||||||
if (result.rows.length !== Number(count) || result.rows.some(item => item.__flowPresent !== true)) throw Error("Invalid bounded NetFlow SQL result")
|
if (result.rows.length !== Number(count) || result.rows.some(item => item.__flowPresent !== true)) throw Error("Invalid bounded NetFlow SQL result")
|
||||||
// Preserve the normal pg column parsers (not JSONB numeric/timestamp coercion).
|
// Preserve the normal pg column parsers (not JSONB numeric/timestamp coercion).
|
||||||
|
|||||||
@@ -18,9 +18,7 @@ export async function readFlowCatalogWindow(minutes: number, serverIds?: readonl
|
|||||||
if (selected?.length === 0) return { rows: [] as PendingFlowRow[], since, until, topRowsPerBucketLimit: null, topConversationsLimit: null }
|
if (selected?.length === 0) return { rows: [] as PendingFlowRow[], since, until, topRowsPerBucketLimit: null, topConversationsLimit: null }
|
||||||
const settings = await getTrafficFlowSettingsRow()
|
const settings = await getTrafficFlowSettingsRow()
|
||||||
if (!Number.isSafeInteger(settings.topN) || settings.topN < 1 || settings.topN > 1000) throw fail("Не подтверждён topN источника NetFlow")
|
if (!Number.isSafeInteger(settings.topN) || settings.topN < 1 || settings.topN > 1000) throw fail("Не подтверждён topN источника NetFlow")
|
||||||
const rows:PendingFlowRow[]=[]
|
const rows = await listStoredFlowRows(since, undefined, { serverIds: selected, maxRows: 49999, untilIso: until })
|
||||||
if(selected===undefined)rows.push(...await listStoredFlowRows(since,undefined,{untilIso:until}))
|
|
||||||
else for(const serverId of selected)rows.push(...await listStoredFlowRows(since,serverId,{maxRows:Math.max(1,Math.floor(50000/selected.length)),untilIso:until}))
|
|
||||||
for (const row of rows) { flowCounter(row.bytes); flowCounter(row.packets) }
|
for (const row of rows) { flowCounter(row.bytes); flowCounter(row.packets) }
|
||||||
return { rows, since, until, topRowsPerBucketLimit: Math.max(20, settings.topN), topConversationsLimit: settings.topN }
|
return { rows, since, until, topRowsPerBucketLimit: Math.max(20, settings.topN), topConversationsLimit: settings.topN }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -557,7 +557,7 @@ function pruneRecent(sinceMs = Date.now() - LIVE_WINDOW_MS): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PendingFlowReadOptions { serverId?:number; sinceIso?:string; untilIso?:string }
|
export interface PendingFlowReadOptions { serverId?:number; serverIds?:readonly number[]; sinceIso?:string; untilIso?:string }
|
||||||
export class FlowPendingReadUnconfirmed extends Error {
|
export class FlowPendingReadUnconfirmed extends Error {
|
||||||
readonly code = "FLOW_PENDING_UNCONFIRMED"
|
readonly code = "FLOW_PENDING_UNCONFIRMED"
|
||||||
constructor(readonly batchState:"running"|"unknown") { super(`NetFlow pending read unavailable: ${batchState} write batch`) }
|
constructor(readonly batchState:"running"|"unknown") { super(`NetFlow pending read unavailable: ${batchState} write batch`) }
|
||||||
@@ -566,8 +566,10 @@ function pendingReadMatches(options:PendingFlowReadOptions):(row:Pick<PendingFlo
|
|||||||
const since=options.sinceIso===undefined?-Infinity:typeof options.sinceIso==="string"?Date.parse(options.sinceIso):NaN
|
const since=options.sinceIso===undefined?-Infinity:typeof options.sinceIso==="string"?Date.parse(options.sinceIso):NaN
|
||||||
const until=options.untilIso===undefined?Infinity:typeof options.untilIso==="string"?Date.parse(options.untilIso):NaN
|
const until=options.untilIso===undefined?Infinity:typeof options.untilIso==="string"?Date.parse(options.untilIso):NaN
|
||||||
if(options.serverId!==undefined&&(!Number.isSafeInteger(options.serverId)||options.serverId<=0)||Number.isNaN(since)||Number.isNaN(until)||since>until)throw Error("Invalid pending flow read scope")
|
if(options.serverId!==undefined&&(!Number.isSafeInteger(options.serverId)||options.serverId<=0)||Number.isNaN(since)||Number.isNaN(until)||since>until)throw Error("Invalid pending flow read scope")
|
||||||
|
const serverIds = options.serverIds && new Set(options.serverIds)
|
||||||
return row=>{
|
return row=>{
|
||||||
if(options.serverId!==undefined&&row.serverId!==options.serverId)return false
|
if(options.serverId!==undefined&&row.serverId!==options.serverId)return false
|
||||||
|
if(serverIds&&!serverIds.has(row.serverId))return false
|
||||||
const time=Date.parse(row.bucketAt)
|
const time=Date.parse(row.bucketAt)
|
||||||
if(!Number.isFinite(time))throw Error("Invalid pending flow timestamp")
|
if(!Number.isFinite(time))throw Error("Invalid pending flow timestamp")
|
||||||
return time>=since&&time<=until
|
return time>=since&&time<=until
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { flowReadBucketSnapshot } from "./traffic-flow-read-policy.js"
|
import { flowReadBucketSnapshot } from "./traffic-flow-read-policy.js"
|
||||||
|
import { FlowSourceWindowTooLarge, FlowSqlSourceTooLarge } from "./traffic-flow-read-window.js"
|
||||||
import {flowIngestQualitySchema} from "@mmapp/contracts/traffic-flow"
|
import {flowIngestQualitySchema} from "@mmapp/contracts/traffic-flow"
|
||||||
import { flowLifecycleBoundary, type FlowLifecycleAuthorization } from "./traffic-flow-lifecycle-fence.js"
|
import { flowLifecycleBoundary, type FlowLifecycleAuthorization } from "./traffic-flow-lifecycle-fence.js"
|
||||||
import { flowCounter } from "./traffic-flow-observed-values.js"
|
import { flowCounter } from "./traffic-flow-observed-values.js"
|
||||||
@@ -475,12 +476,17 @@ interface StoredBucketRow {
|
|||||||
nat_dst_port: number | null
|
nat_dst_port: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listStoredFlowRows(sinceIso: string, serverId?: number, options?: { maxRows?: number; untilIso?: string }): Promise<PendingFlowRow[]> {
|
export async function listStoredFlowRows(sinceIso: string, serverId?: number, options?: { maxRows?: number; untilIso?: string; serverIds?: readonly number[] }): Promise<PendingFlowRow[]> {
|
||||||
if (options?.maxRows !== undefined && (!Number.isSafeInteger(options.maxRows) || options.maxRows < 1 || options.maxRows > 100000)) throw new Error("Некорректный предел flow rows")
|
if (options?.maxRows !== undefined && (!Number.isSafeInteger(options.maxRows) || options.maxRows < 1 || options.maxRows > 100000)) throw new Error("Некорректный предел flow rows")
|
||||||
if (options?.untilIso && !Number.isFinite(Date.parse(options.untilIso))) throw new Error("Некорректная граница flow window")
|
if (options?.untilIso && !Number.isFinite(Date.parse(options.untilIso))) throw new Error("Некорректная граница flow window")
|
||||||
const settings = options?.maxRows === undefined ? await getTrafficFlowSettingsRow() : await readFlowSourceLimits()
|
const settings = options?.maxRows === undefined ? await getTrafficFlowSettingsRow() : await readFlowSourceLimits()
|
||||||
const keep = Math.max(20, settings.topN)
|
const keep = Math.max(20, settings.topN)
|
||||||
const parameters: Array<string | number> = serverId === undefined ? [sinceIso, keep] : [sinceIso, keep, serverId]
|
const serverIds = options?.serverIds
|
||||||
|
if (serverIds !== undefined && (serverId !== undefined || serverIds.some(id => !Number.isSafeInteger(id) || id < 1))) throw new Error("Некорректная область flow rows")
|
||||||
|
if (serverIds?.length === 0) return []
|
||||||
|
const parameters: Array<string | number | readonly number[]> = [sinceIso, keep]
|
||||||
|
if (serverId !== undefined || serverIds !== undefined) parameters.push(serverId ?? serverIds!)
|
||||||
|
const serverFilter = serverId !== undefined ? "AND server_id=$3" : serverIds ? "AND server_id=ANY($3::bigint[])" : ""
|
||||||
const untilParameter = options?.untilIso ? parameters.push(options.untilIso) : undefined
|
const untilParameter = options?.untilIso ? parameters.push(options.untilIso) : undefined
|
||||||
if (options?.maxRows !== undefined) parameters.push(options.maxRows + 1)
|
if (options?.maxRows !== undefined) parameters.push(options.maxRows + 1)
|
||||||
const stored = await flowReadBucketSnapshot<StoredBucketRow>(`
|
const stored = await flowReadBucketSnapshot<StoredBucketRow>(`
|
||||||
@@ -495,12 +501,15 @@ export async function listStoredFlowRows(sinceIso: string, serverId?: number, op
|
|||||||
PARTITION BY server_id, bucket_at ORDER BY bytes DESC
|
PARTITION BY server_id, bucket_at ORDER BY bytes DESC
|
||||||
) AS rn
|
) AS rn
|
||||||
FROM flow_buckets fb
|
FROM flow_buckets fb
|
||||||
WHERE bucket_at >= $1 ${serverId === undefined ? "" : "AND server_id=$3"} ${untilParameter ? `AND bucket_at <= $${untilParameter}` : ""}
|
WHERE bucket_at >= $1 ${serverFilter} ${untilParameter ? `AND bucket_at <= $${untilParameter}` : ""}
|
||||||
) ranked
|
) ranked
|
||||||
WHERE rn <= $2
|
WHERE rn <= $2
|
||||||
${options?.maxRows !== undefined ? `LIMIT $${parameters.length}` : ""}
|
${options?.maxRows !== undefined ? `LIMIT $${parameters.length}` : ""}
|
||||||
`, parameters)
|
`, parameters).catch(error => {
|
||||||
if (options?.maxRows !== undefined && stored.length > options.maxRows) throw new Error("Превышен предел flow rows; сократите окно или число серверов")
|
if (error instanceof FlowSqlSourceTooLarge) throw new FlowSourceWindowTooLarge()
|
||||||
|
throw error
|
||||||
|
})
|
||||||
|
if (options?.maxRows !== undefined && stored.length > options.maxRows) throw new FlowSourceWindowTooLarge()
|
||||||
const merged = new Map<string, PendingFlowRow>()
|
const merged = new Map<string, PendingFlowRow>()
|
||||||
for (const r of stored) {
|
for (const r of stored) {
|
||||||
mergeInto(merged, {
|
mergeInto(merged, {
|
||||||
@@ -525,14 +534,14 @@ export async function listStoredFlowRows(sinceIso: string, serverId?: number, op
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
if (!worker) {
|
if (!worker) {
|
||||||
for (const p of peekPendingFlows({serverId,sinceIso,untilIso:options?.untilIso})) {
|
for (const p of peekPendingFlows({serverId,serverIds,sinceIso,untilIso:options?.untilIso})) {
|
||||||
if (p.bucketAt < sinceIso || options?.untilIso && p.bucketAt > options.untilIso || serverId !== undefined && p.serverId !== serverId) continue
|
if (p.bucketAt < sinceIso || options?.untilIso && p.bucketAt > options.untilIso || serverId !== undefined && p.serverId !== serverId) continue
|
||||||
flowCounter(p.bytes); flowCounter(p.packets)
|
flowCounter(p.bytes); flowCounter(p.packets)
|
||||||
mergeInto(merged, p)
|
mergeInto(merged, p)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const result = capFlowRowsPerServerBucket([...merged.values()], keep)
|
const result = capFlowRowsPerServerBucket([...merged.values()], keep)
|
||||||
if (options?.maxRows !== undefined && result.length > options.maxRows) throw new Error("Превышен предел flow rows с pending; сократите окно или число серверов")
|
if (options?.maxRows !== undefined && result.length > options.maxRows) throw new FlowSourceWindowTooLarge()
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { resetFlowRingsForTests,applyHeartbeatForTests } from './traffic-flow-in
|
|||||||
import { createFlowIngestQuality } from './traffic-flow-ingest-quality.js'
|
import { createFlowIngestQuality } from './traffic-flow-ingest-quality.js'
|
||||||
import { disableRipeEnqueueForTests } from './traffic-flow-ripe.js'
|
import { disableRipeEnqueueForTests } from './traffic-flow-ripe.js'
|
||||||
import { readFlowCatalogWindow } from './traffic-flow-catalog-read.js'
|
import { readFlowCatalogWindow } from './traffic-flow-catalog-read.js'
|
||||||
|
import { invalidateFlowAnalyticsCache } from './traffic-flow-analytics.js'
|
||||||
import { sharedDatabaseGate } from './shared-database-gate.js'
|
import { sharedDatabaseGate } from './shared-database-gate.js'
|
||||||
import { getTrafficFlowSettingsRow,invalidateTrafficFlowSettingsCache } from './traffic-flow-settings.js'
|
import { getTrafficFlowSettingsRow,invalidateTrafficFlowSettingsCache } from './traffic-flow-settings.js'
|
||||||
import { createFlowReadBudget,createFlowReadResponseOwner } from './traffic-flow-read-budget.js'
|
import { createFlowReadBudget,createFlowReadResponseOwner } from './traffic-flow-read-budget.js'
|
||||||
@@ -40,7 +41,8 @@ try{
|
|||||||
const collectorQuality=createFlowIngestQuality();collectorQuality.reject(987654,987,'aggregate-capacity')
|
const collectorQuality=createFlowIngestQuality();collectorQuality.reject(987654,987,'aggregate-capacity')
|
||||||
// Synthetic quality goes through the actual validated heartbeat receiver;
|
// Synthetic quality goes through the actual validated heartbeat receiver;
|
||||||
// this test starts no collector Worker or remote exporter.
|
// this test starts no collector Worker or remote exporter.
|
||||||
applyHeartbeatForTests({bound:false,address:null,packetsReceived:0,lastExporterIp:'',lastError:'',lastDatagramAt:null,pendingSize:0,dropped:0,rowsStored:0,workerAlive:true,rings:[],dataQuality:collectorQuality.snapshot()})
|
const heartbeat={bound:false,address:null,packetsReceived:0,lastExporterIp:'',lastError:'',lastDatagramAt:null,pendingSize:0,dropped:0,rowsStored:0,workerAlive:true,rings:[],dataQuality:collectorQuality.snapshot()}
|
||||||
|
applyHeartbeatForTests(heartbeat)
|
||||||
await readFlowCatalogWindow(5,[1])
|
await readFlowCatalogWindow(5,[1])
|
||||||
{
|
{
|
||||||
const budget=createFlowReadBudget({maxOwners:2,maxReservedBytes:200}),response=new EventEmitter() as ServerResponse,owner=createFlowReadResponseOwner(response,budget,{maxOwners:1,maxReservedBytes:100})
|
const budget=createFlowReadBudget({maxOwners:2,maxReservedBytes:200}),response=new EventEmitter() as ServerResponse,owner=createFlowReadResponseOwner(response,budget,{maxOwners:1,maxReservedBytes:100})
|
||||||
@@ -119,6 +121,45 @@ try{
|
|||||||
const scopedQuality=(result.structuredContent as {result:Record<string,unknown>}).result
|
const scopedQuality=(result.structuredContent as {result:Record<string,unknown>}).result
|
||||||
assert.equal(scopedQuality.dataQuality,null);assert.equal(scopedQuality.collectorQualityUnavailableReason,'global-telemetry-not-granted')
|
assert.equal(scopedQuality.dataQuality,null);assert.equal(scopedQuality.collectorQualityUnavailableReason,'global-telemetry-not-granted')
|
||||||
assert.ok(!JSON.stringify(result).includes('987654'),'Scoped read must not disclose collector-wide loss amounts')
|
assert.ok(!JSON.stringify(result).includes('987654'),'Scoped read must not disclose collector-wide loss amounts')
|
||||||
|
const oldFlowStart = new Date(Date.now() - 7 * 3600000)
|
||||||
|
await ensurePartitionFor(pool, 'flow_buckets', 'day', oldFlowStart)
|
||||||
|
await ensurePartitionFor(pool, 'flow_buckets', 'day', new Date(oldFlowStart.getTime() + 251 * 60000))
|
||||||
|
await pool.query(`INSERT INTO flow_buckets(server_id,bucket_at,src,dst,proto,src_port,dst_port,bytes,packets,in_iface)
|
||||||
|
SELECT 1,$1::timestamptz + minutes * interval '1 minute','198.18.3.0'::inet + host, '8.8.4.4',6,1234,443,50,1,'ether1'
|
||||||
|
FROM generate_series(0,251) minutes CROSS JOIN generate_series(1,200) host`, [oldFlowStart])
|
||||||
|
const denseRest = await fetch(endpoint+'/api/traffic/flow?range=24h')
|
||||||
|
assert.equal(denseRest.status,200)
|
||||||
|
const restWindow = (await denseRest.json() as {sourceWindow:{requestedMinutes:number;effectiveMinutes:number}}).sourceWindow
|
||||||
|
assert.equal(restWindow.requestedMinutes,1440)
|
||||||
|
assert(restWindow.effectiveMinutes<1440)
|
||||||
|
const denseMcp = await client.callTool({name:'mm_netflow_talkers_get',arguments:{serverId:1,minutes:1440}})
|
||||||
|
assert.ok(!denseMcp.isError,JSON.stringify(denseMcp))
|
||||||
|
const mcpDay = (denseMcp.structuredContent as {result:{sourceWindow:{requestedMinutes:number;effectiveMinutes:number}; retainedRowsBytes:number; from:string;to:string}}).result
|
||||||
|
assert.equal(mcpDay.sourceWindow.requestedMinutes,1440)
|
||||||
|
assert(mcpDay.sourceWindow.effectiveMinutes<1440)
|
||||||
|
assert.equal(Date.parse(mcpDay.to)-Date.parse(mcpDay.from),mcpDay.sourceWindow.effectiveMinutes*60000)
|
||||||
|
assert(!JSON.stringify(denseMcp).includes('FORBIDDEN_'))
|
||||||
|
console.log('PASS dense REST and MCP NetFlow windows report the actual safely admitted interval')
|
||||||
|
const counterStart = new Date(Date.now()-10*60000)
|
||||||
|
await ensurePartitionFor(pool,'traffic_samples','week',counterStart)
|
||||||
|
await ensurePartitionFor(pool,'traffic_samples','week',new Date(counterStart.getTime()+50010))
|
||||||
|
await pool.query(`INSERT INTO traffic_samples(server_id,interface_name,sampled_at,rx_bps,tx_bps,rx_bytes,tx_bytes)
|
||||||
|
SELECT 1,'gre-test',$1::timestamptz + n * interval '1 millisecond',n,2*n,3*n,4*n FROM generate_series(1,50010) n`,[counterStart])
|
||||||
|
await pool.query(`INSERT INTO flow_buckets(server_id,bucket_at,src,dst,proto,src_port,dst_port,bytes,packets,in_iface)
|
||||||
|
VALUES(1,$1,'198.18.1.3','8.8.8.8',6,3,443,50,1,'gre-test')`,[bucket])
|
||||||
|
applyHeartbeatForTests({...heartbeat,dataQuality:createFlowIngestQuality().snapshot()})
|
||||||
|
try {
|
||||||
|
const analytics = await fetch(endpoint+'/api/traffic/flow/analytics?range=5m&serverId=1')
|
||||||
|
assert.equal(analytics.status,200,await analytics.clone().text())
|
||||||
|
const shortReport = await analytics.json() as {bpsWire:number;bytesWire:number;sourceWindow?:unknown}
|
||||||
|
assert.equal(shortReport.bpsWire,150030)
|
||||||
|
assert.equal(shortReport.bytesWire,350070)
|
||||||
|
assert.equal(shortReport.sourceWindow,undefined)
|
||||||
|
} finally {
|
||||||
|
applyHeartbeatForTests(heartbeat)
|
||||||
|
invalidateFlowAnalyticsCache()
|
||||||
|
}
|
||||||
|
console.log('PASS five-minute REST analysis uses one latest counter per interface despite 50,010 historical samples')
|
||||||
const globalAccess=await createMcpConnection(mcpConnectionCreateSchema.parse({name:'owned global telemetry',mode:'observer',permissions:['mm:traffic:read'],expiresAt:new Date(Date.now()+600000).toISOString(),scope:{serverIds:[1],operationIds:['traffic.flow.talkers.read','netflow.settings.read'],allowGlobal:true},limits:{callsPerMinute:240}}),actor)
|
const globalAccess=await createMcpConnection(mcpConnectionCreateSchema.parse({name:'owned global telemetry',mode:'observer',permissions:['mm:traffic:read'],expiresAt:new Date(Date.now()+600000).toISOString(),scope:{serverIds:[1],operationIds:['traffic.flow.talkers.read','netflow.settings.read'],allowGlobal:true},limits:{callsPerMinute:240}}),actor)
|
||||||
const globalClient=new Client({name:'owned-global-quality',version:'1'})
|
const globalClient=new Client({name:'owned-global-quality',version:'1'})
|
||||||
try{
|
try{
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
export class FlowSqlSourceTooLarge extends Error {
|
||||||
|
readonly statusCode = 409
|
||||||
|
readonly code = "STATE_UNAVAILABLE"
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super("Источник NetFlow превышает допустимый объём; сократите область или окно")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export class FlowSourceWindowTooLarge extends FlowSqlSourceTooLarge {}
|
||||||
|
|
||||||
|
type FlowReadWindow = { requestedMinutes: number; effectiveMinutes: number }
|
||||||
|
|
||||||
|
/** Retrying a smaller historical window keeps the same response reservation.
|
||||||
|
* Only an explicit source-size refusal allows fallback; other errors propagate. */
|
||||||
|
export async function readFlowWindow<T extends object>(requestedMinutes: number, read: (minutes: number) => Promise<T>, signal?: AbortSignal): Promise<T & { sourceWindow?: FlowReadWindow }> {
|
||||||
|
let effectiveMinutes = requestedMinutes
|
||||||
|
for (;;) {
|
||||||
|
signal?.throwIfAborted()
|
||||||
|
try {
|
||||||
|
const result = await read(effectiveMinutes)
|
||||||
|
return effectiveMinutes === requestedMinutes ? result : { ...result, sourceWindow: { requestedMinutes, effectiveMinutes } }
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof FlowSourceWindowTooLarge) || effectiveMinutes <= 1) throw error
|
||||||
|
effectiveMinutes = Math.max(1, Math.floor(effectiveMinutes / (effectiveMinutes <= 15 ? 2 : 4)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -247,7 +247,6 @@ export function enGreIfaceNames(topo: FlowTopology, serverId: number, ifaceNames
|
|||||||
export async function latestWireBps(serverId: number, ifaceNames: string[], bounded = false): Promise<{ bps: number; bytes: number }> {
|
export async function latestWireBps(serverId: number, ifaceNames: string[], bounded = false): Promise<{ bps: number; bytes: number }> {
|
||||||
if (!ifaceNames.length) return { bps: 0, bytes: 0 }
|
if (!ifaceNames.length) return { bps: 0, bytes: 0 }
|
||||||
if (bounded && ifaceNames.length > 1000) throw new Error("Превышен предел физических интерфейсов NetFlow")
|
if (bounded && ifaceNames.length > 1000) throw new Error("Превышен предел физических интерфейсов NetFlow")
|
||||||
const placeholders = ifaceNames.map(() => "?").join(",")
|
|
||||||
const rows = await flowReadDbAll<{
|
const rows = await flowReadDbAll<{
|
||||||
name: string
|
name: string
|
||||||
rxBps: number
|
rxBps: number
|
||||||
@@ -255,18 +254,18 @@ export async function latestWireBps(serverId: number, ifaceNames: string[], boun
|
|||||||
rxBytes: number
|
rxBytes: number
|
||||||
txBytes: number
|
txBytes: number
|
||||||
}>(`
|
}>(`
|
||||||
SELECT ${bounded ? "DISTINCT ON (interface_name)" : ""} interface_name AS name, rx_bps AS "rxBps", tx_bps AS "txBps", rx_bytes AS "rxBytes", tx_bytes AS "txBytes"
|
SELECT iface.name, sample.rx_bps AS "rxBps", sample.tx_bps AS "txBps", sample.rx_bytes AS "rxBytes", sample.tx_bytes AS "txBytes"
|
||||||
FROM traffic_samples
|
FROM (SELECT DISTINCT unnest(?::text[]) AS name) iface
|
||||||
WHERE server_id = ? AND interface_name IN (${placeholders})
|
CROSS JOIN LATERAL (
|
||||||
ORDER BY ${bounded ? "interface_name," : ""} sampled_at DESC
|
SELECT rx_bps, tx_bps, rx_bytes, tx_bytes FROM traffic_samples
|
||||||
`, [serverId, ...ifaceNames])
|
WHERE server_id = ? AND interface_name = iface.name
|
||||||
const seen = new Set<string>()
|
ORDER BY sampled_at DESC LIMIT 1
|
||||||
|
) sample
|
||||||
|
`, [ifaceNames, serverId])
|
||||||
let bps = 0
|
let bps = 0
|
||||||
let bytes = 0
|
let bytes = 0
|
||||||
for (const r of rows) {
|
for (const r of rows) {
|
||||||
if (bounded && ([r.rxBps,r.txBps].some(value => value === null || !Number.isFinite(Number(value)) || Number(value) < 0 || Number(value) > Number.MAX_SAFE_INTEGER) || [r.rxBytes,r.txBytes].some(value => value === null || !Number.isSafeInteger(Number(value)) || Number(value) < 0))) throw new Error("Не подтверждены физические счётчики NetFlow")
|
if (bounded && ([r.rxBps,r.txBps].some(value => value === null || !Number.isFinite(Number(value)) || Number(value) < 0 || Number(value) > Number.MAX_SAFE_INTEGER) || [r.rxBytes,r.txBytes].some(value => value === null || !Number.isSafeInteger(Number(value)) || Number(value) < 0))) throw new Error("Не подтверждены физические счётчики NetFlow")
|
||||||
if (seen.has(r.name)) continue
|
|
||||||
seen.add(r.name)
|
|
||||||
bps += (Number(r.rxBps) || 0) + (Number(r.txBps) || 0)
|
bps += (Number(r.rxBps) || 0) + (Number(r.txBps) || 0)
|
||||||
bytes += (Number(r.rxBytes) || 0) + (Number(r.txBytes) || 0)
|
bytes += (Number(r.rxBytes) || 0) + (Number(r.txBytes) || 0)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
|
|||||||
import { useSearchParams } from "next/navigation"
|
import { useSearchParams } from "next/navigation"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { useTable, type ColumnDef } from "@tanstack/react-table"
|
import { useTable, type ColumnDef } from "@tanstack/react-table"
|
||||||
import { BotIcon, CopyIcon, PlusIcon, RefreshCwIcon, ShieldIcon, StopCircleIcon } from "lucide-react"
|
import { BotIcon, CheckIcon, CopyIcon, PlusIcon, RefreshCwIcon, ServerIcon, ShieldIcon, StopCircleIcon } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { mcpConnectionCreateSchema, mcpPageQuerySchema, mcpTargetSchema, type McpConnection, type McpOperationDescriptor, type McpPolicyDecision } from "@mmapp/contracts/mcp"
|
import { mcpConnectionCreateSchema, mcpPageQuerySchema, mcpTargetSchema, type McpConnection, type McpOperationDescriptor, type McpPolicyDecision } from "@mmapp/contracts/mcp"
|
||||||
import { routeAiControllerBlockReason, routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
import { routeAiControllerBlockReason, routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||||
@@ -25,6 +25,7 @@ import { Badge } from "@/components/reui/badge"
|
|||||||
import { Button, buttonVariants } from "@/components/ui/button"
|
import { Button, buttonVariants } from "@/components/ui/button"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
import { Checkbox } from "@/components/ui/checkbox"
|
import { Checkbox } from "@/components/ui/checkbox"
|
||||||
|
import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item"
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
|
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"
|
||||||
@@ -157,19 +158,15 @@ function DeviceEditor({ api, connectionId, serverId, resource }: { api: McpApi;
|
|||||||
function TokenDialog({ token, close, connectionName }: { token: string; close: () => void; connectionName?: string }) {
|
function TokenDialog({ token, close, connectionName }: { token: string; close: () => void; connectionName?: string }) {
|
||||||
return <Dialog open={!!token} onOpenChange={open => { if (!open) close() }}><DialogContent className="sm:max-w-xl"><DialogHeader><DialogTitle>Доступ создан</DialogTitle><DialogDescription>{connectionName && `Подключение «${connectionName}». `}Сохраните токен в настройках AI-клиента. Повторно посмотреть его нельзя.</DialogDescription></DialogHeader><Input aria-label="Одноразовый токен MCP" readOnly type="password" value={token} /><Button onClick={() => { void navigator.clipboard.writeText(token).then(() => toast.success("Токен скопирован"), () => toast.error("Не удалось скопировать токен")) }}><CopyIcon />Копировать</Button><Button variant="outline" onClick={close}>Закрыть и скрыть токен</Button></DialogContent></Dialog>
|
return <Dialog open={!!token} onOpenChange={open => { if (!open) close() }}><DialogContent className="sm:max-w-xl"><DialogHeader><DialogTitle>Доступ создан</DialogTitle><DialogDescription>{connectionName && `Подключение «${connectionName}». `}Сохраните токен в настройках AI-клиента. Повторно посмотреть его нельзя.</DialogDescription></DialogHeader><Input aria-label="Одноразовый токен MCP" readOnly type="password" value={token} /><Button onClick={() => { void navigator.clipboard.writeText(token).then(() => toast.success("Токен скопирован"), () => toast.error("Не удалось скопировать токен")) }}><CopyIcon />Копировать</Button><Button variant="outline" onClick={close}>Закрыть и скрыть токен</Button></DialogContent></Dialog>
|
||||||
}
|
}
|
||||||
function ConnectionForm({ api, operations, editing, close, created }: { api: McpApi; operations: McpOperationDescriptor[]; editing?: McpConnection; close: () => void; created: (token?: string) => void }) {
|
function OperationChoices({ operations, selected, onChange, selectAllLabel = "Выбрать все операции" }: {
|
||||||
const [step, setStep] = useState(1), [busy, setBusy] = useState(false), [error, setError] = useState("")
|
operations: McpOperationDescriptor[]
|
||||||
const [name, setName] = useState(editing?.name ?? ""), [mode, setMode] = useState<McpConnection["policy"]["mode"]>(editing?.policy.mode ?? "observer")
|
selected: string[]
|
||||||
const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState<string[]>(editing?.policy.scope.operationIds ?? [])
|
onChange: (ids: string[]) => void
|
||||||
const [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval")
|
selectAllLabel?: string
|
||||||
const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? [])
|
}) {
|
||||||
const [expires, setExpires] = useState(() => editing?.policy.expiresAt.slice(0, 16) ?? new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 16))
|
|
||||||
const [limits, setLimits] = useState(editing?.policy.limits ?? { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 })
|
|
||||||
const permissions = getClaims()?.permissions ?? []
|
|
||||||
const eligible = operations.filter(operation => operation.implementation === "available" && operation.requiredPermissions.every(permission => hasPermission(permissions, permission)))
|
|
||||||
const selectedIds = new Set(selected)
|
const selectedIds = new Set(selected)
|
||||||
const bySection = new Map<string, McpOperationDescriptor[]>()
|
const bySection = new Map<string, McpOperationDescriptor[]>()
|
||||||
for (const operation of eligible) {
|
for (const operation of operations) {
|
||||||
const group = bySection.get(operation.section)
|
const group = bySection.get(operation.section)
|
||||||
if (group) group.push(operation)
|
if (group) group.push(operation)
|
||||||
else bySection.set(operation.section, [operation])
|
else bySection.set(operation.section, [operation])
|
||||||
@@ -178,46 +175,105 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
|||||||
.sort(([left], [right]) => (operationSectionLabels[left] ?? left).localeCompare(operationSectionLabels[right] ?? right, "ru"))
|
.sort(([left], [right]) => (operationSectionLabels[left] ?? left).localeCompare(operationSectionLabels[right] ?? right, "ru"))
|
||||||
const selectOperations = (operations: McpOperationDescriptor[], checked: boolean) => {
|
const selectOperations = (operations: McpOperationDescriptor[], checked: boolean) => {
|
||||||
const groupIds = new Set(operations.map(operation => operation.id))
|
const groupIds = new Set(operations.map(operation => operation.id))
|
||||||
setSelected(ids => checked ? [...new Set([...ids, ...groupIds])] : ids.filter(id => !groupIds.has(id)))
|
onChange(checked ? [...new Set([...selected, ...groupIds])] : selected.filter(id => !groupIds.has(id)))
|
||||||
}
|
}
|
||||||
|
return <>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" disabled={!operations.length} onClick={() => onChange(operations.map(operation => operation.id))}>{selectAllLabel}</Button>
|
||||||
|
<Button variant="ghost" size="sm" disabled={!selected.length} onClick={() => onChange([])}>Снять все</Button>
|
||||||
|
<span className="text-sm text-muted-foreground" role="status">Выбрано {selected.length}</span>
|
||||||
|
</div>
|
||||||
|
<div className="max-h-80 space-y-2 overflow-y-auto">
|
||||||
|
{groups.map(([section, items]) => {
|
||||||
|
const title = operationSectionLabels[section] ?? section
|
||||||
|
const count = items.filter(operation => selectedIds.has(operation.id)).length
|
||||||
|
return <div key={section} className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-3 rounded-md border p-3">
|
||||||
|
<Checkbox aria-label={`Все операции группы «${title}»`} className="mt-0.5" checked={count === items.length} indeterminate={count > 0 && count < items.length} onCheckedChange={checked => selectOperations(items, checked)} />
|
||||||
|
<details>
|
||||||
|
<summary className="cursor-pointer text-sm font-medium">{title} <span className="ms-1 font-normal text-muted-foreground">{count} / {items.length}</span></summary>
|
||||||
|
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
||||||
|
{items.map(operation => <Choice key={operation.id} label={operation.title} checked={selectedIds.has(operation.id)} onChange={checked => selectOperations([operation], checked)} />)}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
})}
|
||||||
|
{!operations.length && <p className="text-sm text-muted-foreground">Нет доступных операций.</p>}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
function ServerChoices({ catalog, selected, onChange, all, onAllChange, forGrant = false }: {
|
||||||
|
catalog: { data: Awaited<ReturnType<McpApi["serverChoices"]>> | null; error: string; refresh: () => void }
|
||||||
|
selected: number[]
|
||||||
|
onChange: (ids: number[]) => void
|
||||||
|
all: boolean
|
||||||
|
onAllChange: (value: boolean) => void
|
||||||
|
forGrant?: boolean
|
||||||
|
}) {
|
||||||
|
const servers = catalog.data?.servers ?? []
|
||||||
|
const unknown = catalog.data ? selected.filter(id => !servers.some(server => server.id === id)) : []
|
||||||
|
return <fieldset className="min-w-0 space-y-2">
|
||||||
|
<legend className="mb-2 text-sm font-medium">{forGrant ? "Серверы временного допуска" : "Разрешённые серверы"}</legend>
|
||||||
|
<Choice label={forGrant ? "Все серверы подключения" : "Все серверы"} checked={all} onChange={onAllChange} />
|
||||||
|
{all ? <><p className="text-sm text-muted-foreground">{forGrant ? "Выбраны серверы, разрешённые основному подключению." : "Доступ получат все серверы, зарегистрированные на момент сохранения."}</p>{forGrant && <ErrorMessage message={catalog.error} />}</> : <>
|
||||||
|
<div className="grid max-h-60 gap-2 overflow-y-auto p-1 sm:grid-cols-2" aria-label="Карточки серверов" role="group">
|
||||||
|
{servers.map(server => {
|
||||||
|
const active = selected.includes(server.id), title = server.name || server.host
|
||||||
|
return <Item key={server.id} variant="outline" size="sm" className="cursor-pointer text-left hover:bg-muted aria-pressed:border-primary aria-pressed:bg-accent"
|
||||||
|
render={<button type="button" aria-label={title} aria-pressed={active} />}
|
||||||
|
onClick={() => onChange(active ? selected.filter(id => id !== server.id) : [...selected, server.id])}>
|
||||||
|
<ItemMedia variant="icon"><ServerIcon /></ItemMedia>
|
||||||
|
<ItemContent className="min-w-0"><ItemTitle className="block max-w-full truncate">{title}</ItemTitle><ItemDescription className="break-all">{server.host !== title ? `${server.host} · ` : ""}ID {server.id}{!server.enabled && " · отключён"}</ItemDescription></ItemContent>
|
||||||
|
{active && <CheckIcon className="size-4 shrink-0" aria-hidden="true" />}
|
||||||
|
</Item>
|
||||||
|
})}
|
||||||
|
{unknown.map(id => <Button key={id} variant="outline" onClick={() => onChange(selected.filter(value => value !== id))}>Убрать отсутствующий сервер №{id}</Button>)}
|
||||||
|
</div>
|
||||||
|
{catalog.error && <><ErrorMessage message={catalog.error} /><Button variant="outline" size="sm" onClick={catalog.refresh}>Обновить список серверов</Button></>}
|
||||||
|
{!catalog.data && !catalog.error && <p role="status" className="text-sm text-muted-foreground">Загрузка серверов…</p>}
|
||||||
|
{catalog.data && <p className="text-sm text-muted-foreground">{selected.length ? `Выбрано серверов: ${selected.length}` : "Серверы не выбраны. Доступ к ним закрыт."}</p>}
|
||||||
|
</>}
|
||||||
|
</fieldset>
|
||||||
|
}
|
||||||
|
function ConnectionForm({ api, operations, editing, close, created }: { api: McpApi; operations: McpOperationDescriptor[]; editing?: McpConnection; close: () => void; created: (token?: string) => void }) {
|
||||||
|
const [step, setStep] = useState(1), [busy, setBusy] = useState(false), [error, setError] = useState("")
|
||||||
|
const [name, setName] = useState(editing?.name ?? ""), [mode, setMode] = useState<McpConnection["policy"]["mode"]>(editing?.policy.mode ?? "observer")
|
||||||
|
const [service, setService] = useState(editing?.policy.authority === "service")
|
||||||
|
const [selectAllServers, setSelectAllServers] = useState(false)
|
||||||
|
const [serverIds, setServerIds] = useState(editing?.policy.scope.serverIds ?? []), [selected, setSelected] = useState<string[]>(editing?.policy.scope.operationIds ?? [])
|
||||||
|
const serverCatalog = useQuery(useCallback(signal => api.serverChoices(undefined, signal), [api]))
|
||||||
|
const [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval")
|
||||||
|
const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? [])
|
||||||
|
const [expires, setExpires] = useState(() => editing?.policy.expiresAt.slice(0, 16) ?? new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 16))
|
||||||
|
const [limits, setLimits] = useState(editing?.policy.limits ?? { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 })
|
||||||
|
const permissions = getClaims()?.permissions ?? []
|
||||||
|
const eligible = operations.filter(operation => operation.implementation === "available" && operation.requiredPermissions.every(permission => hasPermission(permissions, permission)))
|
||||||
|
const selectedIds = new Set(selected)
|
||||||
|
const dangerous = eligible.filter(operation => operation.risk === "dangerous" && selectedIds.has(operation.id))
|
||||||
|
const autonomousDangerIds = dangerous.filter(operation => dangerIds.includes(operation.id)).map(operation => operation.id)
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
setBusy(true); setError("")
|
setBusy(true); setError("")
|
||||||
try {
|
try {
|
||||||
const input = mcpConnectionCreateSchema.parse({ name, mode, expiresAt: new Date(expires + "Z").toISOString(), permissions: [...new Set(eligible.filter(operation => selected.includes(operation.id)).flatMap(operation => operation.requiredPermissions))], scope: { serverIds: serverText.split(/[,\s]+/).filter(Boolean).map(Number), operationIds: selected, allowGlobal: global }, dangerousPolicy: danger, autonomousDangerousOperationIds: dangerIds.filter(id => selected.includes(id)), limits })
|
const input = mcpConnectionCreateSchema.parse({ name, ...(service ? { authority: "service", mode: "autonomous", expiresAt: null } : { mode, expiresAt: new Date(expires + "Z").toISOString() }), permissions: [...new Set(eligible.filter(operation => selected.includes(operation.id)).flatMap(operation => operation.requiredPermissions))], ...(selectAllServers && { selectAllServers: true }), scope: { serverIds: selectAllServers ? [] : serverIds, operationIds: selected, allowGlobal: global }, dangerousPolicy: service ? "approval" : danger, autonomousDangerousOperationIds: service || danger !== "explicit-allow" ? [] : autonomousDangerIds, limits })
|
||||||
if (editing) { await api.update(editing.id, input); created() }
|
if (editing) { await api.update(editing.id, input); created() }
|
||||||
else { const result = await api.create(input); created(result.token) }
|
else { const result = await api.create(input); created(result.token) }
|
||||||
} catch (failure) { setError(errorText(failure)) } finally { setBusy(false) }
|
} catch (failure) { setError(errorText(failure)) } finally { setBusy(false) }
|
||||||
}
|
}
|
||||||
return <Dialog open onOpenChange={open => { if (!open && !busy) close() }}><DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl"><DialogHeader><DialogTitle>{editing ? "Изменить разрешения" : "Новое подключение"}</DialogTitle><DialogDescription>Шаг {step} из 4 · доступ ограничивается правами текущего владельца.</DialogDescription></DialogHeader><ErrorMessage message={error} />
|
return <Dialog open onOpenChange={open => { if (!open && !busy) close() }}><DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl"><DialogHeader><DialogTitle>{editing ? "Изменить разрешения" : "Новое подключение"}</DialogTitle><DialogDescription>Шаг {step} из 4 · доступ ограничивается правами текущего владельца.</DialogDescription></DialogHeader><ErrorMessage message={error} />
|
||||||
{step === 1 && <><Field label="Название"><Input value={name} onChange={event => setName(event.target.value)} placeholder="Агент диагностики" /></Field><Field label="Срок действия (UTC)"><Input type="datetime-local" value={expires} onChange={event => setExpires(event.target.value)} /></Field><NativeSelect label="Режим управления" value={mode} onChange={value => setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => <option key={value} value={value}>{title}</option>)}</NativeSelect></>}
|
{step === 1 && <><Field label="Название"><Input value={name} onChange={event => setName(event.target.value)} placeholder="Агент диагностики" /></Field>{!editing && <NativeSelect label="Тип подключения" value={service ? "service" : "personal"} onChange={value => setService(value === "service")}><option value="personal">Личное</option><option value="service">Сервисное — бессрочный автономный доступ</option></NativeSelect>}
|
||||||
|
{service
|
||||||
|
? <p className="text-sm text-muted-foreground">Подключение действует до отзыва. Агент выполняет разрешённые обычные операции автономно, а опасные действия требуют подтверждения.</p>
|
||||||
|
: <><Field label="Срок действия (UTC)"><Input type="datetime-local" value={expires} onChange={event => setExpires(event.target.value)} /></Field><NativeSelect label="Режим управления" value={mode} onChange={value => setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => <option key={value} value={value}>{title}</option>)}</NativeSelect></>}</>}
|
||||||
{step === 2 && <>
|
{step === 2 && <>
|
||||||
<Field label="ID разрешённых серверов через запятую"><Input value={serverText} onChange={event => setServerText(event.target.value)} placeholder="1, 2" /></Field>
|
<ServerChoices catalog={serverCatalog} selected={serverIds} onChange={setServerIds} all={selectAllServers} onAllChange={setSelectAllServers} />
|
||||||
<Choice label="Разрешить выбранные глобальные операции" checked={global} onChange={setGlobal} />
|
<Choice label="Разрешить выбранные глобальные операции" checked={global} onChange={setGlobal} />
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<OperationChoices operations={eligible} selected={selected} onChange={setSelected} />
|
||||||
<Button variant="outline" size="sm" disabled={!eligible.length} onClick={() => setSelected(eligible.map(operation => operation.id))}>Выбрать все операции</Button>
|
|
||||||
<Button variant="ghost" size="sm" disabled={!selected.length} onClick={() => setSelected([])}>Снять все</Button>
|
|
||||||
<span className="text-sm text-muted-foreground" role="status">Выбрано {selected.length}</span>
|
|
||||||
</div>
|
|
||||||
<div className="max-h-80 space-y-2 overflow-y-auto">
|
|
||||||
{groups.map(([section, items]) => {
|
|
||||||
const title = operationSectionLabels[section] ?? section
|
|
||||||
const count = items.filter(operation => selectedIds.has(operation.id)).length
|
|
||||||
return <div key={section} className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-3 rounded-md border p-3">
|
|
||||||
<Checkbox aria-label={`Все операции группы «${title}»`} className="mt-0.5" checked={count === items.length} indeterminate={count > 0 && count < items.length} onCheckedChange={checked => selectOperations(items, checked)} />
|
|
||||||
<details>
|
|
||||||
<summary className="cursor-pointer text-sm font-medium">{title} <span className="ms-1 font-normal text-muted-foreground">{count} / {items.length}</span></summary>
|
|
||||||
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
|
||||||
{items.map(operation => <Choice key={operation.id} label={operation.title} checked={selectedIds.has(operation.id)} onChange={checked => selectOperations([operation], checked)} />)}
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
})}
|
|
||||||
{!eligible.length && <p className="text-sm text-muted-foreground">Нет доступных операций.</p>}
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground">Выбор операций учитывает права владельца. Режим, список серверов и глобальный доступ задаются отдельно. Новые инструменты нужно добавлять вручную. Для применения планов выберите также инструменты просмотра и применения.</p>
|
<p className="text-xs text-muted-foreground">Выбор операций учитывает права владельца. Режим, список серверов и глобальный доступ задаются отдельно. Новые инструменты нужно добавлять вручную. Для применения планов выберите также инструменты просмотра и применения.</p>
|
||||||
</>}
|
</>}
|
||||||
{step === 3 && <><div className="grid gap-3 sm:grid-cols-2">{Object.entries(limits).map(([key, value]) => <Field key={key} label={({ callsPerMinute: "Вызовов в минуту", concurrentReads: "Одновременных чтений", mutationsPerHour: "Изменений в час", serversPerPlan: "Серверов на план", objectsPerPlan: "Объектов на план" } as Record<string, string>)[key]}><Input type="number" min={1} value={value} onChange={event => setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} /></Field>)}</div><NativeSelect label="Опасные действия" value={danger} onChange={value => setDanger(value as typeof danger)}><option value="approval">Всегда подтверждать</option><option value="explicit-allow">Автономно для явно выбранных действий</option></NativeSelect>{danger === "explicit-allow" && eligible.filter(operation => operation.risk === "dangerous" && selected.includes(operation.id)).map(operation => <Choice key={operation.id} label={operation.title} checked={dangerIds.includes(operation.id)} onChange={checked => setDangerIds(ids => checked ? [...ids, operation.id] : ids.filter(id => id !== operation.id))} />)}</>}
|
{step === 3 && <><div className="grid gap-3 sm:grid-cols-2">{Object.entries(limits).map(([key, value]) => <Field key={key} label={({ callsPerMinute: "Вызовов в минуту", concurrentReads: "Одновременных чтений", mutationsPerHour: "Изменений в час", serversPerPlan: "Серверов на план", objectsPerPlan: "Объектов на план" } as Record<string, string>)[key]}><Input type="number" min={1} value={value} onChange={event => setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} /></Field>)}</div>{service ? <p className="text-sm text-muted-foreground">Опасные действия всегда требуют подтверждения.</p> : <><NativeSelect label="Опасные действия" value={danger} onChange={value => setDanger(value as typeof danger)}><option value="approval">Всегда подтверждать</option><option value="explicit-allow">Автономно для явно выбранных действий</option></NativeSelect>{danger === "explicit-allow" && <>
|
||||||
{step === 4 && <div className="space-y-3 text-sm"><p><strong>{name || "Без названия"}</strong> · {modeLabels[mode]}</p><p>Серверы: {serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.</p><p>Защита объектов продолжает действовать независимо от автономных разрешений.</p><p>После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».</p></div>}
|
<p className="text-sm text-muted-foreground">В автономном режиме выбранные здесь опасные операции смогут выполняться без подтверждения, если этого не требует защита объекта или сама операция.</p>
|
||||||
|
<OperationChoices operations={dangerous} selected={autonomousDangerIds} onChange={setDangerIds} selectAllLabel="Выбрать все опасные операции" />
|
||||||
|
</>}</>}</>}
|
||||||
|
{step === 4 && <div className="space-y-3 text-sm"><p><strong>{name || "Без названия"}</strong> · {service ? "Сервисное, бессрочное" : modeLabels[mode]}</p><p>Серверы: {selectAllServers ? "все на момент сохранения" : serverIds.join(", ") || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.</p>{!service && mode === "autonomous" && danger === "explicit-allow" && <p>Опасных операций выбрано для автономного выполнения: {autonomousDangerIds.length}.</p>}<p>Защита объектов продолжает действовать независимо от автономных разрешений.</p><p>После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».</p></div>}
|
||||||
<div className="flex flex-wrap justify-between gap-2"><Button variant="outline" disabled={busy} onClick={() => step > 1 ? setStep(step - 1) : close()}>{step > 1 ? "Назад" : "Отмена"}</Button>{step < 4 ? <Button onClick={() => setStep(step + 1)}>Далее</Button> : <Button disabled={busy} onClick={() => { void save() }}>{busy ? "Сохранение…" : "Сохранить доступ"}</Button>}</div>
|
<div className="flex flex-wrap justify-between gap-2"><Button variant="outline" disabled={busy} onClick={() => step > 1 ? setStep(step - 1) : close()}>{step > 1 ? "Назад" : "Отмена"}</Button>{step < 4 ? <Button onClick={() => setStep(step + 1)}>Далее</Button> : <Button disabled={busy} onClick={() => { void save() }}>{busy ? "Сохранение…" : "Сохранить доступ"}</Button>}</div>
|
||||||
</DialogContent></Dialog>
|
</DialogContent></Dialog>
|
||||||
}
|
}
|
||||||
@@ -238,9 +294,9 @@ function Connections({ api, operations }: { api: McpApi; operations: McpOperatio
|
|||||||
} },
|
} },
|
||||||
{ id: "mode", header: "Режим", cell: ({ row }) => modeLabels[(row.original.policy as McpConnection["policy"]).mode] },
|
{ id: "mode", header: "Режим", cell: ({ row }) => modeLabels[(row.original.policy as McpConnection["policy"]).mode] },
|
||||||
{ id: "status", header: "Состояние доступа", size: 260, cell: ({ row }) => <ConnectionAccessStatus connection={row.original as unknown as McpConnection} /> },
|
{ id: "status", header: "Состояние доступа", size: 260, cell: ({ row }) => <ConnectionAccessStatus connection={row.original as unknown as McpConnection} /> },
|
||||||
{ id: "expiresAt", header: "Доступ до", size: 170, cell: ({ row }) => date((row.original.policy as McpConnection["policy"]).expiresAt) },
|
{ id: "expiresAt", header: "Доступ до", size: 170, cell: ({ row }) => { const policy = row.original.policy as McpConnection["policy"]; return policy.authority === "service" ? "Бессрочно" : date(policy.expiresAt) } },
|
||||||
{ accessorKey: "lastUsedAt", header: "Последний вызов", cell: ({ row }) => date(row.original.lastUsedAt) },
|
{ accessorKey: "lastUsedAt", header: "Последний вызов", cell: ({ row }) => date(row.original.lastUsedAt) },
|
||||||
{ id: "ownerValidation", header: "Права владельца до", size: 190, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return <div className="flex flex-col gap-1"><span className="text-xs">{date(connection.ownerValidUntil)}</span>{connection.ownerId === getClaims()?.sub && <Button size="sm" variant="outline" disabled={!connection.generationValid || connection.policy.status === "revoked"} onClick={() => { void act(() => api.revalidate(connection.id)) }}>Обновить мои права</Button>}</div> } },
|
{ id: "ownerValidation", header: "Права владельца до", size: 190, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return connection.policy.authority === "service" ? "Сервисный доступ" : <div className="flex flex-col gap-1"><span className="text-xs">{date(connection.ownerValidUntil)}</span>{connection.ownerId === getClaims()?.sub && <Button size="sm" variant="outline" disabled={!connection.generationValid || connection.policy.status === "revoked"} onClick={() => { void act(() => api.revalidate(connection.id)) }}>Обновить мои права</Button>}</div> } },
|
||||||
{ id: "actions", header: "Действия", size: 350, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return admin && <div className="flex flex-wrap gap-1"><Button size="sm" variant="outline" onClick={() => setEditing(connection)}>Разрешения</Button><Button size="sm" variant="outline" disabled={connection.policy.status === "revoked"} onClick={() => { void act(() => api.status(connection.id, connection.policy.status === "active" ? "paused" : "active")) }}>{connection.policy.status === "active" ? "Пауза" : "Включить"}</Button><Button size="sm" variant="outline" disabled={connection.policy.status === "revoked"} onClick={() => { if (window.confirm("Отозвать доступ подключения и все его токены?")) void act(() => api.status(connection.id, "revoked")) }}>Отозвать</Button><Button size="sm" variant="ghost" disabled={connection.policy.status === "revoked"} onClick={() => { if (window.confirm("Заменить токен? Старый токен перестанет работать.")) void act(async () => setToken((await api.rotate(connection.id)).token)) }}>Новый токен</Button></div> } },
|
{ id: "actions", header: "Действия", size: 350, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return admin && <div className="flex flex-wrap gap-1"><Button size="sm" variant="outline" onClick={() => setEditing(connection)}>Разрешения</Button><Button size="sm" variant="outline" disabled={connection.policy.status === "revoked"} onClick={() => { void act(() => api.status(connection.id, connection.policy.status === "active" ? "paused" : "active")) }}>{connection.policy.status === "active" ? "Пауза" : "Включить"}</Button><Button size="sm" variant="outline" disabled={connection.policy.status === "revoked"} onClick={() => { if (window.confirm("Отозвать доступ подключения и все его токены?")) void act(() => api.status(connection.id, "revoked")) }}>Отозвать</Button><Button size="sm" variant="ghost" disabled={connection.policy.status === "revoked"} onClick={() => { if (window.confirm("Заменить токен? Старый токен перестанет работать.")) void act(async () => setToken((await api.rotate(connection.id)).token)) }}>Новый токен</Button></div> } },
|
||||||
], [api, admin, act])
|
], [api, admin, act])
|
||||||
return <><Panel title="Подключения" description="Токены, сроки и разрешения AI-клиентов" actions={admin && <Button onClick={() => setEditing("new")}><PlusIcon />Выдать доступ</Button>}><ErrorMessage message={query.error} /><Grid items={(query.data?.connections ?? []) as unknown as RecordRow[]} columns={columns} loading={!query.data && !query.error} /><p className="text-sm text-muted-foreground">HTTP endpoint: адрес backend + /mcp. Для stdio используйте MCP_URL и MCP_TOKEN с командой npm --prefix backend run mcp:stdio.</p></Panel>{editing && <ConnectionForm api={api} operations={operations} editing={editing === "new" ? undefined : editing} close={() => setEditing(null)} created={value => { setEditing(null); if (value) setToken(value); query.refresh() }} />}<TokenDialog token={token} close={() => setToken("")} /></>
|
return <><Panel title="Подключения" description="Токены, сроки и разрешения AI-клиентов" actions={admin && <Button onClick={() => setEditing("new")}><PlusIcon />Выдать доступ</Button>}><ErrorMessage message={query.error} /><Grid items={(query.data?.connections ?? []) as unknown as RecordRow[]} columns={columns} loading={!query.data && !query.error} /><p className="text-sm text-muted-foreground">HTTP endpoint: адрес backend + /mcp. Для stdio используйте MCP_URL и MCP_TOKEN с командой npm --prefix backend run mcp:stdio.</p></Panel>{editing && <ConnectionForm api={api} operations={operations} editing={editing === "new" ? undefined : editing} close={() => setEditing(null)} created={value => { setEditing(null); if (value) setToken(value); query.refresh() }} />}<TokenDialog token={token} close={() => setToken("")} /></>
|
||||||
@@ -289,8 +345,11 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
|
|||||||
grantBusy: boolean
|
grantBusy: boolean
|
||||||
}) {
|
}) {
|
||||||
const [result, setResult] = useState<Awaited<ReturnType<McpApi["check"]>> | null>(null)
|
const [result, setResult] = useState<Awaited<ReturnType<McpApi["check"]>> | null>(null)
|
||||||
const [operations, setOperations] = useState<string[]>([]), [serverText, setServerText] = useState(""), [minutes, setMinutes] = useState(60), [global, setGlobal] = useState(false)
|
const [serverIds, setServerIds] = useState<number[]>([]), [selectAllServers, setSelectAllServers] = useState(false)
|
||||||
|
const [operations, setOperations] = useState<string[]>([]), [minutes, setMinutes] = useState(60), [global, setGlobal] = useState(false)
|
||||||
const connectionId = connection.id
|
const connectionId = connection.id
|
||||||
|
const serverCatalog = useQuery(useCallback(signal => api.serverChoices(connectionId, signal), [api, connectionId]), connectionId)
|
||||||
|
const grantServers = selectAllServers ? serverCatalog.data?.servers.map(server => server.id) ?? [] : serverIds
|
||||||
const grants = useQuery(useCallback(signal => api.grants(connectionId, signal), [api, connectionId]))
|
const grants = useQuery(useCallback(signal => api.grants(connectionId, signal), [api, connectionId]))
|
||||||
const checkRevision = useRef(0)
|
const checkRevision = useRef(0)
|
||||||
useEffect(() => () => { checkRevision.current++ }, [])
|
useEffect(() => () => { checkRevision.current++ }, [])
|
||||||
@@ -311,7 +370,7 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
|
|||||||
try {
|
try {
|
||||||
void issue({
|
void issue({
|
||||||
id: crypto.randomUUID(), startsAt: now.toISOString(), expiresAt: expires.toISOString(),
|
id: crypto.randomUUID(), startsAt: now.toISOString(), expiresAt: expires.toISOString(),
|
||||||
scope: { serverIds: serverText.split(",").map(value => value.trim()).filter(Boolean).map(Number), operationIds: operations, allowGlobal: global },
|
scope: { serverIds: grantServers, operationIds: operations, allowGlobal: global },
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.error(errorText(error))
|
toast.error(errorText(error))
|
||||||
@@ -320,7 +379,7 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
|
|||||||
|
|
||||||
return <>
|
return <>
|
||||||
<ErrorMessage message={grants.error} />
|
<ErrorMessage message={grants.error} />
|
||||||
<p className="text-sm text-muted-foreground">Права владельца подтверждены до {date(connection.ownerValidUntil)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.</p>
|
<p className="text-sm text-muted-foreground">{connection.policy.authority === "service" ? "Сервисный доступ действует до отзыва." : `Права владельца подтверждены до ${date(connection.ownerValidUntil)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.`}</p>
|
||||||
<Button variant="outline" className="self-start" disabled={connection.ownerId !== getClaims()?.sub} onClick={() => { void api.revalidate(connectionId).then(() => { grants.refresh(); toast.success("Права владельца обновлены") }, error => toast.error(errorText(error))) }}>Подтвердить текущие права владельца</Button>
|
<Button variant="outline" className="self-start" disabled={connection.ownerId !== getClaims()?.sub} onClick={() => { void api.revalidate(connectionId).then(() => { grants.refresh(); toast.success("Права владельца обновлены") }, error => toast.error(errorText(error))) }}>Подтвердить текущие права владельца</Button>
|
||||||
<Button variant="outline" className="self-start" onClick={() => { void check() }}>Проверить готовность доступа</Button>
|
<Button variant="outline" className="self-start" onClick={() => { void check() }}>Проверить готовность доступа</Button>
|
||||||
{result !== null && <>
|
{result !== null && <>
|
||||||
@@ -329,13 +388,11 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
|
|||||||
</p>}
|
</p>}
|
||||||
<pre className="overflow-auto rounded bg-muted p-3 text-xs">{pretty(result)}</pre>
|
<pre className="overflow-auto rounded bg-muted p-3 text-xs">{pretty(result)}</pre>
|
||||||
</>}
|
</>}
|
||||||
<div className="grid gap-3 sm:grid-cols-2">
|
<ServerChoices catalog={serverCatalog} selected={serverIds} onChange={setServerIds} all={selectAllServers} onAllChange={setSelectAllServers} forGrant />
|
||||||
<Field label={`Серверы допуска (доступны: ${connection.policy.scope.serverIds.join(", ")})`}><Input value={serverText} onChange={event => setServerText(event.target.value)} placeholder="ID через запятую" /></Field>
|
<Field label="Срок допуска, минут"><Input type="number" min={1} max={1440} value={minutes} onChange={event => setMinutes(Number(event.target.value))} /></Field>
|
||||||
<Field label="Срок допуска, минут"><Input type="number" min={1} max={1440} value={minutes} onChange={event => setMinutes(Number(event.target.value))} /></Field>
|
|
||||||
</div>
|
|
||||||
{connection.policy.scope.allowGlobal && <Choice label="Разрешить глобальные действия в допуске" checked={global} onChange={setGlobal} />}
|
{connection.policy.scope.allowGlobal && <Choice label="Разрешить глобальные действия в допуске" checked={global} onChange={setGlobal} />}
|
||||||
<div className="grid max-h-60 gap-2 overflow-y-auto sm:grid-cols-2">{connection.policy.scope.operationIds.map(id => <Choice key={id} label={id} checked={operations.includes(id)} onChange={checked => setOperations(values => checked ? [...values, id] : values.filter(value => value !== id))} />)}</div>
|
<div className="grid max-h-60 gap-2 overflow-y-auto sm:grid-cols-2">{connection.policy.scope.operationIds.map(id => <Choice key={id} label={id} checked={operations.includes(id)} onChange={checked => setOperations(values => checked ? [...values, id] : values.filter(value => value !== id))} />)}</div>
|
||||||
<Button className="self-start" disabled={grantBusy || !operations.length || connection.policy.status !== "active"} onClick={create}>Выдать временный допуск</Button>
|
<Button className="self-start" disabled={grantBusy || !operations.length || connection.policy.status !== "active" || (selectAllServers && !serverCatalog.data)} onClick={create}>Выдать временный допуск</Button>
|
||||||
{grants.data?.grants.map(grant => <div key={grant.id} className="flex flex-wrap items-center justify-between gap-2 rounded border p-3 text-sm">
|
{grants.data?.grants.map(grant => <div key={grant.id} className="flex flex-wrap items-center justify-between gap-2 rounded border p-3 text-sm">
|
||||||
<span>До {date(grant.grant.expiresAt)} · {grant.revoked_at ? "отозван" : "выдан"}</span>
|
<span>До {date(grant.grant.expiresAt)} · {grant.revoked_at ? "отозван" : "выдан"}</span>
|
||||||
<Button size="sm" variant="outline" disabled={!!grant.revoked_at} onClick={() => { void api.revokeGrant(grant.id).then(grants.refresh, error => toast.error(errorText(error))) }}>Отозвать допуск</Button>
|
<Button size="sm" variant="outline" disabled={!!grant.revoked_at} onClick={() => { void api.revokeGrant(grant.id).then(grants.refresh, error => toast.error(errorText(error))) }}>Отозвать допуск</Button>
|
||||||
|
|||||||
@@ -70,15 +70,17 @@ export function TrafficRxTxChart({
|
|||||||
rx,
|
rx,
|
||||||
tx,
|
tx,
|
||||||
range = "1h",
|
range = "1h",
|
||||||
|
rangeMinutes: actualMinutes,
|
||||||
embedded = false,
|
embedded = false,
|
||||||
}: {
|
}: {
|
||||||
rx: (number|null)[]
|
rx: (number|null)[]
|
||||||
tx: (number|null)[]
|
tx: (number|null)[]
|
||||||
range?: string
|
range?: string
|
||||||
|
rangeMinutes?: number
|
||||||
/** Skip outer Frame when already inside OpsPanel / Frame. */
|
/** Skip outer Frame when already inside OpsPanel / Frame. */
|
||||||
embedded?: boolean
|
embedded?: boolean
|
||||||
}) {
|
}) {
|
||||||
const rangeMinutes = TRAFFIC_RANGE_MINUTES[range] ?? 60
|
const rangeMinutes = actualMinutes ?? TRAFFIC_RANGE_MINUTES[range] ?? 60
|
||||||
const data = toChartData(rx, tx, rangeMinutes)
|
const data = toChartData(rx, tx, rangeMinutes)
|
||||||
const tickEvery = Math.max(1, Math.ceil(data.length / 6))
|
const tickEvery = Math.max(1, Math.ceil(data.length / 6))
|
||||||
|
|
||||||
|
|||||||
@@ -474,10 +474,12 @@ export function FlowAnalyticsDetail({
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{analytics && <>
|
{analytics && <>
|
||||||
|
{analytics.sourceWindow && <p role="status" className="mb-3 text-sm text-muted-foreground">Данные за последние {analytics.sourceWindow.effectiveMinutes} мин из запрошенных {analytics.sourceWindow.requestedMinutes} мин.</p>}
|
||||||
<TrafficRxTxChart
|
<TrafficRxTxChart
|
||||||
rx={analytics?.rxSeries ?? card?.rxSeries ?? []}
|
rx={analytics?.rxSeries ?? card?.rxSeries ?? []}
|
||||||
tx={analytics?.txSeries ?? card?.txSeries ?? []}
|
tx={analytics?.txSeries ?? card?.txSeries ?? []}
|
||||||
range={range}
|
range={range}
|
||||||
|
rangeMinutes={analytics.sourceWindow?.effectiveMinutes}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="mt-4 pt-4 border-t">
|
<div className="mt-4 pt-4 border-t">
|
||||||
|
|||||||
@@ -65,6 +65,8 @@
|
|||||||
- **«Срок действия (UTC)»** — не больше года. Для первого шага достаточно нескольких дней.
|
- **«Срок действия (UTC)»** — не больше года. Для первого шага достаточно нескольких дней.
|
||||||
- **«Режим управления»** — «Наблюдатель». Он же выбран по умолчанию.
|
- **«Режим управления»** — «Наблюдатель». Он же выбран по умолчанию.
|
||||||
- **Серверы и операции** — только те, что нужны агенту.
|
- **Серверы и операции** — только те, что нужны агенту.
|
||||||
|
- «Все серверы» включает серверы, зарегистрированные на момент сохранения. Новые серверы добавляются при повторном выборе и сохранении разрешений.
|
||||||
|
- Для выборочного доступа отметьте карточки нужных серверов. Если «Все серверы» выключено и ни одна карточка не отмечена, доступ к серверам закрыт.
|
||||||
- Операция, не выданная подключению, получает `OPERATION_DENIED`.
|
- Операция, не выданная подключению, получает `OPERATION_DENIED`.
|
||||||
- Сервер вне списка получает `SERVER_DENIED`.
|
- Сервер вне списка получает `SERVER_DENIED`.
|
||||||
- Глобальные операции работают только с «Разрешить выбранные глобальные операции».
|
- Глобальные операции работают только с «Разрешить выбранные глобальные операции».
|
||||||
@@ -117,6 +119,12 @@
|
|||||||
|
|
||||||
Если в портале отозвать сессии пользователя, Manager отзывает и его подключения MCP вместе с токенами и временными допусками.
|
Если в портале отозвать сессии пользователя, Manager отзывает и его подключения MCP вместе с токенами и временными допусками.
|
||||||
|
|
||||||
|
### Сервисное подключение
|
||||||
|
|
||||||
|
В «Подключения» → «Выдать доступ» администратор MCP может выбрать «Сервисное — бессрочный автономный доступ». Выберите нужные серверы и операции. Доступ действует до отзыва и переживает истечение обычной сессии портала. Опасные операции всегда требуют подтверждения человеком, а лимиты и защита объектов действуют как обычно.
|
||||||
|
|
||||||
|
Сервисный токен можно заменить, приостановить вместе с подключением или отозвать. Явный отзыв прав выдавшего доступ администратора в портале также отзывает его сервисные подключения. Чтобы сменить тип подключения, выдайте новый токен через новое подключение.
|
||||||
|
|
||||||
### Что агент может на этом шаге
|
### Что агент может на этом шаге
|
||||||
|
|
||||||
- **Может** вызывать операции чтения: каталоги, состояние, журналы.
|
- **Может** вызывать операции чтения: каталоги, состояние, журналы.
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ const serverId = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
|
|||||||
const instant = z.string().datetime({ offset: true })
|
const instant = z.string().datetime({ offset: true })
|
||||||
const uniqueStrings = z.array(identifier).max(1000).refine(values => new Set(values).size === values.length, "Повторяющиеся значения")
|
const uniqueStrings = z.array(identifier).max(1000).refine(values => new Set(values).size === values.length, "Повторяющиеся значения")
|
||||||
const serverIds = z.array(serverId).max(1000).refine(values => new Set(values).size === values.length, "Повторяющиеся серверы")
|
const serverIds = z.array(serverId).max(1000).refine(values => new Set(values).size === values.length, "Повторяющиеся серверы")
|
||||||
|
// Keep the existing finite timestamp contract for policy, credential and SQL proofs.
|
||||||
|
export const MCP_SERVICE_EXPIRATION = "9999-12-31T23:59:59.000Z"
|
||||||
|
|
||||||
export const mcpModeSchema = z.enum(["observer", "approval", "autonomous"])
|
export const mcpModeSchema = z.enum(["observer", "approval", "autonomous"])
|
||||||
export const mcpLimitsSchema = z.object({
|
export const mcpLimitsSchema = z.object({
|
||||||
@@ -32,6 +34,7 @@ export const mcpConnectionPolicySchema = z.object({
|
|||||||
id: identifier,
|
id: identifier,
|
||||||
version: z.number().int().positive(),
|
version: z.number().int().positive(),
|
||||||
status: z.enum(["active", "paused", "revoked"]),
|
status: z.enum(["active", "paused", "revoked"]),
|
||||||
|
authority: z.literal("service").optional(),
|
||||||
expiresAt: instant,
|
expiresAt: instant,
|
||||||
mode: mcpModeSchema,
|
mode: mcpModeSchema,
|
||||||
permissions: uniqueStrings,
|
permissions: uniqueStrings,
|
||||||
@@ -39,7 +42,9 @@ export const mcpConnectionPolicySchema = z.object({
|
|||||||
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
|
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
|
||||||
autonomousDangerousOperationIds: uniqueStrings.default([]),
|
autonomousDangerousOperationIds: uniqueStrings.default([]),
|
||||||
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
|
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
|
||||||
}).strict()
|
}).strict().refine(policy => policy.authority !== "service" ||
|
||||||
|
policy.expiresAt === MCP_SERVICE_EXPIRATION && policy.mode === "autonomous" && policy.dangerousPolicy === "approval" && !policy.autonomousDangerousOperationIds.length,
|
||||||
|
"Некорректная политика сервисного подключения")
|
||||||
|
|
||||||
export const mcpTargetSchema = z.discriminatedUnion("scope", [
|
export const mcpTargetSchema = z.discriminatedUnion("scope", [
|
||||||
z.object({ scope: z.literal("servers"), serverIds: serverIds.refine(ids => ids.length > 0, "Выберите серверы") }).strict(),
|
z.object({ scope: z.literal("servers"), serverIds: serverIds.refine(ids => ids.length > 0, "Выберите серверы") }).strict(),
|
||||||
@@ -127,14 +132,19 @@ export type McpPolicyReasonCode = z.infer<typeof mcpPolicyReasonCodeSchema>
|
|||||||
|
|
||||||
export const mcpConnectionCreateSchema = z.object({
|
export const mcpConnectionCreateSchema = z.object({
|
||||||
name: z.string().trim().min(1).max(100),
|
name: z.string().trim().min(1).max(100),
|
||||||
expiresAt: instant,
|
authority: z.literal("service").optional(),
|
||||||
|
expiresAt: instant.nullable(),
|
||||||
mode: mcpModeSchema.default("observer"),
|
mode: mcpModeSchema.default("observer"),
|
||||||
permissions: uniqueStrings,
|
permissions: uniqueStrings,
|
||||||
scope: mcpScopeSchema,
|
scope: mcpScopeSchema,
|
||||||
|
selectAllServers: z.literal(true).optional(),
|
||||||
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
|
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
|
||||||
autonomousDangerousOperationIds: uniqueStrings.default([]),
|
autonomousDangerousOperationIds: uniqueStrings.default([]),
|
||||||
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
|
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
|
||||||
}).strict()
|
}).strict().refine(input => input.authority === "service"
|
||||||
|
? input.expiresAt === null && input.mode === "autonomous" && input.dangerousPolicy === "approval" && !input.autonomousDangerousOperationIds.length
|
||||||
|
: input.expiresAt !== null, "Для сервисного подключения выберите автономный режим с подтверждением опасных действий. Для личного подключения укажите срок действия.")
|
||||||
|
.refine(input => !input.selectAllServers || !input.scope.serverIds.length, "Выберите все серверы или укажите конкретные ID")
|
||||||
export const mcpConnectionSchema = z.object({
|
export const mcpConnectionSchema = z.object({
|
||||||
id: z.string().uuid(), name: z.string(), ownerId: z.string(),
|
id: z.string().uuid(), name: z.string(), ownerId: z.string(),
|
||||||
policy: mcpConnectionPolicySchema, createdAt: instant, updatedAt: instant,
|
policy: mcpConnectionPolicySchema, createdAt: instant, updatedAt: instant,
|
||||||
|
|||||||
@@ -163,7 +163,13 @@ export const flowTalkerDtoSchema = z.object({
|
|||||||
plane: z.string().optional(),
|
plane: z.string().optional(),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const flowSourceWindowSchema = z.object({
|
||||||
|
requestedMinutes: z.number().int().positive(),
|
||||||
|
effectiveMinutes: z.number().int().positive(),
|
||||||
|
}).strict().refine(value => value.effectiveMinutes < value.requestedMinutes)
|
||||||
|
|
||||||
export const flowStatsDtoSchema = z.object({
|
export const flowStatsDtoSchema = z.object({
|
||||||
|
sourceWindow: flowSourceWindowSchema.optional(),
|
||||||
dataQuality:flowIngestQualitySchema.nullable().optional(),
|
dataQuality:flowIngestQualitySchema.nullable().optional(),
|
||||||
exportersOnline: z.number().int().nonnegative(),
|
exportersOnline: z.number().int().nonnegative(),
|
||||||
bytesPerMin: z.number().nonnegative(),
|
bytesPerMin: z.number().nonnegative(),
|
||||||
@@ -246,6 +252,7 @@ export const flowPathRowSchema = z.object({
|
|||||||
})
|
})
|
||||||
|
|
||||||
export const flowAnalyticsDtoSchema = z.object({
|
export const flowAnalyticsDtoSchema = z.object({
|
||||||
|
sourceWindow: flowSourceWindowSchema.optional(),
|
||||||
bpsNow: z.number().nonnegative(),
|
bpsNow: z.number().nonnegative(),
|
||||||
bytes: z.number().nonnegative(),
|
bytes: z.number().nonnegative(),
|
||||||
packets: z.number().nonnegative(),
|
packets: z.number().nonnegative(),
|
||||||
@@ -284,6 +291,7 @@ export const flowAnalyticsDtoSchema = z.object({
|
|||||||
})
|
})
|
||||||
|
|
||||||
export const flowExportersDtoSchema = z.object({
|
export const flowExportersDtoSchema = z.object({
|
||||||
|
sourceWindow: flowSourceWindowSchema.optional(),
|
||||||
exporters: z.array(flowEntityCardSchema),
|
exporters: z.array(flowEntityCardSchema),
|
||||||
lastExporterIp: z.string().nullable().optional(),
|
lastExporterIp: z.string().nullable().optional(),
|
||||||
lastError: z.string().nullable().optional(),
|
lastError: z.string().nullable().optional(),
|
||||||
@@ -294,6 +302,7 @@ export const flowExportersDtoSchema = z.object({
|
|||||||
})
|
})
|
||||||
|
|
||||||
export const flowClientsDtoSchema = z.object({
|
export const flowClientsDtoSchema = z.object({
|
||||||
|
sourceWindow: flowSourceWindowSchema.optional(),
|
||||||
clients: z.array(flowEntityCardSchema),
|
clients: z.array(flowEntityCardSchema),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -390,6 +399,7 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
|
|||||||
})
|
})
|
||||||
|
|
||||||
export const flowMapHopsDtoSchema = z.object({
|
export const flowMapHopsDtoSchema = z.object({
|
||||||
|
sourceWindow: flowSourceWindowSchema.optional(),
|
||||||
hops: z.array(flowMapHopDtoSchema),
|
hops: z.array(flowMapHopDtoSchema),
|
||||||
live: z.boolean(),
|
live: z.boolean(),
|
||||||
rangeMinutes: z.number().int().positive(),
|
rangeMinutes: z.number().int().positive(),
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export function mcpApi(base: string) {
|
|||||||
const get = async <T>(path: string, schema: z.ZodType<T>, signal?: AbortSignal): Promise<T> => schema.parse(await requestJson(base, "/api/mcp" + path, { signal }))
|
const get = async <T>(path: string, schema: z.ZodType<T>, signal?: AbortSignal): Promise<T> => schema.parse(await requestJson(base, "/api/mcp" + path, { signal }))
|
||||||
const send = async <T>(path: string, body: unknown, schema: z.ZodType<T>, method = "POST", signal?: AbortSignal): Promise<T> => schema.parse(await requestJson(base, "/api/mcp" + path, { method, body: JSON.stringify(body), signal }))
|
const send = async <T>(path: string, body: unknown, schema: z.ZodType<T>, method = "POST", signal?: AbortSignal): Promise<T> => schema.parse(await requestJson(base, "/api/mcp" + path, { method, body: JSON.stringify(body), signal }))
|
||||||
return {
|
return {
|
||||||
|
serverChoices: (connectionId?: string, signal?: AbortSignal) => get(connectionId ? "/server-choices?" + new URLSearchParams({ connectionId }) : "/server-choices",
|
||||||
|
deviceCatalogSchema.pick({ servers: true }), signal),
|
||||||
downloadArtifact: (receipt: unknown, signal?: AbortSignal) => downloadHumanArtifact(base, receipt, signal),
|
downloadArtifact: (receipt: unknown, signal?: AbortSignal) => downloadHumanArtifact(base, receipt, signal),
|
||||||
coverage: (signal?: AbortSignal) => get("/coverage", z.object({ version: z.literal(1), routes: z.array(z.object({ method: z.string(), path: z.string(), status: z.enum(["mediated", "excluded", "pending"]), operations: z.array(z.string()), reason: z.string() })) }), signal),
|
coverage: (signal?: AbortSignal) => get("/coverage", z.object({ version: z.literal(1), routes: z.array(z.object({ method: z.string(), path: z.string(), status: z.enum(["mediated", "excluded", "pending"]), operations: z.array(z.string()), reason: z.string() })) }), signal),
|
||||||
uploadRestoreArchive: async (file: File, signal?: AbortSignal) => restoreArchiveSchema.parse(await requestJson(base, "/api/mcp/database/archives", { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: file, signal })),
|
uploadRestoreArchive: async (file: File, signal?: AbortSignal) => restoreArchiveSchema.parse(await requestJson(base, "/api/mcp/database/archives", { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: file, signal })),
|
||||||
|
|||||||
@@ -24,8 +24,16 @@ async function setup(page: Page, permissions: string[], access: { expiresAt?: st
|
|||||||
if (method !== 'GET') mutations.push({ path, body: request.postDataJSON() })
|
if (method !== 'GET') mutations.push({ path, body: request.postDataJSON() })
|
||||||
if (path === '/api/auth/config') return json({ required: true })
|
if (path === '/api/auth/config') return json({ required: true })
|
||||||
if (path === '/api/mcp/catalog') return json({ stage: 'runtime', executionAvailable: true, operations: [read, forbidden] })
|
if (path === '/api/mcp/catalog') return json({ stage: 'runtime', executionAvailable: true, operations: [read, forbidden] })
|
||||||
|
if (path === '/api/mcp/server-choices') return json({ servers: [
|
||||||
|
{ id: 1, name: 'CHR WAN', host: 'wan.example.test', enabled: true },
|
||||||
|
{ id: 2, name: 'CHR LAN', host: 'lan.example.test', enabled: true },
|
||||||
|
] })
|
||||||
if (path === '/api/mcp/overview') return json({ connections: 1, calls: 3, errors: 1, approvals: 0, running: 0, enabled, observedAt: at })
|
if (path === '/api/mcp/overview') return json({ connections: 1, calls: 3, errors: 1, approvals: 0, running: 0, enabled, observedAt: at })
|
||||||
if (path === '/api/mcp/connections') { connectionReads++; const visible = { ...connection, ownerValidUntil }; return json(method === 'POST' ? { connection: visible, token: 'synthetic-one-time-token' } : { connections: [visible] }) }
|
if (path === '/api/mcp/connections') { connectionReads++; const visible = { ...connection, ownerValidUntil }; return json(method === 'POST' ? { connection: visible, token: 'synthetic-one-time-token' } : { connections: [visible] }) }
|
||||||
|
if (path === `/api/mcp/connections/${id}` && method === 'PUT') {
|
||||||
|
const { name, selectAllServers, scope, ...policy } = request.postDataJSON()
|
||||||
|
return json({ ...connection, name, policy: { ...connection.policy, ...policy, scope: selectAllServers ? { ...scope, serverIds: [1, 2] } : scope }, ownerValidUntil })
|
||||||
|
}
|
||||||
if (path === `/api/mcp/connections/${id}/status`) { connection.policy.status = request.postDataJSON().status; return json({ ok: true }) }
|
if (path === `/api/mcp/connections/${id}/status`) { connection.policy.status = request.postDataJSON().status; return json({ ok: true }) }
|
||||||
if (path === '/api/mcp/stop-automation') { enabled = false; return json({ ok: true }) }
|
if (path === '/api/mcp/stop-automation') { enabled = false; return json({ ok: true }) }
|
||||||
if (path === '/api/mcp/requests') return json({ items: [{ id: 'synthetic-call', tool: 'mm_logs_query', created_at: at, connection_id: id, status: connection.policy.status === 'active' ? 'completed' : 'denied', error_code: connection.policy.status === 'active' ? null : `connection_${connection.policy.status}`, detail: 'synthetic fixture outcome' }], total: 1, nextCursor: null })
|
if (path === '/api/mcp/requests') return json({ items: [{ id: 'synthetic-call', tool: 'mm_logs_query', created_at: at, connection_id: id, status: connection.policy.status === 'active' ? 'completed' : 'denied', error_code: connection.policy.status === 'active' ? null : `connection_${connection.policy.status}`, detail: 'synthetic fixture outcome' }], total: 1, nextCursor: null })
|
||||||
@@ -301,7 +309,10 @@ test('synthetic: issue only selected server/read permission and hide one-time to
|
|||||||
await dialog.getByLabel('Название', { exact: true }).fill('Ограниченная диагностика')
|
await dialog.getByLabel('Название', { exact: true }).fill('Ограниченная диагностика')
|
||||||
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
|
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
|
||||||
await expect(dialog.getByRole('checkbox', { name: forbidden.title, exact: true })).toHaveCount(0)
|
await expect(dialog.getByRole('checkbox', { name: forbidden.title, exact: true })).toHaveCount(0)
|
||||||
await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1')
|
const wan = dialog.getByRole('button', { name: 'CHR WAN', exact: true })
|
||||||
|
await wan.click()
|
||||||
|
await expect(wan).toHaveAttribute('aria-pressed', 'true')
|
||||||
|
await expect(dialog.getByRole('button', { name: 'CHR LAN', exact: true })).toHaveAttribute('aria-pressed', 'false')
|
||||||
await dialog.getByRole('button', { name: 'Выбрать все операции' }).click()
|
await dialog.getByRole('button', { name: 'Выбрать все операции' }).click()
|
||||||
await expect(dialog.getByRole('status')).toHaveText('Выбрано 3')
|
await expect(dialog.getByRole('status')).toHaveText('Выбрано 3')
|
||||||
await dialog.getByRole('button', { name: 'Снять все' }).click()
|
await dialog.getByRole('button', { name: 'Снять все' }).click()
|
||||||
@@ -332,6 +343,76 @@ test('synthetic: issue only selected server/read permission and hide one-time to
|
|||||||
await expect(token).toHaveCount(0)
|
await expect(token).toHaveCount(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('synthetic: edit autonomous dangerous operations by group or all at once', async ({ page }) => {
|
||||||
|
const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read'])
|
||||||
|
const danger = { ...read, effect: 'write', risk: 'dangerous' }
|
||||||
|
const logs = { ...danger, id: 'test.logs.change', toolName: 'mm_test_logs_change', title: 'Изменить журналы' }
|
||||||
|
const network = { ...danger, id: 'test.network.change', toolName: 'mm_test_network_change', title: 'Изменить сеть', section: 'network' }
|
||||||
|
const unchecked = { ...network, id: 'test.network.other', toolName: 'mm_test_network_other', title: 'Другая операция сети' }
|
||||||
|
await page.route('**/api/mcp/catalog', route => route.fulfill({ json: { stage: 'runtime', executionAvailable: true, operations: [read, logs, network, unchecked] } }))
|
||||||
|
await page.goto('/mcp?tab=connections')
|
||||||
|
await page.getByRole('row').filter({ hasText: 'Синтетический AI клиент' }).getByRole('button', { name: 'Разрешения', exact: true }).click()
|
||||||
|
const dialog = page.getByRole('dialog', { name: 'Изменить разрешения' })
|
||||||
|
const next = dialog.getByRole('button', { name: 'Далее', exact: true })
|
||||||
|
await dialog.getByLabel('Режим управления', { exact: true }).selectOption('autonomous')
|
||||||
|
await next.click()
|
||||||
|
const allServers = dialog.getByRole('checkbox', { name: 'Все серверы', exact: true })
|
||||||
|
const wan = dialog.getByRole('button', { name: 'CHR WAN', exact: true })
|
||||||
|
await expect(allServers).not.toBeChecked()
|
||||||
|
await expect(wan).toHaveAttribute('aria-pressed', 'true')
|
||||||
|
await allServers.check()
|
||||||
|
await expect(wan).toHaveCount(0)
|
||||||
|
await allServers.uncheck()
|
||||||
|
await expect(wan).toHaveAttribute('aria-pressed', 'true')
|
||||||
|
await allServers.check()
|
||||||
|
await dialog.getByRole('button', { name: 'Выбрать все операции', exact: true }).click()
|
||||||
|
await dialog.locator('summary').filter({ hasText: 'Сеть и маршрутизация' }).click()
|
||||||
|
await dialog.getByRole('checkbox', { name: unchecked.title, exact: true }).uncheck()
|
||||||
|
await next.click()
|
||||||
|
await dialog.getByLabel('Опасные действия', { exact: true }).selectOption('explicit-allow')
|
||||||
|
const selectAll = dialog.getByRole('button', { name: 'Выбрать все опасные операции' })
|
||||||
|
await selectAll.click()
|
||||||
|
await expect(dialog.getByRole('status')).toHaveText('Выбрано 2')
|
||||||
|
await dialog.getByRole('button', { name: 'Снять все' }).click()
|
||||||
|
await dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }).check()
|
||||||
|
await expect(dialog.getByRole('status')).toHaveText('Выбрано 1')
|
||||||
|
await selectAll.click()
|
||||||
|
await next.click()
|
||||||
|
await expect(dialog.getByText(/Серверы: все на момент сохранения/)).toBeVisible()
|
||||||
|
await expect(dialog.getByText('Опасных операций выбрано для автономного выполнения: 2.')).toBeVisible()
|
||||||
|
await dialog.getByRole('button', { name: 'Сохранить доступ' }).click()
|
||||||
|
await expect(dialog).toBeHidden()
|
||||||
|
expect(state.mutations).toEqual([expect.objectContaining({ path: `/api/mcp/connections/${id}`, body: expect.objectContaining({
|
||||||
|
selectAllServers: true,
|
||||||
|
scope: { serverIds: [], operationIds: [read.id, logs.id, network.id], allowGlobal: false },
|
||||||
|
autonomousDangerousOperationIds: [logs.id, network.id],
|
||||||
|
}) })])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('synthetic: issue service access with no expiry and mandatory approval of dangerous actions', async ({ page }) => {
|
||||||
|
const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read'])
|
||||||
|
await page.goto('/mcp?tab=connections')
|
||||||
|
await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click()
|
||||||
|
const dialog = page.getByRole('dialog')
|
||||||
|
const next = dialog.getByRole('button', { name: 'Далее', exact: true })
|
||||||
|
await dialog.getByLabel('Название', { exact: true }).fill('Служебный мониторинг')
|
||||||
|
await dialog.getByLabel('Тип подключения', { exact: true }).selectOption('service')
|
||||||
|
await expect(dialog.getByLabel('Срок действия (UTC)', { exact: true })).toHaveCount(0)
|
||||||
|
await next.click()
|
||||||
|
await dialog.getByRole('button', { name: 'CHR WAN', exact: true }).click()
|
||||||
|
await dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }).check()
|
||||||
|
await next.click()
|
||||||
|
await expect(dialog.getByText('Опасные действия всегда требуют подтверждения.')).toBeVisible()
|
||||||
|
await next.click()
|
||||||
|
await expect(dialog.getByText('Сервисное, бессрочное', { exact: false })).toBeVisible()
|
||||||
|
await dialog.getByRole('button', { name: 'Сохранить доступ', exact: true }).click()
|
||||||
|
await expect(page.getByLabel('Одноразовый токен MCP')).toHaveValue('synthetic-one-time-token')
|
||||||
|
expect(state.mutations).toEqual([expect.objectContaining({ path: '/api/mcp/connections', body: expect.objectContaining({
|
||||||
|
authority: 'service', expiresAt: null, mode: 'autonomous', dangerousPolicy: 'approval', autonomousDangerousOperationIds: [],
|
||||||
|
scope: { serverIds: [1], operationIds: ['logs.query'], allowGlobal: false },
|
||||||
|
}) })])
|
||||||
|
})
|
||||||
|
|
||||||
test('synthetic: pause, resume, cancelled revoke, revoke, monitor denied outcome, stop automation', async ({ page }) => {
|
test('synthetic: pause, resume, cancelled revoke, revoke, monitor denied outcome, stop automation', async ({ page }) => {
|
||||||
const state = await setup(page, ['mm:mcp:admin', 'mm:mcp:pause', 'mm:servers:read'])
|
const state = await setup(page, ['mm:mcp:admin', 'mm:mcp:pause', 'mm:servers:read'])
|
||||||
await page.goto('/mcp?tab=connections')
|
await page.goto('/mcp?tab=connections')
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ async function setup(page: Page, fail = false) {
|
|||||||
const json = (body: unknown) => route.fulfill({ headers, json: body })
|
const json = (body: unknown) => route.fulfill({ headers, json: body })
|
||||||
if (path === "/api/auth/config") return json({ required: false })
|
if (path === "/api/auth/config") return json({ required: false })
|
||||||
if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [operation] })
|
if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [operation] })
|
||||||
|
if (path === "/api/mcp/server-choices") return json({ servers: [{ id: 1, name: "CHR lab", host: "192.0.2.1", enabled: true }] })
|
||||||
if (path === "/api/mcp/coverage") return json({ version: 1, routes: [{ method: "POST", path: "/api/geoip/update", status: "pending", operations: [], reason: "Нужен отдельный сервисный адаптер" }] })
|
if (path === "/api/mcp/coverage") return json({ version: 1, routes: [{ method: "POST", path: "/api/geoip/update", status: "pending", operations: [], reason: "Нужен отдельный сервисный адаптер" }] })
|
||||||
if (path === "/api/mcp/overview") return fail ? route.fulfill({ headers, status: 503, json: { error: "Аудит временно недоступен" } }) : json({ connections: 1, calls: 7, errors: 1, approvals: 1, running: 0, enabled: true, observedAt: at })
|
if (path === "/api/mcp/overview") return fail ? route.fulfill({ headers, status: 503, json: { error: "Аудит временно недоступен" } }) : json({ connections: 1, calls: 7, errors: 1, approvals: 1, running: 0, enabled: true, observedAt: at })
|
||||||
if (path === "/api/mcp/connections") return json(method === "POST" ? { connection, token: "test-one-time-secret" } : { connections: [connection] })
|
if (path === "/api/mcp/connections") return json(method === "POST" ? { connection, token: "test-one-time-secret" } : { connections: [connection] })
|
||||||
@@ -414,7 +415,7 @@ test("MCP: доступ, проверка подключения, выдача
|
|||||||
await page.getByRole("button", { name: "Выдать доступ", exact: true }).click()
|
await page.getByRole("button", { name: "Выдать доступ", exact: true }).click()
|
||||||
await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент")
|
await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент")
|
||||||
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
||||||
await page.getByLabel("ID разрешённых серверов через запятую").fill("1")
|
await page.getByRole("button", { name: "CHR lab", exact: true }).click()
|
||||||
await page.locator("summary").filter({ hasText: "Журналы" }).click()
|
await page.locator("summary").filter({ hasText: "Журналы" }).click()
|
||||||
await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check()
|
await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check()
|
||||||
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
||||||
@@ -478,13 +479,19 @@ test("MCP: временные допуски и результаты прове
|
|||||||
await expect(revoke).toBeVisible()
|
await expect(revoke).toBeVisible()
|
||||||
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${id}/check`), check.click()])
|
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${id}/check`), check.click()])
|
||||||
await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
|
await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
|
||||||
await Promise.all([
|
const serverCard = page.getByRole("button", { name: "CHR lab", exact: true })
|
||||||
|
await serverCard.click()
|
||||||
|
await expect(serverCard).toHaveAttribute("aria-pressed", "true")
|
||||||
|
await page.getByRole("checkbox", { name: "Все серверы подключения", exact: true }).check()
|
||||||
|
const [issuedRequest] = await Promise.all([
|
||||||
page.waitForRequest(request => request.method() === "POST" && request.url().endsWith(`/connections/${id}/grants`)),
|
page.waitForRequest(request => request.method() === "POST" && request.url().endsWith(`/connections/${id}/grants`)),
|
||||||
create.click(),
|
create.click(),
|
||||||
])
|
])
|
||||||
|
expect(issuedRequest.postDataJSON().scope.serverIds).toEqual([1])
|
||||||
|
|
||||||
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${otherId}/grants`), selection.selectOption(otherId)])
|
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${otherId}/grants`), selection.selectOption(otherId)])
|
||||||
await expect(revoke).toHaveCount(0)
|
await expect(revoke).toHaveCount(0)
|
||||||
|
await expect(serverCard).toHaveAttribute("aria-pressed", "false")
|
||||||
await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
|
await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
|
||||||
await expect(create).toBeDisabled()
|
await expect(create).toBeDisabled()
|
||||||
releaseOtherGrants()
|
releaseOtherGrants()
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ for (const mode of ['servers','flows'] as const) for (const minutes of [5,15]) {
|
|||||||
const url=new URL(r.request().url()),path=url.pathname,span=url.searchParams.get('range')==='5m'?5:url.searchParams.get('range')==='15m'?15:60
|
const url=new URL(r.request().url()),path=url.pathname,span=url.searchParams.get('range')==='5m'?5:url.searchParams.get('range')==='15m'?15:60
|
||||||
const built=history(span),server={id:'1',name,site:'TEST',country:'RU',status:'online',...built,rxTotal:1,txTotal:1,volumeUnit:'GiB'}
|
const built=history(span),server={id:'1',name,site:'TEST',country:'RU',status:'online',...built,rxTotal:1,txTotal:1,volumeUnit:'GiB'}
|
||||||
const card={id:'1',name,subtitle:'',site:'TEST',country:'RU',status:'online',rxNow:1,txNow:0,sessions:1,bytes:60000,rxSeries:[1,2,1],txSeries:[0,0,0]}
|
const card={id:'1',name,subtitle:'',site:'TEST',country:'RU',status:'online',rxNow:1,txNow:0,sessions:1,bytes:60000,rxSeries:[1,2,1],txSeries:[0,0,0]}
|
||||||
const analytics={bpsNow:1000000,bytes:60000,packets:10,conversations:1,uniqueSrc:1,uniqueDst:1,topProto:'TCP',rxSeries:Array.from({length:span},(_,i)=>1+i%3),txSeries:Array(span).fill(0),applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[],ifaces:[],live:false}
|
const sourceWindow=mode==='flows'&&span===15?{requestedMinutes:15,effectiveMinutes:7}:undefined
|
||||||
|
const chartMinutes=sourceWindow?.effectiveMinutes??span
|
||||||
|
const analytics={bpsNow:1000000,bytes:60000,packets:10,conversations:1,uniqueSrc:1,uniqueDst:1,topProto:'TCP',rxSeries:Array.from({length:chartMinutes},(_,i)=>1+i%3),txSeries:Array(chartMinutes).fill(0),applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[],ifaces:[],live:false,sourceWindow}
|
||||||
if(path.endsWith('/live'))return r.fulfill({status:503,json:{error:'Live выключен в проверке истории'}})
|
if(path.endsWith('/live'))return r.fulfill({status:503,json:{error:'Live выключен в проверке истории'}})
|
||||||
const json=path==='/api/auth/config'?{required:false}:path==='/api/traffic/servers'?{servers:[server]}:
|
const json=path==='/api/auth/config'?{required:false}:path==='/api/traffic/servers'?{servers:[server]}:
|
||||||
path==='/api/traffic/servers/1'?{server}:path==='/api/traffic/flow/exporters'?{exporters:[card]}:
|
path==='/api/traffic/servers/1'?{server}:path==='/api/traffic/flow/exporters'?{exporters:[card]}:
|
||||||
@@ -28,6 +30,7 @@ for (const mode of ['servers','flows'] as const) for (const minutes of [5,15]) {
|
|||||||
await page.getByRole('button',{name:`${minutes}м`,exact:true}).click()
|
await page.getByRole('button',{name:`${minutes}м`,exact:true}).click()
|
||||||
const chart=page.getByRole('region',{name:'История RX/TX'})
|
const chart=page.getByRole('region',{name:'История RX/TX'})
|
||||||
await expect(chart).toBeVisible()
|
await expect(chart).toBeVisible()
|
||||||
|
if(mode==='flows'&&minutes===15)await expect(page.getByText('Данные за последние 7 мин из запрошенных 15 мин.')).toBeVisible()
|
||||||
const curves=chart.locator('path.recharts-line-curve')
|
const curves=chart.locator('path.recharts-line-curve')
|
||||||
await expect(curves).toHaveCount(2)
|
await expect(curves).toHaveCount(2)
|
||||||
await expect.poll(async()=>((await curves.first().getAttribute('d'))?.match(/[CL]/g)||[]).length).toBeGreaterThan(2)
|
await expect.poll(async()=>((await curves.first().getAttribute('d'))?.match(/[CL]/g)||[]).length).toBeGreaterThan(2)
|
||||||
|
|||||||
Reference in new issue
Block a user