Harden MCP broker sandbox handoff
This commit is contained in:
@@ -19,10 +19,11 @@ function stripAnsi(value: string) {
|
||||
return value.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
|
||||
}
|
||||
|
||||
async function runOpenShell(args: string[]) {
|
||||
async function runOpenShell(args: string[], extraEnv: Record<string, string> = {}) {
|
||||
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
...extraEnv,
|
||||
PATH: HOST_PATH,
|
||||
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||
NO_COLOR: "1",
|
||||
@@ -105,8 +106,12 @@ function optionalString(value: unknown) {
|
||||
return typeof value === "string" ? value.trim() : ""
|
||||
}
|
||||
|
||||
function providerCredentialArg(credentialKey: string, apiKey: string) {
|
||||
return apiKey ? `${credentialKey}=${apiKey}` : credentialKey
|
||||
function redactSecretOutput(value: string, secrets: string[] = []) {
|
||||
let redacted = value
|
||||
for (const secret of secrets) {
|
||||
if (secret) redacted = redacted.split(secret).join("[redacted]")
|
||||
}
|
||||
return redacted.replace(/([A-Z_][A-Z0-9_]*=)([^\s]+)/g, "$1[redacted]")
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
@@ -151,11 +156,12 @@ export async function POST(request: Request) {
|
||||
? ["provider", "update", name]
|
||||
: ["provider", "create", "--name", name, "--type", type]
|
||||
|
||||
const providerEnv = apiKey ? { [credentialKey]: apiKey } : {}
|
||||
if (!existingNames.includes(name) && !apiKey) providerArgs.push("--from-existing")
|
||||
if (apiKey) providerArgs.push("--credential", providerCredentialArg(credentialKey, apiKey))
|
||||
if (apiKey) providerArgs.push("--credential", credentialKey)
|
||||
if (baseUrl) providerArgs.push("--config", `OPENAI_BASE_URL=${baseUrl}`)
|
||||
|
||||
const providerResult = await runOpenShell(providerArgs)
|
||||
const providerResult = await runOpenShell(providerArgs, providerEnv)
|
||||
let inferenceResult = null
|
||||
if (makeActive) {
|
||||
const routeArgs = ["inference", "set", "--provider", name, "--model", model]
|
||||
@@ -172,8 +178,8 @@ export async function POST(request: Request) {
|
||||
active: makeActive,
|
||||
gateway: parseRoute(refreshed.stdout, "Gateway inference"),
|
||||
system: parseRoute(refreshed.stdout, "System inference"),
|
||||
stdout: [providerResult.stdout, inferenceResult?.stdout].filter(Boolean).join("\n\n"),
|
||||
stderr: [providerResult.stderr, inferenceResult?.stderr].filter(Boolean).join("\n\n"),
|
||||
stdout: redactSecretOutput([providerResult.stdout, inferenceResult?.stdout].filter(Boolean).join("\n\n"), [apiKey]),
|
||||
stderr: redactSecretOutput([providerResult.stderr, inferenceResult?.stderr].filter(Boolean).join("\n\n"), [apiKey]),
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to save inference endpoint"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { downloadSandboxFile } from "@/app/lib/sandboxFiles"
|
||||
import { downloadSandboxPath } from "@/app/lib/sandboxFiles"
|
||||
|
||||
function contentDisposition(fileName: string) {
|
||||
const fallback = fileName.replace(/[^\w.-]/g, "_") || "download.bin"
|
||||
@@ -14,7 +14,7 @@ export async function GET(
|
||||
const { sandboxId } = await params
|
||||
const requestUrl = new URL(request.url)
|
||||
const sourcePath = requestUrl.searchParams.get("path") || ""
|
||||
const downloaded = await downloadSandboxFile(sandboxId, sourcePath)
|
||||
const downloaded = await downloadSandboxPath(sandboxId, sourcePath)
|
||||
|
||||
return new NextResponse(new Uint8Array(downloaded.bytes), {
|
||||
status: 200,
|
||||
@@ -22,7 +22,7 @@ export async function GET(
|
||||
"cache-control": "no-store",
|
||||
"content-disposition": contentDisposition(downloaded.fileName),
|
||||
"content-length": String(downloaded.bytes.byteLength),
|
||||
"content-type": "application/octet-stream",
|
||||
"content-type": downloaded.archive ? "application/gzip" : "application/octet-stream",
|
||||
"x-sandbox-name": downloaded.sandboxName,
|
||||
"x-sandbox-path": downloaded.path,
|
||||
},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { assertRequestContentLength, uploadSandboxFile } from "@/app/lib/sandboxFiles"
|
||||
import { assertRequestContentLength, uploadSandboxFile, uploadSandboxFiles } from "@/app/lib/sandboxFiles"
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
@@ -10,13 +10,37 @@ export async function POST(
|
||||
assertRequestContentLength(request)
|
||||
const form = await request.formData()
|
||||
const file = form.get("file")
|
||||
const files = form.getAll("files")
|
||||
const rawPath = form.get("path")
|
||||
if (!(file instanceof File)) throw new Error("file is required")
|
||||
const rawRelativePaths = form.get("relativePaths")
|
||||
const destinationPath = typeof rawPath === "string" && rawPath.trim()
|
||||
? rawPath.trim()
|
||||
: `/sandbox/${file.name}`
|
||||
: "/sandbox/"
|
||||
|
||||
if (files.length > 0) {
|
||||
const relativePaths = typeof rawRelativePaths === "string" ? JSON.parse(rawRelativePaths) : []
|
||||
if (!Array.isArray(relativePaths)) throw new Error("relative paths are required for directory upload")
|
||||
const payloads = await Promise.all(files.map(async (item, index) => {
|
||||
if (!(item instanceof File)) throw new Error("files must contain only file uploads")
|
||||
return {
|
||||
fileName: item.name,
|
||||
relativePath: typeof relativePaths[index] === "string" && relativePaths[index] ? relativePaths[index] : item.name,
|
||||
payload: Buffer.from(await item.arrayBuffer()),
|
||||
}
|
||||
}))
|
||||
const uploaded = await uploadSandboxFiles(sandboxId, destinationPath, payloads)
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
uploaded,
|
||||
note: `Uploaded ${uploaded.files.length} file${uploaded.files.length === 1 ? "" : "s"} to ${destinationPath}.`,
|
||||
})
|
||||
}
|
||||
|
||||
if (!(file instanceof File)) throw new Error("file is required")
|
||||
const targetPath = destinationPath.endsWith("/") ? destinationPath : rawPath ? destinationPath : `/sandbox/${file.name}`
|
||||
const payload = Buffer.from(await file.arrayBuffer())
|
||||
const uploaded = await uploadSandboxFile(sandboxId, destinationPath, file.name, payload)
|
||||
const uploaded = await uploadSandboxFile(sandboxId, targetPath, file.name, payload)
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { syncSandboxMcpManifest } from "@/app/lib/sandboxMcpManifest"
|
||||
import { brokerBaseUrlForSandbox } from "@/app/lib/mcpBrokerUrl"
|
||||
import { revokeSandboxMcpManifest, syncSandboxMcpManifest } from "@/app/lib/sandboxMcpManifest"
|
||||
import { revokeBrokerNetworkAccess, syncBrokerNetworkAccess } from "@/app/lib/sandboxPermissions"
|
||||
|
||||
function readSandboxName(request: Request) {
|
||||
const requestUrl = new URL(request.url)
|
||||
return requestUrl.searchParams.get("sandboxName") || null
|
||||
}
|
||||
|
||||
function brokerBaseUrl(request: Request) {
|
||||
const origin = new URL(request.url).origin
|
||||
return process.env.OPENSHELL_CONTROL_MCP_BROKER_URL || `${origin}/api/mcp/broker`
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sandboxId: string }> },
|
||||
@@ -18,7 +15,7 @@ export async function GET(
|
||||
try {
|
||||
const { sandboxId } = await params
|
||||
const sandboxName = readSandboxName(request)
|
||||
const brokerUrl = brokerBaseUrl(request)
|
||||
const brokerUrl = await brokerBaseUrlForSandbox(request, { id: sandboxId, name: sandboxName })
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId,
|
||||
@@ -50,14 +47,33 @@ export async function POST(
|
||||
const { sandboxId } = await params
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const sandboxName = typeof body?.sandboxName === "string" ? body.sandboxName : readSandboxName(request)
|
||||
const action = typeof body?.action === "string" ? body.action : "sync"
|
||||
const brokerUrl = await brokerBaseUrlForSandbox(request, { id: sandboxId, name: sandboxName })
|
||||
|
||||
if (action === "revoke") {
|
||||
const [synced, network] = await Promise.all([
|
||||
revokeSandboxMcpManifest({ id: sandboxId, name: sandboxName }),
|
||||
revokeBrokerNetworkAccess(sandboxId, brokerUrl),
|
||||
])
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId,
|
||||
synced,
|
||||
network,
|
||||
note: `Revoked MCP broker config for ${synced.sandboxName}.`,
|
||||
})
|
||||
}
|
||||
|
||||
const synced = await syncSandboxMcpManifest(
|
||||
{ id: sandboxId, name: sandboxName },
|
||||
{ brokerBaseUrl: brokerBaseUrl(request) },
|
||||
{ brokerBaseUrl: brokerUrl },
|
||||
)
|
||||
const network = await syncBrokerNetworkAccess(sandboxId, brokerUrl)
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId,
|
||||
synced,
|
||||
network,
|
||||
note: `Issued MCP broker config at ${synced.path}.`,
|
||||
})
|
||||
} catch (error) {
|
||||
|
||||
Reference in New Issue
Block a user