@devries-cameron20 / composio Mirror · read-only / commits / 0cd92dbe2
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

fix(cli): fail whoami when it cannot read the account (#5359)

This PR: - part of [PRDE-2212](https://linear.app/composio/issue/PRDE-2212/cli-e2e-tests-fake-backend-operation-suites-and-agent-journeys-with) - builds on top of https://github.com/ComposioHQ/composio/pull/5358; split from https://github.com/ComposioHQ/composio/pull/5333 - returns exit 1 and empty stdout when the account lookup fails; a partially decoded session still prints its available account fields - makes the whoami Docker suite hermetic and teaches the agent sign-in mock to answer session info, with assertions on whoami’s own email - turns the rejected-key whoami operation test into a passing test - passes the full CLI suite, CLI and workspace typechecks, Effect diagnostics, Oxlint, Prettier, and keyless Docker operations, whoami, and agent-signin suites The CLI test workflow runs for PRs targeting `next`, not this stack base; full CI completes after retargeting. The existing Docker scenarios cover these corrections; no recording changes are needed.

Alberto Schiabel committed Nov 16, 2026 at 13:05 UTC 0cd92dbe288b7b6c0d77f9b2bbab76b7cd75028b
10 files changed +392 -61
ts/e2e-tests/cli/agent-signin/e2e.test.ts
+3
@@ -83,6 +83,8 @@ e2e(import.meta.url, {
83 it('leaves the CLI authenticated as the agent (whoami)', () => {
84 const whoami = lastJsonLine(unattendedSignup.stdout);
85 expect(whoami.account_type).toBe('agent');
86 + // whoami's own line, not the login summary before it.
87 + expect(whoami.email).toBe('e2e-agent@agent.composio.ai');
88 });
89 });
90
@@ -120,6 +122,7 @@ e2e(import.meta.url, {
122 it('leaves the CLI authenticated as the agent (whoami)', () => {
123 const whoami = lastJsonLine(storedIdentityLogin.stdout);
124 expect(whoami.account_type).toBe('agent');
125 + expect(whoami.email).toBe('e2e-agent@agent.composio.ai');
126 });
127 });
128 },
ts/e2e-tests/cli/operations/README.md
+9 -9
@@ -76,15 +76,15 @@ Observed and left as is: on the backend transport an HTML error page is copied w
76
77 ### Auth (`auth-faults.test.ts`)
78
79 -| Fault | Injected at | Must hold | Status |
80 -| -------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
81 -| No key | empty home, seven root and dev commands | exit 1; stdout empty; names `composio login`; no request | ok |
82 -| Key only in `COMPOSIO_USER_API_KEY` | env | exit 1; names `composio login` or `composio orgs switch`; no request | ok |
83 -| Stored key rejected (401 everywhere) | all backend routes | exit 1; rejection visible; nothing but 401s; stored login untouched | ok |
84 -| Same, recovery command | | Names `composio login` | ok |
85 -| Same, `whoami` | | exit 1; stdout empty | expected failure: exit 0 and a JSON object of nulls |
86 -| Key sent to a backend that did not issue it | `COMPOSIO_BASE_URL` to a second fake | Warning on stderr naming both backends and `composio logout && composio login`; stdout free of it; the other backend rejects the key; nothing reaches the issuer; stored login untouched | ok |
87 -| Project key (`ak_`) where a user key belongs | `COMPOSIO_USER_API_KEY` | Arrives classified as a project key and is rejected | ok |
79 +| Fault | Injected at | Must hold | Status |
80 +| -------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ |
81 +| No key | empty home, seven root and dev commands | exit 1; stdout empty; names `composio login`; no request | ok |
82 +| Key only in `COMPOSIO_USER_API_KEY` | env | exit 1; names `composio login` or `composio orgs switch`; no request | ok |
83 +| Stored key rejected (401 everywhere) | all backend routes | exit 1; rejection visible; nothing but 401s; stored login untouched | ok |
84 +| Same, recovery command | | Names `composio login` | ok |
85 +| Same, `whoami` | | exit 1; stdout empty | ok |
86 +| Key sent to a backend that did not issue it | `COMPOSIO_BASE_URL` to a second fake | Warning on stderr naming both backends and `composio logout && composio login`; stdout free of it; the other backend rejects the key; nothing reaches the issuer; stored login untouched | ok |
87 +| Project key (`ak_`) where a user key belongs | `COMPOSIO_USER_API_KEY` | Arrives classified as a project key and is rejected | ok |
88
89 ### Filesystem (`filesystem-faults.test.ts`)
90
ts/e2e-tests/cli/operations/auth-faults.test.ts
+1 -2
@@ -127,8 +127,7 @@ describe('auth faults: a stored key the backend stops accepting', () => {
127 TEST_TIMEOUT_MS
128 );
129
130 - // CLI defect: `whoami` answers a 401 with exit 0 and a JSON object of nulls, so "check the login with whoami" passes on a dead key.
131 - it.failing(
130 + it(
131 '`whoami` fails when the backend rejects the stored key',
132 async () => {
133 reject();
ts/e2e-tests/cli/whoami/README.md
+11 -16
@@ -1,34 +1,29 @@
1 # CLI `composio whoami` Test
2
3 -Verifies that `composio whoami` prints the authenticated API key and respects stdout piping.
3 +Verifies that `composio whoami` prints the account of the user API key as JSON, respects stdout piping, and fails with how to recover when the backend rejects the key.
4
5 ## Why This Exists
6
7 -The CLI separates decoration (stderr) from data (stdout). This suite ensures:
7 +The CLI separates decoration (stderr) from data (stdout), and a rejected key must fail rather than print an empty account. This suite runs the CLI against a mock Composio API (`ts/packages/cli/scripts/mock-whoami-server.ts`), so it needs no secret and no live backend.
8
9 -- `composio whoami` exits with code 0
10 -- stdout contains the API key passed via `COMPOSIO_USER_API_KEY`
11 -- stderr is empty (no decoration leaks into piped output)
12 -- Redirecting stdout to a file captures the clean API key
9 +The mock answers `GET /api/v3.1/auth/session/info` and `GET /api/v3.1/org/consumer/config` for one accepted key, and answers every request with any other key with the backend's 401 for a revoked user API key (`UserApiKey_Unauthorized`).
10
11 ## What It Tests
12
16 -| Test | Description |
17 -| --- | --- |
18 -| Exit code | `composio whoami` returns 0 |
19 -| stdout | Output matches `COMPOSIO_USER_API_KEY` |
20 -| stderr | Empty when piped |
21 -| File redirect | `composio whoami > out.txt` captures the API key in the file |
13 +| Test | Description |
14 +| -------------- | ----------------------------------------------------------------------------------------------------------------------------- |
15 +| Accepted key | `composio whoami` exits 0, stdout is the account JSON with the mock's email and org, stderr is empty |
16 +| File redirect | `composio whoami > out.txt` leaves stdout and stderr empty, and `out.txt` holds the account JSON |
17 +| Rejected key | `composio whoami` exits 1, stdout is empty, stderr names the rejection and says to replace the key in `COMPOSIO_USER_API_KEY` |
18 +| Mock API usage | The CLI read the session info with each key |
19
20 ## Requirements
21
25 -- `COMPOSIO_USER_API_KEY` (**required**) — Composio user API key consumed by CLI
26 -
27 -If `COMPOSIO_USER_API_KEY` is not set, the suite fails fast at startup.
22 +None. Each command sets `COMPOSIO_BASE_URL`, `COMPOSIO_USER_API_KEY` and `COMPOSIO_CACHE_DIR` itself.
23
24 ## Isolation Tool
25
31 -**Docker** with the CLI built from the current monorepo source.
26 +**Docker** with the CLI built from the current monorepo source. The container reaches the mock on the host through `host.docker.internal`.
27
28 ## Running
29
ts/e2e-tests/cli/whoami/e2e.test.ts
+78 -27
@@ -1,52 +1,72 @@
1 /**
2 * CLI whoami command e2e test
3 *
4 - * Verifies that the compiled composio CLI prints the API key in a scratch container.
4 + * Verifies, against a mock Composio API, that the compiled composio CLI prints the account
5 + * of an accepted user API key as JSON, and fails with how to recover for a rejected one.
6 */
7
7 -import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
8 +import {
9 + e2e,
10 + parseJsonStdout,
11 + type E2ETestResult,
12 + type E2ETestResultWithFiles,
13 +} from '@e2e-tests/utils';
14 import { TIMEOUTS } from '@e2e-tests/utils/const';
9 -import { describe, it, expect, beforeAll } from 'bun:test';
10 -
11 -declare module 'bun' {
12 - interface Env {
13 - COMPOSIO_USER_API_KEY: string;
14 - }
15 -}
15 +import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
16 +import {
17 + ACCEPTED_USER_API_KEY,
18 + REJECTED_USER_API_KEY,
19 + SESSION_INFO,
20 + startMockWhoamiServer,
21 + type MockWhoamiServer,
22 +} from '../../../packages/cli/scripts/mock-whoami-server';
23
24 e2e(import.meta.url, {
25 versions: {
26 cli: ['current'],
27 },
21 - env: {
22 - COMPOSIO_USER_API_KEY: Bun.env.COMPOSIO_USER_API_KEY,
23 - },
28 defineTests: ({ runCmd }) => {
25 - const expectedApiKey = Bun.env.COMPOSIO_USER_API_KEY.trim();
26 - const expectedWhoamiJson = JSON.stringify({
27 - global_user_api_key: expectedApiKey,
28 - default_org_id: null,
29 - default_project_id: null,
30 - test_user_id: null,
31 - });
29 + let server: MockWhoamiServer;
30 let whoamiResult: E2ETestResult;
31 let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
32 + let rejectedResult: E2ETestResult;
33 +
34 + const expectedWhoami = {
35 + account_type: 'human',
36 + email: SESSION_INFO.org_member.email,
37 + current_org_name: SESSION_INFO.project.org.name,
38 + enhanced_controls_enabled: false,
39 + };
40
41 beforeAll(async () => {
36 - whoamiResult = await runCmd('composio whoami');
42 + server = await startMockWhoamiServer();
43 +
44 + const envPrefix = (userApiKey: string) =>
45 + [
46 + `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,
47 + 'COMPOSIO_CACHE_DIR=/tmp/composio-whoami',
48 + `COMPOSIO_USER_API_KEY=${userApiKey}`,
49 + ].join(' ');
50 +
51 + whoamiResult = await runCmd(`${envPrefix(ACCEPTED_USER_API_KEY)} composio whoami`);
52 redirectedResult = await runCmd({
38 - command: 'composio whoami > out.txt',
53 + command: `${envPrefix(ACCEPTED_USER_API_KEY)} composio whoami > out.txt`,
54 files: ['out.txt'],
55 });
56 + rejectedResult = await runCmd(`${envPrefix(REJECTED_USER_API_KEY)} composio whoami`);
57 }, TIMEOUTS.FIXTURE);
58
43 - describe('composio whoami', () => {
59 + afterAll(async () => {
60 + await server.close();
61 + });
62 +
63 + describe('composio whoami (accepted key)', () => {
64 it('exits successfully', () => {
65 expect(whoamiResult.exitCode).toBe(0);
66 });
67
48 - it.skip('stdout contains global user context JSON', () => {
49 - expect(sanitizeOutput(whoamiResult.stdout)).toBe(expectedWhoamiJson);
68 + it('stdout is the account as JSON', () => {
69 + expect(parseJsonStdout(whoamiResult)).toEqual(expectedWhoami);
70 });
71
72 it('stderr is empty', () => {
@@ -54,7 +74,7 @@ e2e(import.meta.url, {
74 });
75 });
76
57 - describe('stdout redirection to out.txt', () => {
77 + describe('stdout redirection to out.txt (accepted key)', () => {
78 it('exits successfully', () => {
79 expect(redirectedResult.exitCode).toBe(0);
80 });
@@ -67,8 +87,39 @@ e2e(import.meta.url, {
87 expect(redirectedResult.stderr).toBe('');
88 });
89
70 - it.skip('out.txt contains global user context JSON', () => {
71 - expect(sanitizeOutput(redirectedResult.files['out.txt'])).toBe(expectedWhoamiJson);
90 + it('out.txt holds the account as JSON', () => {
91 + expect(JSON.parse(redirectedResult.files['out.txt'])).toEqual(expectedWhoami);
92 + });
93 + });
94 +
95 + describe('composio whoami (key rejected with 401)', () => {
96 + it('exits with code 1', () => {
97 + expect(rejectedResult.exitCode).toBe(1);
98 + });
99 +
100 + it('stdout is empty', () => {
101 + expect(rejectedResult.stdout).toBe('');
102 + });
103 +
104 + it('stderr names the rejection', () => {
105 + expect(rejectedResult.stderr).toContain('Invalid or revoked user API key');
106 + });
107 +
108 + it('stderr says to replace the key in COMPOSIO_USER_API_KEY', () => {
109 + expect(rejectedResult.stderr).toContain(
110 + 'Replace the key in COMPOSIO_USER_API_KEY, then retry.'
111 + );
112 + });
113 + });
114 +
115 + describe('mock API usage', () => {
116 + it('reads the session info with each key', () => {
117 + expect(server.requests).toContain(
118 + `GET /api/v3.1/auth/session/info ${ACCEPTED_USER_API_KEY}`
119 + );
120 + expect(server.requests).toContain(
121 + `GET /api/v3.1/auth/session/info ${REJECTED_USER_API_KEY}`
122 + );
123 });
124 });
125 },
ts/packages/cli/CHANGELOG.md
+7
@@ -4,6 +4,13 @@
4
5 ### Patch Changes
6
7 +- `composio whoami` now exits 1 when it cannot read the account (the backend
8 + rejects the stored key, cannot be reached, or fails), with nothing on stdout
9 + and the reason on stderr; a rejected key also names `composio login`. It
10 + exited 0 and printed a JSON object of nulls, so checking a login with
11 + `composio whoami` passed on a key that no longer worked. A session it reads
12 + only in part still prints, with the missing fields as `null`.
13 +
14 - A command the Composio API answers with 401 now prints the API's message
15 and how to recover: `composio logout && composio login` when the stored
16 login's key may have expired, `composio agent login <composio_agent_key>`
ts/packages/cli/scripts/mock-agents-server.ts
+15
@@ -1,6 +1,7 @@
1 #!/usr/bin/env bun
2
3 import { createServer, type ServerResponse } from 'node:http';
4 +import { SESSION_INFO } from './mock-whoami-server';
5
6 /**
7 * Mock agents.composio.dev + the minimal Apollo endpoints the login flows
@@ -74,6 +75,20 @@ export async function startMockAgentsServer(options?: {
75 return;
76 }
77
78 + // The session `composio whoami` reads, as the agent's account.
79 + if (method === 'GET' && url.pathname === '/api/v3.1/auth/session/info') {
80 + sendJson(res, 200, {
81 + ...SESSION_INFO,
82 + org_member: { ...SESSION_INFO.org_member, email: AGENT_IDENTITY.email },
83 + });
84 + return;
85 + }
86 +
87 + if (method === 'GET' && url.pathname === '/api/v3.1/org/consumer/config') {
88 + sendJson(res, 200, { enhanced_controls: false });
89 + return;
90 + }
91 +
92 if (method === 'POST' && url.pathname === '/api/v3/cli/analytics') {
93 sendJson(res, 204, {});
94 return;
ts/packages/cli/scripts/mock-whoami-server.ts new
+140
@@ -0,0 +1,140 @@
1 +#!/usr/bin/env bun
2 +
3 +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
4 +
5 +/**
6 + * Mock of the Composio API routes `composio whoami` reads with a user API key.
7 + * `ACCEPTED_USER_API_KEY` gets a session; any other key gets the backend's 401
8 + * for a revoked user API key. Point the CLI at it via COMPOSIO_BASE_URL.
9 + */
10 +
11 +export const ACCEPTED_USER_API_KEY = 'uak_mock_whoami_accepted';
12 +export const REJECTED_USER_API_KEY = 'uak_mock_whoami_rejected';
13 +
14 +// Valid against the client's `GET /api/v3.1/auth/session/info` response schema.
15 +export const SESSION_INFO = {
16 + project: {
17 + auto_id: 1,
18 + id: '00000000-0000-4000-8000-000000000001',
19 + org_id: '00000000-0000-4000-8000-000000000002',
20 + name: 'Whoami E2E Project',
21 + email: 'project@whoami-e2e.test',
22 + nano_id: 'pr_whoami_e2e',
23 + created_at: '2024-01-01T00:00:00.000Z',
24 + updated_at: '2024-01-01T00:00:00.000Z',
25 + webhook_url: null,
26 + event_webhook_url: null,
27 + webhook_secret: null,
28 + triggers_enabled: true,
29 + last_subscribed_at: null,
30 + deleted: false,
31 + is_new_webhook: true,
32 + webhook_version: 'V2',
33 + org: { id: 'ok_whoami_e2e', name: 'Whoami E2E Org', plan: 'FREE' },
34 + },
35 + api_key: null,
36 + org_member: {
37 + id: '00000000-0000-4000-8000-000000000003',
38 + email: 'whoami@whoami-e2e.test',
39 + name: 'Whoami E2E',
40 + role: 'admin',
41 + metadata: {},
42 + },
43 +} as const;
44 +
45 +// The backend's error envelope for a revoked or unknown user API key.
46 +export const REJECTED_USER_API_KEY_BODY = {
47 + error: {
48 + message: 'Invalid or revoked user API key',
49 + code: 1803,
50 + slug: 'UserApiKey_Unauthorized',
51 + status: 401,
52 + },
53 +} as const;
54 +
55 +export interface MockWhoamiServer {
56 + readonly hostBaseUrl: string;
57 + readonly dockerBaseUrl: string;
58 + /** `METHOD /path` plus the user API key it was sent with, in arrival order. */
59 + readonly requests: string[];
60 + readonly close: () => Promise<void>;
61 +}
62 +
63 +const sendJson = (res: ServerResponse, statusCode: number, body: unknown): void => {
64 + res.writeHead(statusCode, { 'Content-Type': 'application/json' });
65 + res.end(JSON.stringify(body));
66 +};
67 +
68 +const userApiKeyOf = (req: IncomingMessage): string | undefined => {
69 + const header = req.headers['x-user-api-key'];
70 + return Array.isArray(header) ? header[0] : header;
71 +};
72 +
73 +export async function startMockWhoamiServer(options?: {
74 + host?: string;
75 + port?: number;
76 +}): Promise<MockWhoamiServer> {
77 + const host = options?.host ?? '0.0.0.0';
78 + const port = options?.port ?? 0;
79 + const requests: string[] = [];
80 +
81 + const server = createServer((req, res) => {
82 + const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`);
83 + const method = req.method ?? 'GET';
84 + const userApiKey = userApiKeyOf(req);
85 + requests.push(`${method} ${url.pathname} ${userApiKey ?? '(no user API key)'}`);
86 +
87 + if (method === 'POST' && url.pathname === '/api/v3/cli/analytics') {
88 + sendJson(res, 204, {});
89 + return;
90 + }
91 +
92 + if (userApiKey !== ACCEPTED_USER_API_KEY) {
93 + sendJson(res, 401, REJECTED_USER_API_KEY_BODY);
94 + return;
95 + }
96 +
97 + if (method === 'GET' && url.pathname === '/api/v3.1/auth/session/info') {
98 + sendJson(res, 200, SESSION_INFO);
99 + return;
100 + }
101 +
102 + if (method === 'GET' && url.pathname === '/api/v3.1/org/consumer/config') {
103 + sendJson(res, 200, { enhanced_controls: false });
104 + return;
105 + }
106 +
107 + sendJson(res, 404, { error: `Unhandled mock route: ${method} ${url.pathname}` });
108 + });
109 +
110 + await new Promise<void>((resolve, reject) => {
111 + server.once('error', reject);
112 + server.listen({ host, port }, () => {
113 + server.off('error', reject);
114 + resolve();
115 + });
116 + });
117 +
118 + const address = server.address();
119 + if (address === null || typeof address === 'string') {
120 + throw new Error('Failed to bind mock whoami server to a TCP port');
121 + }
122 +
123 + const close = () =>
124 + new Promise<void>((resolve, reject) => {
125 + server.close(error => {
126 + if (error) {
127 + reject(error);
128 + return;
129 + }
130 + resolve();
131 + });
132 + });
133 +
134 + return {
135 + hostBaseUrl: `http://127.0.0.1:${address.port}`,
136 + dockerBaseUrl: `http://host.docker.internal:${address.port}`,
137 + requests,
138 + close,
139 + };
140 +}
ts/packages/cli/src/commands/whoami.cmd.ts
+19 -2
@@ -8,10 +8,14 @@ import { TerminalUI } from 'src/services/terminal-ui';
8 import { commandHintStep } from 'src/services/command-hints';
9 import { readStoredAgentIdentity } from 'src/services/agents';
10 import { getOrgEnhancedControlsStatus } from 'src/services/tool-permissions';
11 +import { handleClientApiError } from 'src/effects/handle-http-error';
12 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
13
14 /**
15 * CLI command to display your account information.
14 - * Never prints or exposes API keys. Without a login it fails with `NotLoggedInError`.
16 + * Never prints or exposes API keys. Without a login it fails with `NotLoggedInError`. When the
17 + * account cannot be read (a rejected key, no connection, a server error) it reports why and
18 + * fails, so its exit code tells whether the login works.
19 *
20 * @example
21 * ```bash
@@ -30,11 +34,24 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
34 onNone: () => Effect.fail(notLoggedIn()),
35 onSome: apiKey =>
36 Effect.gen(function* () {
37 + // A session the CLI cannot fully read still proves the key works, so its fields
38 + // print as unknown. Any other failure (a rejected key, no connection, a 5xx)
39 + // means this command cannot vouch for the login, so it fails.
40 const sessionInfo = yield* getSessionInfoByUserApiKey({
41 userApiKey: apiKey,
42 // Reflect the org selected via `composio orgs switch`, not the key's home org.
43 orgId: Option.getOrUndefined(ctx.data.orgId),
37 - }).pipe(Effect.option);
44 + }).pipe(
45 + Effect.map(Option.some),
46 + Effect.catchTag('services/HttpDecodingError', () => Effect.succeedNone),
47 + Effect.catchTag(
48 + CLIENT_API_ERROR_TAGS,
49 + handleClientApiError(ui, {
50 + fallbackMessage: 'Could not read your account from Composio.',
51 + hint: 'Check your network connection, then retry:\n> composio whoami',
52 + })
53 + )
54 + );
55 yield* Option.match(sessionInfo, {
56 onNone: () => Effect.void,
57 onSome: info => linkApolloIdentityForAnalytics(info.org_member.id, apiKey),
ts/packages/cli/test/src/commands/whoami.cmd.test.ts
+109 -5
@@ -1,8 +1,11 @@
1 +import { AuthenticationError, InternalServerError } from '@composio/client/effect';
2 import { assert, describe, expect, layer } from '@effect/vitest';
3 import { isUsageFailure } from 'src/commands/errors';
4 import { ConfigProvider, Effect } from 'effect';
5 import { cli, TestLive, MockConsole } from 'test/__utils__';
6 +import { exitCodeOf } from 'test/__utils__/exit-code';
7 import { makeSessionInfo } from 'test/__utils__/models/account';
8 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
9
10 describe('CLI: composio whoami', () => {
11 layer(TestLive())('without a login', it => {
@@ -25,7 +28,20 @@ describe('CLI: composio whoami', () => {
28 env: { COMPOSIO_USER_API_KEY: 'api_key_from_test_config_provider' },
29 });
30
28 - layer(TestLive({ baseConfigProvider: testConfigProvider }))('with config override', it => {
31 + const readableSession = makeSessionInfo({
32 + orgId: 'org_123',
33 + orgName: 'Acme Org',
34 + orgMemberId: 'om_123',
35 + email: 'person@example.com',
36 + name: 'Test Person',
37 + });
38 +
39 + layer(
40 + TestLive({
41 + baseConfigProvider: testConfigProvider,
42 + accountData: { sessionInfo: readableSession },
43 + })
44 + )('with config override', it => {
45 it.effect('[Given] `COMPOSIO_USER_API_KEY` [Then] prints global user context JSON', () =>
46 Effect.gen(function* () {
47 const args = ['whoami'];
@@ -35,14 +51,15 @@ describe('CLI: composio whoami', () => {
51 const output = lines.join('\n');
52 expect(output).not.toContain(`api_key_from_test_config_provider`);
53 expect(output).not.toContain(`global_user_api_key`);
38 - expect(output).toContain(`"email":null`);
39 - expect(output).toContain(`"current_org_name":null`);
54 + expect(output).toContain(`"email":"person@example.com"`);
55 expect(output).not.toContain(`"test_user_id"`);
56 })
57 );
58 });
59
45 - layer(TestLive({ fixture: 'user-config-example' }))('with fixture', it => {
60 + layer(
61 + TestLive({ fixture: 'user-config-example', accountData: { sessionInfo: readableSession } })
62 + )('with fixture', it => {
63 it.effect('[Given] user_data.json in fixture [Then] prints global user context JSON', () =>
64 Effect.gen(function* () {
65 const args = ['whoami'];
@@ -52,9 +69,96 @@ describe('CLI: composio whoami', () => {
69 const output = lines.join('\n');
70 expect(output).not.toContain(`api_key_from_test_fixture`);
71 expect(output).not.toContain(`global_user_api_key`);
72 + expect(output).toContain(`"email":"person@example.com"`);
73 + expect(output).not.toContain(`"test_user_id"`);
74 + })
75 + );
76 + });
77 +
78 + // A 401 that is not the backend's `UserApiKey_Unauthorized`: the CLI cannot tell which
79 + // credential it is about, so it names the login as the likely way out.
80 + const rejectedKey = new AuthenticationError({
81 + message: '401 Invalid API key',
82 + method: 'GET',
83 + url: 'https://mock.invalid/api/v3.1/auth/session/info',
84 + status: 401,
85 + requestId: undefined,
86 + details: { message: 'Invalid API key', code: 401, slug: 'Auth_InvalidApiKey', status: 401 },
87 + body: undefined,
88 + });
89 +
90 + layer(
91 + TestLive({
92 + fixture: 'user-config-example',
93 + accountData: {
94 + sessionInfo: () => {
95 + throw rejectedKey;
96 + },
97 + },
98 + })
99 + )('with a stored key the backend rejects', it => {
100 + it.effect('[Then] exits 1 with nothing on stdout and names `composio login` on stderr', () =>
101 + Effect.gen(function* () {
102 + const terminal = redirectedTerminalUI();
103 + const exit = yield* Effect.exit(cli(['whoami']).pipe(Effect.provide(terminal.layer)));
104 +
105 + expect(exitCodeOf(exit)).toBe(1);
106 + expect(terminal.stdout()).toBe('');
107 + expect(terminal.stderr()).toBe(
108 + 'Invalid API key\nIf your login expired, log in again, then retry:\n> composio logout && composio login\n'
109 + );
110 + })
111 + );
112 + });
113 +
114 + // A backend that cannot answer: the command cannot vouch for the login, so it fails.
115 + const serverError = new InternalServerError({
116 + message: '500 Internal Server Error',
117 + method: 'GET',
118 + url: 'https://mock.invalid/api/v3.1/auth/session/info',
119 + status: 500,
120 + requestId: undefined,
121 + details: { message: 'Internal Server Error', code: 500, slug: 'Internal', status: 500 },
122 + body: undefined,
123 + });
124 +
125 + layer(
126 + TestLive({
127 + fixture: 'user-config-example',
128 + accountData: {
129 + sessionInfo: () => {
130 + throw serverError;
131 + },
132 + },
133 + })
134 + )('when the backend fails to answer', it => {
135 + it.effect('[Then] exits 1 with nothing on stdout and the failure on stderr', () =>
136 + Effect.gen(function* () {
137 + const terminal = redirectedTerminalUI();
138 + const exit = yield* Effect.exit(cli(['whoami']).pipe(Effect.provide(terminal.layer)));
139 +
140 + expect(exitCodeOf(exit)).toBe(1);
141 + expect(terminal.stdout()).toBe('');
142 + expect(terminal.stderr()).toContain('Internal Server Error');
143 + })
144 + );
145 + });
146 +
147 + // A session the CLI cannot fully read (org-level credentials have no project): the key
148 + // works, so the fields print as unknown.
149 + layer(
150 + TestLive({
151 + fixture: 'user-config-example',
152 + accountData: { sessionInfo: { ...readableSession, project: null } },
153 + })
154 + )('with a session the CLI cannot fully read', it => {
155 + it.effect('[Then] exits 0 and prints the fields as unknown', () =>
156 + Effect.gen(function* () {
157 + yield* cli(['whoami']);
158 +
159 + const output = (yield* MockConsole.getLines()).join('\n');
160 expect(output).toContain(`"email":null`);
161 expect(output).toContain(`"current_org_name":null`);
57 - expect(output).not.toContain(`"test_user_id"`);
162 })
163 );
164 });