Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(composio-broker): bind sessions to the current acting user (#3717)

zicochaose3b9af254731
diff --git a/cloudflare/composio-broker/src/index.test.ts b/cloudflare/composio-broker/src/index.test.ts
index 17443e99be..1ff27f59ff 100644
--- a/cloudflare/composio-broker/src/index.test.ts
+++ b/cloudflare/composio-broker/src/index.test.ts
@@ -29,7 +29,7 @@ function session(id: string, userId: string, configured = true) {
};
}
-function testEnv(fetchCalls: Array<{ url: string; init?: RequestInit }>) {
+function testEnv(fetchCalls: Array<{ url: string; init?: RequestInit }>, userId = "omb_stable") {
const dbRuns: Array<{ sql: string; values: unknown[] }> = [];
const env = {
COMPOSIO_API_BASE: "https://backend.composio.dev/api/v3.1",
@@ -40,8 +40,10 @@ function testEnv(fetchCalls: Array<{ url: string; init?: RequestInit }>) {
return {
bind(...values: unknown[]) {
return {
+ first: async () => ({ id: values[0], composio_user_id: userId, session_id: null, disabled_at: null }),
run: async () => {
dbRuns.push({ sql, values });
+ return { meta: { changes: 1 } };
},
};
},
@@ -293,7 +295,7 @@ describe("connected-apps broker boundaries", () => {
function accountFixture(installationUser: string) {
const fetchCalls: Array<{ url: string; init?: RequestInit }> = [];
- const { env, ctx } = testEnv(fetchCalls);
+ const { env, ctx } = testEnv(fetchCalls, installationUser);
const installation = { id: "retry-install", composio_user_id: installationUser, session_id: "trs_retry", disabled_at: null };
const fixture = {
accounts: [] as Array<{ id: string; status?: string; alias?: string; toolkit: { slug: string } }>,
@@ -516,6 +518,7 @@ describe("MCP relay Session reuse", () => {
lastSeenWrites.push(Number(values[0]));
row.last_seen_at = Number(values[0]);
}
+ return { meta: { changes: 1 } };
},
};
},
diff --git a/cloudflare/composio-broker/src/index.ts b/cloudflare/composio-broker/src/index.ts
index cecca225cc..3da7da759f 100644
--- a/cloudflare/composio-broker/src/index.ts
+++ b/cloudflare/composio-broker/src/index.ts
@@ -188,7 +188,9 @@ async function createSession(env: Env, userId: string, authConfigs: AuthConfigMa
}),
});
if (!response.ok) throw new Error(await upstreamError(response, `Session creation failed (${response.status})`));
- return parseSession(sessionWireSchema.parse(await response.json()));
+ const session = parseSession(sessionWireSchema.parse(await response.json()));
+ if (session.userId && session.userId !== userId) throw new Error("Composio created a Session for another user");
+ return { ...session, userId };
}
/** The project's own (not Composio-managed) auth configs: newest enabled one
@@ -279,10 +281,11 @@ function forgetSession(sessionId: string) {
verifiedSessions.delete(sessionId);
}
-function verifiedSession(sessionId: string | null) {
+function verifiedSession(installation: InstallationRow) {
+ const sessionId = installation.session_id;
if (!sessionId) return undefined;
const entry = verifiedSessions.get(sessionId);
- if (entry && Date.now() - entry.verifiedAt < VERIFIED_SESSION_TTL_MS) return entry.session;
+ if (entry && entry.session.userId === actingUser(installation) && Date.now() - entry.verifiedAt < VERIFIED_SESSION_TTL_MS) return entry.session;
verifiedSessions.delete(sessionId);
return undefined;
}
@@ -314,24 +317,42 @@ async function ensureSession(installation: InstallationRow, env: Env, ctx: Execu
return verifySession(installation, env, ctx);
}
+async function currentInstallation(env: Env, id: string) {
+ const current = await env.DB.prepare("SELECT * FROM installations WHERE id = ?").bind(id).first<InstallationRow>();
+ if (!current || current.disabled_at !== null) throw json({ error: "unauthorized" }, 401);
+ return current;
+}
+
async function verifySession(installation: InstallationRow, env: Env, ctx: ExecutionContext) {
const authConfigs = await projectAuthConfigs(env);
- const user = actingUser(installation);
- let session = installation.session_id ? await getSession(env, installation.session_id) : null;
- if (session && sessionReady(session, authConfigs) && (!session.userId || session.userId === user)) {
- touchLastSeen(installation, env, ctx);
- } else {
- // Connected accounts are attached to this stable Composio user ID, so a
- // Session recreated for it keeps every grant.
- session = await createSession(env, user, authConfigs);
- multiAccountUpgradeAttempted.add(session.sessionId);
- authConfigUpgradeAttempted.add(authConfigsKey(session.sessionId, authConfigs));
- await env.DB.prepare("UPDATE installations SET session_id = ?, last_seen_at = ? WHERE id = ?")
- .bind(session.sessionId, Date.now(), installation.id)
- .run();
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ const user = actingUser(installation);
+ let session = installation.session_id ? await getSession(env, installation.session_id) : null;
+ if (session && sessionReady(session, authConfigs) && session.userId === user) {
+ const current = await currentInstallation(env, installation.id);
+ if (actingUser(current) !== user) {
+ Object.assign(installation, current);
+ continue;
+ }
+ touchLastSeen(installation, env, ctx);
+ } else {
+ session = await createSession(env, user, authConfigs);
+ multiAccountUpgradeAttempted.add(session.sessionId);
+ authConfigUpgradeAttempted.add(authConfigsKey(session.sessionId, authConfigs));
+ const userColumn = installation.shared_user_id === undefined ? "composio_user_id" : "COALESCE(shared_user_id, composio_user_id)";
+ const saved = await env.DB.prepare(
+ `UPDATE installations SET session_id = ?, last_seen_at = ? WHERE id = ? AND ${userColumn} = ? AND disabled_at IS NULL`,
+ ).bind(session.sessionId, Date.now(), installation.id, user).run();
+ if (!saved.meta.changes) {
+ Object.assign(installation, await currentInstallation(env, installation.id));
+ continue;
+ }
+ installation.session_id = session.sessionId;
+ }
+ rememberSession(session);
+ return session;
}
- rememberSession(session);
- return session;
+ throw json({ error: "Connected apps changed. Try again." }, 503);
}
async function authenticate(request: Request, env: Env) {
@@ -362,7 +383,8 @@ async function proxyMcp(request: Request, installation: InstallationRow, env: En
const body = await readBoundedBody(request, MAX_MCP_BODY);
if (!body) return json({ error: "MCP request is too large" }, 413);
await limitSessionRequests(installation, env);
- const reused = verifiedSession(installation.session_id);
+ Object.assign(installation, await currentInstallation(env, installation.id));
+ const reused = verifiedSession(installation);
if (reused) touchLastSeen(installation, env, ctx);
let session = reused ?? await verifySession(installation, env, ctx);
const incomingMcpSession = request.headers.get("mcp-session-id");
diff --git a/cloudflare/composio-broker/src/session-identity.test.ts b/cloudflare/composio-broker/src/session-identity.test.ts
new file mode 100644
index 0000000000..655087eab7
--- /dev/null
+++ b/cloudflare/composio-broker/src/session-identity.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { brokerHarness, Installation } from "./test-harness";
+
+afterEach(() => vi.unstubAllGlobals());
+
+const sendEmail = (h: ReturnType<typeof brokerHarness>, owner: Installation) => h.call(owner, "/v1/mcp", {
+ method: "POST",
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "GMAIL_SEND_EMAIL", arguments: {} } }),
+});
+
+async function emailResult(response: Response) {
+ expect(response.status).toBe(200);
+ const body = await response.json() as { result: { content: Array<{ text: string }> } };
+ return JSON.parse(body.result.content[0]!.text);
+}
+
+async function sharingFixture() {
+ vi.resetModules();
+ const { brokerHarness } = await import("./test-harness");
+ const h = brokerHarness();
+ vi.stubGlobal("fetch", h.composio.fetchImpl);
+ const desktop = await h.install(), cloud = await h.install();
+ const gmail = h.account(desktop);
+ const share = await h.call(desktop, "/v1/installation/share", { method: "POST", body: JSON.stringify({ for: cloud.id }) });
+ expect(share.status).toBe(201);
+ const { code } = await share.json() as { code: string };
+ const adopt = async (otherIsolate = false) => {
+ const init = { method: "POST", body: JSON.stringify({ code }) };
+ if (!otherIsolate) return h.call(cloud, "/v1/installation/adopt", init);
+ vi.resetModules();
+ const { default: worker } = await import("./index");
+ return worker.fetch(new Request("https://broker.test/v1/installation/adopt", {
+ ...init, headers: { authorization: `Bearer ${cloud.token}` },
+ }), h.env as never, h.ctx as never);
+ };
+ return { h, desktop, cloud, gmail, adopt };
+}
+
+describe("Composio session identity across account adoption", () => {
+ it.each(["creation", "lookup"])("retries a session %s that finishes after adoption", async (operation) => {
+ const { h, desktop, cloud, gmail, adopt } = await sharingFixture();
+ if (operation === "lookup") await emailResult(await sendEmail(h, cloud));
+ const started = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ let held = false;
+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ const response = await h.composio.fetchImpl(input, init);
+ const path = new URL(String(input)).pathname;
+ if (!held && (operation === "creation"
+ ? path.endsWith("/tool_router/session") && init?.method === "POST"
+ : /\/tool_router\/session\/[^/]+$/.test(path))) {
+ held = true;
+ started.resolve();
+ await release.promise;
+ }
+ return response;
+ });
+
+ const pending = operation === "creation" ? sendEmail(h, cloud) : h.call(cloud, "/v1/connectors/connected");
+ await started.promise;
+ try {
+ expect((await adopt()).status).toBe(200);
+ } finally {
+ release.resolve();
+ }
+ const response = await pending;
+ if (operation === "creation") {
+ expect(await emailResult(response)).toMatchObject({ user: desktop.userId, accounts: [gmail] });
+ } else {
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({ services: { gmail: { connected: true } } });
+ }
+ expect(await emailResult(await sendEmail(h, cloud))).toMatchObject({ user: desktop.userId, accounts: [gmail] });
+ const [row] = h.d1.rows<{ session_id: string }>("SELECT session_id FROM installations WHERE id = ?", cloud.id);
+ expect(h.composio.sessions.get(row.session_id)?.user_id).toBe(desktop.userId);
+ });
+
+ it("rejects a cached session belonging to the installation's previous user", async () => {
+ const { h, desktop, cloud, gmail, adopt } = await sharingFixture();
+ await emailResult(await sendEmail(h, cloud));
+ const [old] = h.d1.rows<{ session_id: string }>("SELECT session_id FROM installations WHERE id = ?", cloud.id);
+ expect((await adopt(true)).status).toBe(200);
+ h.d1.db.prepare("UPDATE installations SET session_id = ? WHERE id = ?").run(old.session_id, cloud.id);
+
+ expect(await emailResult(await sendEmail(h, cloud))).toMatchObject({ user: desktop.userId, accounts: [gmail] });
+ });
+});