diff --git a/package-lock.json b/package-lock.json index c0b3f5da283..cce155a9d5c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,8 @@ "license": "Apache-2.0", "dependencies": { "@aws-sdk/client-bedrock-runtime": "3.1046.0", + "@grpc/grpc-js": "1.14.4", + "@grpc/proto-loader": "0.8.1", "@oclif/core": "^4.10.5", "execa": "^9.6.1", "js-yaml": "^4.1.1", @@ -3549,6 +3551,37 @@ "node": ">=18" } }, + "node_modules/@grpc/grpc-js": { + "version": "1.14.4", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz", + "integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.1.tgz", + "integrity": "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg==", + "license": "Apache-2.0", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.5.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/@j178/prek": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/@j178/prek/-/prek-0.3.6.tgz", @@ -3619,6 +3652,16 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", @@ -3704,6 +3747,63 @@ "url": "https://github.com/sponsors/Boshen" } }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, "node_modules/@rolldown/binding-android-arm64": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.3.tgz", @@ -4182,7 +4282,6 @@ "version": "25.5.2", "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.2.tgz", "integrity": "sha512-tO4ZIRKNC+MDWV4qKVZe3Ql/woTnmHDr5JD8UI5hn2pwBrHEwOEMZK7WlNb5RKB6EoJ02gwmQS9OrjuFnZYdpg==", - "dev": true, "license": "MIT", "dependencies": { "undici-types": "~7.18.0" @@ -4580,7 +4679,6 @@ "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, "license": "ISC", "dependencies": { "string-width": "^4.2.0", @@ -4998,7 +5096,6 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -5332,7 +5429,6 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, "license": "ISC", "engines": { "node": "6.* || 8.* || >= 10.*" @@ -6081,7 +6177,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", - "dev": true, "license": "MIT" }, "node_modules/lodash.kebabcase": { @@ -6119,6 +6214,12 @@ "dev": true, "license": "MIT" }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/lru-cache": { "version": "11.2.7", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz", @@ -6448,6 +6549,29 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/protobufjs": { + "version": "7.6.5", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.5.tgz", + "integrity": "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/proxy-from-env": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", @@ -6487,7 +6611,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -6815,7 +6938,6 @@ "version": "7.18.2", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", - "dev": true, "license": "MIT" }, "node_modules/unicorn-magic": { @@ -7102,7 +7224,6 @@ "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, "license": "ISC", "engines": { "node": ">=10" @@ -7127,7 +7248,6 @@ "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, "license": "MIT", "dependencies": { "cliui": "^8.0.1", @@ -7146,7 +7266,6 @@ "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, "license": "ISC", "engines": { "node": ">=12" diff --git a/package.json b/package.json index 960cb6339b5..5253469c843 100644 --- a/package.json +++ b/package.json @@ -79,6 +79,8 @@ }, "dependencies": { "@aws-sdk/client-bedrock-runtime": "3.1046.0", + "@grpc/grpc-js": "1.14.4", + "@grpc/proto-loader": "0.8.1", "@oclif/core": "^4.10.5", "execa": "^9.6.1", "js-yaml": "^4.1.1", diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts new file mode 100644 index 00000000000..8c134b38f87 --- /dev/null +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -0,0 +1,380 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { EventEmitter } from "node:events"; +import path from "node:path"; +import { + Metadata, + Server, + ServerCredentials, + type CallOptions, + type sendUnaryData, + type ServerUnaryCall, + type ServerWritableStream, + type ServiceClientConstructor, + type ServiceError, +} from "@grpc/grpc-js"; +import { loadPackageDefinition } from "@grpc/grpc-js"; +import * as protoLoader from "@grpc/proto-loader"; +import { describe, expect, it, vi } from "vitest"; + +import { + createGrpcOpenShellSandboxControl, + createOpenShellGrpcApi, + OpenShellGrpcOutputLimitError, + type OpenShellGrpcApi, +} from "./grpc-sandbox-control"; + +class FakeStream extends EventEmitter { + cancelled = false; + + cancel(): void { + this.cancelled = true; + } +} + +interface FakeApiOptions { + sandboxId?: string; + getError?: ServiceError; + emit?: (stream: FakeStream) => void; +} + +function fakeApi(fixture: FakeApiOptions = {}): { + api: OpenShellGrpcApi; + stream: FakeStream; + getMetadata: Metadata[]; + execMetadata: Metadata[]; + getOptions: CallOptions[]; + execOptions: CallOptions[]; + close: ReturnType; +} { + const stream = new FakeStream(); + const getMetadata: Metadata[] = []; + const execMetadata: Metadata[] = []; + const getOptions: CallOptions[] = []; + const execOptions: CallOptions[] = []; + const close = vi.fn(); + const api: OpenShellGrpcApi = { + close, + getSandbox(request, metadata, options, callback) { + getMetadata.push(metadata); + getOptions.push(options); + queueMicrotask(() => { + fixture.getError + ? callback(fixture.getError) + : callback(null, { + sandbox: { + metadata: fixture.sandboxId === "" ? {} : { id: fixture.sandboxId ?? "sb-id" }, + }, + }); + }); + return request; + }, + execSandbox(request, metadata, options) { + execMetadata.push(metadata); + execOptions.push(options); + queueMicrotask(() => fixture.emit?.(stream)); + return Object.assign(stream, { request }); + }, + }; + return { api, stream, getMetadata, execMetadata, getOptions, execOptions, close }; +} + +function serviceError(message: string): ServiceError { + return Object.assign(new Error(message), { + code: 14, + details: message, + metadata: new Metadata(), + }); +} + +function bind(server: Server): Promise { + return new Promise((resolve, reject) => { + server.bindAsync("127.0.0.1:0", ServerCredentials.createInsecure(), (error, port) => { + error ? reject(error) : resolve(port); + }); + }); +} + +function shutdown(server: Server): Promise { + return new Promise((resolve, reject) => { + server.tryShutdown((error) => { + error ? reject(error) : resolve(); + }); + }); +} + +describe("gRPC OpenShell sandbox control", () => { + it("resolves a sandbox id and normalizes streamed output", async () => { + const euro = Buffer.from("€"); + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: Buffer.from("hello ") } }); + stream.emit("data", { stdout: { data: euro.subarray(0, 1) } }); + stream.emit("data", { stdout: { data: euro.subarray(1) } }); + stream.emit("data", { stderr: { data: Buffer.from("warning\n") } }); + stream.emit("data", { exit: { exitCode: 7 } }); + stream.emit("end"); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "https://gateway.example:443", bearerToken: "secret-token" }, + fake.api, + ); + + await expect( + control.exec({ + sandboxName: "alpha", + command: ["sh", "-lc", "echo hello"], + }), + ).resolves.toEqual({ + status: 7, + stdout: "hello €", + stderr: "warning\n", + }); + expect(fake.getMetadata[0].get("authorization")).toEqual(["Bearer secret-token"]); + expect(fake.execMetadata[0]).toBe(fake.getMetadata[0]); + expect((fake.stream as FakeStream & { request: unknown }).request).toEqual({ + sandboxId: "sb-id", + command: ["sh", "-lc", "echo hello"], + }); + control.close(); + expect(fake.close).toHaveBeenCalledOnce(); + }); + + it("executes against the pinned OpenShell service definition", async () => { + const protoFile = path.resolve( + __dirname, + "../../../../third_party/openshell/v0.0.72/proto/openshell.proto", + ); + const loaded = loadPackageDefinition( + protoLoader.loadSync(protoFile, { + defaults: false, + includeDirs: [path.dirname(protoFile)], + keepCase: false, + oneofs: true, + }), + ) as unknown as { + openshell: { v1: { OpenShell: ServiceClientConstructor } }; + }; + const server = new Server(); + const requests: unknown[] = []; + server.addService(loaded.openshell.v1.OpenShell.service, { + getSandbox( + call: ServerUnaryCall<{ name: string }, { sandbox: { metadata: { id: string } } }>, + callback: sendUnaryData<{ sandbox: { metadata: { id: string } } }>, + ) { + requests.push(call.request); + callback(null, { sandbox: { metadata: { id: "wire-id" } } }); + }, + execSandbox( + call: ServerWritableStream< + { sandboxId: string; command: string[] }, + { + stdout?: { data: Buffer }; + stderr?: { data: Buffer }; + exit?: { exitCode: number }; + } + >, + ) { + requests.push(call.request); + call.write({ stdout: { data: Buffer.from("wire stdout") } }); + call.write({ stderr: { data: Buffer.from("wire stderr") } }); + call.write({ exit: { exitCode: 0 } }); + call.end(); + }, + }); + const port = await bind(server); + const control = createGrpcOpenShellSandboxControl({ + endpoint: `http://127.0.0.1:${port}`, + }); + try { + await expect( + control.exec({ sandboxName: "alpha", command: ["printf", "wire"] }), + ).resolves.toEqual({ + status: 0, + stdout: "wire stdout", + stderr: "wire stderr", + }); + expect(requests).toEqual([ + { name: "alpha" }, + { sandboxId: "wire-id", command: ["printf", "wire"] }, + ]); + } finally { + control.close(); + await shutdown(server); + } + }); + + it("returns lookup failures without starting exec", async () => { + const error = serviceError("gateway unavailable"); + const fake = fakeApi({ getError: error }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect(control.exec({ sandboxName: "alpha", command: ["true"] })).resolves.toEqual({ + status: null, + stdout: "", + stderr: "", + error, + }); + expect(fake.execMetadata).toEqual([]); + }); + + it("uses one deadline for lookup and exec and forwards the command timeout", async () => { + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { exit: { exitCode: 0 } }); + stream.emit("end"); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + const before = Date.now(); + + await control.exec({ sandboxName: "alpha", command: ["true"], timeoutMs: 1500 }); + + expect(fake.getOptions[0].deadline).toBeInstanceOf(Date); + expect(fake.execOptions[0].deadline).toBe(fake.getOptions[0].deadline); + expect((fake.getOptions[0].deadline as Date).getTime()).toBeGreaterThanOrEqual(before + 1500); + expect((fake.stream as FakeStream & { request: unknown }).request).toEqual({ + sandboxId: "sb-id", + command: ["true"], + timeoutSeconds: 2, + }); + }); + + it("rejects sandbox responses without a stable id", async () => { + const fake = fakeApi({ sandboxId: "" }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://localhost:8080" }, + fake.api, + ); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["true"], + }); + + expect(result).toEqual({ + status: null, + stdout: "", + stderr: "", + error: expect.objectContaining({ + message: "OpenShell returned sandbox 'alpha' without an id", + }), + }); + }); + + it.each([ + [{ maxOutputBytes: -1 }, "maxOutputBytes"], + [{ timeoutMs: 1.5 }, "timeoutMs"], + ])("rejects invalid execution limits before gateway lookup", async (limits, field) => { + const fake = fakeApi(); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + const result = await control.exec({ sandboxName: "alpha", command: ["true"], ...limits }); + + expect(result.error?.message).toContain(field); + expect(fake.getMetadata).toEqual([]); + }); + + it("caps combined output, cancels the stream, and returns ENOBUFS-compatible context", async () => { + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: Buffer.from("abcdef") } }); + }, + }); + const control = createGrpcOpenShellSandboxControl({ endpoint: "http://[::1]:8080" }, fake.api); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["cat", "large-file"], + maxOutputBytes: 4, + }); + + expect(result).toEqual({ + status: null, + stdout: "abcd", + stderr: "", + error: expect.any(OpenShellGrpcOutputLimitError), + }); + expect((result.error as NodeJS.ErrnoException).code).toBe("ENOBUFS"); + expect(fake.stream.cancelled).toBe(true); + }); + + it("preserves partial output when the stream fails", async () => { + const error = serviceError("relay reset"); + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: Buffer.from("partial") } }); + stream.emit("error", error); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect(control.exec({ sandboxName: "alpha", command: ["true"] })).resolves.toEqual({ + status: null, + stdout: "partial", + stderr: "", + error, + }); + }); + + it("fails closed when the stream ends without an exit event", async () => { + const fake = fakeApi({ emit: (stream) => stream.emit("end") }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["true"], + }); + + expect(result.error?.message).toBe("OpenShell gRPC exec stream ended without an exit status"); + }); + + it.each([ + ["ftp://localhost:8080", "must use http:// or https://"], + ["http://gateway.example:8080", "restricted to loopback"], + ["http://localhost:8080/path", "must not contain"], + ])("rejects unsafe endpoint %s", (endpoint, message) => { + expect(() => createOpenShellGrpcApi({ endpoint })).toThrow(message); + }); + + it("rejects bearer tokens or TLS material on plaintext endpoints", () => { + expect(() => + createOpenShellGrpcApi({ + endpoint: "http://localhost:8080", + bearerToken: "token", + }), + ).toThrow("requires TLS"); + expect(() => + createOpenShellGrpcApi({ + endpoint: "http://localhost:8080", + caCertificate: Buffer.from("ca"), + }), + ).toThrow("require an https:// endpoint"); + }); + + it("rejects incomplete mTLS credentials", () => { + expect(() => + createOpenShellGrpcApi({ + endpoint: "https://gateway.example:443", + clientCertificate: Buffer.from("cert"), + }), + ).toThrow("clientCertificate and clientKey must be provided together"); + }); +}); diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts new file mode 100644 index 00000000000..63addd72717 --- /dev/null +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -0,0 +1,313 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { EventEmitter } from "node:events"; +import path from "node:path"; +import { StringDecoder } from "node:string_decoder"; + +import * as grpc from "@grpc/grpc-js"; +import * as protoLoader from "@grpc/proto-loader"; + +import type { + OpenShellSandboxControl, + SandboxExecRequest, + SandboxExecResult, +} from "./sandbox-control"; + +const DEFAULT_EXEC_MAX_OUTPUT_BYTES = 1024 * 1024; +const PROTO_VERSION = "0.0.72"; + +interface GetSandboxResponse { + sandbox?: { metadata?: { id?: string } }; +} + +interface ExecSandboxEvent { + stdout?: { data?: Buffer | Uint8Array | string }; + stderr?: { data?: Buffer | Uint8Array | string }; + exit?: { exitCode?: number }; +} + +interface ExecEventStream extends EventEmitter { + cancel(): void; +} + +export interface OpenShellGrpcApi { + getSandbox( + request: { name: string }, + metadata: grpc.Metadata, + options: grpc.CallOptions, + callback: (error: grpc.ServiceError | null, response?: GetSandboxResponse) => void, + ): unknown; + execSandbox( + request: { sandboxId: string; command: readonly string[]; timeoutSeconds?: number }, + metadata: grpc.Metadata, + options: grpc.CallOptions, + ): ExecEventStream; + close(): void; +} + +export interface OpenShellGrpcClientConfig { + /** Full gateway URL, including http:// or https://. */ + endpoint: string; + /** Optional private CA for a TLS gateway. System roots are used when omitted. */ + caCertificate?: Buffer; + /** mTLS client certificate. Must be provided together with clientKey. */ + clientCertificate?: Buffer; + /** mTLS client private key. Must be provided together with clientCertificate. */ + clientKey?: Buffer; + /** Optional gateway authorization token. Allowed only with TLS. */ + bearerToken?: string; +} + +export interface GrpcOpenShellSandboxControl extends OpenShellSandboxControl { + close(): void; +} + +export class OpenShellGrpcOutputLimitError extends Error { + readonly code = "ENOBUFS"; + + constructor(readonly maxOutputBytes: number) { + super(`OpenShell gRPC exec output exceeded ${maxOutputBytes} bytes`); + this.name = "OpenShellGrpcOutputLimitError"; + } +} + +function isLoopback(hostname: string): boolean { + const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase(); + return ( + normalized === "localhost" || normalized === "::1" || /^127(?:\.\d{1,3}){3}$/.test(normalized) + ); +} + +function parseEndpoint(endpoint: string): { target: string; secure: boolean } { + let url: URL; + try { + url = new URL(endpoint); + } catch (error) { + throw new Error(`Invalid OpenShell gRPC endpoint: ${(error as Error).message}`); + } + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("OpenShell gRPC endpoint must use http:// or https://"); + } + if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) { + throw new Error( + "OpenShell gRPC endpoint must not contain credentials, a path, query, or fragment", + ); + } + if (url.protocol === "http:" && !isLoopback(url.hostname)) { + throw new Error("Plaintext OpenShell gRPC is restricted to loopback endpoints"); + } + const secure = url.protocol === "https:"; + return { + target: `${url.hostname}:${url.port || (secure ? "443" : "80")}`, + secure, + }; +} + +function validateBearerToken(token: string | undefined, secure: boolean): void { + if (token === undefined) return; + if (!secure) throw new Error("OpenShell gRPC bearer authentication requires TLS"); + if (!token || token.trim() !== token || /[\r\n]/.test(token)) { + throw new Error( + "OpenShell gRPC bearer token must be non-empty and contain no surrounding whitespace", + ); + } +} + +function validateTlsMaterial(config: OpenShellGrpcClientConfig, secure: boolean): void { + const hasClientCertificate = config.clientCertificate !== undefined; + const hasClientKey = config.clientKey !== undefined; + if (hasClientCertificate !== hasClientKey) { + throw new Error("OpenShell gRPC clientCertificate and clientKey must be provided together"); + } + if (!secure && (config.caCertificate !== undefined || hasClientCertificate || hasClientKey)) { + throw new Error("OpenShell gRPC TLS credentials require an https:// endpoint"); + } +} + +function createChannelCredentials( + config: OpenShellGrpcClientConfig, + secure: boolean, +): grpc.ChannelCredentials { + validateTlsMaterial(config, secure); + if (!secure) { + return grpc.credentials.createInsecure(); + } + return grpc.credentials.createSsl( + config.caCertificate ?? null, + config.clientKey ?? null, + config.clientCertificate ?? null, + ); +} + +function protocolPath(): string { + return path.resolve( + __dirname, + `../../../../third_party/openshell/v${PROTO_VERSION}/proto/openshell.proto`, + ); +} + +export function createOpenShellGrpcApi(config: OpenShellGrpcClientConfig): OpenShellGrpcApi { + const { target, secure } = parseEndpoint(config.endpoint); + validateBearerToken(config.bearerToken, secure); + const credentials = createChannelCredentials(config, secure); + const protoFile = protocolPath(); + const packageDefinition = protoLoader.loadSync(protoFile, { + defaults: false, + enums: String, + includeDirs: [path.dirname(protoFile)], + keepCase: false, + longs: String, + oneofs: true, + }); + const loaded = grpc.loadPackageDefinition(packageDefinition) as unknown as { + openshell: { v1: { OpenShell: grpc.ServiceClientConstructor } }; + }; + return new loaded.openshell.v1.OpenShell(target, credentials) as unknown as OpenShellGrpcApi; +} + +function callMetadata(bearerToken: string | undefined): grpc.Metadata { + const metadata = new grpc.Metadata(); + if (bearerToken) metadata.set("authorization", `Bearer ${bearerToken}`); + return metadata; +} + +function sandboxId( + client: OpenShellGrpcApi, + sandboxName: string, + metadata: grpc.Metadata, + options: grpc.CallOptions, +): Promise { + return new Promise((resolve, reject) => { + client.getSandbox({ name: sandboxName }, metadata, options, (error, response) => { + if (error) { + reject(error); + return; + } + const id = response?.sandbox?.metadata?.id; + if (!id) { + reject(new Error(`OpenShell returned sandbox '${sandboxName}' without an id`)); + return; + } + resolve(id); + }); + }); +} + +function asBuffer(data: Buffer | Uint8Array | string | undefined): Buffer { + if (data === undefined) return Buffer.alloc(0); + return Buffer.isBuffer(data) ? data : Buffer.from(data); +} + +function execute( + client: OpenShellGrpcApi, + id: string, + request: SandboxExecRequest, + metadata: grpc.Metadata, + options: grpc.CallOptions, +): Promise { + const maxOutputBytes = request.maxOutputBytes ?? DEFAULT_EXEC_MAX_OUTPUT_BYTES; + return new Promise((resolve) => { + const timeoutSeconds = + request.timeoutMs && request.timeoutMs > 0 ? Math.ceil(request.timeoutMs / 1000) : undefined; + const stream = client.execSandbox( + { sandboxId: id, command: request.command, timeoutSeconds }, + metadata, + options, + ); + const stdoutDecoder = new StringDecoder("utf8"); + const stderrDecoder = new StringDecoder("utf8"); + let stdout = ""; + let stderr = ""; + let retainedBytes = 0; + let status: number | null = null; + let settled = false; + + const finish = (error?: Error) => { + if (settled) return; + settled = true; + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + const result: SandboxExecResult = { status, stdout, stderr }; + if (error) result.error = error; + resolve(result); + }; + + const append = (destination: "stdout" | "stderr", data: Buffer) => { + const remaining = maxOutputBytes - retainedBytes; + const retained = data.subarray(0, Math.max(0, remaining)); + retainedBytes += retained.length; + if (destination === "stdout") stdout += stdoutDecoder.write(retained); + else stderr += stderrDecoder.write(retained); + if (retained.length < data.length) { + finish(new OpenShellGrpcOutputLimitError(maxOutputBytes)); + stream.cancel(); + } + }; + + stream.on("data", (event: ExecSandboxEvent) => { + if (settled) return; + if (event.stdout) append("stdout", asBuffer(event.stdout.data)); + else if (event.stderr) append("stderr", asBuffer(event.stderr.data)); + else if (event.exit && Number.isInteger(event.exit.exitCode)) { + status = event.exit.exitCode as number; + } + }); + stream.on("error", (error: Error) => finish(error)); + stream.on("end", () => { + if (status === null) { + finish(new Error("OpenShell gRPC exec stream ended without an exit status")); + } else { + finish(); + } + }); + }); +} + +export function createGrpcOpenShellSandboxControl( + config: OpenShellGrpcClientConfig, + injectedClient?: OpenShellGrpcApi, +): GrpcOpenShellSandboxControl { + const { secure } = parseEndpoint(config.endpoint); + validateBearerToken(config.bearerToken, secure); + validateTlsMaterial(config, secure); + const client = injectedClient ?? createOpenShellGrpcApi(config); + return { + close: () => client.close(), + async exec(request): Promise { + const maxOutputBytes = request.maxOutputBytes ?? DEFAULT_EXEC_MAX_OUTPUT_BYTES; + if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0) { + return { + status: null, + stdout: "", + stderr: "", + error: new Error("maxOutputBytes must be a non-negative safe integer"), + }; + } + if ( + request.timeoutMs !== undefined && + (!Number.isSafeInteger(request.timeoutMs) || request.timeoutMs < 0) + ) { + return { + status: null, + stdout: "", + stderr: "", + error: new Error("timeoutMs must be a non-negative safe integer"), + }; + } + const metadata = callMetadata(config.bearerToken); + const deadline = + request.timeoutMs && request.timeoutMs > 0 + ? new Date(Date.now() + request.timeoutMs) + : undefined; + const options: grpc.CallOptions = deadline ? { deadline } : {}; + let id: string; + try { + id = await sandboxId(client, request.sandboxName, metadata, options); + } catch (error) { + return { status: null, stdout: "", stderr: "", error: error as Error }; + } + return execute(client, id, request, metadata, options); + }, + }; +} diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 9bca623a1fc..d2403a22216 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -22,11 +22,12 @@ describe("CLI OpenShell sandbox control", () => { sandboxName: "alpha", command: ["openclaw", "sessions", "list", "--json"], maxOutputBytes: 4096, + timeoutMs: 30_000, }); expect(capture).toHaveBeenCalledWith( ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions", "list", "--json"], - { ignoreError: true, includeStreams: true, maxBuffer: 4096 }, + { ignoreError: true, includeStreams: true, maxBuffer: 4096, timeout: 30_000 }, ); expect(result).toEqual({ status: 0, diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index 52008a5aa5c..e0baa204a91 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -7,7 +7,10 @@ import { captureOpenshell } from "./runtime"; export interface SandboxExecRequest { sandboxName: string; command: readonly string[]; + /** Maximum combined stdout and stderr bytes retained by the transport. */ maxOutputBytes?: number; + /** End-to-end lookup and execution deadline. Zero means no deadline. */ + timeoutMs?: number; } export interface SandboxExecResult { @@ -46,6 +49,7 @@ export function createCliOpenShellSandboxControl( ignoreError: true, includeStreams: true, maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, }, ); return normalizeExecResult(result);