108 lines
9.5 KiB
TypeScript
108 lines
9.5 KiB
TypeScript
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
|
|
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
import type { FastifyInstance } from "fastify"
|
|
import type { AuthUser } from "../../lib/permissions.js"
|
|
import { pool } from "../../db/index.js"
|
|
import { env } from "../../config.js"
|
|
import { agentSocket } from "../../services/traffic-flow-agent-client.js"
|
|
import { createFlowSettingsStore } from "../../services/traffic-flow-settings-store.js"
|
|
import { invalidateTrafficFlowSettingsCache } from "../../services/traffic-flow-settings.js"
|
|
import { updateTrafficFlowSettingsWithListener } from "../../services/traffic-flow-settings-service.js"
|
|
import { getFlowWorkerHealth, getFlowListenerState } from "../../services/traffic-flow-ingest.js"
|
|
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
|
|
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
|
|
import { decryptSecret } from "./security.js"
|
|
import { createFlowSettingsAdapter } from "./flow-settings-actions.js"
|
|
import type { ChangeEvidence } from "./action-types.js"
|
|
|
|
/** Called only by the root-owned disposable --flow-host-keys SQL fixture.
|
|
* Exercises actual main-process full restart/flush with enabled=false. It never
|
|
* requests UDP workers; enabled=true worker wiring is proved by injected tests. */
|
|
export async function acceptMcpFlowSettingsUpdate(actor: AuthUser, app: FastifyInstance) {
|
|
assert.equal(process.env.MMAPP_OWN_FLOW_HOST_KEYS, "true")
|
|
const endpoint = new URL(process.env.DATABASE_URL!)
|
|
assert.equal(endpoint.hostname, "127.0.0.1"); assert.equal(endpoint.pathname, "/postgres")
|
|
assert.equal(env.authRequired, true); assert.ok(!agentSocket())
|
|
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM servers")).rows[0].n), 0)
|
|
const store = createFlowSettingsStore(pool, async () => {}, invalidateTrafficFlowSettingsCache)
|
|
const before = await store.read()
|
|
assert.ok(before.hostPrivateKey); assert.equal(before.enabled, false); assert.equal(getFlowWorkerHealth().alive, false)
|
|
let network = 0
|
|
const savedFetch = globalThis.fetch
|
|
globalThis.fetch = (async () => { network++; throw Error("Disabled settings acceptance forbids network") }) as typeof fetch
|
|
const protectionId = randomUUID()
|
|
const wait = async (id: string) => {
|
|
for (const deadline = Date.now() + 45000; Date.now() < deadline;) {
|
|
const row = (await pool.query("SELECT state,verification,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]
|
|
if (!["pending", "running"].includes(row.state)) return row
|
|
await delay(20)
|
|
}
|
|
throw Error("Unconfirmed settings operation; do not replay")
|
|
}
|
|
try {
|
|
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "full settings disabled acceptance", mode: "autonomous", permissions: ["mm:traffic:write"], expiresAt: new Date(Date.now() + 600000).toISOString(), scope: { allowGlobal: true, serverIds: [], operationIds: ["netflow.settings.update"] }, limits: { callsPerMinute: 240, mutationsPerHour: 1000, concurrentReads: 4, serversPerPlan: 1000, objectsPerPlan: 1000 } }), actor)
|
|
const principal = await authenticateMcpToken(access.token)
|
|
const patch = { enabled: false, collectorIp: "10.255.253.1", flowListenPort: 4740, wgListenPort: 51822, prefix: "10.255.253.0/24", publicEndpoint: "flow.example.test", hubServerId: null, retentionHours: 48, topN: 100, mapServiceMinSharePct: 0 }
|
|
const counts = async () => (await pool.query("SELECT (SELECT count(*)::int FROM flow_settings_intents) AS intents,(SELECT count(*)::int FROM flow_write_receipts) AS writes")).rows[0]
|
|
const stateBeforeBudget = await store.read(), countsBeforeBudget = await counts()
|
|
const limited = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "settings bound four rejects budget three", mode: "autonomous", permissions: ["mm:traffic:write"], expiresAt: new Date(Date.now()+600000).toISOString(), scope: {allowGlobal:true,serverIds:[],operationIds:["netflow.settings.update"]}, limits: {mutationsPerHour:3,callsPerMinute:240,serversPerPlan:1000,objectsPerPlan:1000} }),actor)
|
|
const limitedPrincipal = await authenticateMcpToken(limited.token)
|
|
await assert.rejects(invokeMcpTool(limitedPrincipal,"mm_netflow_settings_update_plan",{settings:patch}),error => (error as {code?:string}).code === "BUDGET_EXCEEDED")
|
|
assert.deepEqual(await store.read(),stateBeforeBudget)
|
|
assert.deepEqual(await counts(),countsBeforeBudget,"insufficient max-four budget cannot reach settings/intent/owned writer effects")
|
|
const oldVersion = await invokeMcpTool(principal,"mm_netflow_settings_update_plan",{settings:patch}) as {planId:string}
|
|
await approvePlan(oldVersion.planId,actor,true)
|
|
await pool.query("UPDATE mcp_plans SET operation_version=2 WHERE id=$1",[oldVersion.planId])
|
|
await assert.rejects(applyPlan(principal,oldVersion.planId,randomUUID()),error=>(error as {code?:string}).code==="PLAN_EXPIRED")
|
|
assert.deepEqual(await store.read(),stateBeforeBudget)
|
|
assert.deepEqual(await counts(),countsBeforeBudget,"old underbudget version2 is refused before phase intent or writer effects")
|
|
for (const input of [patch, { mapServiceMinSharePct: 0 }]) {
|
|
const planned = await invokeMcpTool(principal, "mm_netflow_settings_update_plan", {settings:input}) as {planId:string;state:string}
|
|
assert.equal(planned.state,"awaiting-approval")
|
|
const evidence:ChangeEvidence = JSON.parse(await decryptSecret((await pool.query("SELECT evidence FROM mcp_plans WHERE id=$1",[planned.planId])).rows[0].evidence.sealed))
|
|
assert.equal(evidence.requiresHuman,true);assert.equal(evidence.mutationCost,4)
|
|
const step=evidence.steps[0];assert.equal(step.kind,"service");if(step.kind!=="service")throw Error()
|
|
const adapter=createFlowSettingsAdapter()
|
|
assert.deepEqual(await adapter.service.current!(step.input),evidence.before)
|
|
assert.equal((await adapter.service.reconcile!(step.input,async()=>{})).matchesDesiredState,false)
|
|
await assert.rejects(applyPlan(principal,planned.planId,randomUUID()))
|
|
await approvePlan(planned.planId,actor,true)
|
|
const operation=await applyPlan(principal,planned.planId,randomUUID()),finished=await wait(operation.id)
|
|
assert.equal(finished.state,"applied",JSON.stringify(finished));assert.equal(finished.verification,"passed")
|
|
const saved=(await pool.query("SELECT state,result FROM mcp_operation_steps WHERE operation_id=$1",[operation.id])).rows[0]
|
|
assert.equal(saved.state,"verified")
|
|
const receipt=saved.result
|
|
assert.equal(receipt.configurationConfirmed,true);assert.equal(receipt.receiptConfirmed,true)
|
|
assert.equal(receipt.listener,"request-acknowledged");assert.equal(receipt.listenerReadinessConfirmed,false)
|
|
assert.equal(receipt.attempts,2);assert.equal(receipt.retries,0)
|
|
assert.deepEqual(await store.read(),{...before,...patch})
|
|
const claims=(await pool.query("SELECT phase,state FROM flow_settings_intents WHERE receipt_id=$1 ORDER BY phase",[receipt.receiptId])).rows
|
|
assert.deepEqual(claims,[{phase:"configuration",state:"completed"},{phase:"listener",state:"completed"}])
|
|
assert.equal((await adapter.service.reconcile!(step.input,async()=>{})).matchesDesiredState,true)
|
|
await assert.rejects(updateTrafficFlowSettingsWithListener(input,{receiptId:receipt.receiptId}))
|
|
assert.ok(!JSON.stringify({planned,receipt}).includes(String(before.hostPrivateKey)))
|
|
assert.equal(getFlowWorkerHealth().alive,false);assert.equal(getFlowListenerState().bound,false)
|
|
}
|
|
const jwt=app.jwt.sign({sub:actor.id,apps:actor.apps,permissions:actor.permissions},{iss:env.authIssuer,expiresIn:"10m"})
|
|
const response=await app.inject({method:"PUT",url:"/api/traffic/flow/settings",headers:{authorization:"Bearer "+jwt},payload:{mapServiceMinSharePct:0}})
|
|
assert.equal(response.statusCode,200,response.body);assert.equal(response.json().listenerError,undefined)
|
|
assert.equal((await app.inject({method:"PUT",url:"/api/traffic/flow/settings",payload:{enabled:false}})).statusCode,401)
|
|
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)",[protectionId,{kind:"database-table",id:"flow_ip_meta",protection:"deny"},actor.id])
|
|
const protectedResponse=await app.inject({method:"PUT",url:"/api/traffic/flow/settings",headers:{authorization:"Bearer "+jwt},payload:{topN:99}})
|
|
assert.equal(protectedResponse.statusCode,409,protectedResponse.body)
|
|
await assert.rejects(invokeMcpTool(principal,"mm_netflow_settings_update_plan",{settings:{topN:99}}))
|
|
await pool.query("DELETE FROM mcp_protections WHERE id=$1",[protectionId])
|
|
const revoked=await invokeMcpTool(principal,"mm_netflow_settings_update_plan",{settings:{topN:98}}) as {planId:string}
|
|
await approvePlan(revoked.planId,actor,true);await setConnectionStatus(access.connection.id,"paused",actor)
|
|
await assert.rejects(applyPlan(principal,revoked.planId,randomUUID()))
|
|
assert.equal((await store.read()).topN,100)
|
|
assert.equal(network,0);assert.equal(getFlowWorkerHealth().alive,false);assert.equal(getFlowListenerState().bound,false)
|
|
console.log("Full settings SQL/HTTP/MCP: all ten fields and no-op/display restart with enabled=false, full private CAS/future preservation, durable two-phase receipt, VERIFIED reconciliation, JWT/protection/revocation parity; actual main flush only, no UDP worker/network acceptance")
|
|
} finally {
|
|
globalThis.fetch=savedFetch
|
|
await pool.query("DELETE FROM mcp_protections WHERE id=$1",[protectionId])
|
|
}
|
|
}
|