110 lines
10 KiB
TypeScript
110 lines
10 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import { basename, dirname, resolve } from "node:path"
|
|
import type { McpPrincipal } from "./store.js"
|
|
|
|
/** Owned disposable PostgreSQL only. Real schema, principal validation, private
|
|
* HMAC and guarded configuration.intent; the PATCH callback is just a counter.
|
|
* No module registration, RouterOS/HTTP call, retention or deletion. */
|
|
export async function acceptRoutingProfileAuthoritySql() {
|
|
assert.equal(process.env.MMAPP_OWN_PROBE_JOURNAL, "true")
|
|
const url = new URL(process.env.DATABASE_URL ?? "")
|
|
assert.equal(url.hostname, "127.0.0.1"); assert.equal(url.pathname, "/postgres")
|
|
assert(["postgres:", "postgresql:"].includes(url.protocol))
|
|
assert(process.env.MCP_STATE_DIR && basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-"))
|
|
// All imports with runtime DB/key side effects follow the ownership guard.
|
|
const { pool } = await import("../../db/index.js")
|
|
const security = await import("./security.js")
|
|
const { mcpConnectionPolicySchema } = await import("@mmapp/contracts/mcp")
|
|
const { routeAiProfileSchema } = await import("@mmapp/contracts/mcp-routing")
|
|
const { resolveRoutingProfileAuthority, assertRoutingProfileAuthority } = await import("./routing-profile-authority.js")
|
|
const { readRoutingEndpoints, createRoutingSourceContext } = await import("./routing-observation-source.js")
|
|
const { withVerifiedConfigurationChange, executeGuardedConfigurationWrite } = await import("../../services/config-mutation-policy.js")
|
|
assert.equal((await pool.query("SELECT current_database() AS name")).rows[0].name, "postgres")
|
|
const previousEnabled = (await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled as boolean
|
|
const ids: number[] = [], profileIds: string[] = []
|
|
let cases = 0, simulatedPatchDispatches = 0
|
|
const names: string[] = []
|
|
try {
|
|
const marker = "authority-synthetic-" + randomUUID()
|
|
ids.push(...(await pool.query("INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) VALUES($1,'127.0.0.1',9,true,'SYNTHETIC','SYNTHETIC',false,true),($2,'127.0.0.1',9,true,'SYNTHETIC','SYNTHETIC',false,true) RETURNING id", [marker + "-source", marker + "-exit"])).rows.map(row => Number(row.id)))
|
|
await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1")
|
|
const profile = routeAiProfileSchema.parse({ name: marker, serverId: ids[0], community: "65000:10", family: "ipv4", autoRecovery: true,
|
|
candidates: [{ id: "a", jumpHostId: ids[0], exitNodeId: ids[1], wanInterface: "synthetic-wan", downstreamInterface: "synthetic-hop",
|
|
gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*1" },
|
|
controlProbe: { targetInterface: "synthetic-exit", expectedHops: [{ serverId: ids[1], interface: "synthetic-exit" }] } }] })
|
|
const source = await createRoutingSourceContext(await readRoutingEndpoints(ids))
|
|
const transport = { contextSources: source.expected }
|
|
const fixture = async () => {
|
|
const connectionId = randomUUID(), credentialId = randomUUID(), profileId = randomUUID(), ownerId = marker + "-owner-" + randomUUID()
|
|
const now = Date.now(), expires = new Date(now + 600000).toISOString(), generation = await security.accessGeneration()
|
|
const permissions = ["mm:network:read", "mm:network:write", "mm:filters:write"]
|
|
const policy = mcpConnectionPolicySchema.parse({ id: connectionId, version: 1, status: "active", mode: "approval", permissions, expiresAt: expires,
|
|
scope: { serverIds: ids, operationIds: ["routing.analyze", "routing.community.switch", "routing.path.verify", "operations.recover"], allowGlobal: false },
|
|
limits: { callsPerMinute: 100, mutationsPerHour: 100, concurrentReads: 4, serversPerPlan: 2, objectsPerPlan: 20 } })
|
|
await pool.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,'synthetic routing authority',$2,$3::jsonb,$4::jsonb,$5,$6,$7)", [connectionId, ownerId, JSON.stringify(permissions), JSON.stringify(policy), generation, expires, new Date(now - 1000)])
|
|
await pool.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [credentialId, connectionId, randomUUID(), expires])
|
|
await pool.query("INSERT INTO mcp_routing_profiles(id,connection_id,config,enabled,grant_expires_at,credential_id,generation,policy_version) VALUES($1,$2,$3::jsonb,true,$4,$5,$6,1)", [profileId, connectionId, JSON.stringify(profile), expires, credentialId, generation])
|
|
profileIds.push(profileId)
|
|
const principal: McpPrincipal = { connectionId, credentialId, credentialExpiresAt: expires }
|
|
const context = { profile, principal, ownerId, transport }
|
|
const binding = await resolveRoutingProfileAuthority({ ...context, profileId, expectedVersion: 1 })
|
|
return { context, binding, connectionId, credentialId, profileId, ownerId }
|
|
}
|
|
type Fixture = Awaited<ReturnType<typeof fixture>>
|
|
const check = (name: string) => { cases++; names.push(name) }
|
|
{
|
|
const f = await fixture()
|
|
assert.equal((await assertRoutingProfileAuthority(f.binding, f.context)).profileVersion, 1)
|
|
await assertRoutingProfileAuthority(f.binding, { ...f.context, use: "recovery" })
|
|
await assert.rejects(resolveRoutingProfileAuthority({ ...f.context, profileId: f.profileId, expectedVersion: 2 }))
|
|
await assert.rejects(assertRoutingProfileAuthority({ ...f.binding, proof: "f".repeat(64) }, f.context))
|
|
await assert.rejects(assertRoutingProfileAuthority(f.binding, { ...f.context, ownerId: "foreign" }))
|
|
await assert.rejects(assertRoutingProfileAuthority(f.binding, { ...f.context, transport: { contextSources: source.expected.map(row => ({ ...row, proof: "f".repeat(64) })) } }))
|
|
check("real resolver, recovery authority, version, tamper, owner and transport")
|
|
}
|
|
const changes: Array<[string, (f: Fixture) => Promise<unknown>]> = [
|
|
["profile version", f => pool.query("UPDATE mcp_routing_profiles SET version=version+1 WHERE id=$1", [f.profileId])],
|
|
["profile edit", f => pool.query("UPDATE mcp_routing_profiles SET config=jsonb_set(config,'{name}','\"edited\"') WHERE id=$1", [f.profileId])],
|
|
["same-config ABA version", async f => {
|
|
await pool.query("UPDATE mcp_routing_profiles SET config=jsonb_set(config,'{name}','\"temporary\"'),version=version+1 WHERE id=$1", [f.profileId])
|
|
await pool.query("UPDATE mcp_routing_profiles SET config=$2::jsonb,version=version+1 WHERE id=$1", [f.profileId, JSON.stringify(profile)])
|
|
}],
|
|
["disabled", f => pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=$1", [f.profileId])],
|
|
["emergency pause", f => pool.query("UPDATE mcp_routing_profiles SET state='{\"pausedReason\":\"synthetic emergency\"}'::jsonb WHERE id=$1", [f.profileId])],
|
|
["profile grant expired", f => pool.query("UPDATE mcp_routing_profiles SET grant_expires_at=clock_timestamp()-interval '1 second' WHERE id=$1", [f.profileId])],
|
|
["profile grant extended", f => pool.query("UPDATE mcp_routing_profiles SET grant_expires_at=grant_expires_at+interval '1 second' WHERE id=$1", [f.profileId])],
|
|
["credential revoked", f => pool.query("UPDATE mcp_credentials SET revoked_at=clock_timestamp() WHERE id=$1", [f.credentialId])],
|
|
["credential expired", f => pool.query("UPDATE mcp_credentials SET expires_at=clock_timestamp()-interval '1 second' WHERE id=$1", [f.credentialId])],
|
|
["policy version", f => pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{version}','2') WHERE id=$1", [f.connectionId])],
|
|
["policy paused", f => pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"paused\"') WHERE id=$1", [f.connectionId])],
|
|
["server scope", f => pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{scope,serverIds}',$2::jsonb) WHERE id=$1", [f.connectionId, JSON.stringify([ids[0]])])],
|
|
["owner identity", f => pool.query("UPDATE mcp_connections SET owner_id=$2 WHERE id=$1", [f.connectionId, marker + "-foreign"])],
|
|
["owner expired", f => pool.query("UPDATE mcp_connections SET owner_valid_until=clock_timestamp()-interval '1 second' WHERE id=$1", [f.connectionId])],
|
|
["owner permission revoked", f => pool.query("UPDATE mcp_connections SET owner_permissions='[\"mm:network:read\"]'::jsonb WHERE id=$1", [f.connectionId])],
|
|
["portal owner claims revoked", f => pool.query("INSERT INTO mcp_owner_revocations(owner_id,invalid_before) VALUES($1,clock_timestamp())", [f.ownerId])],
|
|
]
|
|
for (const [name, change] of changes) {
|
|
const f = await fixture(), path = "/routing/filter/rule/*1", before = simulatedPatchDispatches
|
|
await assert.rejects(withVerifiedConfigurationChange({ actorId: f.ownerId, connectionId: f.connectionId, approved: true,
|
|
serverIds: ids, objects: [], serverWide: true, authorize: async () => { await assertRoutingProfileAuthority(f.binding, f.context) },
|
|
beforeDispatch: async () => {
|
|
const intent = (await pool.query("SELECT id FROM mcp_audit WHERE connection_id=$1 AND action='configuration.intent' AND payload->>'path'=$2 LIMIT 2", [f.connectionId, path])).rows
|
|
assert.equal(intent.length, 1, "Common guarded boundary must durably record intent before the mutation")
|
|
await change(f)
|
|
await assertRoutingProfileAuthority(f.binding, f.context)
|
|
},
|
|
}, () => executeGuardedConfigurationWrite(ids[0], "PATCH", path, async () => { simulatedPatchDispatches++ })), /Постоянный допуск/)
|
|
assert.equal(simulatedPatchDispatches, before, `${name}: no simulated PATCH after lost authority`)
|
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_audit WHERE connection_id=$1 AND action='configuration.unconfirmed'", [f.connectionId])).rows[0].n, 1)
|
|
check(name + " after durable intent")
|
|
}
|
|
return { cases, names, simulatedPatchDispatches, realSql: true, productionHmac: true, realGuardedIntent: true, externalNetwork: false, controllerEnabled: false }
|
|
} finally {
|
|
// Retain evidence. Never delete fixture rows or touch pre-existing servers.
|
|
if (profileIds.length) await pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=ANY($1::uuid[])", [profileIds])
|
|
if (ids.length) await pool.query("UPDATE servers SET enabled=false WHERE id=ANY($1::int[])", [ids])
|
|
await pool.query("UPDATE mcp_settings SET enabled=$1 WHERE id=1", [previousEnabled])
|
|
}
|
|
}
|