- контекст маршрута: проверка перед каждым GET (права, ключ источника, поколение, SQL) переиспользует доказательство этапа (2 с); границы фаз и внешний context.fence() по-прежнему проверяют заново; - IPsec (удаление пира, пользователя, сертификата, изменение пира): собственная проверка сервиса раз на этап для чтений, assertVerifiedConfigurationReadAccess для чтений; перед каждой нативной записью права и защиты проверяются заново (executeGuardedConfigurationWrite), checkpoint-записи аудита - свежая проверка; сверка (reconcile) остаётся строгой: отзыв прав останавливает следующее же чтение. Шарды: scoped forward/inverse/route-ai 205/240/324 -> 61/88/133 с, overlay-ipsec 175 -> 133 с (четыре приёмки IPsec 49 -> 19 с); весь набор 276 с, 149 строк на месте. Co-Authored-By: Claude Opus 5.5 <[email protected]>
76 lines
9.7 KiB
TypeScript
76 lines
9.7 KiB
TypeScript
import { z } from "zod"
|
|
import { coalesceAuthorization } from "./authorization-stage.js"
|
|
import { randomUUID } from "node:crypto"
|
|
import { pool } from "../../db/index.js"
|
|
import { hasPermission } from "../../lib/permissions.js"
|
|
import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js"
|
|
import { ipsecPeerUpdatePatchSchema, ipsecPeerUpdateNativePatch, planIpsecPeerUpdate, readIpsecPeerUpdateState, ipsecPeerUpdateProof, updateIpsecPeerGuarded } from "../../services/ipsec-peer-update.js"
|
|
import { effectiveMcpConnection, audit } from "./store.js"
|
|
import { routerClient } from "./resources.js"
|
|
import { accessGeneration, fingerprint, McpError, redact } from "./security.js"
|
|
import { registerMcpService } from "./service-registry.js"
|
|
import type { ActionContext, ChangeEvidence } from "./action-types.js"
|
|
import type { add } from "./actions.js"
|
|
|
|
export const ipsecPeerUpdateActionSchema=z.object({serverId:z.number().int().positive().safe(),peerId:z.string().regex(/^\*[a-z0-9]+$/i).max(100),patch:ipsecPeerUpdatePatchSchema}).strict()
|
|
const operation="network.ipsec.peers.update"
|
|
async function access(input:Record<string,unknown>,signal?:AbortSignal){
|
|
if(signal?.aborted)throw new McpError("READ_CANCELLED","Чтение IPsec отменено",409)
|
|
const principal=z.object({connectionId:z.string().uuid(),credentialId:z.string().uuid(),credentialExpiresAt:z.string()}).strict().parse(input.principal)
|
|
const current=await effectiveMcpConnection(principal)
|
|
if(input.operationId!==operation||current.owner_id!==input.ownerId||!hasPermission(current.owner_permissions,"mm:network:write")||!hasPermission(current.policy.permissions,"mm:network:write")||!current.policy.scope.operationIds.includes(operation))throw new McpError("PERMISSION_DENIED","Допуск PATCH IPsec отозван",403)
|
|
if(!current.policy.scope.serverIds.includes(Number(input.serverId)))throw new McpError("SERVER_DENIED","Сервер IPsec вне допуска",403)
|
|
const request=ipsecPeerUpdateActionSchema.parse({serverId:input.serverId,peerId:input.peerId,patch:input.patch})
|
|
if(fingerprint(request)!==input.requestProof||fingerprint(current.policy)!==input.policyProof||fingerprint(current.owner_permissions)!==input.ownerProof||await accessGeneration()!==input.generation)throw new McpError("RESET_REQUIRED","Допуск или запрос IPsec изменился",409)
|
|
if(signal?.aborted)throw new McpError("READ_CANCELLED","Чтение IPsec отменено",409)
|
|
}
|
|
async function source(input:Record<string,unknown>,signal?:AbortSignal,allow?:()=>Promise<unknown>){
|
|
// Service checks once per stage (reads reuse a proof younger than 2 s); every native write still
|
|
// re-proves MCP rights and protections in executeGuardedConfigurationWrite.
|
|
const check=async()=>{await allow?.();await access(input,signal)},authorize=allow?check:coalesceAuthorization(check).coalesced
|
|
await authorize()
|
|
const{server}=await routerClient(Number(input.serverId)),state=await readIpsecPeerUpdateState(server,authorize)
|
|
if(input.expectedSource!==undefined&&input.expectedSource!==state.source)throw new McpError("STATE_CONFLICT","Источник IPsec изменился",409)
|
|
await authorize();return{server,state,authorize}
|
|
}
|
|
export function hasVerifiedIpsecPeerUpdate(candidate:unknown,input:Record<string,unknown>,proof:string){
|
|
if(!candidate||typeof candidate!=="object")return false
|
|
const row=candidate as Record<string,unknown>,result=row.result as Record<string,unknown>|null
|
|
return row.connection_id===(input.principal as{connectionId?:string}|undefined)?.connectionId&&row.state==="verified"&&fingerprint(row.intended_state)===fingerprint(redact({kind:"service",service:operation,input}))&&!!result&&result.receiptId===input.receiptId&&result.verified===true&&result.historyRecorded===true&&result.revisionRecorded===true&&result.peerId===input.peerId&&result.commandCount===input.commandCount&&result.completedCommands===input.commandCount&&result.afterProof===proof&&proof===input.expectedAfterProof
|
|
}
|
|
export async function prepareIpsecPeerUpdate(serverId:number,peerId:string,patch:unknown,context:ActionContext):Promise<ChangeEvidence>{
|
|
const request=ipsecPeerUpdateActionSchema.parse({serverId,peerId,patch})
|
|
const internal={...request,requestProof:fingerprint(request),principal:context.principal,ownerId:context.connection.owner_id,policyProof:fingerprint(context.connection.policy),ownerProof:fingerprint(context.connection.owner_permissions),generation:await accessGeneration(),operationId:operation,receiptId:randomUUID()}
|
|
const{state,authorize}=await source(internal,context.signal),plan=planIpsecPeerUpdate(state,peerId,patch)
|
|
const objects:ChangeEvidence["objects"]=[{kind:"server",id:String(serverId),serverId},{kind:"ipsec_peer",id:peerId,serverId},...plan.companions.map(ref=>({...ref,serverId}))]
|
|
for(const item of state.protections as{object_ref:{kind:string;id:string}}[])objects.push({...item.object_ref,serverId})
|
|
await authorize()
|
|
return{target:{scope:"servers",serverIds:[serverId]},objects,snapshots:[],requiresHuman:true,mutationCost:plan.commandCount+1+plan.companions.length,before:{proof:state.proof},
|
|
steps:[{kind:"service",service:operation,input:{...internal,expectedSource:state.source,expectedProof:state.proof,expectedAfterProof:await ipsecPeerUpdateProof(plan.projected),commandCount:plan.commandCount,proofRevision:2,beforeFingerprint:fingerprint({proof:state.proof})}}],
|
|
warnings:[`Будет отправлено native PATCH: ${plan.commandCount}; затем обязательная managed-only история IPsec. Пустые строки адреса/profile/exchange-mode передаются как есть; same-value поля не пропускают PATCH. Пустой patch оставляет только историю.`, `Ожидаемых автоматических ссылок при rename: ${plan.companions.length}. Дополнительные PATCH identities/policies не отправляются; только точный whole-state read-back может подтвердить результат. Бюджет включает peer PATCH, историю и все затронутые ссылки.`,"Автоматический native rename ещё требует отдельной CHR-приёмки. Несовпадение ссылок или постороннее изменение даёт partial; потеря ответа — unknown. Ни повтор, ни обратное изменение автоматически не выполняются; пересылка трафика не подтверждается."]}
|
|
}
|
|
/** Generic native updates still require an explicit business-operation grant;
|
|
* the shared source access check runs before the first RouterOS read. */
|
|
export async function prepareNativeIpsecPeerUpdate(serverId:number,nativeId:string,fields:unknown,context:ActionContext):Promise<ChangeEvidence>{
|
|
return prepareIpsecPeerUpdate(serverId,nativeId,ipsecPeerUpdateNativePatch(fields),context)
|
|
}
|
|
export function registerIpsecPeerUpdateActions(register:typeof add){
|
|
registerMcpService(operation,{
|
|
current:async input=>({proof:(await source(input)).state.proof}),
|
|
execute:async input=>{
|
|
const before=await source(input)
|
|
return updateIpsecPeerGuarded(before.server,String(input.peerId),input.patch,String(input.expectedProof),async()=>{await assertVerifiedConfigurationReadAccess();await before.authorize()},{receiptId:String(input.receiptId),checkpoint:async value=>{await assertVerifiedConfigurationAccess();await before.authorize();await audit(pool,String(input.ownerId),"ipsec.peer.update.checkpoint",(input.principal as{connectionId:string}).connectionId,{...value,inputProof:fingerprint(redact(input))})}})
|
|
},
|
|
verify:async(input,result)=>{const latest=await source(input);return hasVerifiedIpsecPeerUpdate({connection_id:(input.principal as{connectionId:string}).connectionId,state:"verified",intended_state:redact({kind:"service",service:operation,input}),result},input,latest.state.proof)},
|
|
reconcile:async(input,allow)=>{
|
|
if(input.proofRevision!==2||!z.string().uuid().safeParse(input.receiptId).success||![0,1].includes(Number(input.commandCount))||typeof input.expectedProof!=="string"||!/^[a-f0-9]{64}$/.test(input.expectedProof)||typeof input.expectedAfterProof!=="string"||!/^[a-f0-9]{64}$/.test(input.expectedAfterProof))throw new McpError("UNSUPPORTED_CAPABILITY","Нет совместимого private proof PATCH IPsec",409)
|
|
const latest=await source(input,undefined,allow)
|
|
const rows=(await pool.query("SELECT o.connection_id,s.state,s.intended_state,s.result FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id WHERE o.connection_id=$1 AND s.intended_state->'input'->>'receiptId'=$2 LIMIT 2",[(input.principal as{connectionId:string}).connectionId,input.receiptId])).rows
|
|
const verified=rows.length===1&&hasVerifiedIpsecPeerUpdate(rows[0],input,latest.state.proof)
|
|
if((await source(input,undefined,allow)).state.proof!==latest.state.proof)throw new McpError("STATE_CONFLICT","IPsec изменился во время сверки",409)
|
|
return{matchesOriginalState:latest.state.proof===input.expectedProof,configurationMatchesDesiredState:latest.state.proof===input.expectedAfterProof,matchesDesiredState:verified,verifiedFinalCheckpointAvailable:verified,automaticReplay:false,forwardingVerified:false}
|
|
},
|
|
})
|
|
register(operation,"mm_ipsec_peer_edit_plan","Изменить IPsec peer с точными native ссылками и managed-only историей","network","mm:network:write","write","servers",ipsecPeerUpdateActionSchema,{version:2,prepare:(input,context)=>prepareIpsecPeerUpdate(Number(input.serverId),String(input.peerId),input.patch,context)})
|
|
}
|