feat(mcp): расширить управление маршрутизацией, доступом и обслуживанием базы
This commit is contained in:
1 parent
9240e8be11
commit
cffcfada88
125 files changed
+6021
-602
No files matched your search
@@ -6,6 +6,7 @@ import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'
|
||||
const endpoint = new URL(process.env.OWN_MCP_ENDPOINT), origin = endpoint.origin
|
||||
assert.equal(endpoint.hostname, '127.0.0.1'); assert.equal(process.env.OWN_EXTERNAL_CLIENT, 'true')
|
||||
let phase = 'start', next = 0, maxResponseBytes = 0, stderrBytes = 0, bridgePid = null
|
||||
const responseLimitBytes = 1024 * 1024
|
||||
const pending = new Map(), cases = []
|
||||
const activeClients = new Set()
|
||||
let closing = false
|
||||
@@ -22,7 +23,7 @@ async function boundedFetch(input, init) {
|
||||
if (response.body) {
|
||||
const reader = response.body.getReader()
|
||||
try {
|
||||
for (;;) { const item = await reader.read(); if (item.done) break; count += item.value.length; if (count >= 1048576) { await reader.cancel(); throw Error('Own external client response bound') }; chunks.push(item.value) }
|
||||
for (;;) { const item = await reader.read(); if (item.done) break; count += item.value.length; if (count >= responseLimitBytes) { await reader.cancel(); throw Error('Own external client response bound') }; chunks.push(item.value) }
|
||||
} finally { reader.releaseLock() }
|
||||
}
|
||||
const bytes = Buffer.concat(chunks); maxResponseBytes = Math.max(maxResponseBytes, bytes.length)
|
||||
@@ -36,14 +37,14 @@ function content(result) {
|
||||
return parsed
|
||||
}
|
||||
async function denied(work) { try { const r = await work(); assert.equal(r?.isError, true) } catch (e) { if (e?.code === 'ERR_ASSERTION') throw e; assert(!/timeout|timed out/i.test(String(e?.message)), 'A timeout is not authorization denial') } }
|
||||
async function opened(mode, token) {
|
||||
async function opened(mode, token, maxBufferSize = 131072) {
|
||||
const client = new Client({ name: 'actual-external-process-' + mode, version: '1.0.0' })
|
||||
activeClients.add(client)
|
||||
let transport
|
||||
if (mode === 'http') transport = new StreamableHTTPClientTransport(endpoint, { requestInit: { headers: { authorization: 'Bearer ' + token } }, fetch: boundedFetch })
|
||||
else {
|
||||
transport = new StdioClientTransport({ command: process.execPath, args: ['--import', import.meta.resolve('tsx'), process.env.OWN_BRIDGE_FILE],
|
||||
cwd: process.cwd(), env: { MCP_URL: endpoint.href, MCP_TOKEN: token }, stderr: 'pipe', maxBufferSize: 131072 })
|
||||
cwd: process.cwd(), env: { MCP_URL: endpoint.href, MCP_TOKEN: token }, stderr: 'pipe', maxBufferSize })
|
||||
transport.stderr?.on('data', chunk => { stderrBytes += chunk.length; const text = String(chunk); assert(!text.includes(token)); assert(stderrBytes < 1048576) })
|
||||
const start = transport.start.bind(transport)
|
||||
transport.start = async () => { await start(); bridgePid = transport.pid; assert(bridgePid && bridgePid !== process.pid && bridgePid !== Number(process.env.OWN_SERVER_PID)); process.send({ kind: 'bridge-pid', pid: bridgePid }) }
|
||||
@@ -68,6 +69,36 @@ try {
|
||||
phase = mode + ':initialize'; let client = await opened(mode, token)
|
||||
try {
|
||||
await scoped(client); cases.push(mode + ': separate SDK process initializes, filters tool/host scope, bounds page/result and redacts credentials')
|
||||
phase = mode + ':policy-edit'
|
||||
const editScope = async operationIds => {
|
||||
const response = await boundedFetch(origin + '/api/mcp/connections/' + initial.connectionId, {
|
||||
method: 'PUT', headers: { authorization: 'Bearer ' + process.env.OWN_PORTAL_JWT, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Owned external SDK process', mode: 'observer', expiresAt: new Date(Date.now() + 600000).toISOString(),
|
||||
permissions: ['mm:servers:read'], scope: { serverIds: [Number(process.env.OWN_ALLOWED_SERVER)], operationIds, allowGlobal: false }, limits: { callsPerMinute: 200 } }),
|
||||
})
|
||||
assert.equal(response.status, 200)
|
||||
}
|
||||
await editScope(['logs.query'])
|
||||
assert.deepEqual((await client.listTools({}, { timeout: 5000 })).tools.map(tool => tool.name), ['mm_logs_query'])
|
||||
const allowedServer = Number(process.env.OWN_ALLOWED_SERVER), forbiddenServer = Number(process.env.OWN_FORBIDDEN_SERVER)
|
||||
const queryLogs = arguments_ => client.callTool({ name: 'mm_logs_query', arguments: arguments_ }, undefined, { timeout: 5000 })
|
||||
const filters = { q: 'external-sdk-log-', limit: 1 }
|
||||
const first = content(await queryLogs(filters))
|
||||
assert.ok(first.nextCursor)
|
||||
const second = content(await queryLogs({ ...filters, cursor: first.nextCursor }))
|
||||
assert.equal(second.nextCursor, null)
|
||||
assert.deepEqual([first.entries, second.entries].map(entries => entries.map(({ serverId, message }) => ({ serverId, message }))), [
|
||||
[{ serverId: allowedServer, message: 'external-sdk-log-1' }],
|
||||
[{ serverId: allowedServer, message: 'external-sdk-log-2' }],
|
||||
])
|
||||
await denied(() => queryLogs({ ...filters, serverId: forbiddenServer }))
|
||||
cases.push(mode + ': populated log search pages return only allowed server records and reject the forbidden server')
|
||||
await denied(() => client.callTool({ name: 'mm_servers_list', arguments: {} }, { timeout: 5000 }))
|
||||
await editScope([])
|
||||
assert.deepEqual((await client.listTools({}, { timeout: 5000 })).tools, [])
|
||||
await editScope(['servers.list'])
|
||||
await scoped(client)
|
||||
cases.push(mode + ': established client observes removed and restored tool scope through the web policy API')
|
||||
if (mode === 'stdio' && process.env.OWN_EXTERNAL_CLEANUP_FAULT === 'failure') throw Error('Owned deliberate external client failure with bridge active')
|
||||
if (mode === 'stdio' && process.env.OWN_EXTERNAL_CLEANUP_FAULT === 'timeout') { process.send({ kind: 'arm-cleanup-timeout' }); await new Promise(() => {}) }
|
||||
phase = mode + ':result-bound'; await control('large-result')
|
||||
@@ -86,7 +117,7 @@ try {
|
||||
} finally { await client.close().catch(() => {}) }
|
||||
}
|
||||
phase = 'http:body-bound'; const bound = await control('new-connection')
|
||||
const oversized = await fetch(endpoint, { method: 'POST', headers: { authorization: 'Bearer ' + bound.token, 'content-type': 'application/json', accept: 'application/json,text/event-stream' },
|
||||
const oversized = await fetch(endpoint, { method: 'POST', headers: { authorization: 'Bearer ' + bound.token, 'content-type': 'application/json', accept: 'application/json,text/event-stream', connection: 'close' },
|
||||
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'mm_servers_list', arguments: { padding: 'x'.repeat(1048576) } } }), signal: AbortSignal.timeout(5000) })
|
||||
assert.equal(oversized.status, 413); assert((await oversized.text()).length < 65536)
|
||||
cases.push('actual HTTP request envelope over1MiB refused before tool execution; successful client results remain bounded')
|
||||
@@ -126,8 +157,123 @@ try {
|
||||
await denied(() => oauthClient.callTool({ name: 'mm_servers_list', arguments: {} }, undefined, { timeout: 5000 }))
|
||||
cases.push('actual OAuth family revocation refuses established and fresh external transport; no implicit new consent granted')
|
||||
} finally { await oauthClient.close().catch(() => {}) }
|
||||
phase = 'discovery:issue'
|
||||
const catalogue = await control('discovery-connection')
|
||||
const expectedNames = catalogue.names.toSorted()
|
||||
assert(expectedNames.includes('mm_logs_follow'))
|
||||
const discoveryByTransport = {}
|
||||
for (const mode of ['http', 'stdio']) {
|
||||
phase = `discovery:${mode}`
|
||||
const client = await opened(mode, catalogue.token, responseLimitBytes)
|
||||
try {
|
||||
const names = [], cursors = new Set()
|
||||
let cursor, largestPageBytes = 0, pages = 0
|
||||
do {
|
||||
const page = await client.listTools(cursor ? { cursor } : {}, { timeout: 10000 })
|
||||
assert(page.tools.length > 0)
|
||||
for (const tool of page.tools) {
|
||||
assert.equal(tool.inputSchema.type, 'object')
|
||||
names.push(tool.name)
|
||||
}
|
||||
const encoded = JSON.stringify(page)
|
||||
assert(!encoded.includes(catalogue.token) && !encoded.includes(process.env.OWN_SERVER_SECRET))
|
||||
largestPageBytes = Math.max(largestPageBytes, Buffer.byteLength(encoded))
|
||||
assert(largestPageBytes < responseLimitBytes)
|
||||
pages++
|
||||
cursor = page.nextCursor
|
||||
if (cursor) { assert(!cursors.has(cursor)); cursors.add(cursor) }
|
||||
assert(names.length <= expectedNames.length)
|
||||
} while (cursor)
|
||||
assert.deepEqual(names.toSorted(), expectedNames)
|
||||
discoveryByTransport[mode] = { tools: names.length, pages, largestPageBytes }
|
||||
cases.push(mode + ': external SDK discovers every delegated tool exactly once with an object input schema')
|
||||
} finally { await client.close().catch(() => {}) }
|
||||
}
|
||||
phase = 'discovery:revoke'
|
||||
await control('revoke')
|
||||
for (const [mode, arm] of [['http', 'arm-log-revocation'], ['stdio', 'arm-log-revocation-after-commit'], ['http', 'arm-log-follow-revocation']]) {
|
||||
phase = mode + ':' + arm
|
||||
const { token } = await control(arm)
|
||||
const logClient = await opened(mode, token)
|
||||
try {
|
||||
const follow = arm === 'arm-log-follow-revocation'
|
||||
const tool = follow ? 'mm_logs_follow' : 'mm_logs_query'
|
||||
const filters = { q: follow ? 'external-sdk-live-event' : 'external-sdk-log-1', limit: 1 }
|
||||
if (follow) {
|
||||
Object.assign(filters, { serverId: Number(process.env.OWN_ALLOWED_SERVER), waitSeconds: 0 })
|
||||
const start = content(await logClient.callTool({ name: tool, arguments: filters }, undefined, { timeout: 5000 }))
|
||||
assert.deepEqual(start.entries, [])
|
||||
assert.equal(typeof start.cursor, 'string')
|
||||
filters.cursor = start.cursor
|
||||
filters.waitSeconds = 10
|
||||
}
|
||||
const query = logClient.callTool({ name: tool, arguments: filters }, undefined, { timeout: 10000 })
|
||||
const checked = query.then(result => {
|
||||
assert.equal(result.isError, true)
|
||||
const wire = JSON.stringify(result)
|
||||
assert.match(wire, /OWNER_CLAIMS_REVOKED|UNAUTHORIZED/)
|
||||
assert.doesNotMatch(wire, /external-sdk-log-1|external-sdk-live-event|"entries"|"nextCursor"|"cursor"/)
|
||||
})
|
||||
const deliver = async () => {
|
||||
if (follow) await control('publish-follow-fixture-row')
|
||||
await control('deliver-log-revocation')
|
||||
}
|
||||
await Promise.all([checked, deliver()])
|
||||
await assert.rejects(opened(mode, token))
|
||||
cases.push(mode + ': signed portal revocation ' + (mode === 'stdio' ? 'after' : 'before') + ' audit commit denies ' + tool + ' result and reconnect')
|
||||
} finally { await logClient.close().catch(() => {}) }
|
||||
}
|
||||
phase = 'portal:revoke-export-download'
|
||||
const exportAccess = await control('new-artifact-connection')
|
||||
const exportClient = await opened('http', exportAccess.token)
|
||||
try {
|
||||
const exported = content(await exportClient.callTool({ name: 'mm_logs_export', arguments: {
|
||||
serverId: Number(process.env.OWN_ALLOWED_SERVER), q: 'external-sdk-log-1', format: 'json',
|
||||
} }, undefined, { timeout: 5000 }))
|
||||
assert.equal(exported.rows, 1)
|
||||
assert.equal(exported.downloadPath, '/api/mcp/artifacts/' + exported.artifactId)
|
||||
assert.doesNotMatch(JSON.stringify(exported), /external-sdk-log-1/)
|
||||
const download = jwt => boundedFetch(origin + exported.downloadPath, { headers: { authorization: 'Bearer ' + jwt } })
|
||||
const before = await download(exportAccess.ownerJwt)
|
||||
assert.equal(before.status, 200)
|
||||
assert.equal(before.headers.get('cache-control'), 'private, no-store')
|
||||
const bytes = Buffer.from(await before.arrayBuffer())
|
||||
assert.equal(createHash('sha256').update(bytes).digest('hex'), exported.sha256)
|
||||
assert.match(bytes.toString('utf8'), /external-sdk-log-1/)
|
||||
const fresh = await control('revoke-artifact-owner')
|
||||
for (const jwt of [exportAccess.ownerJwt, fresh.ownerJwt]) {
|
||||
const refused = await download(jwt)
|
||||
assert.ok([401, 403].includes(refused.status))
|
||||
assert.equal(refused.headers.has('content-disposition'), false)
|
||||
assert.doesNotMatch(await refused.text(), /external-sdk-log-1/)
|
||||
}
|
||||
const management = await boundedFetch(origin + '/api/mcp/connections', { headers: { authorization: 'Bearer ' + fresh.ownerJwt } })
|
||||
assert.equal(management.status, 200)
|
||||
cases.push('portal owner revocation blocks an existing unexpired log artifact even with refreshed owner login')
|
||||
} finally { await exportClient.close().catch(() => {}) }
|
||||
phase = 'portal:revoke-approved-plan'
|
||||
const planAccess = await control('new-revocable-plan-connection')
|
||||
const planClient = await opened('http', planAccess.token)
|
||||
try {
|
||||
const plan = content(await planClient.callTool({ name: 'mm_logs_settings_update_plan', arguments: {
|
||||
settings: { enabled: false },
|
||||
} }, undefined, { timeout: 5000 }))
|
||||
assert.equal(plan.state, 'awaiting-approval')
|
||||
const approved = await boundedFetch(origin + '/api/mcp/plans/' + plan.planId + '/decision', {
|
||||
method: 'POST', headers: { authorization: 'Bearer ' + planAccess.ownerJwt, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ approve: true }),
|
||||
})
|
||||
assert.equal(approved.status, 200)
|
||||
assert.deepEqual(await approved.json(), { ok: true })
|
||||
await control('revoke-approved-plan-owner')
|
||||
await denied(() => planClient.callTool({ name: 'mm_change_apply', arguments: {
|
||||
planId: plan.planId, idempotencyKey: randomUUID(),
|
||||
} }, undefined, { timeout: 5000 }))
|
||||
cases.push('signed portal revocation invalidates the exact approved log settings plan before apply')
|
||||
} finally { await planClient.close().catch(() => {}) }
|
||||
process.send({ kind: 'result', result: { cases: cases.length, names: cases, externalClientPid: process.pid, serverPid: Number(process.env.OWN_SERVER_PID), bridgePid,
|
||||
sdkOnlyExternalClient: true, maxObservedHttpResponseBytes: maxResponseBytes, clientResponseLimitBytes: 1048576, stdioSdkBufferLimitBytes: 131072,
|
||||
sdkOnlyExternalClient: true, maxObservedHttpResponseBytes: maxResponseBytes, clientResponseLimitBytes: responseLimitBytes, stdioSdkBufferLimitBytes: 131072,
|
||||
discoveryByTransport, discoveryStdioSdkBufferLimitBytes: responseLimitBytes,
|
||||
actualPublicStringLimitObserved: 16000, wholeGenericResultEnvelopeLimitAccepted: false,
|
||||
syntheticPortalJwtAndConsent: true, liveAuthPortal: false, livePortalSender: false, endUserUi: false, wholeExternalDirectionComplete: false } })
|
||||
} catch (error) { process.send?.({ kind: 'failure', phase, errorType: error?.name ?? 'Error', completedCases: cases }); process.exitCode = 1 }
|
||||
|
||||
@@ -12,7 +12,9 @@ const output = resolve(sourceRoot, scenario === 'bridge-vlan' ? 'tmp/mcp-bridge-
|
||||
const paths = ['backend/src/scripts/mcp-stdio.ts', 'backend/src/routes/mcp-transport.ts', 'backend/src/routes/mcp-oauth.ts', 'backend/src/modules/mcp/store.ts',
|
||||
'backend/src/modules/mcp/runtime.ts', 'backend/src/modules/mcp/actions.ts', 'backend/src/modules/mcp/security.ts', 'backend/src/modules/mcp/protocol-limits.ts',
|
||||
'backend/src/modules/mcp/portal-revocation.ts', 'backend/src/plugins/auth.ts', 'backend/src/index.ts', 'node_modules/@modelcontextprotocol/client/package.json', 'node_modules/@modelcontextprotocol/server/package.json']
|
||||
if (scenario === 'bridge-vlan') paths.push('backend/scripts/mcp-external-process/bridge-vlan-client.mjs', 'backend/scripts/mcp-external-process/bridge-vlan-fixture.ts',
|
||||
if (scenario === 'acceptance') paths.push('backend/scripts/mcp-external-process/client.mjs', 'backend/scripts/mcp-external-process/server-fixture.ts',
|
||||
'backend/src/routes/mcp-portal.ts', 'backend/src/modules/mcp/portal-revocation-event.ts', 'backend/src/services/router-logs-query.ts')
|
||||
else paths.push('backend/scripts/mcp-external-process/bridge-vlan-client.mjs', 'backend/scripts/mcp-external-process/bridge-vlan-fixture.ts',
|
||||
'backend/src/modules/mcp/bridge-vlan-actions.ts', 'backend/src/services/bridge-vlan-configuration.ts', 'packages/contracts/src/bridge-vlan.ts')
|
||||
async function pins() { const result = []; for (const path of paths) result.push({ path, sha256: createHash('sha256').update(await readFile(resolve(sourceRoot, path))).digest('hex') }); return result }
|
||||
const before = await pins(), directory = await mkdtemp(join(resolve(sourceRoot, 'tmp'), 'mm-mcp-external-')), state = join(directory, 'state'); await mkdir(state)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { createHash } from "node:crypto"
|
||||
import { createHash, createHmac, randomUUID } from "node:crypto"
|
||||
import { spawn } from "node:child_process"
|
||||
import { createServer } from "node:net"
|
||||
import { fileURLToPath, pathToFileURL } from "node:url"
|
||||
@@ -20,6 +20,7 @@ const { pool, closePool } = await import(source("db/index.js"))
|
||||
const { applySqlMigrations } = await import(source("db/migrate.js"))
|
||||
const { mcpConnectionCreateSchema } = await import("@mmapp/contracts/mcp")
|
||||
const { createMcpConnection, rotateConnectionToken, setConnectionStatus, updateMcpSettings } = await import(source("modules/mcp/store.js"))
|
||||
const { listActions } = await import(source("modules/mcp/actions.js")) as typeof import("../../src/modules/mcp/actions.js")
|
||||
const { env } = await import(source("config.js"))
|
||||
const { buildApp } = await import(source("index.js"))
|
||||
const actor = { id: "owned-external-process-owner", email: "[email protected]", name: "Owned external SDK fixture", apps: ["mm"],
|
||||
@@ -28,7 +29,27 @@ let currentId: string | undefined, app: Awaited<ReturnType<typeof buildApp>> | u
|
||||
const credentials: string[] = []
|
||||
const bridgePids = new Set<number>()
|
||||
let childExit: Promise<number> | undefined
|
||||
let releaseLogRead: (() => void) | undefined
|
||||
let logReadCompleted: Promise<void> | undefined
|
||||
let revocationOwnerId: string | undefined
|
||||
const revokedLogRequests: { connectionId: string; tool: string }[] = []
|
||||
const originalConnect = pool.connect
|
||||
const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
|
||||
async function deliverPortalRevocation(ownerId: string) {
|
||||
const secret = randomUUID() + randomUUID()
|
||||
process.env.MCP_PORTAL_WEBHOOK_SECRET = secret
|
||||
const occurredAt = Date.now(), timestamp = String(Math.floor(occurredAt / 1000))
|
||||
const eventId = randomUUID(), body = JSON.stringify({ version: 2, eventId, userId: ownerId, type: "permissions.changed", eventOccurredAt: occurredAt })
|
||||
const signature = "sha256=" + createHmac("sha256", secret).update(timestamp + "." + body).digest("hex")
|
||||
const response = await fetch(origin + "/_internal/mcp/portal/revocations", {
|
||||
method: "POST", headers: { "content-type": "application/json", "x-mm-timestamp": timestamp, "x-mm-signature": signature },
|
||||
body, signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
assert.equal(response.status, 200)
|
||||
assert.deepEqual(await response.json(), { ok: true, duplicate: false })
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS count FROM mcp_portal_events WHERE id=$1", [eventId])).rows[0].count, 1)
|
||||
return occurredAt
|
||||
}
|
||||
function alive(pid: number) { try { process.kill(pid, 0); return true } catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return false; throw error } }
|
||||
async function drainChildAndBridges() {
|
||||
if (child && child.exitCode === null && child.signalCode === null) { child.kill(); await Promise.race([childExit, delay(5000).then(() => { throw Error("Owned external child failed to exit") })]) }
|
||||
@@ -47,9 +68,18 @@ try {
|
||||
const secret = "OWNED_DEVICE_CREDENTIAL_MUST_NOT_ESCAPE"
|
||||
const allowed = (await pool.query("INSERT INTO servers(name,host,enabled,password) VALUES('owned allowed','192.0.2.1',false,$1) RETURNING id", [secret])).rows[0].id
|
||||
const forbidden = (await pool.query("INSERT INTO servers(name,host,enabled) VALUES('owned forbidden','192.0.2.2',false) RETURNING id")).rows[0].id
|
||||
await pool.query(`INSERT INTO router_log_entries(server_id,server_name,host,router_id,raw_time,received_at,effective_at,topics,level,message,generation)
|
||||
SELECT id,name,host,'fixture','00:00:01',now(),now()-n*interval '1 second',ARRAY['system'],'info','external-sdk-log-'||n,0
|
||||
FROM servers CROSS JOIN generate_series(1,2) AS n WHERE id=ANY($1::int[])`, [[allowed, forbidden]])
|
||||
await updateMcpSettings({ enabled: true }, actor)
|
||||
app = await buildApp({ startScheduler: false, logger: false }); await app.listen({ port, host: "127.0.0.1" })
|
||||
const jwt = await new SignJWT({ sub: actor.id, apps: actor.apps, permissions: actor.permissions }).setProtectedHeader({ alg: "HS256" }).setIssuer(env.authIssuer).setIssuedAt().setExpirationTime("1h").sign(new TextEncoder().encode(env.jwtSecret))
|
||||
const artifactOwner = { ...actor, id: actor.id + "-artifact" }
|
||||
const signArtifactOwner = () => new SignJWT({ sub: artifactOwner.id, apps: artifactOwner.apps, permissions: artifactOwner.permissions })
|
||||
.setProtectedHeader({ alg: "HS256" }).setIssuer(env.authIssuer).setIssuedAt().setExpirationTime("1h").sign(new TextEncoder().encode(env.jwtSecret))
|
||||
let artifactConnectionId: string | undefined
|
||||
const planOwner = { ...actor, id: actor.id + "-approved-plan", permissions: [...actor.permissions, "mm:mcp:approve"] }
|
||||
let planConnectionId: string | undefined
|
||||
const portalHeaders = { authorization: `Bearer ${jwt}`, "content-type": "application/json" }
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS count FROM mcp_connections WHERE owner_id=$1", [actor.id])).rows[0].count, 0)
|
||||
const callback = "http://localhost:45678/callback?registered=1"
|
||||
@@ -123,10 +153,131 @@ try {
|
||||
if (message.kind !== "control" || !Number.isSafeInteger(message.id)) return
|
||||
try {
|
||||
let value: unknown
|
||||
if (message.command === "new-connection") {
|
||||
if (message.command === "new-revocable-plan-connection") {
|
||||
assert(!planConnectionId)
|
||||
const issued = await createMcpConnection(mcpConnectionCreateSchema.parse({
|
||||
name: "Owned approved plan revocation", mode: "approval", permissions: ["mm:settings:admin"],
|
||||
expiresAt: new Date(Date.now() + 600000).toISOString(),
|
||||
scope: { serverIds: [Number(allowed), Number(forbidden)], operationIds: ["logs.settings.update", "changes.apply"], allowGlobal: true },
|
||||
}), planOwner)
|
||||
currentId = planConnectionId = issued.connection.id
|
||||
const ownerJwt = await new SignJWT({ sub: planOwner.id, apps: planOwner.apps, permissions: planOwner.permissions })
|
||||
.setProtectedHeader({ alg: "HS256" }).setIssuer(env.authIssuer).setIssuedAt().setExpirationTime("1h").sign(new TextEncoder().encode(env.jwtSecret))
|
||||
credentials.push(issued.token, ownerJwt)
|
||||
value = { token: issued.token, ownerJwt }
|
||||
} else if (message.command === "revoke-approved-plan-owner") {
|
||||
assert(planConnectionId && currentId === planConnectionId)
|
||||
const plans = (await pool.query("SELECT id,state,approved_by FROM mcp_plans WHERE connection_id=$1", [planConnectionId])).rows
|
||||
assert.equal(plans.length, 1)
|
||||
assert.equal(plans[0].state, "approved")
|
||||
assert.equal(plans[0].approved_by, planOwner.id)
|
||||
await deliverPortalRevocation(planOwner.id)
|
||||
value = { ok: true }
|
||||
} else if (message.command === "new-artifact-connection") {
|
||||
assert(!artifactConnectionId)
|
||||
const issued = await createMcpConnection(mcpConnectionCreateSchema.parse({
|
||||
name: "Owned export revocation", mode: "observer", permissions: ["mm:servers:read"],
|
||||
expiresAt: new Date(Date.now() + 600000).toISOString(),
|
||||
scope: { serverIds: [Number(allowed)], operationIds: ["logs.export"], allowGlobal: false },
|
||||
}), artifactOwner)
|
||||
currentId = artifactConnectionId = issued.connection.id
|
||||
const ownerJwt = await signArtifactOwner()
|
||||
credentials.push(issued.token, ownerJwt)
|
||||
value = { token: issued.token, ownerJwt }
|
||||
} else if (message.command === "revoke-artifact-owner") {
|
||||
assert(artifactConnectionId && currentId === artifactConnectionId)
|
||||
const occurredAt = await deliverPortalRevocation(artifactOwner.id)
|
||||
while (Math.floor(Date.now() / 1000) <= Math.floor(occurredAt / 1000)) await delay(25)
|
||||
const ownerJwt = await signArtifactOwner()
|
||||
credentials.push(ownerJwt)
|
||||
value = { ownerJwt }
|
||||
} else if (["arm-log-revocation", "arm-log-revocation-after-commit", "arm-log-follow-revocation"].includes(message.command ?? "")) {
|
||||
assert(!releaseLogRead)
|
||||
const afterCommit = message.command === "arm-log-revocation-after-commit"
|
||||
const follow = message.command === "arm-log-follow-revocation"
|
||||
const owner = { ...actor, id: `${actor.id}-${follow ? "follow" : afterCommit ? "postcommit" : "precommit"}` }
|
||||
revocationOwnerId = owner.id
|
||||
if (follow) {
|
||||
await pool.query("UPDATE servers SET enabled=true WHERE id=$1", [allowed])
|
||||
await pool.query("UPDATE router_log_settings SET enabled=true WHERE id=1")
|
||||
}
|
||||
const issued = await createMcpConnection(mcpConnectionCreateSchema.parse({
|
||||
name: "Owned portal revocation during log read", mode: "observer", permissions: ["mm:servers:read"],
|
||||
expiresAt: new Date(Date.now() + 600000).toISOString(),
|
||||
scope: { serverIds: [Number(allowed)], operationIds: [follow ? "logs.follow" : "logs.query"], allowGlobal: false },
|
||||
}), owner)
|
||||
currentId = issued.connection.id
|
||||
revokedLogRequests.push({ connectionId: currentId, tool: follow ? "mm_logs_follow" : "mm_logs_query" })
|
||||
credentials.push(issued.token)
|
||||
let completed!: () => void
|
||||
logReadCompleted = new Promise<void>(resolve => { completed = resolve })
|
||||
const hold = new Promise<void>(resolve => { releaseLogRead = resolve })
|
||||
pool.connect = ((callback?: unknown) => {
|
||||
if (typeof callback === "function") return Reflect.apply(originalConnect, pool, [callback])
|
||||
return (async () => {
|
||||
const client = await originalConnect.call(pool)
|
||||
const query = client.query, release = client.release
|
||||
let completingLog = false
|
||||
client.query = (async (...args: unknown[]) => {
|
||||
const params = args[1]
|
||||
if (typeof args[0] === "string" && args[0].startsWith("UPDATE mcp_requests SET status=$2,result=")
|
||||
&& Array.isArray(params) && params[1] === "completed" && String(params[2]).includes(follow ? "external-sdk-live-event" : "external-sdk-log-1")) {
|
||||
completingLog = true
|
||||
if (!afterCommit) { completed(); await hold }
|
||||
}
|
||||
const result = await Reflect.apply(query, client, args)
|
||||
if (afterCommit && completingLog && args[0] === "COMMIT") { completed(); await hold }
|
||||
return result
|
||||
}) as typeof query
|
||||
client.release = error => {
|
||||
client.query = query
|
||||
client.release = release
|
||||
release(error)
|
||||
}
|
||||
return client
|
||||
})()
|
||||
}) as typeof originalConnect
|
||||
value = { token: issued.token }
|
||||
} else if (message.command === "publish-follow-fixture-row") {
|
||||
assert(releaseLogRead && currentId && revokedLogRequests.at(-1)?.tool === "mm_logs_follow")
|
||||
const deadline = Date.now() + 3000
|
||||
for (;;) {
|
||||
const live = await pool.query("SELECT count(*)::int AS count FROM mcp_read_leases WHERE connection_id=$1", [currentId])
|
||||
if (live.rows[0].count === 1) break
|
||||
assert(Date.now() < deadline, "Owned follow did not acquire a live read lease")
|
||||
await delay(25)
|
||||
}
|
||||
await pool.query(`INSERT INTO router_log_entries(server_id,server_name,host,router_id,raw_time,received_at,effective_at,topics,level,message,generation)
|
||||
SELECT id,name,host,'fixture','00:00:01',now(),now(),ARRAY['system'],'info','external-sdk-live-event',0
|
||||
FROM servers WHERE id=$1`, [allowed])
|
||||
value = { ok: true }
|
||||
} else if (message.command === "deliver-log-revocation") {
|
||||
assert(logReadCompleted && releaseLogRead && currentId && revocationOwnerId)
|
||||
try {
|
||||
await Promise.race([logReadCompleted, delay(5000).then(() => { throw Error("Owned log read did not reach the barrier") })])
|
||||
await deliverPortalRevocation(revocationOwnerId)
|
||||
value = { ok: true }
|
||||
} finally {
|
||||
pool.connect = originalConnect
|
||||
releaseLogRead()
|
||||
releaseLogRead = undefined
|
||||
logReadCompleted = undefined
|
||||
revocationOwnerId = undefined
|
||||
}
|
||||
} else if (message.command === "new-connection") {
|
||||
const issued = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Owned external SDK process", mode: "observer", expiresAt: new Date(Date.now() + 1200000).toISOString(),
|
||||
permissions: ["mm:servers:read"], scope: { serverIds: [Number(allowed)], operationIds: ["servers.list"], allowGlobal: false }, limits: { callsPerMinute: 200 } }), actor)
|
||||
currentId = issued.connection.id; credentials.push(issued.token); value = { token: issued.token, connectionId: currentId }
|
||||
} else if (message.command === "discovery-connection") {
|
||||
const operations = listActions().map(action => action.operation)
|
||||
const permissions = [...new Set(operations.flatMap(operation => operation.requiredPermissions))]
|
||||
const issued = await createMcpConnection(mcpConnectionCreateSchema.parse({
|
||||
name: "Owned full catalogue discovery", mode: "approval", expiresAt: new Date(Date.now() + 600000).toISOString(),
|
||||
permissions, scope: { serverIds: [Number(allowed)], operationIds: operations.map(operation => operation.id), allowGlobal: true },
|
||||
}), { ...actor, permissions: [...new Set([...actor.permissions, ...permissions])] })
|
||||
currentId = issued.connection.id
|
||||
credentials.push(issued.token)
|
||||
value = { token: issued.token, names: operations.map(operation => operation.toolName) }
|
||||
} else if (message.command === "large-result" || message.command === "reset-result") {
|
||||
await pool.query("UPDATE servers SET comment=$2 WHERE id=$1", [allowed, message.command === "large-result" ? "Z".repeat(40000) + "OWNED_TRUNCATION_TAIL" : ""])
|
||||
value = { ok: true }
|
||||
@@ -144,6 +295,22 @@ try {
|
||||
const code = await childExit; clearTimeout(timer)
|
||||
if (code !== 0 || !result) { console.log("OWNED_EXTERNAL_PROCESS_FAILURE", JSON.stringify({ code, failure, stdout: stdout.slice(0,1000), stderr: stderr.slice(0,1000) })); throw Error("External SDK process did not complete") }
|
||||
const logs = JSON.stringify((await pool.query("SELECT tool,input,result,error_code FROM mcp_requests ORDER BY created_at")).rows)
|
||||
assert.equal(revokedLogRequests.length, 3)
|
||||
assert.ok(planConnectionId)
|
||||
const invalidated = (await pool.query("SELECT state FROM mcp_plans WHERE connection_id=$1", [planConnectionId])).rows
|
||||
assert.deepEqual(invalidated, [{ state: "invalidated" }])
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS count FROM mcp_operations WHERE connection_id=$1", [planConnectionId])).rows[0].count, 0)
|
||||
assert.equal((await pool.query("SELECT enabled FROM router_log_settings WHERE id=1")).rows[0].enabled, true)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS count FROM mcp_artifacts WHERE connection_id=$1 AND expires_at>now()", [artifactConnectionId])).rows[0].count, 1)
|
||||
for (const { connectionId, tool } of revokedLogRequests) {
|
||||
const revokedRead = (await pool.query("SELECT status,error_code,result FROM mcp_requests WHERE connection_id=$1 AND tool=$2 AND status='error'", [connectionId, tool])).rows
|
||||
assert.equal(revokedRead.length, 1)
|
||||
assert.equal(revokedRead[0].status, "error")
|
||||
assert.deepEqual(Object.keys(revokedRead[0].result), ["message"])
|
||||
assert.doesNotMatch(JSON.stringify(revokedRead[0].result), /external-sdk-log-1|external-sdk-live-event|"entries"|"nextCursor"|"cursor"/)
|
||||
assert.ok(["OWNER_CLAIMS_REVOKED", "UNAUTHORIZED"].includes(revokedRead[0].error_code))
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS count FROM mcp_read_leases WHERE connection_id=$1", [connectionId])).rows[0].count, 0)
|
||||
}
|
||||
for (const token of [...credentials, jwt, secret]) { assert(!logs.includes(token)); assert(!stdout.includes(token)); assert(!stderr.includes(token)) }
|
||||
const final = { ...(result as object), actualOwnPg: true, actualProductionHttpServer: true, serverFixturePid: process.pid,
|
||||
controlTransitions: transcript, auditCredentialLeakAbsent: true, denialWithoutConnection: true,
|
||||
@@ -151,5 +318,7 @@ try {
|
||||
await writeFile(process.env.OWN_EXTERNAL_RESULT_FILE!, JSON.stringify(final, null, 2))
|
||||
console.log("Owned external process SDK result:", JSON.stringify(final))
|
||||
} finally {
|
||||
pool.connect = originalConnect
|
||||
releaseLogRead?.()
|
||||
try { await drainChildAndBridges() } finally { try { if (app) await app.close() } finally { await closePool() } }
|
||||
}
|
||||
Reference in new issue
Block a user