Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(connectors): read-only scopes hold even at Full access for the apps' sandbox
milind-sonieecee9f82dca
diff --git a/server/connector-verdict.test.ts b/server/connector-verdict.test.tsindex fb5c01385e..429d37fa73 100644--- a/server/connector-verdict.test.ts+++ b/server/connector-verdict.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";import type { ConnectorToolGrant } from "../shared/wire.ts";import {APP_SANDBOX_REFUSAL,+ appSandboxAllowed,appSandboxRule,COMPOSIO_MULTI_EXECUTE_TOOL,connectorCallFromFrame,@@ -74,24 +75,37 @@ describe("connectorCallFromFrame", () => {});describe("appSandboxRule", () => {+ const granted = {};it("opens only a direct call to the apps' sandbox, and only while the turn runs at Full access", () => {let full = true;const level = () => full;for (const name of ["COMPOSIO_REMOTE_WORKBENCH", "COMPOSIO_REMOTE_BASH_TOOL"]) {const rule = appSandboxRule(toolsCall(name, { code: "print(1)" }), level);- expect(rule.open()).toBe(true);+ expect(rule.direct).toBe(true);+ expect(rule.open(granted)).toBe(true);expect(rule.refusal).toBe(APP_SANDBOX_REFUSAL);}const direct = appSandboxRule(toolsCall("COMPOSIO_REMOTE_WORKBENCH", {}), level);full = false;- expect(direct.open(), "asked again at dispatch: the level dropped meanwhile").toBe(false);+ expect(direct.open(granted), "asked again at dispatch: the level dropped meanwhile").toBe(false);full = true;const wrapped = appSandboxRule(multiExecute({ tools: [{ tool_slug: "COMPOSIO_REMOTE_WORKBENCH", arguments: {} }] }), level);- expect(wrapped.open()).toBe(false);+ expect(wrapped.direct).toBe(false);+ expect(wrapped.open(granted)).toBe(false);expect(wrapped.refusal).not.toBe(APP_SANDBOX_REFUSAL);- expect(appSandboxRule(toolsCall("COMPOSIO_SEARCH_TOOLS", {}), level).open()).toBe(false);- expect(appSandboxRule({ method: "tools/list" }, level).open()).toBe(false);- expect(appSandboxRule(null, level).open()).toBe(false);+ expect(appSandboxRule(toolsCall("COMPOSIO_SEARCH_TOOLS", {}), level).open(granted)).toBe(false);+ expect(appSandboxRule({ method: "tools/list" }, level).open(granted)).toBe(false);+ expect(appSandboxRule(null, level).open(granted)).toBe(false);+ });++ it("stays shut at Full access for a bot whose scopes limit its apps, and says the read-only setting is why", () => {+ const rule = appSandboxRule(toolsCall("COMPOSIO_REMOTE_WORKBENCH", { code_to_execute: "print(1)" }), () => true);+ expect(rule.open({ connectorScopes: { apps: { gmail: "read" } } })).toBe(false);+ expect(rule.open({ connectorScopes: { apps: { gmail: "write" } } }), "an app left off is a limit too").toBe(false);+ expect(rule.open({ connectorScopes: { apps: {} } })).toBe(false);+ expect(appSandboxAllowed({ connectorScopes: { apps: { gmail: "read" } } })).toBe(false);+ expect(appSandboxAllowed({})).toBe(true);+ expect(rule.refusal).toContain("read only");});});diff --git a/server/connector-verdict.ts b/server/connector-verdict.tsindex 737901168e..72d8ffeaa8 100644--- a/server/connector-verdict.ts+++ b/server/connector-verdict.ts@@ -5,16 +5,18 @@ import { CONNECTOR_TOOL_NAME_PATTERN, type ConnectorToolGrant } from "../shared/import { EMAIL_SLUG } from "../shared/email.ts";/** The connected apps' sandbox: Composio's code tools. Code run there can reach any connected app, past a bot's per-app- * grants and scopes, so a bot that has either runs it only at Full access, and only by a direct call. */+ * grants and scopes, so a bot with per-app grants runs it only at Full access, only by a direct call, and never while its+ * scopes limit its apps (a read-only app holds even at Full access). */export const APP_SANDBOX_TOOLS: readonly string[] = ["COMPOSIO_REMOTE_WORKBENCH", "COMPOSIO_REMOTE_BASH_TOOL"];/** The service Composio's own tools are named for (COMPOSIO_REMOTE_WORKBENCH → composio). */export const APP_SANDBOX_SERVICE = "composio";-/** A bot with per-app grants asked to run code in the apps' sandbox below Full access, or inside a batch. */+/** A bot asked to run code in the apps' sandbox below Full access, with its apps limited, or inside a batch. */export const APP_SANDBOX_REFUSAL = "This call was not performed. A bot with its own connected-app grants runs code in the apps' "+ "sandbox only at Full access, and only by calling COMPOSIO_REMOTE_WORKBENCH or COMPOSIO_REMOTE_BASH_TOOL directly (never inside "- + "COMPOSIO_MULTI_EXECUTE_TOOL). Use a direct app tool, or tell the person this needs Full access.";+ + "COMPOSIO_MULTI_EXECUTE_TOOL). It never runs while the bot's settings limit its connected apps, such as an app set to read only, "+ + "because that code could reach past the limit. Use a direct app tool, or tell the person what this needs.";const OPAQUE_CODE_REFUSAL = "OpenMausBot cannot verify this code against this bot's tool grants. Use a direct app tool.";@@ -26,12 +28,15 @@ function appSandboxCall(frame: unknown): boolean {return method === "tools/call" && typeof name === "string" && APP_SANDBOX_TOOLS.includes(name);}-/** The relay's rule for the apps' sandbox: a direct call to it passes a bot's per-app grants and scopes only while the turn- * runs at Full access, judged again each time it is asked (at dispatch too). `refusal` is what a bot with grants is told- * when code it sent cannot be checked against them. */-export function appSandboxRule(frame: unknown, fullAccess: () => boolean): { open(): boolean; refusal: string } {+/** Whether the apps' sandbox may be offered to a bot at all: a bot whose scopes limit its apps never gets it. */+export const appSandboxAllowed = (bot: { connectorScopes?: unknown }): boolean => bot.connectorScopes === undefined;++/** The relay's rule for the apps' sandbox: a direct call (`direct`) passes a bot's per-app grants only while the turn runs at+ * Full access and the bot's scopes limit nothing, judged again each time it is asked (at dispatch too, with the bot as it is+ * then). `refusal` is what the bot is told when the call stays refused. */+export function appSandboxRule(frame: unknown, fullAccess: () => boolean): { direct: boolean; open(bot: { connectorScopes?: unknown }): boolean; refusal: string } {const direct = appSandboxCall(frame);- return { open: () => direct && fullAccess(), refusal: direct ? APP_SANDBOX_REFUSAL : OPAQUE_CODE_REFUSAL };+ return { direct, open: (bot) => direct && appSandboxAllowed(bot) && fullAccess(), refusal: direct ? APP_SANDBOX_REFUSAL : OPAQUE_CODE_REFUSAL };}/** The only Composio meta-tool whose arguments name target tools. */diff --git a/server/host/team-connections-host.test.ts b/server/host/team-connections-host.test.tsindex 82fd6bef47..2396159873 100644--- a/server/host/team-connections-host.test.ts+++ b/server/host/team-connections-host.test.ts@@ -220,18 +220,20 @@ describe("apps each person connects", () => {expect(await host.callRefusal({ threadId: "cleo-chat", generation: "gen-1" }, [{ slug: "GMAIL_FETCH_EMAILS" }]), "Cleo's chat never reaches Ada's Gmail").toMatch(/Connect your Gmail/);});- it("offers a bot with app grants the apps' sandbox only in a turn at Full access", async () => {+ it("offers a bot with app grants the apps' sandbox only in a turn at Full access, never while its scopes limit its apps", async () => {const { host, composio } = setup({ fullAccess: (_botId, threadId) => threadId === "work-chat" });const scout = { id: "scout", name: "Scout", connectorTools: { gmail: { tools: "*" as const } } };await host.appsIntegrations(scout, "main-chat", "g1");await host.appsIntegrations(scout, "work-chat", "g2");await host.appsIntegrations({ id: "mausbot", name: "MausBot" }, "work-chat", "g3");+ await host.appsIntegrations({ ...scout, connectorScopes: { apps: { gmail: "read" } } }, "work-chat", "g4");const offered = composio.mcpIntegration.mock.calls.map(([, context]) => context as typeof context & { connectorTools?: unknown }).filter((context) => !context.as).map((context) => context.connectorTools);expect(offered).toEqual([{ gmail: { tools: "*" } },{ gmail: { tools: "*" }, composio: { tools: ["COMPOSIO_REMOTE_WORKBENCH", "COMPOSIO_REMOTE_BASH_TOOL"] } },undefined,+ { gmail: { tools: "*" } },]);});diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.tsindex 14fa663235..76e899a795 100644--- a/server/host/team-connections-host.ts+++ b/server/host/team-connections-host.ts@@ -15,7 +15,7 @@ import type * as Composio from "../composio.ts";import type { AppConfig } from "../config.ts";import type { McpServerSpec } from "../contracts.ts";import { advertisedGrants } from "../connector-advertisement.ts";-import { serviceSlugFor } from "../connector-verdict.ts";+import { appSandboxAllowed, serviceSlugFor } from "../connector-verdict.ts";import { type McpOAuthManager, type McpRefreshOutcome, type McpSignInPhase, withMcpSignIn, withoutPendingSignIn } from "../mcp-oauth.ts";import { isRemoteMcpServer, parseStoredMcpServer, type McpOAuthClientConfig } from "../mcp-registry.ts";import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";@@ -59,7 +59,8 @@ export interface TeamConnectionsHostDeps {onPersonChanged?(person: string, kind: "app" | "mcp", id: string): void;/** The connected-apps service a member's own installation is made on; null: none here. */brokerUrl(): string | null;- /** Whether this bot's turn in this conversation runs at Full access: its tools/list then offers the apps' sandbox. */+ /** Whether this bot's turn in this conversation runs at Full access: its tools/list then offers the apps' sandbox, unless its+ * scopes limit its apps. */fullAccess?(botId: string, threadId: string): boolean;composio: Pick<typeof Composio, "configured" | "mcpIntegration" | "connectedServices" | "verifiedConnectedServiceSlugs" | "authorizeService" | "removeService">;}@@ -259,7 +260,7 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {async appsIntegrations(bot: Bot, threadId: string, generation: string, names: "dotted" | "plain" = "plain"): Promise<{ composio?: Integration; composioOwn?: Integration }> {const cfg = deps.cfg();const out: { composio?: Integration; composioOwn?: Integration } = {};- const base = { harnessUrl: deps.harnessUrl, botId: bot.id, threadId, connectorTools: advertisedGrants(bot.connectorTools, deps.fullAccess?.(bot.id, threadId) === true) };+ const base = { harnessUrl: deps.harnessUrl, botId: bot.id, threadId, connectorTools: advertisedGrants(bot.connectorTools, appSandboxAllowed(bot) && deps.fullAccess?.(bot.id, threadId) === true) };const shared = await deps.composio.mcpIntegration(cfg, { ...base, commsToken: deps.mint({ botId: bot.id, threadId, generation }) });if (shared) out.composio = await withAppTools(shared, bot, names);const person = personApps().length ? turnPerson(threadId, generation) : null;diff --git a/server/index.ts b/server/index.tsindex 207302f4e4..afcb836052 100644--- a/server/index.ts+++ b/server/index.ts@@ -14467,7 +14467,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {// A room turn can run at a Chief's delegated level, which only the room handoff carries.const sendsFreely = () => roomTurnLevels.forRequest(internalCapability.threadId, internalCapability.botId,() => sourceApprovalMode(internalCapability.botId, internalCapability.threadId)) === "full"; const sandbox = appSandboxRule(body, sendsFreely);- const access = connectorAccessDecision(currentSender.connectorScopes, sandbox.open() ? [] : connectorCalls, serviceSlugs);+ const access = connectorAccessDecision(currentSender.connectorScopes, connectorCalls, serviceSlugs);if (!access.ok) {const described = describeTool(access.slug);const appName = described.app ?? access.toolkit;@@ -14475,10 +14475,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {threadId: internalCapability.threadId, botId: currentSender.id, botName: currentSender.name,tool: access.slug, decision: "auto-denied", source: "connector-scope", rule: `scope:${access.toolkit}:${access.reason}`,});- return refuseOutbound(connectorScopeRefusalText(call, access.reason, currentSender.name, appName, described.label));+ return refuseOutbound(sandbox.direct ? sandbox.refusal : connectorScopeRefusalText(call, access.reason, currentSender.name, appName, described.label));}const opaque = connectorCalls.some(call => call.slug === "COMPOSIO_PROXY_EXECUTE");- if (opaque && currentSender.connectorTools !== undefined && !sandbox.open()) return refuseOutbound(sandbox.refusal);+ if (opaque && currentSender.connectorTools !== undefined && !sandbox.open(currentSender)) return refuseOutbound(sandbox.refusal);const fullAccess = outboundTool !== null && sendsFreely();const held: OutboundHoldAnswer = outboundTool? await outboundHold.hold({@@ -14505,8 +14505,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {requireActiveInternalCapability();const fresh = store.bot(internalCapability.botId);if (!fresh || fresh.composio === false || !composio.configured(cfg) || managedPolicy.appsCallRefusal(connectorCalls, serviceSlugs)) refuseDispatch("Connected apps were disabled while this call waited.");- const freshAccess = connectorAccessDecision(fresh.connectorScopes, sandbox.open() ? [] : connectorCalls, serviceSlugs);- if (!freshAccess.ok || (opaque && fresh.connectorTools !== undefined && !sandbox.open()) ||+ const freshAccess = connectorAccessDecision(fresh.connectorScopes, connectorCalls, serviceSlugs);+ if (!freshAccess.ok || (opaque && fresh.connectorTools !== undefined && !sandbox.open(fresh)) ||(call.kind === "tools" && !evaluateConnectorTools(call.names, fresh.connectorTools, serviceSlugs).allowed) ||(call.kind === "unrecognized" && fresh.connectorTools !== undefined)) {refuseDispatch("This bot's connected-app permissions changed. The call was not run.");diff --git a/server/trust-controls.e2e.test.ts b/server/trust-controls.e2e.test.tsindex ce614b68d2..a417936f0c 100644--- a/server/trust-controls.e2e.test.ts+++ b/server/trust-controls.e2e.test.ts@@ -524,7 +524,7 @@ it("still asks before arbitrary workbench code under Send without asking", asyncexpect(relayed).toHaveLength(before);});-it("runs sandbox code for a bot with app grants only at Full access, only by a direct call", async () => {+it("runs sandbox code for a bot with app grants only at Full access, only by a direct call, never past its scopes", async () => {const b = sandboxBot;expect((await api("PATCH", `/api/bots/${b.id}`, { connectorTools: { gmail: { tools: "*" } } })).status).toBe(200);const token = await mint(b.id, b.threadId);@@ -539,6 +539,13 @@ it("runs sandbox code for a bot with app grants only at Full access, only by a dexpect(batched.body.result.isError).toBe(true);expect(JSON.stringify(batched.body.result)).toContain("only at Full access");expect(relayed).toHaveLength(before + 1);+ expect((await api("PATCH", `/api/bots/${b.id}`, { connectorScopes: { apps: { gmail: "read" } } })).status).toBe(200);+ for (const name of ["COMPOSIO_REMOTE_WORKBENCH", "COMPOSIO_REMOTE_BASH_TOOL"]) {+ const limited = await relay(token, name, { code_to_execute: 'run_tool("GMAIL_SEND_EMAIL", {})' });+ expect(limited.body.result.isError, "a read-only app holds even at Full access").toBe(true);+ expect(JSON.stringify(limited.body.result)).toContain("read only");+ }+ expect(relayed).toHaveLength(before + 1);const low = await bot("Sandbox below Full access");expect((await api("PATCH", `/api/bots/${low.id}`, { connectorTools: { gmail: { tools: "*" } } })).status).toBe(200);const lowToken = await mint(low.id, low.threadId);