Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c20b6b33c3 | ||
|
|
79ab7b45aa | ||
|
|
26249e1a4d | ||
|
|
136474ba95 | ||
|
|
f0e08f9731 |
No files matched your search
@@ -32,6 +32,7 @@ import { subscribeLogDevice } from "../../services/router-logs-collector.js"
|
|||||||
import { ospfFilterFields, rosResources, readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfUnsetUpdate } from "./resources.js"
|
import { ospfFilterFields, rosResources, readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfUnsetUpdate } from "./resources.js"
|
||||||
import { registerMcpOperation, listMcpOperations } from "./registry.js"
|
import { registerMcpOperation, listMcpOperations } from "./registry.js"
|
||||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, MAX_MCP_PUBLIC_ARRAY_ITEMS, MAX_MCP_PUBLIC_STRING_LENGTH, McpError, redact } from "./security.js"
|
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, MAX_MCP_PUBLIC_ARRAY_ITEMS, MAX_MCP_PUBLIC_STRING_LENGTH, McpError, redact } from "./security.js"
|
||||||
|
import { hasUnattendedPlanAuthority } from "./policy.js"
|
||||||
import { effectiveMcpConnection } from "./store.js"
|
import { effectiveMcpConnection } from "./store.js"
|
||||||
import type { McpAction, ActionContext, ChangeEvidence } from "./action-types.js"
|
import type { McpAction, ActionContext, ChangeEvidence } from "./action-types.js"
|
||||||
import { registerRoutingActions } from "./routing-actions.js"
|
import { registerRoutingActions } from "./routing-actions.js"
|
||||||
@@ -623,11 +624,15 @@ add("changes.read", "mm_change_get", "Просмотр своего плана",
|
|||||||
const { loadPlan, publicPlan } = await import("./runtime.js")
|
const { loadPlan, publicPlan } = await import("./runtime.js")
|
||||||
const plan = await loadPlan(String(input.planId))
|
const plan = await loadPlan(String(input.planId))
|
||||||
await assertPlanReadScope(plan, context)
|
await assertPlanReadScope(plan, context)
|
||||||
return publicPlan(plan)
|
return publicPlan(plan, hasUnattendedPlanAuthority(context.connection.policy) && plan.policy_version === context.connection.policy.version)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
add("changes.apply", "mm_change_apply", "Применить свой план", "mcp", null, "write", "connection", z.object({ planId: z.string().uuid(), idempotencyKey: z.string().min(1).max(200) }).strict(), {
|
add("changes.apply", "mm_change_apply", "Применить свой план", "mcp", null, "write", "connection", z.object({
|
||||||
read: async (input, context) => (await import("./runtime.js")).applyPlan(context.principal, String(input.planId), String(input.idempotencyKey)),
|
planId: z.string().uuid(),
|
||||||
|
idempotencyKey: z.string().min(1).max(200),
|
||||||
|
announcedPlanDigest: z.string().regex(/^[0-9a-f]{64}$/).optional().describe("Значение announcement.digest. Передавайте только после отдельного видимого сообщения с точным планом в чате."),
|
||||||
|
}).strict(), {
|
||||||
|
read: async (input, context) => (await import("./runtime.js")).applyPlan(context.principal, String(input.planId), String(input.idempotencyKey), input.announcedPlanDigest as string | undefined),
|
||||||
})
|
})
|
||||||
add("changes.cancel", "mm_change_cancel", "Отменить свой незапущенный план", "mcp", null, "read", "connection", z.object({ planId: z.string().uuid() }).strict(), {
|
add("changes.cancel", "mm_change_cancel", "Отменить свой незапущенный план", "mcp", null, "read", "connection", z.object({ planId: z.string().uuid() }).strict(), {
|
||||||
read: async (input, context) => {
|
read: async (input, context) => {
|
||||||
|
|||||||
@@ -133,7 +133,9 @@ async function executeRestore(operationId: string, principal: McpPrincipal,origi
|
|||||||
if (ids.some(id => !connection.policy.scope.serverIds.includes(id) || !evidence.objects.some(object => object.kind === "server" && object.serverId === id))) throw new McpError("SERVER_DENIED", "Область восстановления изменилась")
|
if (ids.some(id => !connection.policy.scope.serverIds.includes(id) || !evidence.objects.some(object => object.kind === "server" && object.serverId === id))) throw new McpError("SERVER_DENIED", "Область восстановления изменилась")
|
||||||
const { rows: grants } = await pool.query("SELECT payload FROM mcp_grants WHERE connection_id=$1 AND revoked_at IS NULL AND payload->>'credentialId'=$2", [connection.id, principal.credentialId])
|
const { rows: grants } = await pool.query("SELECT payload FROM mcp_grants WHERE connection_id=$1 AND revoked_at IS NULL AND payload->>'credentialId'=$2", [connection.id, principal.credentialId])
|
||||||
if (grants.some(grant => !grant.payload.scope?.allowGlobal || !grant.payload.scope?.operationIds?.includes("database.restore") || ids.some(id => !grant.payload.scope?.serverIds?.includes(id)))) throw new McpError("PERMISSION_DENIED", "Временный допуск не разрешает восстановление")
|
if (grants.some(grant => !grant.payload.scope?.allowGlobal || !grant.payload.scope?.operationIds?.includes("database.restore") || ids.some(id => !grant.payload.scope?.serverIds?.includes(id)))) throw new McpError("PERMISSION_DENIED", "Временный допуск не разрешает восстановление")
|
||||||
if ((await pool.query("SELECT 1 FROM mcp_protections WHERE object_ref->>'protection'='deny' LIMIT 1")).rows.length) throw new McpError("PROTECTED_OBJECT", "Восстановление заменяет запрещённый защищённый объект")
|
const { rows: [protection] } = await pool.query<{ denied: boolean }>("SELECT (object_ref->>'protection'='deny') AS denied FROM mcp_protections WHERE object_ref->>'protection'='deny' OR $1::boolean ORDER BY denied DESC LIMIT 1", [!!plan.evidence.approvalSource])
|
||||||
|
if (protection?.denied) throw new McpError("PROTECTED_OBJECT", "Восстановление заменяет запрещённый защищённый объект")
|
||||||
|
if (protection) throw new McpError("APPROVAL_REQUIRED", "Полное восстановление затрагивает объект с ручным подтверждением")
|
||||||
return { connection, ids }
|
return { connection, ids }
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -145,7 +147,7 @@ async function executeRestore(operationId: string, principal: McpPrincipal,origi
|
|||||||
if (createHash("sha256").update(buffer).digest("hex") !== source.sha256) throw new McpError("STATE_CONFLICT", "Содержимое архива изменилось", 409)
|
if (createHash("sha256").update(buffer).digest("hex") !== source.sha256) throw new McpError("STATE_CONFLICT", "Содержимое архива изменилось", 409)
|
||||||
if (!(await pool.query("UPDATE mcp_operations SET state='running' WHERE id=$1 AND state='pending' RETURNING id", [operationId])).rowCount) throw new McpError("STATE_CONFLICT", "Операция уже остановлена", 409)
|
if (!(await pool.query("UPDATE mcp_operations SET state='running' WHERE id=$1 AND state='pending' RETURNING id", [operationId])).rowCount) throw new McpError("STATE_CONFLICT", "Операция уже остановлена", 409)
|
||||||
stage = "restore"
|
stage = "restore"
|
||||||
const outcome = await withVerifiedConfigurationChange({ actorId: connection.owner_id, connectionId: connection.id, serverIds: ids, objects: evidence.objects, approved: true, serverWide: true }, () => restoreSystemDatabaseBackup(buffer, { beforeRestore: async () => {
|
const outcome = await withVerifiedConfigurationChange({ actorId: connection.owner_id, connectionId: connection.id, serverIds: ids, objects: evidence.objects, approved: true, approvalSource: plan.evidence.approvalSource, serverWide: true }, () => restoreSystemDatabaseBackup(buffer, { beforeRestore: async () => {
|
||||||
await assertAuthority(); await archive(payload.archiveRef, connection.owner_id)
|
await assertAuthority(); await archive(payload.archiveRef, connection.owner_id)
|
||||||
await durableWrite(filename(source.id, ".used"), JSON.stringify({ operationId, at: new Date().toISOString() }), true)
|
await durableWrite(filename(source.id, ".used"), JSON.stringify({ operationId, at: new Date().toISOString() }), true)
|
||||||
await assertOriginalMcpTemporaryGrant(pool,principal.connectionId,principal.credentialId,originalGrant)
|
await assertOriginalMcpTemporaryGrant(pool,principal.connectionId,principal.credentialId,originalGrant)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { decryptSecret, decryptSecretExisting, fingerprint, privateFingerprinter
|
|||||||
const MAX_BYTES = 2097152
|
const MAX_BYTES = 2097152
|
||||||
const uuid = z.string().uuid()
|
const uuid = z.string().uuid()
|
||||||
const deny = (): never => { throw new McpError("STATE_CONFLICT", "Исходная привязка отмены диагностики не подтверждена", 409) }
|
const deny = (): never => { throw new McpError("STATE_CONFLICT", "Исходная привязка отмены диагностики не подтверждена", 409) }
|
||||||
const sealedSchema = z.object({ sealed: z.string().min(1).max(MAX_BYTES) }).strict()
|
const sealedSchema = z.object({ sealed: z.string().min(1).max(MAX_BYTES), approvalSource: z.literal("connection-policy").optional() }).strict()
|
||||||
interface SourceCrypto { open(value: string): Promise<string>; proof(value: unknown): Promise<string> }
|
interface SourceCrypto { open(value: string): Promise<string>; proof(value: unknown): Promise<string> }
|
||||||
export interface DiagnosticCancellationOwner { connectionId: string; ownerId: string }
|
export interface DiagnosticCancellationOwner { connectionId: string; ownerId: string }
|
||||||
export interface DiagnosticCancellationSource {
|
export interface DiagnosticCancellationSource {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { createMcpConnection, authenticateMcpToken, updateMcpSettings, rotateCon
|
|||||||
import { invokeMcpTool, approvePlan, applyPlan, recoverMcpOperations } from "./runtime.js"
|
import { invokeMcpTool, approvePlan, applyPlan, recoverMcpOperations } from "./runtime.js"
|
||||||
import { decryptSecret, encryptSecret, invalidateMcpAccess, tokenDigest } from "./security.js"
|
import { decryptSecret, encryptSecret, invalidateMcpAccess, tokenDigest } from "./security.js"
|
||||||
import { addRoutingDependencies } from "./routing-dependencies.js"
|
import { addRoutingDependencies } from "./routing-dependencies.js"
|
||||||
|
import { FlowSourceWindowTooLarge } from "../../services/traffic-flow-read-window.js"
|
||||||
import { acceptOspfRouteProofMcp } from "./ospf-route-proof-acceptance.js"
|
import { acceptOspfRouteProofMcp } from "./ospf-route-proof-acceptance.js"
|
||||||
import { acceptNetworkNeighborsMcp } from "./network-neighbors-acceptance.js"
|
import { acceptNetworkNeighborsMcp } from "./network-neighbors-acceptance.js"
|
||||||
import { acceptIpv6NdWriteMcp } from "./ipv6-nd-write-acceptance.js"
|
import { acceptIpv6NdWriteMcp } from "./ipv6-nd-write-acceptance.js"
|
||||||
@@ -1629,13 +1630,33 @@ try {
|
|||||||
await assert.rejects(invokeMcpTool(ospfPrincipal, "mm_ospf_instance_create_plan", { serverId: 1, fields: { name: "blocked-ospf", "router-id": "192.0.2.1", version: "3", vrf: "main" } }))
|
await assert.rejects(invokeMcpTool(ospfPrincipal, "mm_ospf_instance_create_plan", { serverId: 1, fields: { name: "blocked-ospf", "router-id": "192.0.2.1", version: "3", vrf: "main" } }))
|
||||||
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [vrfProtection])
|
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [vrfProtection])
|
||||||
bgpFixtures = true
|
bgpFixtures = true
|
||||||
const bgpAccess = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "BGP dependency test", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:bgp:read", "mm:bgp:write", "mm:network:read"], scope: { serverIds: [1], operationIds: ["ros.bgp_instance.delete", "ros.bgp_instance.update", "ros.bgp_connection.create", "ros.vrf.delete"], allowGlobal: false } }), actor)
|
const bgpAccess = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "BGP dependency test", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:bgp:read", "mm:bgp:write", "mm:network:read"], scope: { serverIds: [1], operationIds: ["ros.bgp_instance.delete", "ros.bgp_instance.update", "ros.bgp_connection.create", "ros.bgp_connection.update", "ros.vrf.delete"], allowGlobal: false } }), actor)
|
||||||
const bgpPrincipal = await authenticateMcpToken(bgpAccess.token)
|
const bgpPrincipal = await authenticateMcpToken(bgpAccess.token)
|
||||||
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_instance_delete_plan", { serverId: 1, id: "*bgp" }), /используется подключением/)
|
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_instance_delete_plan", { serverId: 1, id: "*bgp" }), /используется подключением/)
|
||||||
const peerFields = { name: "new-peer", instance: "missing", "remote.address": "192.0.2.2", "local.address": "192.0.2.1", "remote.as": 64513, "local.role": "ebgp" }
|
const peerFields = { name: "new-peer", instance: "missing", "remote.address": "192.0.2.2", "local.address": "192.0.2.1", "remote.as": 64513, "local.role": "ebgp" }
|
||||||
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_connection_create_plan", { serverId: 1, fields: peerFields }), /Не подтверждена зависимость/)
|
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_connection_create_plan", { serverId: 1, fields: peerFields }), /Не подтверждена зависимость/)
|
||||||
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_connection_create_plan", { serverId: 1, fields: { ...peerFields, instance: "fixture-bgp", "local.address": "fd00::1" } }), /одного семейства/)
|
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_connection_create_plan", { serverId: 1, fields: { ...peerFields, instance: "fixture-bgp", "local.address": "fd00::1" } }), /одного семейства/)
|
||||||
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_connection_create_plan", { serverId: 1, fields: { ...peerFields, instance: "fixture-bgp", "remote.address": "0.0.0.0/0" } }))
|
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_connection_create_plan", { serverId: 1, fields: { ...peerFields, instance: "fixture-bgp", "remote.address": "0.0.0.0/0" } }))
|
||||||
|
const savedPeer = fixtureBgp.connection[0]
|
||||||
|
const preparePassivePeer = () => invokeMcpTool(bgpPrincipal, "mm_bgp_connection_update_plan", {
|
||||||
|
serverId: 1, id: savedPeer[".id"], fields: { connect: false, listen: true },
|
||||||
|
}) as Promise<{ state: string; changes: { steps: { step: { fields: unknown } }[] } }>
|
||||||
|
try {
|
||||||
|
for (const [local, remote] of [["10.255.255.100", "10.255.255.11/32"], ["2001:db8::1", "2001:db8::2/128"]]) {
|
||||||
|
fixtureBgp.connection[0] = { ...savedPeer, "local.address": local, "remote.address": remote }
|
||||||
|
const plan = await preparePassivePeer()
|
||||||
|
assert.equal(plan.state, "awaiting-approval")
|
||||||
|
assert.equal(plan.changes.steps.length, 1)
|
||||||
|
assert.deepEqual(plan.changes.steps[0].step.fields, { connect: "false", listen: "true" })
|
||||||
|
}
|
||||||
|
fixtureBgp.connection[0] = { ...savedPeer, "remote.address": "2001:db8::2/128" }
|
||||||
|
await assert.rejects(preparePassivePeer(), /одного семейства/)
|
||||||
|
fixtureBgp.connection[0] = { ...savedPeer, "remote.address": "192.0.2.2/33" }
|
||||||
|
await assert.rejects(preparePassivePeer(), /Некорректный адрес или префикс/)
|
||||||
|
} finally {
|
||||||
|
fixtureBgp.connection[0] = savedPeer
|
||||||
|
}
|
||||||
|
console.log("✓ MCP BGP dependency validation accepts stored IPv4/IPv6 CIDR for a passive-mode update and rejects mixed families and invalid prefix lengths")
|
||||||
const peerProtection = randomUUID()
|
const peerProtection = randomUUID()
|
||||||
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'integration')", [peerProtection, JSON.stringify({ kind: "bgp_connection", id: "*peer", serverId: 1, protection: "deny" })])
|
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'integration')", [peerProtection, JSON.stringify({ kind: "bgp_connection", id: "*peer", serverId: 1, protection: "deny" })])
|
||||||
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_instance_update_plan", { serverId: 1, id: "*bgp", fields: { as: 64514 } }))
|
await assert.rejects(invokeMcpTool(bgpPrincipal, "mm_bgp_instance_update_plan", { serverId: 1, id: "*bgp", fields: { as: 64514 } }))
|
||||||
@@ -2033,7 +2054,7 @@ try {
|
|||||||
assert.equal(badPeer.configurationMembershipVerified,false); assert.equal(badPeer.incomplete,true); assert.equal(badPeer.failures.length,1); assert.equal(badPeer.exporters[0].storedPeerRecord,null)
|
assert.equal(badPeer.configurationMembershipVerified,false); assert.equal(badPeer.incomplete,true); assert.equal(badPeer.failures.length,1); assert.equal(badPeer.exporters[0].storedPeerRecord,null)
|
||||||
await pool.query("UPDATE traffic_flow_settings SET peers_json=jsonb_set(peers_json,'{0,publicKey}',$1::jsonb) WHERE id=1",[JSON.stringify("public-one")]); invalidateFlowSettings()
|
await pool.query("UPDATE traffic_flow_settings SET peers_json=jsonb_set(peers_json,'{0,publicKey}',$1::jsonb) WHERE id=1",[JSON.stringify("public-one")]); invalidateFlowSettings()
|
||||||
const rawWindow = await flowWindow(5,[1]); assert.equal(rawWindow.rows.length,4); assert.ok(rawWindow.rows.every(row=>row.serverId===1&&row.bucketAt<=rawWindow.until))
|
const rawWindow = await flowWindow(5,[1]); assert.equal(rawWindow.rows.length,4); assert.ok(rawWindow.rows.every(row=>row.serverId===1&&row.bucketAt<=rawWindow.until))
|
||||||
await assert.rejects(flowRows(rawWindow.since,1,{maxRows:1,untilIso:rawWindow.until}),/предел/)
|
await assert.rejects(flowRows(rawWindow.since,1,{maxRows:1,untilIso:rawWindow.until}),FlowSourceWindowTooLarge)
|
||||||
type TalkerPage = { items: {serverId:string;src:string;bytes:number;bps:number}[]; total:number; totalConversations:number; retainedRowsBytes:number; nextOffset:number|null; incomplete:boolean; serverIds:number[] }
|
type TalkerPage = { items: {serverId:string;src:string;bytes:number;bps:number}[]; total:number; totalConversations:number; retainedRowsBytes:number; nextOffset:number|null; incomplete:boolean; serverIds:number[] }
|
||||||
const talkers = await invokeMcpTool(flowPrincipal,"mm_netflow_talkers_get",{minutes:5,limit:1}) as TalkerPage
|
const talkers = await invokeMcpTool(flowPrincipal,"mm_netflow_talkers_get",{minutes:5,limit:1}) as TalkerPage
|
||||||
assert.equal(talkers.retainedRowsBytes,3100); assert.equal(talkers.totalConversations,4); assert.equal(talkers.total,4); assert.equal(talkers.nextOffset,1); assert.equal(talkers.incomplete,true)
|
assert.equal(talkers.retainedRowsBytes,3100); assert.equal(talkers.totalConversations,4); assert.equal(talkers.total,4); assert.equal(talkers.nextOffset,1); assert.equal(talkers.incomplete,true)
|
||||||
@@ -2099,8 +2120,14 @@ try {
|
|||||||
assert.ok(restVisible.every((row:{src:string})=>row.src!=="198.18.242.6"),"Future rows must not enter REST talkers")
|
assert.ok(restVisible.every((row:{src:string})=>row.src!=="198.18.242.6"),"Future rows must not enter REST talkers")
|
||||||
assert.equal((await flowHttp.inject({method:"GET",url:"/api/traffic/flows?range=5m"})).statusCode,200)
|
assert.equal((await flowHttp.inject({method:"GET",url:"/api/traffic/flows?range=5m"})).statusCode,200)
|
||||||
for(const path of ["/api/traffic/flow/exporters?range=5m","/api/traffic/flow/clients?range=5m","/api/traffic/flow/monthly?month="+flowMonth+"&serverId=1"]) { const response = await flowHttp.inject({method:"GET",url:path}); assert.equal(response.statusCode,200,response.body); assert.equal(typeof response.json(),"object") } } finally { await flowHttp.close() }
|
for(const path of ["/api/traffic/flow/exporters?range=5m","/api/traffic/flow/clients?range=5m","/api/traffic/flow/monthly?month="+flowMonth+"&serverId=1"]) { const response = await flowHttp.inject({method:"GET",url:path}); assert.equal(response.statusCode,200,response.body); assert.equal(typeof response.json(),"object") } } finally { await flowHttp.close() }
|
||||||
await pool.query("INSERT INTO flow_buckets(server_id,bucket_at,src,dst,bytes,packets,in_iface) SELECT 1,now()-interval '90 seconds'+n*interval '1 millisecond','198.18.242.11','8.8.8.8',1,1,'cap' FROM generate_series(1,50001) n")
|
await pool.query("INSERT INTO flow_buckets(server_id,bucket_at,src,dst,bytes,packets,in_iface) SELECT 1,now()-interval '90 seconds'+n*interval '1 microsecond','198.18.242.11','8.8.8.8',1,1,'cap' FROM generate_series(1,50001) n")
|
||||||
await assert.rejects(invokeMcpTool(flowPrincipal,"mm_netflow_talkers_get",{minutes:5}), (error:{code?:string})=>error.code==="STATE_UNAVAILABLE")
|
const denseReport = await invokeMcpTool(flowPrincipal, "mm_netflow_talkers_get", { minutes: 5 }) as TalkerPage & {
|
||||||
|
sourceWindow: { requestedMinutes: number; effectiveMinutes: number }; from: string; to: string
|
||||||
|
}
|
||||||
|
assert.equal(denseReport.sourceWindow.requestedMinutes, 5)
|
||||||
|
assert.equal(denseReport.sourceWindow.effectiveMinutes, 1)
|
||||||
|
assert.equal(Date.parse(denseReport.to) - Date.parse(denseReport.from), denseReport.sourceWindow.effectiveMinutes * 60_000)
|
||||||
|
assert(denseReport.items.every(row => row.src !== "198.18.242.11"), "The skipped dense window must not publish a partial page")
|
||||||
await pool.query("DELETE FROM flow_buckets WHERE server_id=1 AND src='198.18.242.11'")
|
await pool.query("DELETE FROM flow_buckets WHERE server_id=1 AND src='198.18.242.11'")
|
||||||
const talkerRace = async (change:()=>Promise<unknown>, principal=flowPrincipal, signal?:AbortSignal) => {
|
const talkerRace = async (change:()=>Promise<unknown>, principal=flowPrincipal, signal?:AbortSignal) => {
|
||||||
const blocker = await pool.connect()
|
const blocker = await pool.connect()
|
||||||
@@ -2134,7 +2161,7 @@ try {
|
|||||||
assert.equal(catalogCalls,0,"Talker history and races must never poll RouterOS")
|
assert.equal(catalogCalls,0,"Talker history and races must never poll RouterOS")
|
||||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans WHERE connection_id=$1",[flowAccess.connection.id])).rows[0].n,0)
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans WHERE connection_id=$1",[flowAccess.connection.id])).rows[0].n,0)
|
||||||
assert.ok(!JSON.stringify((await pool.query("SELECT result FROM mcp_requests WHERE connection_id=$1",[flowAccess.connection.id])).rows).includes("NEVER_FLOW"))
|
assert.ok(!JSON.stringify((await pool.query("SELECT result FROM mcp_requests WHERE connection_id=$1",[flowAccess.connection.id])).rows).includes("NEVER_FLOW"))
|
||||||
console.log("✓ NetFlow talkers: shared REST parity, scoped SQL/pending, topN/pages, 50001-row refusal, real blocked-read source/topN/grant/owner/cancel/pause races, no global fields or network")
|
console.log("✓ NetFlow talkers: shared REST parity, scoped SQL/pending, topN/pages, bounded dense-window fallback, real blocked-read source/topN/grant/owner/cancel/pause races, no global fields or network")
|
||||||
} finally {
|
} finally {
|
||||||
countCatalogCalls = false; clearPendingFlows(); resetFlowRipe()
|
countCatalogCalls = false; clearPendingFlows(); resetFlowRipe()
|
||||||
await pool.query("DELETE FROM app_users WHERE id=ANY($1::text[])",[flowUsers])
|
await pool.query("DELETE FROM app_users WHERE id=ANY($1::text[])",[flowUsers])
|
||||||
@@ -3891,6 +3918,55 @@ try {
|
|||||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_audit WHERE action='owner.revoke' AND payload->>'eventId'=$1", [event.eventId])).rows[0].n, 1)
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_audit WHERE action='owner.revoke' AND payload->>'eventId'=$1", [event.eventId])).rows[0].n, 1)
|
||||||
delete process.env.MCP_PORTAL_WEBHOOK_SECRET
|
delete process.env.MCP_PORTAL_WEBHOOK_SECRET
|
||||||
console.log("✓ Signed portal revocation: tamper/stale rejection, one atomic event, revoked credentials and stale-JWT regrant prevention")
|
console.log("✓ Signed portal revocation: tamper/stale rejection, one atomic event, revoked credentials and stale-JWT regrant prevention")
|
||||||
|
{
|
||||||
|
const serviceInput = mcpConnectionCreateSchema.parse({
|
||||||
|
name: "Announced service plans", authority: "service", allowUnattendedPlans: true, mode: "autonomous", expiresAt: null,
|
||||||
|
permissions: ["mm:network:write", "mm:settings:admin"],
|
||||||
|
scope: { serverIds: (await pool.query<{ id: number }>("SELECT id FROM servers")).rows.map(({ id }) => id),
|
||||||
|
allowGlobal: true, operationIds: ["ros.ip_settings.update", "logs.settings.update", "changes.read", "changes.apply"] },
|
||||||
|
limits: { mutationsPerHour: 500, objectsPerPlan: 500, serversPerPlan: 100 },
|
||||||
|
})
|
||||||
|
const { token } = await createMcpConnection(serviceInput, actor)
|
||||||
|
const service = await authenticateMcpToken(token)
|
||||||
|
const prepare = () => invokeMcpTool(service, "mm_ip_settings_update_plan", { serverId: 1, fields: { "rp-filter": "loose" } }) as Promise<{ planId: string; state: string; announcement?: { digest: string } }>
|
||||||
|
const beforeWrites = writes
|
||||||
|
const first = await prepare()
|
||||||
|
assert.equal(first.state, "draft")
|
||||||
|
assert.match(first.announcement!.digest, /^[a-f0-9]{64}$/)
|
||||||
|
const inspected = await invokeMcpTool(service, "mm_change_get", { planId: first.planId }) as { announcement: { digest: string } }
|
||||||
|
assert.equal(inspected.announcement.digest, first.announcement!.digest)
|
||||||
|
const apply = (planId: string, digest?: string) => invokeMcpTool(service, "mm_change_apply", {
|
||||||
|
planId, idempotencyKey: randomUUID(), ...(digest && { announcedPlanDigest: digest }),
|
||||||
|
}) as Promise<{ id: string }>
|
||||||
|
const denied = { code: "APPROVAL_REQUIRED" }
|
||||||
|
await assert.rejects(apply(first.planId), denied)
|
||||||
|
const second = await prepare()
|
||||||
|
await assert.rejects(apply(first.planId, second.announcement!.digest), denied)
|
||||||
|
const protection = randomUUID()
|
||||||
|
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'integration')", [protection, JSON.stringify({ kind: "server", id: "1", serverId: 1, protection: "human-approval-required" })])
|
||||||
|
try {
|
||||||
|
await assert.rejects(apply(first.planId, first.announcement!.digest), denied)
|
||||||
|
const protectedPlan = await prepare()
|
||||||
|
assert.equal(protectedPlan.state, "awaiting-approval")
|
||||||
|
assert.equal(protectedPlan.announcement, undefined)
|
||||||
|
assert.equal(writes, beforeWrites)
|
||||||
|
} finally { await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection]) }
|
||||||
|
const operation = await apply(first.planId, first.announcement!.digest)
|
||||||
|
await awaitOperation(operation.id, "applied")
|
||||||
|
assert.equal(writes, beforeWrites + 1)
|
||||||
|
const publicResult = await invokeMcpTool(service, "mm_change_get", { planId: first.planId }) as { approvalSource: string; approvedBy: string | null }
|
||||||
|
assert.equal(publicResult.approvalSource, "connection-policy")
|
||||||
|
assert.equal(publicResult.approvedBy, null)
|
||||||
|
const { rows: [start] } = await pool.query("SELECT payload FROM mcp_audit WHERE action='operation.start' AND payload->>'planId'=$1", [first.planId])
|
||||||
|
assert.equal(start.payload.announcedPlanDigest, first.announcement!.digest)
|
||||||
|
assert.equal((await pool.query("SELECT 1 FROM mcp_audit WHERE action='plan.approve' AND payload->>'planId'=$1", [first.planId])).rowCount, 0)
|
||||||
|
const { getLogSettings } = await import("../../services/router-logs-collector.js")
|
||||||
|
const retentionDays = Math.min(365, (await getLogSettings()).retentionDays + 1)
|
||||||
|
const global = await invokeMcpTool(service, "mm_logs_settings_update_plan", { settings: { retentionDays } }) as { planId: string; announcement: { digest: string } }
|
||||||
|
await awaitOperation((await apply(global.planId, global.announcement.digest)).id, "applied")
|
||||||
|
assert.equal((await getLogSettings()).retentionDays, retentionDays)
|
||||||
|
console.log("✓ Unattended MCP checks exact plan digest, current protections and delegated provenance for RouterOS and application writes")
|
||||||
|
}
|
||||||
await setConnectionStatus(issued.connection.id, "paused", actor)
|
await setConnectionStatus(issued.connection.id, "paused", actor)
|
||||||
await assert.rejects(authenticateMcpToken(rotated.token))
|
await assert.rejects(authenticateMcpToken(rotated.token))
|
||||||
await setConnectionStatus(issued.connection.id, "active", actor)
|
await setConnectionStatus(issued.connection.id, "active", actor)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import { assertNoOperationConfigurationLockContext } from "../../services/operat
|
|||||||
import { validatePrincipal, audit, type McpPrincipal, type StoredOperation } from "./store.js"
|
import { validatePrincipal, audit, type McpPrincipal, type StoredOperation } from "./store.js"
|
||||||
import { decryptSecret, fingerprint, McpError, mcpStateDirectory, privateFingerprinterExisting } from "./security.js"
|
import { decryptSecret, fingerprint, McpError, mcpStateDirectory, privateFingerprinterExisting } from "./security.js"
|
||||||
import { findActionByOperation } from "./actions.js"
|
import { findActionByOperation } from "./actions.js"
|
||||||
import { evaluateMcpPolicy } from "./policy.js"
|
import { evaluateMcpPolicy, hasUnattendedPlanAuthority, operationApprovalRequirement } from "./policy.js"
|
||||||
import { changeMutationCost } from "./change-cost.js"
|
import { changeMutationCost } from "./change-cost.js"
|
||||||
import { assertOriginalMcpTemporaryGrant, type OriginalServiceGrant } from "./temporary-grant-origin.js"
|
import { assertOriginalMcpTemporaryGrant, type OriginalServiceGrant } from "./temporary-grant-origin.js"
|
||||||
import type { ChangeEvidence } from "./action-types.js"
|
import type { ChangeEvidence } from "./action-types.js"
|
||||||
@@ -24,7 +24,7 @@ export const MCP_OPERATION_PRIVATE_CLAIM_KEY = "__mmappMcpOperationClaimV1"
|
|||||||
export interface McpOperationExecutionMetadata {
|
export interface McpOperationExecutionMetadata {
|
||||||
readonly operationId: string; readonly planId: string; readonly connectionId: string; readonly ownerId: string
|
readonly operationId: string; readonly planId: string; readonly connectionId: string; readonly ownerId: string
|
||||||
readonly operationName: string; readonly operationVersion: number; readonly policyVersion: number; readonly generation: string
|
readonly operationName: string; readonly operationVersion: number; readonly policyVersion: number; readonly generation: string
|
||||||
readonly phase: "forward"; readonly approved: boolean; readonly principal: Readonly<McpPrincipal>
|
readonly phase: "forward"; readonly approved: boolean; readonly approvalSource?: "connection-policy"; readonly principal: Readonly<McpPrincipal>
|
||||||
readonly sealedEvidenceProof: string; readonly sealedPayloadProof: string
|
readonly sealedEvidenceProof: string; readonly sealedPayloadProof: string
|
||||||
readonly originalTemporaryGrantProof: string; readonly originalTemporaryGrantExpiresAt: number | null; readonly originalExpiresAt: number
|
readonly originalTemporaryGrantProof: string; readonly originalTemporaryGrantExpiresAt: number | null; readonly originalExpiresAt: number
|
||||||
readonly serverIds: readonly number[]; readonly resources: readonly McpObjectRef[]
|
readonly serverIds: readonly number[]; readonly resources: readonly McpObjectRef[]
|
||||||
@@ -40,7 +40,7 @@ declare const admissionBrand: unique symbol
|
|||||||
export type McpOperationAdmissionStart = Readonly<{ [admissionStartBrand]: true }>
|
export type McpOperationAdmissionStart = Readonly<{ [admissionStartBrand]: true }>
|
||||||
export type McpOperationAdmission = Readonly<{ [admissionBrand]: true }>
|
export type McpOperationAdmission = Readonly<{ [admissionBrand]: true }>
|
||||||
type Admission = { operationId: string; planId: string; connectionId: string; nonce: string; principal: Readonly<McpPrincipal>; grant: Readonly<OriginalServiceGrant>
|
type Admission = { operationId: string; planId: string; connectionId: string; nonce: string; principal: Readonly<McpPrincipal>; grant: Readonly<OriginalServiceGrant>
|
||||||
generation: string; directory: string; keyEpoch: string; operationName: string; operationVersion: number; policyVersion: number; evidenceProof: string; payloadProof: string }
|
generation: string; directory: string; keyEpoch: string; operationName: string; operationVersion: number; policyVersion: number; evidenceProof: string; payloadProof: string; approvalSource?: "connection-policy" }
|
||||||
const starts = new WeakMap<object, { principal: Readonly<McpPrincipal>; wall: number; mono: number; directory: string; generation: string; keyEpoch: string }>(), admissions = new WeakMap<object, Admission>()
|
const starts = new WeakMap<object, { principal: Readonly<McpPrincipal>; wall: number; mono: number; directory: string; generation: string; keyEpoch: string }>(), admissions = new WeakMap<object, Admission>()
|
||||||
const deny = (): never => { throw new McpError("PERMISSION_DENIED", "Исходный MCP operation root недоступен", 403) }
|
const deny = (): never => { throw new McpError("PERMISSION_DENIED", "Исходный MCP operation root недоступен", 403) }
|
||||||
const purpose = "mcp-operation-execution-origin-v1", keyMessage = "mcp-operation-execution-origin-key-epoch-v1"
|
const purpose = "mcp-operation-execution-origin-v1", keyMessage = "mcp-operation-execution-origin-key-epoch-v1"
|
||||||
@@ -142,7 +142,7 @@ export async function insertMcpOperationAdmission(client: PoolClient, start: Mcp
|
|||||||
const admission = Object.freeze(Object.create(null)) as McpOperationAdmission
|
const admission = Object.freeze(Object.create(null)) as McpOperationAdmission
|
||||||
admissions.set(admission, { operationId: id, planId, connectionId: principal.connectionId, nonce: randomUUID(), principal, grant,
|
admissions.set(admission, { operationId: id, planId, connectionId: principal.connectionId, nonce: randomUUID(), principal, grant,
|
||||||
generation: row.generation, directory: anchor.directory, keyEpoch: anchor.keyEpoch, operationName: row.operation_id, operationVersion: row.operation_version, policyVersion: row.policy_version,
|
generation: row.generation, directory: anchor.directory, keyEpoch: anchor.keyEpoch, operationName: row.operation_id, operationVersion: row.operation_version, policyVersion: row.policy_version,
|
||||||
evidenceProof: sha(row.evidence.sealed), payloadProof: sha(row.payload.sealed) })
|
evidenceProof: sha(row.evidence.sealed), payloadProof: sha(row.payload.sealed), approvalSource: row.evidence.approvalSource })
|
||||||
return { operation: inserted.rows[0], admission, originalGrant: grant }
|
return { operation: inserted.rows[0], admission, originalGrant: grant }
|
||||||
}
|
}
|
||||||
function grantFrom(row: Record<string, unknown>, principal: McpPrincipal) {
|
function grantFrom(row: Record<string, unknown>, principal: McpPrincipal) {
|
||||||
@@ -160,23 +160,25 @@ function source(entry: Entry, row: Record<string, unknown>, state: "pending" | "
|
|||||||
|| state === "running" && row.claim_nonce !== entry.nonce || row.plan_state !== "executing" || row.owner_id !== m.ownerId
|
|| state === "running" && row.claim_nonce !== entry.nonce || row.plan_state !== "executing" || row.owner_id !== m.ownerId
|
||||||
|| row.operation_id !== m.operationName || row.operation_version !== m.operationVersion || row.policy_version !== m.policyVersion
|
|| row.operation_id !== m.operationName || row.operation_version !== m.operationVersion || row.policy_version !== m.policyVersion
|
||||||
|| row.generation !== m.generation || row.connection_generation !== m.generation || !!row.approved_by !== m.approved
|
|| row.generation !== m.generation || row.connection_generation !== m.generation || !!row.approved_by !== m.approved
|
||||||
|
|| m.approvalSource && row.approved_by !== m.ownerId
|
||||||
|| !(row.expires_at instanceof Date) || row.expires_at.getTime() < m.originalExpiresAt
|
|| !(row.expires_at instanceof Date) || row.expires_at.getTime() < m.originalExpiresAt
|
||||||
|| !row.evidence || typeof row.evidence !== "object" || !row.payload || typeof row.payload !== "object") deny()
|
|| !row.evidence || typeof row.evidence !== "object" || !row.payload || typeof row.payload !== "object") deny()
|
||||||
const evidence = row.evidence as { sealed?: unknown }, payload = row.payload as { sealed?: unknown }
|
const evidence = row.evidence as { sealed?: unknown; approvalSource?: unknown }, payload = row.payload as { sealed?: unknown }
|
||||||
if (typeof evidence.sealed !== "string" || typeof payload.sealed !== "string" || sha(evidence.sealed) !== m.sealedEvidenceProof || sha(payload.sealed) !== m.sealedPayloadProof) deny()
|
if (typeof evidence.sealed !== "string" || typeof payload.sealed !== "string" || evidence.approvalSource !== m.approvalSource || sha(evidence.sealed) !== m.sealedEvidenceProof || sha(payload.sealed) !== m.sealedPayloadProof) deny()
|
||||||
const action = findActionByOperation(m.operationName)
|
const action = findActionByOperation(m.operationName)
|
||||||
if (action.operation.version !== m.operationVersion) deny()
|
if (action.operation.version !== m.operationVersion) deny()
|
||||||
const grant = grantFrom(row, m.principal)
|
const grant = grantFrom(row, m.principal)
|
||||||
if (grant.proof !== m.originalTemporaryGrantProof || grant.expiresAt !== m.originalTemporaryGrantExpiresAt || !Array.isArray(row.protections) || row.protections.length > 1000) deny()
|
if (grant.proof !== m.originalTemporaryGrantProof || grant.expiresAt !== m.originalTemporaryGrantExpiresAt || !Array.isArray(row.protections) || row.protections.length > 1000) deny()
|
||||||
const policy = row.policy as Parameters<typeof evaluateMcpPolicy>[0]["policy"]
|
const policy = row.policy as Parameters<typeof evaluateMcpPolicy>[0]["policy"]
|
||||||
const protections = row.protections as Parameters<typeof evaluateMcpPolicy>[0]["protections"]
|
const protections = row.protections as Parameters<typeof evaluateMcpPolicy>[0]["protections"]
|
||||||
if (policy.version !== m.policyVersion || !(row.owner_valid_until instanceof Date) || row.owner_valid_until.getTime() < m.originalExpiresAt) deny()
|
if (policy.version !== m.policyVersion || m.approvalSource && !hasUnattendedPlanAuthority(policy) || !(row.owner_valid_until instanceof Date) || row.owner_valid_until.getTime() < m.originalExpiresAt) deny()
|
||||||
|
const approval = operationApprovalRequirement(policy, m.operationName, m.evidence.target, m.evidence.requiresHuman)
|
||||||
const decision = evaluateMcpPolicy({ operationId: m.operationName, policy, ownerPermissions: row.owner_permissions as string[], target: m.evidence.target,
|
const decision = evaluateMcpPolicy({ operationId: m.operationName, policy, ownerPermissions: row.owner_permissions as string[], target: m.evidence.target,
|
||||||
objects: [...m.evidence.objects, ...(m.evidence.requiresHuman && m.evidence.target.scope !== "servers" ? [{ kind: "mcp-operation", id: m.operationName }] : [])],
|
objects: [...m.evidence.objects, ...approval.objects],
|
||||||
objectCount: changeMutationCost(m.evidence) + (m.evidence.recovery ? 1 : 0),
|
objectCount: changeMutationCost(m.evidence) + (m.evidence.recovery ? 1 : 0),
|
||||||
protections: [...protections, ...(m.evidence.requiresHuman && m.evidence.target.scope === "servers" ? m.evidence.target.serverIds.map(serverId => ({ kind: "server", id: String(serverId), serverId, protection: "human-approval-required" as const })) : [])],
|
protections: [...protections, ...approval.protections],
|
||||||
usage: { callsInMinute: 0, mutationsInHour: 0, concurrentReads: Number(row.concurrent_reads) }, auditAvailable: true, temporaryGrant: grant.value })
|
usage: { callsInMinute: 0, mutationsInHour: 0, concurrentReads: Number(row.concurrent_reads) }, auditAvailable: true, temporaryGrant: grant.value })
|
||||||
if (decision.decision === "denied" || decision.decision === "approval-required" && !m.approved) deny()
|
if (decision.decision === "denied" || decision.decision === "approval-required" && (!m.approved || m.approvalSource)) deny()
|
||||||
}
|
}
|
||||||
/** Two current joined snapshots around real principal/grant checks. Nothing is
|
/** Two current joined snapshots around real principal/grant checks. Nothing is
|
||||||
* cached across calls; the final SQL validates exact source + policy + grant. */
|
* cached across calls; the final SQL validates exact source + policy + grant. */
|
||||||
@@ -268,13 +270,14 @@ export async function withMcpOperationExecutionOrigin(admission: unknown, work:
|
|||||||
if (row.operation_state !== "pending") { interruptOwn = false; return }
|
if (row.operation_state !== "pending") { interruptOwn = false; return }
|
||||||
if (!row.evidence?.sealed || !row.payload?.sealed || row.connection_generation !== generation || row.generation !== generation
|
if (!row.evidence?.sealed || !row.payload?.sealed || row.connection_generation !== generation || row.generation !== generation
|
||||||
|| row.plan_id !== admitted.planId || generation !== admitted.generation || row.operation_id !== admitted.operationName || row.operation_version !== admitted.operationVersion
|
|| row.plan_id !== admitted.planId || generation !== admitted.generation || row.operation_id !== admitted.operationName || row.operation_version !== admitted.operationVersion
|
||||||
|| row.policy_version !== admitted.policyVersion || sha(row.evidence.sealed) !== admitted.evidenceProof || sha(row.payload.sealed) !== admitted.payloadProof) return deny()
|
|| row.policy_version !== admitted.policyVersion || row.evidence.approvalSource !== admitted.approvalSource
|
||||||
|
|| sha(row.evidence.sealed) !== admitted.evidenceProof || sha(row.payload.sealed) !== admitted.payloadProof) return deny()
|
||||||
const evidence = JSON.parse(await decryptSecret(row.evidence.sealed)) as ChangeEvidence, privateInput = JSON.parse(await decryptSecret(row.payload.sealed)) as Record<string, unknown>
|
const evidence = JSON.parse(await decryptSecret(row.evidence.sealed)) as ChangeEvidence, privateInput = JSON.parse(await decryptSecret(row.payload.sealed)) as Record<string, unknown>
|
||||||
if (!Array.isArray(evidence.steps) || !Array.isArray(evidence.objects) || !Array.isArray(evidence.snapshots) || !privateInput || typeof privateInput !== "object" || Array.isArray(privateInput)) return deny()
|
if (!Array.isArray(evidence.steps) || !Array.isArray(evidence.objects) || !Array.isArray(evidence.snapshots) || !privateInput || typeof privateInput !== "object" || Array.isArray(privateInput)) return deny()
|
||||||
const expiresAt = Math.min(originalGrant.admissionExpiresAt, row.expires_at.getTime(), Date.parse(capturedPrincipal.credentialExpiresAt), Date.parse(connection.policy.expiresAt), connection.owner_valid_until.getTime(), evidence.validUntil ? Date.parse(evidence.validUntil) : Infinity)
|
const expiresAt = Math.min(originalGrant.admissionExpiresAt, row.expires_at.getTime(), Date.parse(capturedPrincipal.credentialExpiresAt), Date.parse(connection.policy.expiresAt), connection.owner_valid_until.getTime(), evidence.validUntil ? Date.parse(evidence.validUntil) : Infinity)
|
||||||
const metadata = frozen({ operationId, planId: String(row.plan_id), connectionId: capturedPrincipal.connectionId, ownerId: connection.owner_id,
|
const metadata = frozen({ operationId, planId: String(row.plan_id), connectionId: capturedPrincipal.connectionId, ownerId: connection.owner_id,
|
||||||
operationName: String(row.operation_id), operationVersion: Number(row.operation_version), policyVersion: Number(row.policy_version), generation, phase: "forward" as const,
|
operationName: String(row.operation_id), operationVersion: Number(row.operation_version), policyVersion: Number(row.policy_version), generation, phase: "forward" as const,
|
||||||
approved: !!row.approved_by, principal: capturedPrincipal, sealedEvidenceProof: sha(row.evidence.sealed), sealedPayloadProof: sha(row.payload.sealed),
|
approved: !!row.approved_by, ...(admitted.approvalSource && { approvalSource: admitted.approvalSource }), principal: capturedPrincipal, sealedEvidenceProof: sha(row.evidence.sealed), sealedPayloadProof: sha(row.payload.sealed),
|
||||||
originalTemporaryGrantProof: originalGrant.proof, originalTemporaryGrantExpiresAt: originalGrant.expiresAt, originalExpiresAt: expiresAt,
|
originalTemporaryGrantProof: originalGrant.proof, originalTemporaryGrantExpiresAt: originalGrant.expiresAt, originalExpiresAt: expiresAt,
|
||||||
serverIds: [...new Set([...(evidence.target.scope === "servers" ? evidence.target.serverIds : []), ...evidence.objects.flatMap(object => object.serverId === undefined ? [] : [object.serverId])])].sort((a, b) => a - b),
|
serverIds: [...new Set([...(evidence.target.scope === "servers" ? evidence.target.serverIds : []), ...evidence.objects.flatMap(object => object.serverId === undefined ? [] : [object.serverId])])].sort((a, b) => a - b),
|
||||||
resources: structuredClone(evidence.objects), privateInput, evidence })
|
resources: structuredClone(evidence.objects), privateInput, evidence })
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { decryptSecretExisting, fingerprint, privateFingerprinterExisting, redac
|
|||||||
const uuid = z.string().uuid()
|
const uuid = z.string().uuid()
|
||||||
const positive = z.number().int().positive().safe()
|
const positive = z.number().int().positive().safe()
|
||||||
const object = z.record(z.string(),z.unknown())
|
const object = z.record(z.string(),z.unknown())
|
||||||
const sealed = z.object({sealed:z.string().min(1).max(262144)}).strict()
|
const sealed = z.object({sealed:z.string().min(1).max(262144),approvalSource:z.literal("connection-policy").optional()}).strict()
|
||||||
const ids = z.array(positive).max(1000)
|
const ids = z.array(positive).max(1000)
|
||||||
const retention = z.number().int().min(1).max(365)
|
const retention = z.number().int().min(1).max(365)
|
||||||
const bool = z.boolean()
|
const bool = z.boolean()
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import assert from "node:assert/strict"
|
import assert from "node:assert/strict"
|
||||||
import { test } from "node:test"
|
import { test } from "node:test"
|
||||||
import { mcpOperationDescriptorSchema, mcpPolicyPreviewRequestSchema, mcpPolicyDecisionSchema, mcpTemporaryGrantSchema, type McpPolicyPreviewRequest } from "@mmapp/contracts/mcp"
|
import { MCP_SERVICE_EXPIRATION, mcpConnectionPolicySchema, mcpOperationDescriptorSchema, mcpPolicyPreviewRequestSchema, mcpPolicyDecisionSchema, mcpTemporaryGrantSchema, type McpPolicyPreviewRequest } from "@mmapp/contracts/mcp"
|
||||||
import { evaluateMcpPolicy } from "./policy.js"
|
import { evaluateMcpPolicy } from "./policy.js"
|
||||||
import { findMcpOperation, listMcpOperations } from "./registry.js"
|
import { findMcpOperation, listMcpOperations } from "./registry.js"
|
||||||
|
|
||||||
@@ -42,6 +42,19 @@ test("mode × dangerous policy matrix never grants autonomy implicitly", () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("unattended plans require an explicit service policy and retain server protections", () => {
|
||||||
|
const input = request()
|
||||||
|
assert.equal(mcpConnectionPolicySchema.safeParse({ ...input.policy, allowUnattendedPlans: true }).success, false)
|
||||||
|
input.policy = mcpConnectionPolicySchema.parse({ ...input.policy, authority: "service", expiresAt: MCP_SERVICE_EXPIRATION })
|
||||||
|
assert.equal(evaluateMcpPolicy(input, now).decision, "approval-required")
|
||||||
|
input.policy.allowUnattendedPlans = true
|
||||||
|
assert.equal(evaluateMcpPolicy(input, now).decision, "allowed")
|
||||||
|
input.protections = [{ kind: "server", id: "1", protection: "human-approval-required" }]
|
||||||
|
assert.equal(evaluateMcpPolicy(input, now).decision, "approval-required")
|
||||||
|
input.protections[0].protection = "deny"
|
||||||
|
denied(input, "PROTECTED_OBJECT")
|
||||||
|
})
|
||||||
|
|
||||||
test("observer reads permitted logs, but cannot run bandwidth or create users", () => {
|
test("observer reads permitted logs, but cannot run bandwidth or create users", () => {
|
||||||
const read = request("logs.query"); read.policy.mode = "observer"
|
const read = request("logs.query"); read.policy.mode = "observer"
|
||||||
assert.equal(evaluateMcpPolicy(read, now).decision, "allowed")
|
assert.equal(evaluateMcpPolicy(read, now).decision, "allowed")
|
||||||
|
|||||||
@@ -3,10 +3,22 @@ import {
|
|||||||
type McpPolicyDecision,
|
type McpPolicyDecision,
|
||||||
type McpPolicyPreviewRequest,
|
type McpPolicyPreviewRequest,
|
||||||
type McpPolicyReasonCode,
|
type McpPolicyReasonCode,
|
||||||
|
type McpConnectionPolicy,
|
||||||
} from "@mmapp/contracts/mcp"
|
} from "@mmapp/contracts/mcp"
|
||||||
import { hasPermission } from "../../lib/permissions.js"
|
import { hasPermission } from "../../lib/permissions.js"
|
||||||
import { findMcpOperation } from "./registry.js"
|
import { findMcpOperation } from "./registry.js"
|
||||||
|
|
||||||
|
export function hasUnattendedPlanAuthority(policy: McpConnectionPolicy) {
|
||||||
|
return policy.authority === "service" && policy.mode === "autonomous" && policy.allowUnattendedPlans === true
|
||||||
|
}
|
||||||
|
|
||||||
|
export function operationApprovalRequirement(policy: McpConnectionPolicy, operationId: string, target: McpPolicyPreviewRequest["target"], requiresHuman?: boolean): Pick<McpPolicyPreviewRequest, "objects" | "protections"> {
|
||||||
|
if (!requiresHuman || hasUnattendedPlanAuthority(policy)) return { objects: [], protections: [] }
|
||||||
|
const objects = target.scope === "servers" ? [] : [{ kind: "mcp-operation", id: operationId }]
|
||||||
|
const protectedObjects = target.scope === "servers" ? target.serverIds.map(serverId => ({ kind: "server", id: String(serverId), serverId })) : objects
|
||||||
|
return { objects, protections: protectedObjects.map(object => ({ ...object, protection: "human-approval-required" })) }
|
||||||
|
}
|
||||||
|
|
||||||
/** Pure policy simulation. Does not grant authority, reserve budgets or execute handlers. */
|
/** Pure policy simulation. Does not grant authority, reserve budgets or execute handlers. */
|
||||||
export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Date()): McpPolicyDecision {
|
export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Date()): McpPolicyDecision {
|
||||||
const input = mcpPolicyPreviewRequestSchema.parse(payload)
|
const input = mcpPolicyPreviewRequestSchema.parse(payload)
|
||||||
@@ -87,7 +99,7 @@ export function evaluateMcpPolicy(payload: McpPolicyPreviewRequest, now = new Da
|
|||||||
else approve("Защищённый объект требует подтверждения человеком")
|
else approve("Защищённый объект требует подтверждения человеком")
|
||||||
}
|
}
|
||||||
if (policy.mode === "approval") approve("Режим подключения требует подтверждения человеком")
|
if (policy.mode === "approval") approve("Режим подключения требует подтверждения человеком")
|
||||||
if (operation.risk === "dangerous" && !(policy.dangerousPolicy === "explicit-allow" && policy.autonomousDangerousOperationIds.includes(operation.id))) {
|
if (operation.risk === "dangerous" && !hasUnattendedPlanAuthority(policy) && !(policy.dangerousPolicy === "explicit-allow" && policy.autonomousDangerousOperationIds.includes(operation.id))) {
|
||||||
approve("Опасная операция не разрешена для автономного выполнения")
|
approve("Опасная операция не разрешена для автономного выполнения")
|
||||||
}
|
}
|
||||||
return result()
|
return result()
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import ts from "typescript"
|
|||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
import { routeAiControllerBlockReason, routeAiProfileSchema, usesScopedRouteAiContext } from "@mmapp/contracts/mcp-routing"
|
import { routeAiControllerBlockReason, routeAiProfileSchema, usesScopedRouteAiContext } from "@mmapp/contracts/mcp-routing"
|
||||||
import { fingerprint, McpError } from "./security.js"
|
import { fingerprint, McpError } from "./security.js"
|
||||||
|
import { hasUnattendedPlanAuthority } from "./policy.js"
|
||||||
|
|
||||||
type Handler = { prepare?: (input: Record<string, unknown>, context: unknown) => Promise<Record<string, unknown>>; execute?: (input: Record<string, unknown>) => Promise<unknown> }
|
type Handler = { prepare?: (input: Record<string, unknown>, context: unknown) => Promise<Record<string, unknown>>; execute?: (input: Record<string, unknown>) => Promise<unknown> }
|
||||||
async function load(name: string, providers: Record<string, unknown>) {
|
async function load(name: string, providers: Record<string, unknown>) {
|
||||||
@@ -47,6 +48,7 @@ async function fixture() {
|
|||||||
"./path-proof-purpose.js": { COMMUNITY_PATH_MAX_AGE_MS: 90000 },
|
"./path-proof-purpose.js": { COMMUNITY_PATH_MAX_AGE_MS: 90000 },
|
||||||
"./routing-controller-fence.js": { saveControllerProfileCas: async () => { casWrites++; return { id: "saved", version: 1 } } },
|
"./routing-controller-fence.js": { saveControllerProfileCas: async () => { casWrites++; return { id: "saved", version: 1 } } },
|
||||||
"./routing-reservation-store.js": { createRoutingReservationStore: () => { throw new Error("Overlap-only fixture must not read or mutate routing charges") } },
|
"./routing-reservation-store.js": { createRoutingReservationStore: () => { throw new Error("Overlap-only fixture must not read or mutate routing charges") } },
|
||||||
|
"./policy.js": { hasUnattendedPlanAuthority },
|
||||||
})
|
})
|
||||||
const register = profileModule.registerRoutingProfileActions as (register: (...args: unknown[]) => void) => void
|
const register = profileModule.registerRoutingProfileActions as (register: (...args: unknown[]) => void) => void
|
||||||
register((...args) => operations.set(String(args[0]), args.at(-1) as Handler))
|
register((...args) => operations.set(String(args[0]), args.at(-1) as Handler))
|
||||||
|
|||||||
@@ -134,6 +134,15 @@ export async function resolveOspfInterfaceSelectors(serverId: number, selectors:
|
|||||||
return names
|
return names
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function bgpAddressFamily(value: string): number {
|
||||||
|
if (!value.includes("/")) return isIP(value)
|
||||||
|
try {
|
||||||
|
return isIP(canonicalBgpPolicyPrefix(value).split("/")[0])
|
||||||
|
} catch {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function addRoutingDependencies(serverId: number, resource: string, action: RosStep["action"], current: ConfigurationRow | undefined, fields: Record<string, string>, snapshots: RosSnapshot[], objects: ChangeEvidence["objects"]) {
|
export async function addRoutingDependencies(serverId: number, resource: string, action: RosStep["action"], current: ConfigurationRow | undefined, fields: Record<string, string>, snapshots: RosSnapshot[], objects: ChangeEvidence["objects"]) {
|
||||||
const read = async (id: string) => {
|
const read = async (id: string) => {
|
||||||
const existing = snapshots.find(snapshot => snapshot.resource === id)
|
const existing = snapshots.find(snapshot => snapshot.resource === id)
|
||||||
@@ -227,7 +236,11 @@ export async function addRoutingDependencies(serverId: number, resource: string,
|
|||||||
}
|
}
|
||||||
if (resource === "bgp_connection") {
|
if (resource === "bgp_connection") {
|
||||||
const local = fields["local.address"] ?? current?.["local.address"], remote = fields["remote.address"] ?? current?.["remote.address"]
|
const local = fields["local.address"] ?? current?.["local.address"], remote = fields["remote.address"] ?? current?.["remote.address"]
|
||||||
if (typeof local === "string" && typeof remote === "string" && isIP(local) !== isIP(remote)) throw new McpError("INVALID_INPUT", "Адреса BGP-соединения должны быть одного семейства", 400)
|
if (typeof local === "string" && typeof remote === "string") {
|
||||||
|
const localFamily = bgpAddressFamily(local), remoteFamily = bgpAddressFamily(remote)
|
||||||
|
if (!localFamily || !remoteFamily) throw new McpError("INVALID_INPUT", "Некорректный адрес или префикс BGP-соединения", 400)
|
||||||
|
if (localFamily !== remoteFamily) throw new McpError("INVALID_INPUT", "Адреса BGP-соединения должны быть одного семейства", 400)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (resource === "bgp_instance" && current && ["as", "router-id", "disabled"].some(key => fields[key] !== undefined && fields[key] !== current[key])) {
|
if (resource === "bgp_instance" && current && ["as", "router-id", "disabled"].some(key => fields[key] !== undefined && fields[key] !== current[key])) {
|
||||||
for (const row of (await read("bgp_connection")).rows.filter(row => [current.name, current[".id"]].includes(row.instance))) objects.push({ kind: "bgp_connection", id: String(row[".id"]), serverId })
|
for (const row of (await read("bgp_connection")).rows.filter(row => [current.name, current[".id"]].includes(row.instance))) objects.push({ kind: "bgp_connection", id: String(row[".id"]), serverId })
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import type { ActionContext } from "./action-types.js"
|
|||||||
import { COMMUNITY_PATH_MAX_AGE_MS } from "./path-proof-purpose.js"
|
import { COMMUNITY_PATH_MAX_AGE_MS } from "./path-proof-purpose.js"
|
||||||
import { controllerProfileCurrent, publishControllerState, saveControllerProfileCas, withControllerProfileLease } from "./routing-controller-fence.js"
|
import { controllerProfileCurrent, publishControllerState, saveControllerProfileCas, withControllerProfileLease } from "./routing-controller-fence.js"
|
||||||
import { assertIdentifiedRoutingCompletion, createRoutingReservationStore } from "./routing-reservation-store.js"
|
import { assertIdentifiedRoutingCompletion, createRoutingReservationStore } from "./routing-reservation-store.js"
|
||||||
|
import { hasUnattendedPlanAuthority } from "./policy.js"
|
||||||
|
|
||||||
const targetIds = (profile: RouteAiProfile) => [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])]
|
const targetIds = (profile: RouteAiProfile) => [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])]
|
||||||
const profilePublicColumns = "id,version,config,state,enabled,grant_expires_at,updated_at"
|
const profilePublicColumns = "id,version,config,state,enabled,grant_expires_at,updated_at"
|
||||||
@@ -142,6 +143,7 @@ async function tickAdmittedRoutingProfiles() {
|
|||||||
next.reason = "Изменение конфигурации проверено; ожидаются новые измерения сети"
|
next.reason = "Изменение конфигурации проверено; ожидаются новые измерения сети"
|
||||||
} else if (plan.operation_id) next.reason = "Операция выполняется"
|
} else if (plan.operation_id) next.reason = "Операция выполняется"
|
||||||
else if (plan.expires_at.getTime() <= Date.now()) { await stop("План истёк без подтверждения"); return }
|
else if (plan.expires_at.getTime() <= Date.now()) { await stop("План истёк без подтверждения"); return }
|
||||||
|
else if (plan.state === "draft" && hasUnattendedPlanAuthority(connection.policy)) next.reason = "Ожидается публикация плана клиентом MCP"
|
||||||
else if (["approved", "draft"].includes(plan.state)) {
|
else if (["approved", "draft"].includes(plan.state)) {
|
||||||
await current()
|
await current()
|
||||||
await assertRoutingControllerBaseline(state.baseline,row.id,row.version,profile,row.grant_expires_at.toISOString(),{principal,connection})
|
await assertRoutingControllerBaseline(state.baseline,row.id,row.version,profile,row.grant_expires_at.toISOString(),{principal,connection})
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ import { readPollRuntimePolicySource, type PollRuntimePolicySource } from "./pol
|
|||||||
import { withVerifiedConfigurationChange, assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
|
import { withVerifiedConfigurationChange, assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
|
||||||
import { beginMcpOperationAdmission, insertMcpOperationAdmission, retireMcpOperationAdmission, withMcpOperationExecutionOrigin, stripMcpOperationExecutionPrivateResult, type McpOperationAdmission } from "./operation-execution-origin.js"
|
import { beginMcpOperationAdmission, insertMcpOperationAdmission, retireMcpOperationAdmission, withMcpOperationExecutionOrigin, stripMcpOperationExecutionPrivateResult, type McpOperationAdmission } from "./operation-execution-origin.js"
|
||||||
import { createOspfOwnerSourceGuard, verifyOspfOwnerGraph, verifyOspfOwnerGraphAtPhase } from "./ospf-owner-graph.js"
|
import { createOspfOwnerSourceGuard, verifyOspfOwnerGraph, verifyOspfOwnerGraphAtPhase } from "./ospf-owner-graph.js"
|
||||||
import { evaluateMcpPolicy } from "./policy.js"
|
import { evaluateMcpPolicy, hasUnattendedPlanAuthority, operationApprovalRequirement } from "./policy.js"
|
||||||
import { findAction, findActionByOperation } from "./actions.js"
|
import { findAction, findActionByOperation } from "./actions.js"
|
||||||
import { refuseExpiredOperationReplay } from "./operation-replay-tombstones.js"
|
import { refuseExpiredOperationReplay } from "./operation-replay-tombstones.js"
|
||||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, privateSecretFingerprint, McpError, redact } from "./security.js"
|
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, privateSecretFingerprint, McpError, redact } from "./security.js"
|
||||||
@@ -105,14 +105,11 @@ async function policyInput(client: Pick<PoolClient, "query">, connection: Connec
|
|||||||
SELECT COALESCE((SELECT used FROM mcp_budget_buckets WHERE connection_id=$1 AND kind='calls' AND bucket=date_trunc('minute',now())),0) AS calls,
|
SELECT COALESCE((SELECT used FROM mcp_budget_buckets WHERE connection_id=$1 AND kind='calls' AND bucket=date_trunc('minute',now())),0) AS calls,
|
||||||
COALESCE((SELECT used FROM mcp_budget_buckets WHERE connection_id=$1 AND kind='mutations' AND bucket=date_trunc('hour',now())),0) AS mutations,
|
COALESCE((SELECT used FROM mcp_budget_buckets WHERE connection_id=$1 AND kind='mutations' AND bucket=date_trunc('hour',now())),0) AS mutations,
|
||||||
(SELECT count(*)::int FROM mcp_read_leases WHERE connection_id=$1 AND expires_at>now()) AS reads`, [connection.id])
|
(SELECT count(*)::int FROM mcp_read_leases WHERE connection_id=$1 AND expires_at>now()) AS reads`, [connection.id])
|
||||||
|
const approval = operationApprovalRequirement(connection.policy, operationId, target, evidence?.requiresHuman)
|
||||||
return {
|
return {
|
||||||
operationId, policy: connection.policy, ownerPermissions: connection.owner_permissions, target,
|
operationId, policy: connection.policy, ownerPermissions: connection.owner_permissions, target,
|
||||||
objects: [...(evidence?.objects ?? []), ...(evidence?.requiresHuman && target.scope !== "servers" ? [{ kind: "mcp-operation", id: operationId }] : [])], objectCount: evidence ? changeMutationCost(evidence) + (evidence.recovery ? 1 : 0) : 0,
|
objects: [...(evidence?.objects ?? []), ...approval.objects], objectCount: evidence ? changeMutationCost(evidence) + (evidence.recovery ? 1 : 0) : 0,
|
||||||
protections: [
|
protections: [...protections.map(row => mcpProtectedObjectSchema.parse(row.object_ref)), ...approval.protections],
|
||||||
...protections.map(row => mcpProtectedObjectSchema.parse(row.object_ref)),
|
|
||||||
...(evidence?.requiresHuman && target.scope === "servers" ? target.serverIds.map(serverId => ({ kind: "server", id: String(serverId), serverId, protection: "human-approval-required" as const })) : []),
|
|
||||||
...(evidence?.requiresHuman && target.scope !== "servers" ? [{ kind: "mcp-operation", id: operationId, protection: "human-approval-required" as const }] : []),
|
|
||||||
],
|
|
||||||
usage: { callsInMinute: Number(usage.calls), mutationsInHour: Number(usage.mutations), concurrentReads: Number(usage.reads) }, auditAvailable: true,
|
usage: { callsInMinute: Number(usage.calls), mutationsInHour: Number(usage.mutations), concurrentReads: Number(usage.reads) }, auditAvailable: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -209,7 +206,8 @@ async function invokeMcpToolInner(principal: McpPrincipal, toolName: string, raw
|
|||||||
const id = randomUUID(), expiresAt = preparedPlanExpiry(action.operation.id, action.operation.section, evidence)
|
const id = randomUUID(), expiresAt = preparedPlanExpiry(action.operation.id, action.operation.section, evidence)
|
||||||
if (!expiresAt) throw new McpError("PLAN_EXPIRED", "Срок исходных данных плана истёк или недоступен; подготовьте новый план", 409)
|
if (!expiresAt) throw new McpError("PLAN_EXPIRED", "Срок исходных данных плана истёк или недоступен; подготовьте новый план", 409)
|
||||||
const generation = await accessGeneration()
|
const generation = await accessGeneration()
|
||||||
await client.query("INSERT INTO mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8::jsonb,$9,$10)", [id, connection.id, action.operation.id, action.operation.version, connection.policy.version, generation, JSON.stringify({ sealed: await encryptSecret(JSON.stringify(input)) }), JSON.stringify({ sealed: await encryptSecret(JSON.stringify(evidence)) }), decision.decision === "approval-required" ? "awaiting-approval" : "draft", expiresAt])
|
let sealedEvidence = await encryptSecret(JSON.stringify(evidence))
|
||||||
|
await client.query("INSERT INTO mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8::jsonb,$9,$10)", [id, connection.id, action.operation.id, action.operation.version, connection.policy.version, generation, JSON.stringify({ sealed: await encryptSecret(JSON.stringify(input)) }), JSON.stringify({ sealed: sealedEvidence }), decision.decision === "approval-required" ? "awaiting-approval" : "draft", expiresAt])
|
||||||
const vrfTicket = await prepareRuntimeVrfTicket({ operationId: action.operation.id, operationVersion: action.operation.version, planId: id, connectionId: connection.id, ownerId: connection.owner_id, evidence, sql: client,
|
const vrfTicket = await prepareRuntimeVrfTicket({ operationId: action.operation.id, operationVersion: action.operation.version, planId: id, connectionId: connection.id, ownerId: connection.owner_id, evidence, sql: client,
|
||||||
assertAuthority: async () => {
|
assertAuthority: async () => {
|
||||||
if (signal?.aborted || generation !== await accessGeneration() || expiresAt.getTime() <= Date.now()) throw new McpError("PLAN_EXPIRED", "Подготовка VRF отменена или устарела", 409)
|
if (signal?.aborted || generation !== await accessGeneration() || expiresAt.getTime() <= Date.now()) throw new McpError("PLAN_EXPIRED", "Подготовка VRF отменена или устарела", 409)
|
||||||
@@ -238,11 +236,14 @@ async function invokeMcpToolInner(principal: McpPrincipal, toolName: string, raw
|
|||||||
finalCheck.usage.callsInMinute = Math.max(0, finalCheck.usage.callsInMinute - 1)
|
finalCheck.usage.callsInMinute = Math.max(0, finalCheck.usage.callsInMinute - 1)
|
||||||
decision = evaluateMcpPolicy(finalCheck)
|
decision = evaluateMcpPolicy(finalCheck)
|
||||||
if (decision.decision === "denied") throw new McpError(decision.reasons[0].code, decision.reasons.map(reason => reason.message).join("; "))
|
if (decision.decision === "denied") throw new McpError(decision.reasons[0].code, decision.reasons.map(reason => reason.message).join("; "))
|
||||||
await client.query("UPDATE mcp_plans SET evidence=$2::jsonb,state=$3 WHERE id=$1", [id, JSON.stringify({ sealed: await encryptSecret(JSON.stringify(evidence)) }), decision.decision === "approval-required" ? "awaiting-approval" : "draft"])
|
sealedEvidence = await encryptSecret(JSON.stringify(evidence))
|
||||||
|
await client.query("UPDATE mcp_plans SET evidence=$2::jsonb,state=$3 WHERE id=$1", [id, JSON.stringify({ sealed: sealedEvidence }), decision.decision === "approval-required" ? "awaiting-approval" : "draft"])
|
||||||
}
|
}
|
||||||
await audit(client, connection.owner_id, "plan.create", connection.id, { planId: id, operationId: action.operation.id, decision })
|
await audit(client, connection.owner_id, "plan.create", connection.id, { planId: id, operationId: action.operation.id, decision })
|
||||||
assertActive()
|
assertActive()
|
||||||
return { planId: id, expiresAt: expiresAt.toISOString(), state: decision.decision === "approval-required" ? "awaiting-approval" : "draft", decision, changes: redact(publicMcpChangeEvidence(action.operation.id, evidence)), ...(vrfTicket ? { vrfTicket } : {}), executionAvailable: true }
|
const announcement = decision.decision === "allowed" && hasUnattendedPlanAuthority(connection.policy)
|
||||||
|
? planAnnouncement(id, sealedEvidence) : undefined
|
||||||
|
return { planId: id, expiresAt: expiresAt.toISOString(), state: decision.decision === "approval-required" ? "awaiting-approval" : "draft", decision, changes: redact(publicMcpChangeEvidence(action.operation.id, evidence)), ...(announcement && { operationId: action.operation.id, announcement }), ...(vrfTicket ? { vrfTicket } : {}), executionAvailable: true }
|
||||||
})
|
})
|
||||||
vrfPreparing = false
|
vrfPreparing = false
|
||||||
} else throw new McpError("UNSUPPORTED_CAPABILITY", "Нет обработчика операции", 409)
|
} else throw new McpError("UNSUPPORTED_CAPABILITY", "Нет обработчика операции", 409)
|
||||||
@@ -278,10 +279,19 @@ export async function loadPlan(id: string, client: Pick<PoolClient, "query"> = p
|
|||||||
if (!plan) throw new McpError("NOT_FOUND", "План не найден", 404)
|
if (!plan) throw new McpError("NOT_FOUND", "План не найден", 404)
|
||||||
return plan
|
return plan
|
||||||
}
|
}
|
||||||
export async function publicPlan(plan: StoredPlan) {
|
function planAnnouncement(planId: string, sealedEvidence: string) {
|
||||||
|
return {
|
||||||
|
digest: fingerprint({ planId, sealedEvidence }),
|
||||||
|
instruction: "Сначала отправьте пользователю отдельное видимое сообщение в чате с ID плана, целями, конкретными изменениями и предупреждениями из changes. Затем вызовите mm_change_apply с announcedPlanDigest. Ответ пользователя для этого плана не требуется.",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function publicPlan(plan: StoredPlan, unattended = false) {
|
||||||
const evidence = JSON.parse(await decryptSecret(plan.evidence.sealed)) as ChangeEvidence
|
const evidence = JSON.parse(await decryptSecret(plan.evidence.sealed)) as ChangeEvidence
|
||||||
return { id: plan.id, connectionId: plan.connection_id, operationId: plan.operation_id, state: plan.state,
|
return { id: plan.id, connectionId: plan.connection_id, operationId: plan.operation_id, state: plan.state,
|
||||||
expiresAt: plan.expires_at.toISOString(), createdAt: plan.created_at.toISOString(), approvedBy: plan.approved_by,
|
expiresAt: plan.expires_at.toISOString(), createdAt: plan.created_at.toISOString(), approvedBy: plan.evidence.approvalSource ? null : plan.approved_by,
|
||||||
|
...(plan.evidence.approvalSource && { approvalSource: plan.evidence.approvalSource, authorizedBy: plan.approved_by }),
|
||||||
|
...(unattended && plan.state === "draft" && plan.expires_at.getTime() > Date.now() && { announcement: planAnnouncement(plan.id, plan.evidence.sealed) }),
|
||||||
changes: redact(publicMcpChangeEvidence(plan.operation_id, evidence)), input: redact(JSON.parse(await decryptSecret(plan.payload.sealed))) }
|
changes: redact(publicMcpChangeEvidence(plan.operation_id, evidence)), input: redact(JSON.parse(await decryptSecret(plan.payload.sealed))) }
|
||||||
}
|
}
|
||||||
export async function approvePlan(id: string, actor: AuthUser, approve: boolean) {
|
export async function approvePlan(id: string, actor: AuthUser, approve: boolean) {
|
||||||
@@ -378,10 +388,10 @@ export async function verifyStep(step: ChangeStep, result: unknown, before?: Ros
|
|||||||
if (!before) return false
|
if (!before) return false
|
||||||
return verifyRosStepSnapshots(step.step, result, before, after ?? await readRosSnapshot(step.step.serverId, step.step.resource))
|
return verifyRosStepSnapshots(step.step, result, before, after ?? await readRosSnapshot(step.step.serverId, step.step.resource))
|
||||||
}
|
}
|
||||||
export async function applyPlan(principal: McpPrincipal, planId: string, idempotencyKey: string): Promise<StoredOperation> {
|
export async function applyPlan(principal: McpPrincipal, planId: string, idempotencyKey: string, announcedPlanDigest?: string): Promise<StoredOperation> {
|
||||||
return withMcpDatabaseRequest(() => admitPlan(principal, planId, idempotencyKey))
|
return withMcpDatabaseRequest(() => admitPlan(principal, planId, idempotencyKey, announcedPlanDigest))
|
||||||
}
|
}
|
||||||
async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey: string): Promise<StoredOperation> {
|
async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey: string, announcedPlanDigest?: string): Promise<StoredOperation> {
|
||||||
const operationAdmissionStart = beginMcpOperationAdmission(principal)
|
const operationAdmissionStart = beginMcpOperationAdmission(principal)
|
||||||
let reservedRouting = false
|
let reservedRouting = false
|
||||||
let originalServiceGrant:OriginalServiceGrant|undefined
|
let originalServiceGrant:OriginalServiceGrant|undefined
|
||||||
@@ -408,6 +418,10 @@ async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey
|
|||||||
const action = findActionByOperation(plan.operation_id)
|
const action = findActionByOperation(plan.operation_id)
|
||||||
if (plan.policy_version !== connection.policy.version || plan.operation_version !== action.operation.version || plan.generation !== await accessGeneration() || plan.expires_at.getTime() <= Date.now()) throw new McpError("PLAN_EXPIRED", "План или его разрешения устарели", 409)
|
if (plan.policy_version !== connection.policy.version || plan.operation_version !== action.operation.version || plan.generation !== await accessGeneration() || plan.expires_at.getTime() <= Date.now()) throw new McpError("PLAN_EXPIRED", "План или его разрешения устарели", 409)
|
||||||
if (!["draft", "approved"].includes(plan.state)) throw new McpError("APPROVAL_REQUIRED", "План требует подтверждения или недоступен", 409)
|
if (!["draft", "approved"].includes(plan.state)) throw new McpError("APPROVAL_REQUIRED", "План требует подтверждения или недоступен", 409)
|
||||||
|
const delegated = plan.state === "draft" && hasUnattendedPlanAuthority(connection.policy)
|
||||||
|
if (delegated && announcedPlanDigest !== planAnnouncement(plan.id, plan.evidence.sealed).digest) {
|
||||||
|
throw new McpError("APPROVAL_REQUIRED", "Сначала опубликуйте точный план в чате и передайте его announcedPlanDigest", 409)
|
||||||
|
}
|
||||||
for (const change of evidence.steps) {
|
for (const change of evidence.steps) {
|
||||||
if (change.kind === "ros" && change.step.resource === "ip_settings" && change.step.fields["rp-filter"] === "strict") {
|
if (change.kind === "ros" && change.step.resource === "ip_settings" && change.step.fields["rp-filter"] === "strict") {
|
||||||
checkRpfPolicy(change.step.serverId, evidence.snapshots, "strict")
|
checkRpfPolicy(change.step.serverId, evidence.snapshots, "strict")
|
||||||
@@ -415,7 +429,7 @@ async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey
|
|||||||
}
|
}
|
||||||
let scopedPathExpiresAt: number | undefined
|
let scopedPathExpiresAt: number | undefined
|
||||||
if (plan.operation_id === "routing.community.switch" && requiresScopedRoutingOwnerApproval(evidence)) {
|
if (plan.operation_id === "routing.community.switch" && requiresScopedRoutingOwnerApproval(evidence)) {
|
||||||
if (plan.approved_by !== connection.owner_id) throw new McpError("APPROVAL_REQUIRED", "Переключение постоянного профиля подтверждает владелец подключения", 409)
|
if (!delegated && plan.approved_by !== connection.owner_id) throw new McpError("APPROVAL_REQUIRED", "Переключение постоянного профиля подтверждает владелец подключения", 409)
|
||||||
scopedPathExpiresAt = await readScopedRoutingPathAdmissionDeadline(client, evidence, connection.id)
|
scopedPathExpiresAt = await readScopedRoutingPathAdmissionDeadline(client, evidence, connection.id)
|
||||||
}
|
}
|
||||||
if (evidence.validUntil && (!Number.isFinite(Date.parse(evidence.validUntil)) || Date.now() >= Date.parse(evidence.validUntil))) {
|
if (evidence.validUntil && (!Number.isFinite(Date.parse(evidence.validUntil)) || Date.now() >= Date.parse(evidence.validUntil))) {
|
||||||
@@ -449,18 +463,23 @@ async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey
|
|||||||
const mutationCost = reservedRouting ? 2 : changeMutationCost(evidence) + (evidence.recovery ? 1 : 0)
|
const mutationCost = reservedRouting ? 2 : changeMutationCost(evidence) + (evidence.recovery ? 1 : 0)
|
||||||
if (input.usage.mutationsInHour + mutationCost > connection.policy.limits.mutationsPerHour) throw new McpError("BUDGET_EXCEEDED", "Недостаточно бюджета для всех шагов плана", 429)
|
if (input.usage.mutationsInHour + mutationCost > connection.policy.limits.mutationsPerHour) throw new McpError("BUDGET_EXCEEDED", "Недостаточно бюджета для всех шагов плана", 429)
|
||||||
if (!reservedRouting) await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'mutations',date_trunc('hour',now()),$2) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+EXCLUDED.used", [connection.id, mutationCost])
|
if (!reservedRouting) await client.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'mutations',date_trunc('hour',now()),$2) ON CONFLICT(connection_id,kind,bucket) DO UPDATE SET used=mcp_budget_buckets.used+EXCLUDED.used", [connection.id, mutationCost])
|
||||||
|
if (delegated) {
|
||||||
|
// Execution receipts use the delegating owner's ID. Object protections still require a human decision.
|
||||||
|
plan.evidence.approvalSource = "connection-policy"
|
||||||
|
await client.query("UPDATE mcp_plans SET state='executing',approved_by=$2,approved_at=now(),evidence=$3::jsonb WHERE id=$1", [planId, connection.owner_id, JSON.stringify(plan.evidence)])
|
||||||
|
plan.approved_by = connection.owner_id
|
||||||
|
} else await client.query("UPDATE mcp_plans SET state='executing' WHERE id=$1", [planId])
|
||||||
const inserted = await insertMcpOperationAdmission(client, operationAdmissionStart, planId, idempotencyKey, originalServiceGrant)
|
const inserted = await insertMcpOperationAdmission(client, operationAdmissionStart, planId, idempotencyKey, originalServiceGrant)
|
||||||
const row = inserted.operation, id = row.id
|
const row = inserted.operation, id = row.id
|
||||||
operationAdmission = inserted.admission; originalServiceGrant = inserted.originalGrant
|
operationAdmission = inserted.admission; originalServiceGrant = inserted.originalGrant
|
||||||
if (plan.operation_id === "routing.community.switch" || plan.operation_id === "operations.recover") {
|
if (plan.operation_id === "routing.community.switch" || plan.operation_id === "operations.recover") {
|
||||||
bindRoutingChargeAdmission(client, connection.id, principal.credentialId, inserted.originalGrant)
|
bindRoutingChargeAdmission(client, connection.id, principal.credentialId, inserted.originalGrant)
|
||||||
}
|
}
|
||||||
await client.query("UPDATE mcp_plans SET state='executing' WHERE id=$1", [planId])
|
|
||||||
if (reservedRouting) await reserveRouting(id)
|
if (reservedRouting) await reserveRouting(id)
|
||||||
else if (plan.operation_id === "routing.community.switch") await admitPersistentRoutingForwardWithinOwner(client, id)
|
else if (plan.operation_id === "routing.community.switch") await admitPersistentRoutingForwardWithinOwner(client, id)
|
||||||
else if (plan.operation_id === "operations.recover") await admitManualInverseWithinOwner(client, id, plan, evidence, principal,
|
else if (plan.operation_id === "operations.recover") await admitManualInverseWithinOwner(client, id, plan, evidence, principal,
|
||||||
(profileId, current, observedAt, deadlineAt) => readHistoricalChargesWithinOwner(client, profileId, current, observedAt, deadlineAt))
|
(profileId, current, observedAt, deadlineAt) => readHistoricalChargesWithinOwner(client, profileId, current, observedAt, deadlineAt))
|
||||||
await audit(client, connection.owner_id, "operation.start", connection.id, { operationId: id, planId })
|
await audit(client, connection.owner_id, "operation.start", connection.id, { operationId: id, planId, ...(delegated && { approvalSource: "connection-policy", announcedPlanDigest }) })
|
||||||
return row
|
return row
|
||||||
}).catch(async error => { await retireMcpOperationAdmission(operationAdmission); throw error })
|
}).catch(async error => { await retireMcpOperationAdmission(operationAdmission); throw error })
|
||||||
const operation = admitted.value
|
const operation = admitted.value
|
||||||
@@ -568,7 +587,7 @@ async function executeOperationWithLease(operationId: string, principal: McpPrin
|
|||||||
policy.usage.callsInMinute = 0; policy.usage.mutationsInHour = 0
|
policy.usage.callsInMinute = 0; policy.usage.mutationsInHour = 0
|
||||||
const decision = evaluateMcpPolicy(policy)
|
const decision = evaluateMcpPolicy(policy)
|
||||||
if (decision.decision === "denied") throw new McpError(decision.reasons[0].code, decision.reasons.map(reason => reason.message).join("; "))
|
if (decision.decision === "denied") throw new McpError(decision.reasons[0].code, decision.reasons.map(reason => reason.message).join("; "))
|
||||||
if (decision.decision === "approval-required" && !plan.approved_by) throw new McpError("APPROVAL_REQUIRED", "Изменение теперь требует подтверждения", 409)
|
if (decision.decision === "approval-required" && (!plan.approved_by || plan.evidence.approvalSource)) throw new McpError("APPROVAL_REQUIRED", "Изменение теперь требует подтверждения", 409)
|
||||||
}
|
}
|
||||||
if (policyLoan) await executeRuntimePollPolicyTransaction(policyLoan, checkPolicy)
|
if (policyLoan) await executeRuntimePollPolicyTransaction(policyLoan, checkPolicy)
|
||||||
else await transaction(checkPolicy)
|
else await transaction(checkPolicy)
|
||||||
@@ -681,7 +700,7 @@ async function executeOperationWithLease(operationId: string, principal: McpPrin
|
|||||||
}
|
}
|
||||||
stepDispatches++
|
stepDispatches++
|
||||||
} : undefined
|
} : undefined
|
||||||
const result = await withVerifiedConfigurationChange({ actorId: connection.owner_id, connectionId: connection.id, serverIds, objects: evidence.objects, approved: !!plan.approved_by, serverWide: step.kind === "service", ...(serviceExecution?{serviceExecution}:{}), authorize: async () => { await (step.kind === "ros" ? authorizeCatalog() : authorize()) }, authorizeWrite: async () => { await (step.kind === "ros" ? catalogStage.fresh() : authorizeStage.fresh()) }, beforeDispatch },
|
const result = await withVerifiedConfigurationChange({ actorId: connection.owner_id, connectionId: connection.id, serverIds, objects: evidence.objects, approved: !!plan.approved_by, approvalSource: plan.evidence.approvalSource, serverWide: step.kind === "service", ...(serviceExecution?{serviceExecution}:{}), authorize: async () => { await (step.kind === "ros" ? authorizeCatalog() : authorize()) }, authorizeWrite: async () => { await (step.kind === "ros" ? catalogStage.fresh() : authorizeStage.fresh()) }, beforeDispatch },
|
||||||
async () => {
|
async () => {
|
||||||
vrfDiagnosticFallback?.executorEntered()
|
vrfDiagnosticFallback?.executorEntered()
|
||||||
if (step.kind === "ros") {
|
if (step.kind === "ros") {
|
||||||
@@ -830,7 +849,7 @@ async function performReservedRecovery(operation: StoredOperation, plan: StoredP
|
|||||||
input.temporaryGrant = await temporaryScope(client, connection, principal.credentialId)
|
input.temporaryGrant = await temporaryScope(client, connection, principal.credentialId)
|
||||||
input.usage.callsInMinute = 0; input.usage.mutationsInHour = 0
|
input.usage.callsInMinute = 0; input.usage.mutationsInHour = 0
|
||||||
const decision = evaluateMcpPolicy(input)
|
const decision = evaluateMcpPolicy(input)
|
||||||
if (decision.decision === "denied" || decision.decision === "approval-required" && !plan.approved_by) throw new McpError("PERMISSION_DENIED", "Текущая защита или допуск запрещает восстановление")
|
if (decision.decision === "denied" || decision.decision === "approval-required" && (!plan.approved_by || plan.evidence.approvalSource)) throw new McpError("PERMISSION_DENIED", "Текущая защита или допуск запрещает восстановление")
|
||||||
})
|
})
|
||||||
for (const channel of evidence.managementChannels ?? []) await verifyManagementChannel(channel.serverId, channel.channelId)
|
for (const channel of evidence.managementChannels ?? []) await verifyManagementChannel(channel.serverId, channel.channelId)
|
||||||
if (!evidence.managementChannels?.length) throw new McpError("APPROVAL_REQUIRED", "Восстановление требует независимого канала")
|
if (!evidence.managementChannels?.length) throw new McpError("APPROVAL_REQUIRED", "Восстановление требует независимого канала")
|
||||||
@@ -847,7 +866,7 @@ async function performReservedRecovery(operation: StoredOperation, plan: StoredP
|
|||||||
await audit(pool, connection.owner_id, "recovery.intent", connection.id, { operationId: operation.id, authorityProfileId: recovery.authorityProfileId })
|
await audit(pool, connection.owner_id, "recovery.intent", connection.id, { operationId: operation.id, authorityProfileId: recovery.authorityProfileId })
|
||||||
attempted = true
|
attempted = true
|
||||||
const step = recovery.step
|
const step = recovery.step
|
||||||
const result = await withVerifiedConfigurationChange({ actorId: connection.owner_id, connectionId: connection.id, serverIds, objects: evidence.objects, approved: !!plan.approved_by, serverWide: true }, () => serviceExecute(step.service, step.input, { operationId: operation.id, phase: "recovery" }))
|
const result = await withVerifiedConfigurationChange({ actorId: connection.owner_id, connectionId: connection.id, serverIds, objects: evidence.objects, approved: !!plan.approved_by, approvalSource: plan.evidence.approvalSource, serverWide: true }, () => serviceExecute(step.service, step.input, { operationId: operation.id, phase: "recovery" }))
|
||||||
if (!await verifyStep(step, result)) throw new McpError("VERIFICATION_FAILED", "Проверка восстановления не прошла", 409)
|
if (!await verifyStep(step, result)) throw new McpError("VERIFICATION_FAILED", "Проверка восстановления не прошла", 409)
|
||||||
await pool.query("UPDATE mcp_recovery_intents SET state='verified',finished_at=now() WHERE operation_id=$1", [operation.id])
|
await pool.query("UPDATE mcp_recovery_intents SET state='verified',finished_at=now() WHERE operation_id=$1", [operation.id])
|
||||||
await audit(pool, connection.owner_id, "recovery.verified", connection.id, { operationId: operation.id })
|
await audit(pool, connection.owner_id, "recovery.verified", connection.id, { operationId: operation.id })
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ export async function effectiveMcpConnection(principal: McpPrincipal, client: Pi
|
|||||||
}
|
}
|
||||||
export interface StoredPlan extends QueryResultRow {
|
export interface StoredPlan extends QueryResultRow {
|
||||||
id: string; connection_id: string; operation_id: string; operation_version: number; policy_version: number;
|
id: string; connection_id: string; operation_id: string; operation_version: number; policy_version: number;
|
||||||
generation: string; payload: { sealed: string }; evidence: { sealed: string }; state: string;
|
generation: string; payload: { sealed: string }; evidence: { sealed: string; approvalSource?: "connection-policy" }; state: string;
|
||||||
expires_at: Date; approved_by: string | null; created_at: Date
|
expires_at: Date; approved_by: string | null; created_at: Date
|
||||||
}
|
}
|
||||||
export interface StoredOperation extends QueryResultRow {
|
export interface StoredOperation extends QueryResultRow {
|
||||||
|
|||||||
@@ -45,7 +45,11 @@ function makeMcpServerWithBindings(principal: McpPrincipal, bindings: ReturnType
|
|||||||
for (const action of bindings) {
|
for (const action of bindings) {
|
||||||
const descriptor = action.operation
|
const descriptor = action.operation
|
||||||
server.registerTool(descriptor.toolName, {
|
server.registerTool(descriptor.toolName, {
|
||||||
title: descriptor.title, description: `${descriptor.title}. ${action.prepare ? "Подготавливает неизменяемый план; применение отдельным вызовом после проверки политики." : "Возвращает данные только из разрешённой области."}`,
|
title: descriptor.title, description: `${descriptor.title}. ${action.prepare
|
||||||
|
? "Подготавливает неизменяемый план. Если возвращён announcement, опубликуйте точные изменения отдельным сообщением в чате до вызова применения."
|
||||||
|
: descriptor.id === "changes.apply"
|
||||||
|
? "Если план содержит announcement, сначала отправьте точные изменения пользователю в чат, затем передайте announcedPlanDigest."
|
||||||
|
: "Возвращает данные только из разрешённой области."}`,
|
||||||
inputSchema: action.schema, annotations: descriptor.annotations,
|
inputSchema: action.schema, annotations: descriptor.annotations,
|
||||||
}, async (input, sdkContext) => {
|
}, async (input, sdkContext) => {
|
||||||
const execute = async () => {
|
const execute = async () => {
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ export interface VerifiedMcpServiceMetadata {
|
|||||||
}
|
}
|
||||||
// `authorize` guards reads inside a stage and may reuse a recent proof; `authorizeWrite`, when given, is a
|
// `authorize` guards reads inside a stage and may reuse a recent proof; `authorizeWrite`, when given, is a
|
||||||
// fresh check before every native or application write (each write is a stage boundary).
|
// fresh check before every native or application write (each write is a stage boundary).
|
||||||
interface VerifiedChange { active: boolean; actorId: string; connectionId: string; approved: boolean; serverIds: number[]; objects: McpObjectRef[]; serverWide: boolean; authorize?: () => Promise<void>; authorizeWrite?: () => Promise<void>; beforeDispatch?: () => Promise<void>; serviceExecution?:VerifiedMcpServiceMetadata }
|
interface VerifiedChange { active: boolean; actorId: string; connectionId: string; approved: boolean; approvalSource?: "connection-policy" | null; serverIds: number[]; objects: McpObjectRef[]; serverWide: boolean; authorize?: () => Promise<void>; authorizeWrite?: () => Promise<void>; beforeDispatch?: () => Promise<void>; serviceExecution?:VerifiedMcpServiceMetadata }
|
||||||
const verified = new AsyncLocalStorage<VerifiedChange>()
|
const verified = new AsyncLocalStorage<VerifiedChange>()
|
||||||
declare const serviceExecutionBrand:unique symbol
|
declare const serviceExecutionBrand:unique symbol
|
||||||
export type VerifiedMcpServiceExecution=Readonly<{[serviceExecutionBrand]:true}>
|
export type VerifiedMcpServiceExecution=Readonly<{[serviceExecutionBrand]:true}>
|
||||||
@@ -136,7 +136,7 @@ export async function assertDatabaseRestoreAllowed() {
|
|||||||
const inherited = verified.getStore(), context = inherited?.active ? inherited : undefined
|
const inherited = verified.getStore(), context = inherited?.active ? inherited : undefined
|
||||||
const { rows } = await pool.query("SELECT object_ref FROM mcp_protections")
|
const { rows } = await pool.query("SELECT object_ref FROM mcp_protections")
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
if (row.object_ref.protection === "deny" || !context?.approved) {
|
if (row.object_ref.protection === "deny" || !context?.approved || context.approvalSource) {
|
||||||
const code = row.object_ref.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED"
|
const code = row.object_ref.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED"
|
||||||
await audit(pool, context?.actorId ?? actor.getStore() ?? "system", "configuration.denied", context?.connectionId ?? null, { domain: "database.restore", code })
|
await audit(pool, context?.actorId ?? actor.getStore() ?? "system", "configuration.denied", context?.connectionId ?? null, { domain: "database.restore", code })
|
||||||
throw new McpError(code, "Полное восстановление затрагивает защищённый объект", 409)
|
throw new McpError(code, "Полное восстановление затрагивает защищённый объект", 409)
|
||||||
@@ -165,7 +165,7 @@ export async function executeGuardedConfigurationWrite<T>(serverId: number, meth
|
|||||||
// typed plan instead of guessing that their writes miss a protected object.
|
// typed plan instead of guessing that their writes miss a protected object.
|
||||||
const matches = !context || context.serverWide || protection.kind === "server" || context.objects.some(object => object.serverId === serverId && object.kind === protection.kind && object.id === protection.id)
|
const matches = !context || context.serverWide || protection.kind === "server" || context.objects.some(object => object.serverId === serverId && object.kind === protection.kind && object.id === protection.id)
|
||||||
if (!matches) continue
|
if (!matches) continue
|
||||||
if (protection.protection === "deny" || !context?.approved) {
|
if (protection.protection === "deny" || !context?.approved || context.approvalSource) {
|
||||||
const code = protection.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED"
|
const code = protection.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED"
|
||||||
await auditConfiguration(actorId, "configuration.denied", context?.connectionId ?? null, { serverId, method, path, code })
|
await auditConfiguration(actorId, "configuration.denied", context?.connectionId ?? null, { serverId, method, path, code })
|
||||||
throw new McpError(code, protection.protection === "deny" ? "Изменение заблокировано защитой объекта. Используйте план с проверкой зависимостей." : "Защищённый объект требует подтверждённого плана изменений.", 409)
|
throw new McpError(code, protection.protection === "deny" ? "Изменение заблокировано защитой объекта. Используйте план с проверкой зависимостей." : "Защищённый объект требует подтверждённого плана изменений.", 409)
|
||||||
@@ -208,7 +208,7 @@ export async function executeGuardedApplicationWrite<T>(object: { kind: string;
|
|||||||
const { rows } = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) OR (object_ref->>'kind'='server' AND object_ref->>'id'=ANY($1::text[])) OR (object_ref->>'kind'=$2 AND object_ref->>'id'=$3) OR EXISTS(SELECT 1 FROM jsonb_array_elements($4::jsonb) AS target WHERE target->>'kind'=object_ref->>'kind' AND target->>'id'=object_ref->>'id')", [serverIds.map(String), object.kind, object.id, JSON.stringify(objects)])
|
const { rows } = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) OR (object_ref->>'kind'='server' AND object_ref->>'id'=ANY($1::text[])) OR (object_ref->>'kind'=$2 AND object_ref->>'id'=$3) OR EXISTS(SELECT 1 FROM jsonb_array_elements($4::jsonb) AS target WHERE target->>'kind'=object_ref->>'kind' AND target->>'id'=object_ref->>'id')", [serverIds.map(String), object.kind, object.id, JSON.stringify(objects)])
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
const protection = row.object_ref as { protection: string }
|
const protection = row.object_ref as { protection: string }
|
||||||
if (protection.protection === "deny" || !context?.approved) {
|
if (protection.protection === "deny" || !context?.approved || context.approvalSource) {
|
||||||
await auditConfiguration(actorId, "configuration.denied", context?.connectionId ?? null, { domain: "application", object, serverIds })
|
await auditConfiguration(actorId, "configuration.denied", context?.connectionId ?? null, { domain: "application", object, serverIds })
|
||||||
throw new McpError(protection.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED", "Изменение приложения затрагивает защищённый объект; нужен проверенный план", 409)
|
throw new McpError(protection.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED", "Изменение приложения затрагивает защищённый объект; нужен проверенный план", 409)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,7 +34,8 @@ const admissionSchema = z.object({ receipt_id: uuid, identity_kind: z.literal("m
|
|||||||
const operationSchema = z.object({ id: uuid, plan_id: uuid, connection_id: uuid, state: z.literal("applied"), verification: z.literal("passed"),
|
const operationSchema = z.object({ id: uuid, plan_id: uuid, connection_id: uuid, state: z.literal("applied"), verification: z.literal("passed"),
|
||||||
error_code: z.null(), result: z.unknown(), created_at: time, finished_at: time }).passthrough()
|
error_code: z.null(), result: z.unknown(), created_at: time, finished_at: time }).passthrough()
|
||||||
const planSchema = z.object({ id: uuid, connection_id: uuid, operation_id: z.literal("servers.poll"), operation_version: z.literal(1),
|
const planSchema = z.object({ id: uuid, connection_id: uuid, operation_id: z.literal("servers.poll"), operation_version: z.literal(1),
|
||||||
state: z.literal("completed"), created_at: time, approved_by: actor, approved_at: time, expires_at: time, payload: sealed, evidence: sealed }).passthrough()
|
state: z.literal("completed"), created_at: time, approved_by: actor, approved_at: time, expires_at: time, payload: sealed,
|
||||||
|
evidence: sealed.extend({ approvalSource: z.literal("connection-policy").optional() }) }).passthrough()
|
||||||
const stepSchema = z.object({ operation_id: uuid, step_index: z.literal(0), server_id: z.null(), state: z.literal("verified"), intended_state: z.unknown(),
|
const stepSchema = z.object({ operation_id: uuid, step_index: z.literal(0), server_id: z.null(), state: z.literal("verified"), intended_state: z.unknown(),
|
||||||
result: z.unknown(), finished_at: time }).passthrough()
|
result: z.unknown(), finished_at: time }).passthrough()
|
||||||
const inputSchema = z.object({ serverId: sid, receiptId: uuid, inputDigest: hash, bindingCiphertext: z.string().min(1).max(2097152) }).strict()
|
const inputSchema = z.object({ serverId: sid, receiptId: uuid, inputDigest: hash, bindingCiphertext: z.string().min(1).max(2097152) }).strict()
|
||||||
|
|||||||
@@ -163,7 +163,7 @@ for(const mode of ['runtime-policy-entry','policy-authorize','executor-entry','e
|
|||||||
const error=Object.assign(Error('PRIVATE_RUNTIME_POLICY_FAILURE'),{code:'ECONNRESET'}),events=[]
|
const error=Object.assign(Error('PRIVATE_RUNTIME_POLICY_FAILURE'),{code:'ECONNRESET'}),events=[]
|
||||||
const env={failure:error,failAfterWrapper:mode==='after-wrapper',productionVrf:mode!=='non-production',
|
const env={failure:error,failAfterWrapper:mode==='after-wrapper',productionVrf:mode!=='non-production',
|
||||||
operationId:id,connection:{owner_id:'owner',id:'connection'},serverIds:[1],evidence:{objects:[],snapshots:[{resource:'vrf',serverId:1,sourceProof:'a'.repeat(64)}]},serviceExecution:undefined,reservedStep:{},
|
operationId:id,connection:{owner_id:'owner',id:'connection'},serverIds:[1],evidence:{objects:[],snapshots:[{resource:'vrf',serverId:1,sourceProof:'a'.repeat(64)}]},serviceExecution:undefined,reservedStep:{},
|
||||||
plan:{id:'plan',operation_id:'ros.vrf.create',operation_version:1,approved_by:'owner'},step:{kind:'ros',step:{serverId:1,resource:'vrf',action:'create',fields:{name:'customers',interfaces:'none'}}},
|
plan:{id:'plan',operation_id:'ros.vrf.create',operation_version:1,approved_by:'owner',evidence:{sealed:'fixture-ciphertext'}},step:{kind:'ros',step:{serverId:1,resource:'vrf',action:'create',fields:{name:'customers',interfaces:'none'}}},
|
||||||
prefix:{async check(){}},async authorize(){},async authorizeCatalog(){if(mode==='policy-authorize')throw error},McpError,createVrfRuntimeDiagnosticBoundary:diagnostic.createVrfRuntimeDiagnosticBoundary,
|
prefix:{async check(){}},async authorize(){},async authorizeCatalog(){if(mode==='policy-authorize')throw error},McpError,createVrfRuntimeDiagnosticBoundary:diagnostic.createVrfRuntimeDiagnosticBoundary,
|
||||||
console:{error(raw){events.push(JSON.parse(raw));if(loggerThrows)throw Error('PRIVATE_LOGGER_FAILURE')}},
|
console:{error(raw){events.push(JSON.parse(raw));if(loggerThrows)throw Error('PRIVATE_LOGGER_FAILURE')}},
|
||||||
async executeRosStep(){throw error},
|
async executeRosStep(){throw error},
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { ensurePartitionFor } from "../db/partitions.js"
|
|||||||
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "../modules/mcp/store.js"
|
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "../modules/mcp/store.js"
|
||||||
import { invokeMcpTool } from "../modules/mcp/runtime.js"
|
import { invokeMcpTool } from "../modules/mcp/runtime.js"
|
||||||
import { buildFlowAnalytics, invalidateFlowAnalyticsCache } from "../services/traffic-flow-analytics.js"
|
import { buildFlowAnalytics, invalidateFlowAnalyticsCache } from "../services/traffic-flow-analytics.js"
|
||||||
|
import { FlowSourceWindowTooLarge } from "../services/traffic-flow-read-window.js"
|
||||||
import { loadFlowTopology, invalidateFlowCatalogCache } from "../services/traffic-flow-topology.js"
|
import { loadFlowTopology, invalidateFlowCatalogCache } from "../services/traffic-flow-topology.js"
|
||||||
import { resetFlowRingsForTests as clearPendingFlows } from "../services/traffic-flow-ingest.js"
|
import { resetFlowRingsForTests as clearPendingFlows } from "../services/traffic-flow-ingest.js"
|
||||||
import { disableRipeEnqueueForTests, resetRipeCacheForTests } from "../services/traffic-flow-ripe.js"
|
import { disableRipeEnqueueForTests, resetRipeCacheForTests } from "../services/traffic-flow-ripe.js"
|
||||||
@@ -53,7 +54,7 @@ export async function verifyMcpFlowAnalytics(actor: AuthUser) {
|
|||||||
await pool.query("DELETE FROM flow_buckets WHERE server_id=110 AND in_iface='analytics-duplicate-in'")
|
await pool.query("DELETE FROM flow_buckets WHERE server_id=110 AND in_iface='analytics-duplicate-in'")
|
||||||
await assert.rejects(read({userId:users[1]})); await assert.rejects(read({userId:users[2]}))
|
await assert.rejects(read({userId:users[1]})); await assert.rejects(read({userId:users[2]}))
|
||||||
await assert.rejects(read({serverId:111})); await assert.rejects(read({minutes:1441})); await assert.rejects(read({interface:"__all__"})); await assert.rejects(read({skipHeavy:true}))
|
await assert.rejects(read({serverId:111})); await assert.rejects(read({minutes:1441})); await assert.rejects(read({interface:"__all__"})); await assert.rejects(read({skipHeavy:true}))
|
||||||
await assert.rejects(buildFlowAnalytics({serverId:110,minutes:5},{serverIds:[110],maxRows:1,authorize:async()=>{}}),/предел/)
|
await assert.rejects(buildFlowAnalytics({serverId:110,minutes:5},{serverIds:[110],maxRows:1,authorize:async()=>{}}),FlowSourceWindowTooLarge)
|
||||||
const cancelled = new AbortController(); cancelled.abort(); await assert.rejects(invokeMcpTool(principal,"mm_netflow_analytics_report_get",{serverId:110},cancelled.signal))
|
const cancelled = new AbortController(); cancelled.abort(); await assert.rejects(invokeMcpTool(principal,"mm_netflow_analytics_report_get",{serverId:110},cancelled.signal))
|
||||||
const duringQuery = (match: string, action: () => Promise<unknown>) =>
|
const duringQuery = (match: string, action: () => Promise<unknown>) =>
|
||||||
duringFlowSourceQuery(pool, match, action, () => assert.rejects(read()))
|
duringFlowSourceQuery(pool, match, action, () => assert.rejects(read()))
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { ensurePartitionFor } from "../db/partitions.js"
|
|||||||
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "../modules/mcp/store.js"
|
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "../modules/mcp/store.js"
|
||||||
import { invokeMcpTool } from "../modules/mcp/runtime.js"
|
import { invokeMcpTool } from "../modules/mcp/runtime.js"
|
||||||
import { buildFlowMapHops, invalidateFlowMapHopsCache } from "../services/traffic-flow-map-hops.js"
|
import { buildFlowMapHops, invalidateFlowMapHopsCache } from "../services/traffic-flow-map-hops.js"
|
||||||
|
import { FlowSourceWindowTooLarge } from "../services/traffic-flow-read-window.js"
|
||||||
import { invalidateFlowCatalogCache } from "../services/traffic-flow-topology.js"
|
import { invalidateFlowCatalogCache } from "../services/traffic-flow-topology.js"
|
||||||
import { resetFlowRingsForTests, ingestParsedFlowsForServerForTests } from "../services/traffic-flow-ingest.js"
|
import { resetFlowRingsForTests, ingestParsedFlowsForServerForTests } from "../services/traffic-flow-ingest.js"
|
||||||
import { disableRipeEnqueueForTests, resetRipeCacheForTests } from "../services/traffic-flow-ripe.js"
|
import { disableRipeEnqueueForTests, resetRipeCacheForTests } from "../services/traffic-flow-ripe.js"
|
||||||
@@ -57,7 +58,7 @@ export async function verifyMcpFlowMap(actor: AuthUser) {
|
|||||||
ingestParsedFlowsForServerForTests(113,[{src:"198.18.240.6",dst:"8.8.4.4",proto:6,srcPort:1,dstPort:443,bytes:999,packets:1,inIface:"NEVER_MAP_PENDING",outIface:""}])
|
ingestParsedFlowsForServerForTests(113,[{src:"198.18.240.6",dst:"8.8.4.4",proto:6,srcPort:1,dstPort:443,bytes:999,packets:1,inIface:"NEVER_MAP_PENDING",outIface:""}])
|
||||||
assert.equal((await read()).map.totalBytes,600)
|
assert.equal((await read()).map.totalBytes,600)
|
||||||
for (const input of [{userId:users[2]},{userId:users[3]},{serverId:113},{minutes:1441},{interface:"__all__"},{minSharePct:0},{nestedLimit:51}]) await assert.rejects(read(input))
|
for (const input of [{userId:users[2]},{userId:users[3]},{serverId:113},{minutes:1441},{interface:"__all__"},{minSharePct:0},{nestedLimit:51}]) await assert.rejects(read(input))
|
||||||
await assert.rejects(buildFlowMapHops({serverId:112,minutes:5},{serverIds:[112],maxRows:1,authorize:async()=>{}}),/предел/)
|
await assert.rejects(buildFlowMapHops({serverId:112,minutes:5},{serverIds:[112],maxRows:1,authorize:async()=>{}}),FlowSourceWindowTooLarge)
|
||||||
const cancelled=new AbortController();cancelled.abort();await assert.rejects(invokeMcpTool(principal,"mm_netflow_map_hops_get",{serverId:112},cancelled.signal))
|
const cancelled=new AbortController();cancelled.abort();await assert.rejects(invokeMcpTool(principal,"mm_netflow_map_hops_get",{serverId:112},cancelled.signal))
|
||||||
const duringQuery = (match: string, action: () => Promise<unknown>) =>
|
const duringQuery = (match: string, action: () => Promise<unknown>) =>
|
||||||
duringFlowSourceQuery(pool, match, action, () => assert.rejects(read()))
|
duringFlowSourceQuery(pool, match, action, () => assert.rejects(read()))
|
||||||
|
|||||||
@@ -238,6 +238,7 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
|||||||
const [step, setStep] = useState(1), [busy, setBusy] = useState(false), [error, setError] = useState("")
|
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 [name, setName] = useState(editing?.name ?? ""), [mode, setMode] = useState<McpConnection["policy"]["mode"]>(editing?.policy.mode ?? "observer")
|
||||||
const [service, setService] = useState(editing?.policy.authority === "service")
|
const [service, setService] = useState(editing?.policy.authority === "service")
|
||||||
|
const [unattended, setUnattended] = useState(editing?.policy.allowUnattendedPlans === true)
|
||||||
const [selectAllServers, setSelectAllServers] = useState(false)
|
const [selectAllServers, setSelectAllServers] = useState(false)
|
||||||
const [serverIds, setServerIds] = useState(editing?.policy.scope.serverIds ?? []), [selected, setSelected] = useState<string[]>(editing?.policy.scope.operationIds ?? [])
|
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 serverCatalog = useQuery(useCallback(signal => api.serverChoices(undefined, signal), [api]))
|
||||||
@@ -253,7 +254,7 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
|||||||
const save = async () => {
|
const save = async () => {
|
||||||
setBusy(true); setError("")
|
setBusy(true); setError("")
|
||||||
try {
|
try {
|
||||||
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 })
|
const input = mcpConnectionCreateSchema.parse({ name, ...(service ? { authority: "service", mode: "autonomous", expiresAt: null, ...(unattended && { allowUnattendedPlans: true }) } : { 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) }
|
||||||
@@ -261,7 +262,7 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
|||||||
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>{!editing && <NativeSelect label="Тип подключения" value={service ? "service" : "personal"} onChange={value => setService(value === "service")}><option value="personal">Личное</option><option value="service">Сервисное — бессрочный автономный доступ</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
|
{service
|
||||||
? <p className="text-sm text-muted-foreground">Подключение действует до отзыва. Агент выполняет разрешённые обычные операции автономно, а опасные действия требуют подтверждения.</p>
|
? <p className="text-sm text-muted-foreground">Подключение действует до отзыва. Способ подтверждения планов можно выбрать на шаге 3.</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></>}</>}
|
: <><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 && <>
|
||||||
<ServerChoices catalog={serverCatalog} selected={serverIds} onChange={setServerIds} all={selectAllServers} onAllChange={setSelectAllServers} />
|
<ServerChoices catalog={serverCatalog} selected={serverIds} onChange={setServerIds} all={selectAllServers} onAllChange={setSelectAllServers} />
|
||||||
@@ -269,11 +270,14 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
|||||||
<OperationChoices operations={eligible} selected={selected} onChange={setSelected} />
|
<OperationChoices operations={eligible} selected={selected} onChange={setSelected} />
|
||||||
<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>{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 === 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 ? <>
|
||||||
|
<Choice label="Выполнять планы без ручного подтверждения" checked={unattended} onChange={setUnattended} />
|
||||||
|
<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" && <>
|
||||||
<p className="text-sm text-muted-foreground">В автономном режиме выбранные здесь опасные операции смогут выполняться без подтверждения, если этого не требует защита объекта или сама операция.</p>
|
<p className="text-sm text-muted-foreground">В автономном режиме выбранные здесь опасные операции смогут выполняться без подтверждения, если этого не требует защита объекта или сама операция.</p>
|
||||||
<OperationChoices operations={dangerous} selected={autonomousDangerIds} onChange={setDangerIds} selectAllLabel="Выбрать все опасные операции" />
|
<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>}
|
{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 && unattended && <p>Ручное подтверждение планов отключено. Клиент публикует план в чате перед применением.</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>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,7 +121,11 @@
|
|||||||
|
|
||||||
### Сервисное подключение
|
### Сервисное подключение
|
||||||
|
|
||||||
В «Подключения» → «Выдать доступ» администратор MCP может выбрать «Сервисное — бессрочный автономный доступ». Выберите нужные серверы и операции. Доступ действует до отзыва и переживает истечение обычной сессии портала. Опасные операции всегда требуют подтверждения человеком, а лимиты и защита объектов действуют как обычно.
|
В «Подключения» → «Выдать доступ» администратор MCP может выбрать «Сервисное — бессрочный автономный доступ». Выберите нужные серверы и операции. Доступ действует до отзыва и переживает истечение обычной сессии портала. По умолчанию опасные действия требуют ручного подтверждения.
|
||||||
|
|
||||||
|
На шаге 3 можно включить «Выполнять планы без ручного подтверждения». Режим действует на все выданные ключу операции. Списки серверов, права, лимиты и правила защиты объектов продолжают действовать.
|
||||||
|
|
||||||
|
Если план содержит `announcement`, клиент сначала публикует отдельное сообщение в чате с ID плана, целями, изменениями и предупреждениями из `changes`. Затем вызывает `mm_change_apply` с `planId`, `idempotencyKey` и `announcedPlanDigest`, равным `announcement.digest`. Manager проверяет контрольную сумму сохранённого плана. Публикацию сообщения обеспечивает клиент. В аудите такой запуск отмечается как допуск по политике подключения.
|
||||||
|
|
||||||
Сервисный токен можно заменить, приостановить вместе с подключением или отозвать. Явный отзыв прав выдавшего доступ администратора в портале также отзывает его сервисные подключения. Чтобы сменить тип подключения, выдайте новый токен через новое подключение.
|
Сервисный токен можно заменить, приостановить вместе с подключением или отозвать. Явный отзыв прав выдавшего доступ администратора в портале также отзывает его сервисные подключения. Чтобы сменить тип подключения, выдайте новый токен через новое подключение.
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ export const mcpConnectionPolicySchema = z.object({
|
|||||||
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(),
|
authority: z.literal("service").optional(),
|
||||||
|
allowUnattendedPlans: z.literal(true).optional(),
|
||||||
expiresAt: instant,
|
expiresAt: instant,
|
||||||
mode: mcpModeSchema,
|
mode: mcpModeSchema,
|
||||||
permissions: uniqueStrings,
|
permissions: uniqueStrings,
|
||||||
@@ -42,8 +43,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().refine(policy => policy.authority !== "service" ||
|
}).strict().refine(policy => policy.authority === "service"
|
||||||
policy.expiresAt === MCP_SERVICE_EXPIRATION && policy.mode === "autonomous" && policy.dangerousPolicy === "approval" && !policy.autonomousDangerousOperationIds.length,
|
? policy.expiresAt === MCP_SERVICE_EXPIRATION && policy.mode === "autonomous" && policy.dangerousPolicy === "approval" && !policy.autonomousDangerousOperationIds.length
|
||||||
|
: !policy.allowUnattendedPlans,
|
||||||
"Некорректная политика сервисного подключения")
|
"Некорректная политика сервисного подключения")
|
||||||
|
|
||||||
export const mcpTargetSchema = z.discriminatedUnion("scope", [
|
export const mcpTargetSchema = z.discriminatedUnion("scope", [
|
||||||
@@ -133,6 +135,7 @@ 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),
|
||||||
authority: z.literal("service").optional(),
|
authority: z.literal("service").optional(),
|
||||||
|
allowUnattendedPlans: z.literal(true).optional(),
|
||||||
expiresAt: instant.nullable(),
|
expiresAt: instant.nullable(),
|
||||||
mode: mcpModeSchema.default("observer"),
|
mode: mcpModeSchema.default("observer"),
|
||||||
permissions: uniqueStrings,
|
permissions: uniqueStrings,
|
||||||
@@ -143,7 +146,7 @@ export const mcpConnectionCreateSchema = z.object({
|
|||||||
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
|
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
|
||||||
}).strict().refine(input => input.authority === "service"
|
}).strict().refine(input => input.authority === "service"
|
||||||
? input.expiresAt === null && input.mode === "autonomous" && input.dangerousPolicy === "approval" && !input.autonomousDangerousOperationIds.length
|
? input.expiresAt === null && input.mode === "autonomous" && input.dangerousPolicy === "approval" && !input.autonomousDangerousOperationIds.length
|
||||||
: input.expiresAt !== null, "Для сервисного подключения выберите автономный режим с подтверждением опасных действий. Для личного подключения укажите срок действия.")
|
: input.expiresAt !== null && !input.allowUnattendedPlans, "Опция доступна только бессрочному сервисному подключению. Для личного подключения укажите срок действия.")
|
||||||
.refine(input => !input.selectAllServers || !input.scope.serverIds.length, "Выберите все серверы или укажите конкретные ID")
|
.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(),
|
||||||
|
|||||||
@@ -389,7 +389,7 @@ test('synthetic: edit autonomous dangerous operations by group or all at once',
|
|||||||
}) })])
|
}) })])
|
||||||
})
|
})
|
||||||
|
|
||||||
test('synthetic: issue service access with no expiry and mandatory approval of dangerous actions', async ({ page }) => {
|
for (const unattended of [false, true]) test(`synthetic: issue service access with unattended plans ${unattended ? 'enabled' : 'disabled'}`, async ({ page }) => {
|
||||||
const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read'])
|
const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read'])
|
||||||
await page.goto('/mcp?tab=connections')
|
await page.goto('/mcp?tab=connections')
|
||||||
await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click()
|
await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click()
|
||||||
@@ -402,7 +402,9 @@ test('synthetic: issue service access with no expiry and mandatory approval of d
|
|||||||
await dialog.getByRole('button', { name: 'CHR WAN', exact: true }).click()
|
await dialog.getByRole('button', { name: 'CHR WAN', exact: true }).click()
|
||||||
await dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }).check()
|
await dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }).check()
|
||||||
await next.click()
|
await next.click()
|
||||||
await expect(dialog.getByText('Опасные действия всегда требуют подтверждения.')).toBeVisible()
|
const unattendedChoice = dialog.getByRole('checkbox', { name: 'Выполнять планы без ручного подтверждения', exact: true })
|
||||||
|
await expect(unattendedChoice).not.toBeChecked()
|
||||||
|
if (unattended) await unattendedChoice.check()
|
||||||
await next.click()
|
await next.click()
|
||||||
await expect(dialog.getByText('Сервисное, бессрочное', { exact: false })).toBeVisible()
|
await expect(dialog.getByText('Сервисное, бессрочное', { exact: false })).toBeVisible()
|
||||||
await dialog.getByRole('button', { name: 'Сохранить доступ', exact: true }).click()
|
await dialog.getByRole('button', { name: 'Сохранить доступ', exact: true }).click()
|
||||||
@@ -411,6 +413,7 @@ test('synthetic: issue service access with no expiry and mandatory approval of d
|
|||||||
authority: 'service', expiresAt: null, mode: 'autonomous', dangerousPolicy: 'approval', autonomousDangerousOperationIds: [],
|
authority: 'service', expiresAt: null, mode: 'autonomous', dangerousPolicy: 'approval', autonomousDangerousOperationIds: [],
|
||||||
scope: { serverIds: [1], operationIds: ['logs.query'], allowGlobal: false },
|
scope: { serverIds: [1], operationIds: ['logs.query'], allowGlobal: false },
|
||||||
}) })])
|
}) })])
|
||||||
|
expect(state.mutations[0].body.allowUnattendedPlans).toBe(unattended ? true : undefined)
|
||||||
})
|
})
|
||||||
|
|
||||||
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 }) => {
|
||||||
|
|||||||
Reference in new issue
Block a user