feat(mcp): разрешить автономное выполнение планов сервисным ключом
Docker images / prepare-release (push) Successful in 14s
Docker images / backend-test (push) Failing after 3m16s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 2m47s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Docker images / prepare-release (push) Successful in 14s
Docker images / backend-test (push) Failing after 3m16s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 2m47s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
This commit is contained in:
1 parent
26249e1a4d
commit
79ab7b45aa
18 files changed
+184
-60
No files matched your search
@@ -31,7 +31,7 @@ import { readPollRuntimePolicySource, type PollRuntimePolicySource } from "./pol
|
||||
import { withVerifiedConfigurationChange, assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
|
||||
import { beginMcpOperationAdmission, insertMcpOperationAdmission, retireMcpOperationAdmission, withMcpOperationExecutionOrigin, stripMcpOperationExecutionPrivateResult, type McpOperationAdmission } from "./operation-execution-origin.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 { refuseExpiredOperationReplay } from "./operation-replay-tombstones.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,
|
||||
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])
|
||||
const approval = operationApprovalRequirement(connection.policy, operationId, target, evidence?.requiresHuman)
|
||||
return {
|
||||
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,
|
||||
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 }] : []),
|
||||
],
|
||||
objects: [...(evidence?.objects ?? []), ...approval.objects], objectCount: evidence ? changeMutationCost(evidence) + (evidence.recovery ? 1 : 0) : 0,
|
||||
protections: [...protections.map(row => mcpProtectedObjectSchema.parse(row.object_ref)), ...approval.protections],
|
||||
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)
|
||||
if (!expiresAt) throw new McpError("PLAN_EXPIRED", "Срок исходных данных плана истёк или недоступен; подготовьте новый план", 409)
|
||||
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,
|
||||
assertAuthority: async () => {
|
||||
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)
|
||||
decision = evaluateMcpPolicy(finalCheck)
|
||||
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 })
|
||||
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
|
||||
} 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)
|
||||
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
|
||||
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))) }
|
||||
}
|
||||
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
|
||||
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> {
|
||||
return withMcpDatabaseRequest(() => admitPlan(principal, planId, idempotencyKey))
|
||||
export async function applyPlan(principal: McpPrincipal, planId: string, idempotencyKey: string, announcedPlanDigest?: string): Promise<StoredOperation> {
|
||||
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)
|
||||
let reservedRouting = false
|
||||
let originalServiceGrant:OriginalServiceGrant|undefined
|
||||
@@ -408,6 +418,10 @@ async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey
|
||||
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 (!["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) {
|
||||
if (change.kind === "ros" && change.step.resource === "ip_settings" && change.step.fields["rp-filter"] === "strict") {
|
||||
checkRpfPolicy(change.step.serverId, evidence.snapshots, "strict")
|
||||
@@ -415,7 +429,7 @@ async function admitPlan(principal: McpPrincipal, planId: string, idempotencyKey
|
||||
}
|
||||
let scopedPathExpiresAt: number | undefined
|
||||
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)
|
||||
}
|
||||
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)
|
||||
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 (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 row = inserted.operation, id = row.id
|
||||
operationAdmission = inserted.admission; originalServiceGrant = inserted.originalGrant
|
||||
if (plan.operation_id === "routing.community.switch" || plan.operation_id === "operations.recover") {
|
||||
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)
|
||||
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,
|
||||
(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
|
||||
}).catch(async error => { await retireMcpOperationAdmission(operationAdmission); throw error })
|
||||
const operation = admitted.value
|
||||
@@ -568,7 +587,7 @@ async function executeOperationWithLease(operationId: string, principal: McpPrin
|
||||
policy.usage.callsInMinute = 0; policy.usage.mutationsInHour = 0
|
||||
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 === "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)
|
||||
else await transaction(checkPolicy)
|
||||
@@ -681,7 +700,7 @@ async function executeOperationWithLease(operationId: string, principal: McpPrin
|
||||
}
|
||||
stepDispatches++
|
||||
} : 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 () => {
|
||||
vrfDiagnosticFallback?.executorEntered()
|
||||
if (step.kind === "ros") {
|
||||
@@ -830,7 +849,7 @@ async function performReservedRecovery(operation: StoredOperation, plan: StoredP
|
||||
input.temporaryGrant = await temporaryScope(client, connection, principal.credentialId)
|
||||
input.usage.callsInMinute = 0; input.usage.mutationsInHour = 0
|
||||
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)
|
||||
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 })
|
||||
attempted = true
|
||||
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)
|
||||
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 })
|
||||
|
||||
Reference in new issue
Block a user