Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import fs from 'node:fs'; |
| 2 | import path from 'node:path'; |
| 3 | import { spawn, spawnSync } from 'node:child_process'; |
| 4 | import type { IncomingMessage, ServerResponse } from 'node:http'; |
| 5 | import { Schema } from 'effect'; |
| 6 | import { describe, expect, it } from 'vitest'; |
| 7 | import * as tempy from 'tempy'; |
| 8 | import { withHttpServer } from 'test/__utils__/http-server'; |
| 9 | |
| 10 | // Cases that run in-process go through `cli()` (test/src/invocation/invocation.test.ts); these need |
| 11 | // the real process: the bootstrap, the stored login a spawned CLI reads, real HTTP, and signals. |
| 12 | describe('CLI bootstrap', () => { |
| 13 | it('normalizes telemetry debug before dispatching a background worker', () => { |
| 14 | const configDirectory = tempy.temporaryDirectory(); |
| 15 | const encodedPayload = Buffer.from( |
| 16 | JSON.stringify({ |
| 17 | event: 'worker_bootstrap_test', |
| 18 | sentAt: '2026-08-14T00:00:00.000Z', |
| 19 | source: 'cli', |
| 20 | distinctId: 'install_test', |
| 21 | installId: 'install_test', |
| 22 | }) |
| 23 | ).toString('base64url'); |
| 24 | |
| 25 | const result = spawnSync( |
| 26 | 'bun', |
| 27 | ['run', 'src/bin.ts', '__analytics-worker', encodedPayload, '--telemetry-debug'], |
| 28 | { |
| 29 | cwd: process.cwd(), |
| 30 | encoding: 'utf8', |
| 31 | env: { |
| 32 | ...process.env, |
| 33 | CI: 'true', |
| 34 | NO_COLOR: '1', |
| 35 | COMPOSIO_CACHE_DIR: configDirectory, |
| 36 | }, |
| 37 | } |
| 38 | ); |
| 39 | |
| 40 | expect(result.status).toBe(0); |
| 41 | expect(`${result.stdout}\n${result.stderr}`).toContain('[telemetry-debug]'); |
| 42 | expect(`${result.stdout}\n${result.stderr}`).toContain('posthog_delivery_skipped'); |
| 43 | }); |
| 44 | }); |
| 45 | |
| 46 | describe('CLI backend of a stored login', () => { |
| 47 | const STAGING_BASE_URL = 'https://staging-backend.composio.dev'; |
| 48 | |
| 49 | /** A cache dir holding a stored login issued by `baseURL`. */ |
| 50 | const storedLogin = (baseURL: string) => { |
| 51 | const configDirectory = tempy.temporaryDirectory(); |
| 52 | fs.writeFileSync( |
| 53 | path.join(configDirectory, 'user_data.json'), |
| 54 | JSON.stringify({ api_key: 'uak_stored', base_url: baseURL, web_url: null, org_id: 'org_1' }) |
| 55 | ); |
| 56 | return configDirectory; |
| 57 | }; |
| 58 | |
| 59 | /** The environment of a spawned CLI: no backend variables from the host, telemetry off. */ |
| 60 | const cliEnv = (configDirectory: string, extra: Record<string, string> = {}) => { |
| 61 | const { |
| 62 | COMPOSIO_BASE_URL: _baseURL, |
| 63 | COMPOSIO_WEB_URL: _webURL, |
| 64 | COMPOSIO_ENVIRONMENT: _environment, |
| 65 | COMPOSIO_USER_API_KEY: _apiKey, |
| 66 | ...host |
| 67 | } = process.env; |
| 68 | return { |
| 69 | ...host, |
| 70 | CI: '1', |
| 71 | NO_COLOR: '1', |
| 72 | HOME: configDirectory, |
| 73 | COMPOSIO_CACHE_DIR: configDirectory, |
| 74 | COMPOSIO_CLI_TELEMETRY_DISABLED: '1', |
| 75 | ...extra, |
| 76 | }; |
| 77 | }; |
| 78 | |
| 79 | it('warns on stderr only when an env var sends the stored key to another backend', () => { |
| 80 | const configDirectory = storedLogin(STAGING_BASE_URL); |
| 81 | const run = (args: ReadonlyArray<string>, env: Record<string, string> = {}) => |
| 82 | spawnSync('bun', ['run', 'src/bin.ts', ...args], { |
| 83 | cwd: process.cwd(), |
| 84 | encoding: 'utf8', |
| 85 | env: cliEnv(configDirectory, env), |
| 86 | }); |
| 87 | const mismatched = { COMPOSIO_BASE_URL: 'http://127.0.0.1:9' }; |
| 88 | |
| 89 | const result = run(['version'], mismatched); |
| 90 | |
| 91 | expect(result.status).toBe(0); |
| 92 | const warning = |
| 93 | 'COMPOSIO_BASE_URL sends your stored API key to http://127.0.0.1:9, but it was issued by https://staging-backend.composio.dev.'; |
| 94 | expect(result.stderr.split(warning)).toHaveLength(2); |
| 95 | expect(result.stdout).not.toContain('COMPOSIO_BASE_URL'); |
| 96 | |
| 97 | expect(run(['version']).stderr).not.toContain('sends your stored API key'); |
| 98 | // `--version` runs no command, so no invocation hook. |
| 99 | expect(run(['--version'], mismatched).stderr).not.toContain('sends your stored API key'); |
| 100 | }); |
| 101 | |
| 102 | it('sends requests to the stored backend and explains a rejected key', async () => { |
| 103 | const requests: Array<{ url?: string; key?: string | string[] }> = []; |
| 104 | await withHttpServer( |
| 105 | (req, res) => { |
| 106 | requests.push({ url: req.url, key: req.headers['x-user-api-key'] }); |
| 107 | res.writeHead(401, { 'content-type': 'application/json' }); |
| 108 | res.end( |
| 109 | JSON.stringify({ |
| 110 | error: { |
| 111 | message: 'Invalid or revoked user API key', |
| 112 | code: 1803, |
| 113 | slug: 'UserApiKey_Unauthorized', |
| 114 | status: 401, |
| 115 | }, |
| 116 | }) |
| 117 | ); |
| 118 | }, |
| 119 | async baseURL => { |
| 120 | const configDirectory = storedLogin(baseURL); |
| 121 | const child = spawn('bun', ['run', 'src/bin.ts', 'orgs', 'list'], { |
| 122 | cwd: process.cwd(), |
| 123 | env: cliEnv(configDirectory), |
| 124 | }); |
| 125 | let stdout = ''; |
| 126 | let stderr = ''; |
| 127 | child.stdout.on('data', chunk => (stdout += String(chunk))); |
| 128 | child.stderr.on('data', chunk => (stderr += String(chunk))); |
| 129 | const status = await new Promise<number | null>(resolve => child.on('close', resolve)); |
| 130 | |
| 131 | expect(requests.length).toBeGreaterThan(0); |
| 132 | expect(requests[0]?.key).toBe('uak_stored'); |
| 133 | expect(status).toBe(1); |
| 134 | expect(stdout).toBe(''); |
| 135 | expect(stderr).toContain('Invalid or revoked user API key'); |
| 136 | expect(stderr).toContain(`composio logout && COMPOSIO_BASE_URL=${baseURL} composio login`); |
| 137 | } |
| 138 | ); |
| 139 | }); |
| 140 | }); |
| 141 | |
| 142 | // A stand-in for the backend and the Dashboard: the backend calls `composio execute` makes before |
| 143 | // it runs a tool get minimal answers, and the Dashboard's execute procedures answer per tool slug. |
| 144 | const DashboardRequest = Schema.fromJsonString( |
| 145 | Schema.Struct({ |
| 146 | json: Schema.Struct({ |
| 147 | tool_slug: Schema.optional(Schema.String), |
| 148 | slug: Schema.optional(Schema.String), |
| 149 | }), |
| 150 | }) |
| 151 | ); |
| 152 | const decodeDashboardRequest = Schema.decodeUnknownSync(DashboardRequest); |
| 153 | |
| 154 | const sendJson = (res: ServerResponse, status: number, body: unknown) => { |
| 155 | res.writeHead(status, { 'content-type': 'application/json' }); |
| 156 | res.end(JSON.stringify(body)); |
| 157 | }; |
| 158 | |
| 159 | const dashboardReply = (response: Record<string, unknown>) => ({ |
| 160 | result: { data: { json: { ok: true, response } } }, |
| 161 | }); |
| 162 | |
| 163 | const fakeComposio = (req: IncomingMessage, res: ServerResponse) => { |
| 164 | const { pathname } = new URL(req.url ?? '/', 'http://127.0.0.1'); |
| 165 | const chunks: Array<Buffer> = []; |
| 166 | req.on('data', (chunk: Buffer) => chunks.push(chunk)); |
| 167 | req.on('end', () => { |
| 168 | if (pathname.startsWith('/api/cli/trpc/')) { |
| 169 | const { json } = decodeDashboardRequest(Buffer.concat(chunks).toString('utf8')); |
| 170 | const slug = json.tool_slug ?? json.slug; |
| 171 | if (slug === 'HACKERNEWS_GET_FRONTPAGE') { |
| 172 | return sendJson(res, 200, dashboardReply({ result_type: 'completed', data: { ok: 1 } })); |
| 173 | } |
| 174 | if (slug === 'HACKERNEWS_GET_USER' || slug === 'COMPOSIO_SEARCH_TOOLS') { |
| 175 | return sendJson( |
| 176 | res, |
| 177 | 200, |
| 178 | dashboardReply({ result_type: 'failed', data: {}, error: 'User not found' }) |
| 179 | ); |
| 180 | } |
| 181 | return sendJson(res, 503, { error: { message: 'Service unavailable' } }); |
| 182 | } |
| 183 | if (pathname.endsWith('/org/consumer/project/resolve')) { |
| 184 | return sendJson(res, 200, { |
| 185 | org_id: 'org_test', |
| 186 | project_id: 'proj_test', |
| 187 | project_nano_id: 'pr_test', |
| 188 | project_name: 'consumer', |
| 189 | consumer_user_id: 'consumer-user-test', |
| 190 | }); |
| 191 | } |
| 192 | const toolSlug = /^\/api\/v3\.1\/tools\/([A-Z_]+)$/u.exec(pathname)?.[1]; |
| 193 | if (toolSlug !== undefined) { |
| 194 | return sendJson(res, 200, { |
| 195 | slug: toolSlug, |
| 196 | name: toolSlug, |
| 197 | description: '', |
| 198 | available_versions: ['20260101_00'], |
| 199 | input_parameters: { type: 'object', properties: {} }, |
| 200 | output_parameters: {}, |
| 201 | tags: [], |
| 202 | }); |
| 203 | } |
| 204 | if (pathname.endsWith('/toolkits') || pathname.endsWith('/connected_accounts')) { |
| 205 | return sendJson(res, 200, { items: [], next_cursor: null, total_pages: 1, current_page: 1 }); |
| 206 | } |
| 207 | return sendJson(res, 404, { error: { message: `Not found: ${pathname}` } }); |
| 208 | }); |
| 209 | }; |
| 210 | |
| 211 | /** Shorter than the tests' 30s timeout. */ |
| 212 | const CLI_DEADLINE_MS = 20_000; |
| 213 | |
| 214 | const runCliAgainst = ( |
| 215 | baseUrl: string, |
| 216 | args: ReadonlyArray<string>, |
| 217 | options: { |
| 218 | /** Writes files into the CLI's cache directory before it starts. */ |
| 219 | readonly seed?: (configDirectory: string) => void; |
| 220 | readonly env?: Readonly<Record<string, string>>; |
| 221 | } = {} |
| 222 | ) => { |
| 223 | const configDirectory = tempy.temporaryDirectory(); |
| 224 | options.seed?.(configDirectory); |
| 225 | fs.writeFileSync( |
| 226 | path.join(configDirectory, 'user_data.json'), |
| 227 | JSON.stringify({ |
| 228 | api_key: 'uak_test_api_key', |
| 229 | base_url: baseUrl, |
| 230 | web_url: baseUrl, |
| 231 | org_id: 'org_test', |
| 232 | test_user_id: null, |
| 233 | }) |
| 234 | ); |
| 235 | // A host key would replace the stored one. |
| 236 | const { |
| 237 | COMPOSIO_USER_API_KEY: _apiKey, |
| 238 | COMPOSIO_ENVIRONMENT: _environment, |
| 239 | ...host |
| 240 | } = process.env; |
| 241 | // Asynchronous: the fake server answers from this process's event loop. |
| 242 | return new Promise<{ status: number | null; stdout: string; stderr: string }>( |
| 243 | (resolve, reject) => { |
| 244 | const child = spawn('bun', ['run', 'src/bin.ts', ...args], { |
| 245 | cwd: process.cwd(), |
| 246 | env: { |
| 247 | ...host, |
| 248 | CI: '1', |
| 249 | NO_COLOR: '1', |
| 250 | COMPOSIO_CACHE_DIR: configDirectory, |
| 251 | COMPOSIO_BASE_URL: baseUrl, |
| 252 | COMPOSIO_WEB_URL: baseUrl, |
| 253 | COMPOSIO_CLI_TELEMETRY_DISABLED: '1', |
| 254 | ...options.env, |
| 255 | }, |
| 256 | }); |
| 257 | let stdout = ''; |
| 258 | let stderr = ''; |
| 259 | child.stdout.setEncoding('utf8').on('data', (chunk: string) => (stdout += chunk)); |
| 260 | child.stderr.setEncoding('utf8').on('data', (chunk: string) => (stderr += chunk)); |
| 261 | // Stop a hung CLI before the test times out, so the fake server can close. |
| 262 | const deadline = setTimeout(() => { |
| 263 | child.kill('SIGKILL'); |
| 264 | reject(new Error(`CLI did not exit within ${CLI_DEADLINE_MS}ms\nstderr:\n${stderr}`)); |
| 265 | }, CLI_DEADLINE_MS); |
| 266 | child.once('error', error => { |
| 267 | clearTimeout(deadline); |
| 268 | reject(error); |
| 269 | }); |
| 270 | child.once('close', status => { |
| 271 | clearTimeout(deadline); |
| 272 | resolve({ status, stdout, stderr }); |
| 273 | }); |
| 274 | } |
| 275 | ); |
| 276 | }; |
| 277 | |
| 278 | describe('reported tool execution failures', () => { |
| 279 | it.each([ |
| 280 | { |
| 281 | name: 'a tool that reports a failure', |
| 282 | args: ['execute', 'HACKERNEWS_GET_USER', '-d', '{"username":"nobody"}'], |
| 283 | stdout: { successful: false, data: {}, error: 'User not found' }, |
| 284 | }, |
| 285 | { |
| 286 | name: 'a Dashboard outage', |
| 287 | args: ['execute', 'HACKERNEWS_GET_ITEM', '-d', '{"id":1}'], |
| 288 | // The tool may have run before the Dashboard failed, so the result says to check first. |
| 289 | stdout: { |
| 290 | successful: false, |
| 291 | error: expect.stringContaining('(HTTP 503)'), |
| 292 | retry: 'check-first', |
| 293 | }, |
| 294 | }, |
| 295 | { |
| 296 | name: 'a meta tool that reports a failure', |
| 297 | args: ['execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"queries":[]}'], |
| 298 | stdout: { successful: false, data: {}, error: 'User not found' }, |
| 299 | }, |
| 300 | { |
| 301 | name: 'a parallel run with one failed call', |
| 302 | args: [ |
| 303 | 'execute', |
| 304 | '--parallel', |
| 305 | 'HACKERNEWS_GET_FRONTPAGE', |
| 306 | '-d', |
| 307 | '{}', |
| 308 | 'HACKERNEWS_GET_USER', |
| 309 | '-d', |
| 310 | '{"username":"nobody"}', |
| 311 | ], |
| 312 | stdout: { |
| 313 | successful: false, |
| 314 | parallel: true, |
| 315 | results: [ |
| 316 | { slug: 'HACKERNEWS_GET_FRONTPAGE', successful: true }, |
| 317 | { slug: 'HACKERNEWS_GET_USER', successful: false, error: 'User not found' }, |
| 318 | ], |
| 319 | }, |
| 320 | }, |
| 321 | ])( |
| 322 | '[Given] $name [Then] prints only the JSON result and exits 1', |
| 323 | ({ args, stdout }) => |
| 324 | withHttpServer(fakeComposio, async baseUrl => { |
| 325 | const result = await runCliAgainst(baseUrl, args); |
| 326 | |
| 327 | expect(JSON.parse(result.stdout)).toMatchObject(stdout); |
| 328 | expect(result.stderr).toBe(''); |
| 329 | expect(result.status).toBe(1); |
| 330 | }), |
| 331 | 30_000 |
| 332 | ); |
| 333 | |
| 334 | it.each([ |
| 335 | { |
| 336 | name: 'a successful call', |
| 337 | args: ['execute', 'HACKERNEWS_GET_FRONTPAGE', '-d', '{}'], |
| 338 | }, |
| 339 | { |
| 340 | name: 'a parallel run where every call succeeds', |
| 341 | args: [ |
| 342 | 'execute', |
| 343 | '--parallel', |
| 344 | 'HACKERNEWS_GET_FRONTPAGE', |
| 345 | '-d', |
| 346 | '{}', |
| 347 | 'HACKERNEWS_GET_FRONTPAGE', |
| 348 | '-d', |
| 349 | '{}', |
| 350 | ], |
| 351 | }, |
| 352 | ])( |
| 353 | '[Given] $name [Then] exits 0', |
| 354 | ({ args }) => |
| 355 | withHttpServer(fakeComposio, async baseUrl => { |
| 356 | const result = await runCliAgainst(baseUrl, args); |
| 357 | |
| 358 | expect(JSON.parse(result.stdout)).toMatchObject({ successful: true }); |
| 359 | expect(result.stderr).toBe(''); |
| 360 | expect(result.status).toBe(0); |
| 361 | }), |
| 362 | 30_000 |
| 363 | ); |
| 364 | }); |
| 365 | |
| 366 | describe('failures a command reports itself', () => { |
| 367 | it( |
| 368 | '[Given] a request failure the command reports [Then] prints it once, exits 1, and records the command as failed', |
| 369 | () => |
| 370 | withHttpServer( |
| 371 | (_req, res) => sendJson(res, 503, { error: { message: 'Service unavailable' } }), |
| 372 | async baseUrl => { |
| 373 | const result = await runCliAgainst(baseUrl, ['dev', 'toolkits', 'list'], { |
| 374 | env: { COMPOSIO_CLI_TELEMETRY_DEBUG: '1' }, |
| 375 | }); |
| 376 | |
| 377 | expect(result.status).toBe(1); |
| 378 | expect(result.stdout).toBe('[]\n'); |
| 379 | expect(result.stderr).toContain('CLI_COMMAND_FAILED'); |
| 380 | expect(result.stderr).not.toContain('CLI_COMMAND_SUCCEEDED'); |
| 381 | expect(result.stderr).not.toContain('ReportedFailure'); |
| 382 | } |
| 383 | ), |
| 384 | 30_000 |
| 385 | ); |
| 386 | }); |
| 387 | |
| 388 | describe('account selection errors', () => { |
| 389 | it( |
| 390 | '[Given] an `--account` that matches no connected account [Then] prints the message as one line and exits 1', |
| 391 | () => |
| 392 | withHttpServer(fakeComposio, async baseUrl => { |
| 393 | const result = await runCliAgainst(baseUrl, [ |
| 394 | 'execute', |
| 395 | 'GMAIL_FETCH_EMAILS', |
| 396 | '--account', |
| 397 | 'does-not-exist-xyz', |
| 398 | '-d', |
| 399 | '{}', |
| 400 | ]); |
| 401 | |
| 402 | expect(result.status).toBe(1); |
| 403 | expect(result.stdout).toBe(''); |
| 404 | expect(result.stderr.trim()).toBe( |
| 405 | 'No connected account matched "does-not-exist-xyz" for toolkit "gmail". No active connected accounts were found for that toolkit.' |
| 406 | ); |
| 407 | expect(result.stderr).not.toContain('💥'); |
| 408 | expect(result.stderr).not.toContain('ConnectedAccountResolutionError'); |
| 409 | expect(result.stderr).not.toContain('composio-cli'); |
| 410 | }), |
| 411 | 30_000 |
| 412 | ); |
| 413 | }); |
| 414 | |
| 415 | describe('expected failures without the crash banner', () => { |
| 416 | /** |
| 417 | * The connected-toolkits cache turned on, and fresh with no toolkit connected for the consumer |
| 418 | * user `fakeComposio` resolves. |
| 419 | */ |
| 420 | const noConnectedToolkits = { |
| 421 | env: { COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE: 'false' }, |
| 422 | seed: (configDirectory: string) => |
| 423 | fs.writeFileSync( |
| 424 | path.join(configDirectory, 'consumer-short-term-cache.json'), |
| 425 | JSON.stringify({ |
| 426 | 'org_test:consumer-user-test': { |
| 427 | toolkits: [], |
| 428 | // The spawned CLI reads the real clock, so the entry must outlive any test run. |
| 429 | expiresAt: '2999-01-01T00:00:00.000Z', |
| 430 | }, |
| 431 | }) |
| 432 | ), |
| 433 | }; |
| 434 | |
| 435 | /** `fakeComposio`, except the consumer project has no consumer user. */ |
| 436 | const withoutConsumerUser = (req: IncomingMessage, res: ServerResponse) => |
| 437 | new URL(req.url ?? '/', 'http://127.0.0.1').pathname.endsWith('/org/consumer/project/resolve') |
| 438 | ? sendJson(res, 200, { |
| 439 | org_id: 'org_test', |
| 440 | project_id: 'proj_test', |
| 441 | project_nano_id: 'pr_test', |
| 442 | project_name: 'consumer', |
| 443 | consumer_user_id: '', |
| 444 | }) |
| 445 | : fakeComposio(req, res); |
| 446 | |
| 447 | /** Every root-tree command without a consumer user says this. */ |
| 448 | const ROOT_MISSING_USER = 'Missing consumer user id. Run `composio login` and try again.'; |
| 449 | |
| 450 | const notConnected = (toolkit: string) => |
| 451 | `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`; |
| 452 | |
| 453 | it.each([ |
| 454 | { |
| 455 | name: '`login --poll` without a pending login', |
| 456 | args: ['login', '--poll'], |
| 457 | setup: {}, |
| 458 | server: fakeComposio, |
| 459 | tag: 'PendingLoginError', |
| 460 | message: 'No pending login found. Run `composio login < /dev/null` first.', |
| 461 | }, |
| 462 | { |
| 463 | name: '`execute --file` for a tool without a file input', |
| 464 | args: ['execute', 'GMAIL_FETCH_EMAILS', '--file', 'report.pdf', '-d', '{}'], |
| 465 | setup: {}, |
| 466 | server: fakeComposio, |
| 467 | tag: 'ToolExecutionError', |
| 468 | message: |
| 469 | 'Tool "GMAIL_FETCH_EMAILS" has no file_uploadable input. Remove --file or pass JSON via -d.', |
| 470 | }, |
| 471 | { |
| 472 | name: '`proxy` without a consumer user', |
| 473 | args: [ |
| 474 | 'proxy', |
| 475 | 'https://gmail.googleapis.com/gmail/v1/users/me/profile', |
| 476 | '--toolkit', |
| 477 | 'gmail', |
| 478 | ], |
| 479 | setup: {}, |
| 480 | server: withoutConsumerUser, |
| 481 | tag: 'MissingActingUserError', |
| 482 | message: ROOT_MISSING_USER, |
| 483 | }, |
| 484 | // An empty consumer user id is no user; these commands used to act as the user "", and |
| 485 | // told a consumer to pass --user-id, which the root tree does not take. |
| 486 | { |
| 487 | name: '`execute` without a consumer user', |
| 488 | args: ['execute', 'GMAIL_FETCH_EMAILS', '-d', '{}'], |
| 489 | setup: {}, |
| 490 | server: withoutConsumerUser, |
| 491 | tag: 'MissingActingUserError', |
| 492 | message: ROOT_MISSING_USER, |
| 493 | }, |
| 494 | { |
| 495 | name: '`search` without a consumer user', |
| 496 | args: ['search', 'send an email'], |
| 497 | setup: {}, |
| 498 | server: withoutConsumerUser, |
| 499 | tag: 'MissingActingUserError', |
| 500 | message: ROOT_MISSING_USER, |
| 501 | }, |
| 502 | { |
| 503 | name: '`link` without a consumer user', |
| 504 | args: ['link', 'gmail', '--no-wait'], |
| 505 | setup: {}, |
| 506 | server: withoutConsumerUser, |
| 507 | tag: 'MissingActingUserError', |
| 508 | message: ROOT_MISSING_USER, |
| 509 | }, |
| 510 | // These printed the defect banner for a missing consumer user. |
| 511 | { |
| 512 | name: '`connections list` without a consumer user', |
| 513 | args: ['connections', 'list'], |
| 514 | setup: {}, |
| 515 | server: withoutConsumerUser, |
| 516 | tag: 'MissingActingUserError', |
| 517 | message: ROOT_MISSING_USER, |
| 518 | }, |
| 519 | { |
| 520 | name: '`connections remove` without a consumer user', |
| 521 | args: ['connections', 'remove', 'gmail', '--yes'], |
| 522 | setup: {}, |
| 523 | server: withoutConsumerUser, |
| 524 | tag: 'MissingActingUserError', |
| 525 | message: ROOT_MISSING_USER, |
| 526 | }, |
| 527 | { |
| 528 | name: '`listen` without a consumer user', |
| 529 | args: ['listen', 'GMAIL_NEW_GMAIL_MESSAGE'], |
| 530 | setup: {}, |
| 531 | server: withoutConsumerUser, |
| 532 | tag: 'MissingActingUserError', |
| 533 | message: ROOT_MISSING_USER, |
| 534 | }, |
| 535 | ])( |
| 536 | '[Given] $name [Then] prints the message without the banner and exits 1', |
| 537 | ({ args, setup, server, tag, message }) => |
| 538 | withHttpServer(server, async baseUrl => { |
| 539 | const result = await runCliAgainst(baseUrl, args, setup); |
| 540 | |
| 541 | expect(result.status).toBe(1); |
| 542 | expect(result.stdout).toBe(''); |
| 543 | expect(result.stderr.trim()).toBe(message); |
| 544 | expect(result.stderr).not.toContain('💥'); |
| 545 | expect(result.stderr).not.toContain(tag); |
| 546 | expect(result.stderr).not.toContain('composio-cli'); |
| 547 | }), |
| 548 | 30_000 |
| 549 | ); |
| 550 | |
| 551 | it.each([ |
| 552 | { |
| 553 | name: '`execute` with a toolkit that is not connected', |
| 554 | args: ['execute', 'GMAIL_FETCH_EMAILS', '-d', '{}'], |
| 555 | }, |
| 556 | { |
| 557 | name: '`proxy` with a toolkit that is not connected', |
| 558 | args: [ |
| 559 | 'proxy', |
| 560 | 'https://gmail.googleapis.com/gmail/v1/users/me/profile', |
| 561 | '--toolkit', |
| 562 | 'gmail', |
| 563 | ], |
| 564 | }, |
| 565 | ])( |
| 566 | '[Given] $name [Then] prints only the failed result and exits 1', |
| 567 | ({ args }) => |
| 568 | withHttpServer(fakeComposio, async baseUrl => { |
| 569 | const result = await runCliAgainst(baseUrl, args, noConnectedToolkits); |
| 570 | |
| 571 | expect(result.status).toBe(1); |
| 572 | expect(JSON.parse(result.stdout)).toMatchObject({ |
| 573 | successful: false, |
| 574 | error: notConnected('gmail'), |
| 575 | }); |
| 576 | expect(result.stderr).toBe(''); |
| 577 | }), |
| 578 | 30_000 |
| 579 | ); |
| 580 | }); |
| 581 | |
| 582 | describe('local file uploads', () => { |
| 583 | const PPTX = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'; |
| 584 | |
| 585 | // Records the presigned-URL request, then refuses it so no upload is attempted. |
| 586 | const fakeUploadBackend = |
| 587 | (presignRequests: Array<unknown>) => (req: IncomingMessage, res: ServerResponse) => { |
| 588 | const { pathname } = new URL(req.url ?? '/', 'http://127.0.0.1'); |
| 589 | if (/^\/api\/v3(\.1)?\/tools\/CANVA_CREATE_DESIGN_IMPORT_JOB$/u.test(pathname)) { |
| 590 | return sendJson(res, 200, { |
| 591 | slug: 'CANVA_CREATE_DESIGN_IMPORT_JOB', |
| 592 | name: 'Create Design Import Job', |
| 593 | description: '', |
| 594 | version: '20260101_00', |
| 595 | available_versions: ['20260101_00'], |
| 596 | input_parameters: { |
| 597 | type: 'object', |
| 598 | properties: { |
| 599 | file: { type: 'object', file_uploadable: true }, |
| 600 | title: { type: 'string' }, |
| 601 | }, |
| 602 | }, |
| 603 | output_parameters: {}, |
| 604 | tags: [], |
| 605 | }); |
| 606 | } |
| 607 | if (pathname.endsWith('/files/upload/request')) { |
| 608 | const chunks: Array<Buffer> = []; |
| 609 | req.on('data', (chunk: Buffer) => chunks.push(chunk)); |
| 610 | req.on('end', () => { |
| 611 | presignRequests.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))); |
| 612 | sendJson(res, 400, { error: { message: 'stop here', status: 400 } }); |
| 613 | }); |
| 614 | return; |
| 615 | } |
| 616 | fakeComposio(req, res); |
| 617 | }; |
| 618 | |
| 619 | const uploadWith = async ( |
| 620 | baseUrl: string, |
| 621 | file: string, |
| 622 | stagedFiles?: Record<string, { name: string; mimetype?: string }> |
| 623 | ) => { |
| 624 | const metadataDirectory = fs.mkdtempSync(path.join(tempy.temporaryDirectory(), 'labels-')); |
| 625 | const metadataFile = path.join(metadataDirectory, 'files.json'); |
| 626 | if (stagedFiles) fs.writeFileSync(metadataFile, JSON.stringify(stagedFiles)); |
| 627 | try { |
| 628 | return await runCliAgainst( |
| 629 | baseUrl, |
| 630 | [ |
| 631 | 'execute', |
| 632 | 'CANVA_CREATE_DESIGN_IMPORT_JOB', |
| 633 | '--skip-connection-check', |
| 634 | '--file', |
| 635 | file, |
| 636 | '-d', |
| 637 | '{"title":"Deck"}', |
| 638 | ], |
| 639 | { |
| 640 | env: { COMPOSIO_RUN_STAGED_FILES_FILE: stagedFiles ? metadataFile : '' }, |
| 641 | } |
| 642 | ); |
| 643 | } finally { |
| 644 | fs.rmSync(metadataDirectory, { recursive: true, force: true }); |
| 645 | } |
| 646 | }; |
| 647 | |
| 648 | it.each([ |
| 649 | { |
| 650 | name: 'a .pptx path', |
| 651 | onDisk: 'deck.pptx', |
| 652 | staged: undefined, |
| 653 | filename: 'deck.pptx', |
| 654 | mimetype: PPTX, |
| 655 | }, |
| 656 | { |
| 657 | name: 'an extensionless path with no staged name or type', |
| 658 | onDisk: 'deck', |
| 659 | staged: undefined, |
| 660 | filename: 'deck', |
| 661 | mimetype: 'application/octet-stream', |
| 662 | }, |
| 663 | { |
| 664 | name: 'a path `composio run` staged an extensionless PPTX File at', |
| 665 | onDisk: 'file-a1b2c3d4', |
| 666 | staged: { name: 'deck', mimetype: PPTX }, |
| 667 | filename: 'deck', |
| 668 | mimetype: PPTX, |
| 669 | }, |
| 670 | { |
| 671 | name: 'a path `composio run` staged a `.env.example` File at', |
| 672 | onDisk: 'file-a1b2c3d4.example', |
| 673 | staged: { name: '.env.example', mimetype: 'text/plain' }, |
| 674 | filename: '.env.example', |
| 675 | mimetype: 'text/plain', |
| 676 | }, |
| 677 | ])( |
| 678 | '[Given] $name [Then] `composio execute --file` requests the upload as $filename, $mimetype', |
| 679 | ({ onDisk, staged, filename, mimetype }) => { |
| 680 | const file = path.join(tempy.temporaryDirectory(), onDisk); |
| 681 | fs.writeFileSync(file, 'PK fake pptx'); |
| 682 | const presignRequests: Array<unknown> = []; |
| 683 | return withHttpServer(fakeUploadBackend(presignRequests), async baseUrl => { |
| 684 | await uploadWith(baseUrl, file, staged && { [file]: staged }); |
| 685 | |
| 686 | expect(presignRequests).toEqual([ |
| 687 | expect.objectContaining({ filename, mimetype, toolkit_slug: 'canva' }), |
| 688 | ]); |
| 689 | }); |
| 690 | }, |
| 691 | 30_000 |
| 692 | ); |
| 693 | |
| 694 | it('[Given] a `.env` path staged under a harmless name [Then] the denylist still refuses it', () => { |
| 695 | const file = path.join(tempy.temporaryDirectory(), '.env'); |
| 696 | fs.writeFileSync(file, 'SECRET=value'); |
| 697 | const presignRequests: Array<unknown> = []; |
| 698 | return withHttpServer(fakeUploadBackend(presignRequests), async baseUrl => { |
| 699 | const result = await uploadWith(baseUrl, file, { |
| 700 | [file]: { name: 'deck.pptx', mimetype: PPTX }, |
| 701 | }); |
| 702 | |
| 703 | expect(result.status).toBe(1); |
| 704 | expect(`${result.stdout}${result.stderr}`).toContain('looks like a credential'); |
| 705 | expect(presignRequests).toEqual([]); |
| 706 | }); |
| 707 | }, 30_000); |
| 708 | }); |
| 709 | |
| 710 | describe('signals', () => { |
| 711 | /** |
| 712 | * Runs `composio orgs list` against a backend that never answers, sends `signal` once the |
| 713 | * request arrives, and reports how the process ended. |
| 714 | */ |
| 715 | const signalBlockedCommand = async (signal: NodeJS.Signals) => { |
| 716 | let child: ReturnType<typeof spawn> | undefined; |
| 717 | let ended: { code: number | null; signal: NodeJS.Signals | null } | undefined; |
| 718 | // Holds every request open: the command blocks until the signal ends it. |
| 719 | await withHttpServer( |
| 720 | () => child?.kill(signal), |
| 721 | async baseUrl => { |
| 722 | const configDirectory = tempy.temporaryDirectory(); |
| 723 | fs.writeFileSync( |
| 724 | path.join(configDirectory, 'user_data.json'), |
| 725 | JSON.stringify({ api_key: 'uak_test', base_url: baseUrl, web_url: baseUrl, org_id: null }) |
| 726 | ); |
| 727 | const { |
| 728 | COMPOSIO_USER_API_KEY: _apiKey, |
| 729 | COMPOSIO_ENVIRONMENT: _environment, |
| 730 | ...host |
| 731 | } = process.env; |
| 732 | const spawned = spawn('bun', ['run', 'src/bin.ts', 'orgs', 'list'], { |
| 733 | cwd: process.cwd(), |
| 734 | env: { |
| 735 | ...host, |
| 736 | CI: '1', |
| 737 | NO_COLOR: '1', |
| 738 | COMPOSIO_CACHE_DIR: configDirectory, |
| 739 | COMPOSIO_BASE_URL: baseUrl, |
| 740 | COMPOSIO_CLI_TELEMETRY_DISABLED: '1', |
| 741 | }, |
| 742 | stdio: 'ignore', |
| 743 | }); |
| 744 | child = spawned; |
| 745 | ended = await new Promise((resolve, reject) => { |
| 746 | const deadline = setTimeout(() => { |
| 747 | spawned.kill('SIGKILL'); |
| 748 | reject(new Error(`CLI did not exit within ${CLI_DEADLINE_MS}ms after ${signal}`)); |
| 749 | }, CLI_DEADLINE_MS); |
| 750 | spawned.once('close', (code, endSignal) => { |
| 751 | clearTimeout(deadline); |
| 752 | resolve({ code, signal: endSignal }); |
| 753 | }); |
| 754 | }); |
| 755 | } |
| 756 | ); |
| 757 | return ended; |
| 758 | }; |
| 759 | |
| 760 | it.each([ |
| 761 | { signal: 'SIGINT', code: 130 }, |
| 762 | { signal: 'SIGTERM', code: 143 }, |
| 763 | { signal: 'SIGHUP', code: 129 }, |
| 764 | ] as const)( |
| 765 | '[Given] a one-shot command waiting on the backend [When] it receives $signal [Then] it exits $code', |
| 766 | async ({ signal, code }) => { |
| 767 | expect(await signalBlockedCommand(signal)).toEqual({ code, signal: null }); |
| 768 | }, |
| 769 | 30_000 |
| 770 | ); |
| 771 | }); |