@devries-cameron20 / composio-1 / commits / f0973e6c2
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.

fix(cli): name how to log in again on every 401 (#5358)

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/5355; split from https://github.com/ComposioHQ/composio/pull/5333 - adds a recovery command to every reported 401; stored logins name logout/login, environment keys name the variable to replace, and saved agents name reuse-only agent login without exposing their key - turns the rejected-stored-key recovery and rejected-key login operation tests into passing tests without a defect report - passes the full CLI suite, CLI and workspace typechecks, Effect diagnostics, Oxlint, Prettier, and keyless Docker operations 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. ## Context The source head still points saved-agent recovery at `~/.composio/agent.json` when `COMPOSIO_CACHE_DIR` is set. This split preserves that behavior; the [remaining source review comment](https://github.com/ComposioHQ/composio/pull/5333#discussion_r4556739368) is a follow-up.

Alberto Schiabel committed Nov 16, 2026 at 13:03 UTC f0973e6c233fb35233d6f41798815f43a3e2e804
11 files changed +380 -84
ts/e2e-tests/cli/operations/README.md
+24 -24
@@ -43,21 +43,21 @@ The catalogue starts from one question: what can go wrong for a CLI that an agen
43
44 "Session" here is the CLI login session (created, polled, linked) and the session artifact directory.
45
46 -| Fault or question | Injected at | Must hold | Status |
47 -| ------------------------------------ | ----------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
48 -| First run, `whoami` | empty home | exit 1; stdout empty; names `composio login`; no request | ok |
49 -| Headless `login` | no terminal | exit 0; one session created; URL with the session key and `composio login --poll` on stdout; pending session cached; nothing stored | ok |
50 -| `login --poll`, session never linked | world | Keeps polling (at least two reads in 8 s); nothing stored | ok |
51 -| `login --poll`, session linked | world | exit 0; JSON summary; key, backend URLs, org and global test user stored; pending file removed | ok |
52 -| `whoami` after login | | exit 0; JSON on stdout; stderr empty; only user-key requests | ok |
53 -| `login` when already logged in | | exit 0; no request; stored login unchanged | ok |
54 -| `logout` | | Key removed; `whoami` then exits 1 without a request | ok |
55 -| `login --key`, session not linked | world | exit 1; `Session not yet linked`; nothing stored | ok |
56 -| `login --key`, linked | world | exit 0; login stored | ok |
57 -| `login --key`, unknown session | 404 | exit 1; names `composio login --no-wait`; nothing stored | ok |
58 -| `login --user-api-key`, rejected key | 401 | exit 1; stdout empty; key not written anywhere | ok |
59 -| Same, as an expected failure | 401 | No defect report | expected failure: printed as a defect report with an empty title |
60 -| `artifacts cwd` | | exit 0; one absolute path; no login or request needed; stable per directory; follows `COMPOSIO_SESSION_DIR` | ok |
46 +| Fault or question | Injected at | Must hold | Status |
47 +| ------------------------------------ | ----------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------ |
48 +| First run, `whoami` | empty home | exit 1; stdout empty; names `composio login`; no request | ok |
49 +| Headless `login` | no terminal | exit 0; one session created; URL with the session key and `composio login --poll` on stdout; pending session cached; nothing stored | ok |
50 +| `login --poll`, session never linked | world | Keeps polling (at least two reads in 8 s); nothing stored | ok |
51 +| `login --poll`, session linked | world | exit 0; JSON summary; key, backend URLs, org and global test user stored; pending file removed | ok |
52 +| `whoami` after login | | exit 0; JSON on stdout; stderr empty; only user-key requests | ok |
53 +| `login` when already logged in | | exit 0; no request; stored login unchanged | ok |
54 +| `logout` | | Key removed; `whoami` then exits 1 without a request | ok |
55 +| `login --key`, session not linked | world | exit 1; `Session not yet linked`; nothing stored | ok |
56 +| `login --key`, linked | world | exit 0; login stored | ok |
57 +| `login --key`, unknown session | 404 | exit 1; names `composio login --no-wait`; nothing stored | ok |
58 +| `login --user-api-key`, rejected key | 401 | exit 1; stdout empty; key not written anywhere | ok |
59 +| Same, as an expected failure | 401 | No defect report | ok |
60 +| `artifacts cwd` | | exit 0; one absolute path; no login or request needed; stable per directory; follows `COMPOSIO_SESSION_DIR` | ok |
61
62 ### Network (`network-faults.test.ts`)
63
@@ -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` | expected failure: `search` prints only `Invalid API key` |
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 | 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 |
88
89 ### Filesystem (`filesystem-faults.test.ts`)
90
ts/e2e-tests/cli/operations/auth-faults.test.ts
+1 -2
@@ -117,8 +117,7 @@ describe('auth faults: a stored key the backend stops accepting', () => {
117 );
118 }
119
120 - // CLI gap: `search` prints only the backend's "Invalid API key", with no command to recover.
121 - it.failing(
120 + it(
121 'a rejected stored key names `composio login` as the way out',
122 async () => {
123 reject();
ts/e2e-tests/cli/operations/login-session.test.ts
+1 -2
@@ -261,8 +261,7 @@ describe('login session: a user API key given directly', () => {
261 TEST_TIMEOUT_MS
262 );
263
264 - // CLI defect: a rejected key at login is printed as a defect report with an empty title, not as an expected failure.
265 - it.failing(
264 + it(
265 'a key the backend rejects is reported as an expected failure, without a defect report',
266 async () => {
267 const result = await rig.run(
ts/packages/cli/AGENTS.md
+1 -1
@@ -25,7 +25,7 @@ The CLI is built on the **Effect.ts ecosystem** and runs on **Bun**. Service-ori
25 - `UpgradeBinaryLive` — Self-update from GitHub releases
26 - `BunFileSystem.layer`, `BunPath.layer`, `BunServices.layer`, `FetchHttpClient.layer` — Bun runtime integration (`@effect/platform-bun`'s `BunContext` no longer exists in v4; `BunServices.layer` is the aggregate replacement)
27
28 -Explicit help and version actions complete successfully. `Command.runWith` renders parse/validation errors and contextual help itself before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses the runner's automatic error log) and `[Runtime.errorExitCode]` (1 alongside parse errors). `runInvocation` prints every failure not yet on screen (an expected failure's message, a rejected key, or the defect report), never one already on screen (`[Runtime.errorReported] = false`, `ShowHelp` included), and fails with the command's own `Cause`, so tests can match its typed error. `forRunner` hands that to the runner with what it printed marked reported (`ReportedFailure`), keeping the markers of failures already on screen, and the runner exits through `Runtime.defaultTeardown`: 0 on success, otherwise the squashed failure's `[Runtime.errorExitCode]`, or 1 without one. This preserves failing exit codes without duplicate error output. Never assign `process.exitCode`; an error that needs a code other than 1 declares it (`ChildProcessExited` in `src/effects/child-process-exited.ts`, which `composio run` fails with when its script exits non-zero). See the module docstring at the top of `cli-main.ts` for the argv-prefix contract with `src/commands/index.ts`. In tests, `cliExit(args)` returns `{ exit, exitCode }` and `exitCodeOf(exit)` the code, both mapped the way `runCli` maps them (`runnerExit`, then the runner's `exitActionFor`).
28 +Explicit help and version actions complete successfully. `Command.runWith` renders parse/validation errors and contextual help itself before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses the runner's automatic error log) and `[Runtime.errorExitCode]` (1 alongside parse errors). `runInvocation` prints every failure not yet on screen (an expected failure's message, a 401 with the login hint from `unauthorizedHint` in `src/effects/rejected-user-api-key.ts`, or the defect report), never one already on screen (`[Runtime.errorReported] = false`, `ShowHelp` included), and fails with the command's own `Cause`, so tests can match its typed error. `forRunner` hands that to the runner with what it printed marked reported (`ReportedFailure`), keeping the markers of failures already on screen, and the runner exits through `Runtime.defaultTeardown`: 0 on success, otherwise the squashed failure's `[Runtime.errorExitCode]`, or 1 without one. This preserves failing exit codes without duplicate error output. Never assign `process.exitCode`; an error that needs a code other than 1 declares it (`ChildProcessExited` in `src/effects/child-process-exited.ts`, which `composio run` fails with when its script exits non-zero). See the module docstring at the top of `cli-main.ts` for the argv-prefix contract with `src/commands/index.ts`. In tests, `cliExit(args)` returns `{ exit, exitCode }` and `exitCodeOf(exit)` the code, both mapped the way `runCli` maps them (`runnerExit`, then the runner's `exitActionFor`).
29
30 Signals belong to the runner, the one place that installs SIGINT, SIGTERM and SIGHUP handlers; never add `process.on` for them elsewhere. It hands the first signal to the invocation's `ShutdownSignal` service (`src/services/shutdown-signal.ts`). A command that registered with `cooperate` for that signal stops by itself and ends normally: `listen` and `dev triggers listen` register `LISTENER_STOP` (SIGINT, SIGTERM) once Pusher confirms the subscription, through `TriggersRealtime`'s `onSubscribed`, and exit 0; `run` registers every signal, forwards it to its script's process group, and mirrors how the script ended (its code, or `ChildProcessSignaled`, whose signal the runner re-raises; when the CLI's own SIGTERM/SIGKILL escalation ended the script, the first signal instead). Every other command is interrupted, and an exit made of interruptions alone after a signal is 128 + its number: 130 (SIGINT), 143 (SIGTERM), 129 (SIGHUP). A second signal, or a stop longer than `SHUTDOWN_DEADLINE` (10 seconds), forces the exit: 128 + n, or for `run`, kill the script's group and re-raise.
31
ts/packages/cli/CHANGELOG.md
+11
@@ -4,6 +4,17 @@
4
5 ### Patch Changes
6
7 +- A command the Composio API answers with 401 now prints the API's message
8 + and how to recover: `composio logout && composio login` when the stored
9 + login's key may have expired, `composio agent login <composio_agent_key>`
10 + with the key from `~/.composio/agent.json` when that login is the saved
11 + Composio agent identity's, or replacing `COMPOSIO_USER_API_KEY` when the key
12 + came from there. Agent recovery reuses the identity without signing up a
13 + replacement or printing its key. `composio search` and other commands printed only the
14 + API's `Invalid API key` (inside a defect report), so an agent had no command
15 + to get unstuck. The hint was shown only when the API said the user API key
16 + itself was rejected; any other 401 now names the login as the likely cause.
17 +
18 - The `composio-cli` skill now says how to run a tool inside a developer
19 project: `composio dev playground-execute`, with
20 `composio dev connected-accounts link <toolkit>` for a missing connection.
ts/packages/cli/src/effects/handle-http-error.ts
+12 -5
@@ -1,10 +1,10 @@
1 import { isAPIError } from '@composio/client/effect';
2 -import { Effect } from 'effect';
2 +import { Effect, Option } from 'effect';
3 import type { ClientApiError } from 'src/services/composio-errors';
4 import type { TerminalUI } from 'src/services/terminal-ui';
5 import { reportFailure, type ReportedFailure } from 'src/effects/report-failure';
6 import { describeDecodeError, isClientDecodeError } from 'src/utils/api-error-extraction';
7 -import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
7 +import { isUnauthorized, unauthorizedHint } from 'src/effects/rejected-user-api-key';
8
9 export interface Suggestion {
10 readonly label: string;
@@ -29,9 +29,16 @@ interface ErrorReport {
29 const reportOf = (e: ClientApiError): Effect.Effect<ErrorReport> => {
30 if (isClientDecodeError(e)) return Effect.succeed(describeDecodeError(e));
31 if (isAPIError(e)) {
32 - return isRejectedUserApiKey(e)
33 - ? Effect.map(rejectedUserApiKeyHint, hint => ({ message: e.details?.message, hint }))
34 - : Effect.succeed({ message: e.details?.message, suggestedFix: e.details?.suggested_fix });
32 + const statusReport = { message: e.details?.message, suggestedFix: e.details?.suggested_fix };
33 + return isUnauthorized(e)
34 + ? Effect.map(
35 + unauthorizedHint(e),
36 + Option.match({
37 + onNone: () => statusReport,
38 + onSome: hint => ({ message: e.details?.message, hint }),
39 + })
40 + )
41 + : Effect.succeed(statusReport);
42 }
43 return Effect.succeed({});
44 };
ts/packages/cli/src/effects/rejected-user-api-key.ts
+82 -12
@@ -1,14 +1,23 @@
1 -import { Effect, Option } from 'effect';
1 +import { Effect, FileSystem, Option, Path } from 'effect';
2 import { APP_CONFIG } from 'src/config';
3 import { withoutTrailingSlashes } from 'src/config/backend';
4 import * as constants from 'src/constants';
5 +import { getCurrentLoggedInAgent } from 'src/services/agents';
6 +import { NodeOs } from 'src/services/node-os';
7 import { ComposioUserContext } from 'src/services/user-context';
8 import { findApiError } from 'src/utils/api-error-extraction';
9
10 /** Whether `value` (or a failure it wraps) is the backend rejecting the user API key. */
9 -export const isRejectedUserApiKey = (value: unknown): boolean =>
11 +const isRejectedUserApiKey = (value: unknown): boolean =>
12 findApiError(value)?.details?.slug === 'UserApiKey_Unauthorized';
13
14 +/**
15 + * Whether `value` (or a failure it wraps) is a 401 from the Composio API. Only
16 + * {@link isRejectedUserApiKey} says the user API key itself was rejected; any other 401 may be
17 + * about another credential.
18 + */
19 +export const isUnauthorized = (value: unknown): boolean => findApiError(value)?.status === 401;
20 +
21 /**
22 * The env vars that make `composio login` target the backend at `baseURL` and its Dashboard at
23 * `webURL`, as a command prefix. `COMPOSIO_WEB_URL` is named only when `webURL` is not the
@@ -33,23 +42,84 @@ const loginTargetPrefix = (baseURL: string, webURL: string) => {
42 return `${backendVar}${webVar}`;
43 };
44
45 +const keyFromEnv = APP_CONFIG.USER_API_KEY.pipe(
46 + Effect.map(key => key !== undefined),
47 + Effect.orElseSucceed(() => false)
48 +);
49 +
50 /**
37 - * How to recover from a rejected user API key. `composio logout` forgets the stored login's
38 - * backend, so the login command names the backend that rejected the key, and its Dashboard,
39 - * when they are not production's. Reads the user context when the caller has one, without requiring it.
51 + * Whether the stored login is the saved Composio agent identity's. False when it is not, or when
52 + * the caller has none of the services that read it.
53 */
41 -export const rejectedUserApiKeyHint = Effect.gen(function* () {
42 - const keyFromEnv = yield* APP_CONFIG.USER_API_KEY.pipe(
43 - Effect.map(key => key !== undefined),
54 +const loggedInAsAgent = Effect.gen(function* () {
55 + const services = Option.all({
56 + ctx: yield* Effect.serviceOption(ComposioUserContext),
57 + fs: yield* Effect.serviceOption(FileSystem.FileSystem),
58 + path: yield* Effect.serviceOption(Path.Path),
59 + os: yield* Effect.serviceOption(NodeOs),
60 + });
61 + if (Option.isNone(services)) {
62 + return false;
63 + }
64 + const { ctx, fs, path, os } = services.value;
65 + return yield* getCurrentLoggedInAgent.pipe(
66 + Effect.map(Option.isSome),
67 + Effect.provideService(ComposioUserContext, ctx),
68 + Effect.provideService(FileSystem.FileSystem, fs),
69 + Effect.provideService(Path.Path, path),
70 + Effect.provideService(NodeOs, os),
71 Effect.orElseSucceed(() => false)
72 );
46 - if (keyFromEnv) {
47 - return 'Replace the key in COMPOSIO_USER_API_KEY, then retry.';
48 - }
73 +});
74 +
75 +/**
76 + * The login command that replaces the stored login, on the backend that rejected its key. An
77 + * agent identity's login uses the saved key through `agent login`, which never signs up a new
78 + * agent. `composio logout` would delete that key; `login --agent` can replace the identity.
79 + */
80 +const loginAgainCommand = Effect.gen(function* () {
81 const ctx = yield* Effect.serviceOption(ComposioUserContext);
82 const prefix = Option.match(ctx, {
83 onNone: () => '',
84 onSome: c => loginTargetPrefix(c.data.baseURL, c.data.webURL),
85 });
54 - return `Log in again, then retry:\n> composio logout && ${prefix}composio login`;
86 + return (yield* loggedInAsAgent)
87 + ? `${prefix}composio agent login <composio_agent_key>\nUse the composio_agent_key from ~/.composio/agent.json.`
88 + : `composio logout && ${prefix}composio login`;
89 });
90 +
91 +/**
92 + * How to recover from a rejected user API key. `composio logout` forgets the stored login's
93 + * backend, so the login command names the backend that rejected the key, and its Dashboard,
94 + * when they are not production's. Reads the user context when the caller has one, without requiring it.
95 + */
96 +export const rejectedUserApiKeyHint = Effect.gen(function* () {
97 + if (yield* keyFromEnv) {
98 + return 'Replace the key in COMPOSIO_USER_API_KEY, then retry.';
99 + }
100 + return `Log in again, then retry:\n> ${yield* loginAgainCommand}`;
101 +});
102 +
103 +/**
104 + * How to recover from the 401 in `value`: {@link rejectedUserApiKeyHint} when the backend said
105 + * the user API key was rejected. Any other 401 names the login only as the likely cause, and
106 + * not at all without a user API key, which no login could have expired.
107 + */
108 +export const unauthorizedHint = (value: unknown): Effect.Effect<Option.Option<string>> =>
109 + Effect.gen(function* () {
110 + if (isRejectedUserApiKey(value)) {
111 + return Option.some(yield* rejectedUserApiKeyHint);
112 + }
113 + if (yield* keyFromEnv) {
114 + return Option.some(
115 + 'If the key in COMPOSIO_USER_API_KEY is no longer valid, replace it, then retry.'
116 + );
117 + }
118 + const ctx = yield* Effect.serviceOption(ComposioUserContext);
119 + const loggedIn = Option.exists(ctx, c => Option.isSome(c.data.apiKey));
120 + return loggedIn
121 + ? Option.some(
122 + `If your login expired, log in again, then retry:\n> ${yield* loginAgainCommand}`
123 + )
124 + : Option.none();
125 + });
ts/packages/cli/src/invocation/invocation.ts
+19 -10
@@ -6,9 +6,9 @@
6 *
7 * Every failure leaves `runInvocation` on screen exactly once: printed by `Command.runWith` (help
8 * and parse errors, `CliError.ShowHelp`), by the command itself (`[Runtime.errorReported] = false`),
9 - * or here (an expected failure's message, a rejected key, or the defect report). It leaves with
10 - * its own cause, so a caller can still match its typed error; `forRunner` turns it into what the
11 - * runner needs to print nothing more and exit with the right code.
9 + * or here (an expected failure's message, a 401 and how to recover, or the defect report). It
10 + * leaves with its own cause, so a caller can still match its typed error; `forRunner` turns it
11 + * into what the runner needs to print nothing more and exit with the right code.
12 */
13 import { Cause, Effect, Exit, Option, Ref, Runtime, type Layer } from 'effect';
14 import { CliError } from 'effect/cli';
@@ -21,7 +21,7 @@ import type { CliCommandTelemetryContext } from 'src/analytics/types';
21 import { runWithConfig } from 'src/commands';
22 import * as constants from 'src/constants';
23 import { isExpectedFailure } from 'src/effects/expected-failure';
24 -import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
24 +import { isUnauthorized, unauthorizedHint } from 'src/effects/rejected-user-api-key';
25 import { ReportedFailure } from 'src/effects/report-failure';
26 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
27 import { getVersion } from 'src/effects/version';
@@ -192,17 +192,26 @@ const report = (cause: Cause.Cause<unknown>) =>
192 const error = Cause.findErrorOption(cause);
193 // A usage mistake, a missing setup or login, or a failure a remote service reported clearly
194 // (see `ExpectedFailure`) is not a broken invariant: its message alone, no defect report.
195 + // A 401 behind the failure, from whichever command it escaped, adds the way to log in
196 + // again when a login can fix it.
197 + const printUnauthorizedHint = (failure: unknown) =>
198 + isUnauthorized(failure)
199 + ? Effect.flatMap(
200 + unauthorizedHint(failure),
201 + Option.match({ onNone: () => Effect.void, onSome: ui.error })
202 + )
203 + : Effect.void;
204 const expected = Option.filter(error, isExpectedFailure);
205 if (Option.isSome(expected)) {
206 yield* ui.error(expected.value.message);
207 + yield* printUnauthorizedHint(expected.value);
208 return;
209 }
200 - // A rejected user API key gets the backend's message and the way to log in again, from
201 - // whichever command it escaped.
202 - const rejectedKey = Option.filter(error, isRejectedUserApiKey);
203 - if (Option.isSome(rejectedKey)) {
204 - yield* ui.error(extractMessage(rejectedKey.value) ?? 'The user API key was rejected.');
205 - yield* ui.error(yield* rejectedUserApiKeyHint);
210 + // Any other 401 gets the backend's message in place of a defect report.
211 + const rejected = Option.filter(error, isUnauthorized);
212 + if (Option.isSome(rejected)) {
213 + yield* ui.error(extractMessage(rejected.value) ?? 'The Composio API rejected the request.');
214 + yield* printUnauthorizedHint(rejected.value);
215 return;
216 }
217 // A failure already on screen — `ShowHelp` (`Command.runWith` printed help and any
ts/packages/cli/test/src/commands/tools/search/tools.search.client.cmd.test.ts
+37
@@ -2,6 +2,8 @@ import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 +import { exitCodeOf } from 'test/__utils__/exit-code';
6 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
7 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
8
9 const sendEmailInput = {
@@ -200,4 +202,39 @@ describe('CLI: composio search over the API client', () => {
202 })
203 );
204 });
205 +
206 + // A stored login, not COMPOSIO_USER_API_KEY, whose key the backend no longer accepts.
207 + layer(TestLive({ fixture: 'global-test-user-id' }))(
208 + '[Given] the API rejects the stored key',
209 + it => {
210 + it.effect('[Then] the rejection is on stderr with `composio login` as the way out', () =>
211 + Effect.gen(function* () {
212 + // Every request is rejected, the project lookup before the search first.
213 + const stub = stubClientResources(['_internal', 'toolRouter', 'connectedAccounts'], () =>
214 + Response.json(
215 + {
216 + error: {
217 + message: 'Invalid API key',
218 + code: 401,
219 + slug: 'Auth_InvalidApiKey',
220 + status: 401,
221 + },
222 + },
223 + { status: 401 }
224 + )
225 + );
226 + const terminal = redirectedTerminalUI();
227 + const exit = yield* Effect.exit(
228 + cli(['search', 'send an email']).pipe(Effect.provide([stub.layer, terminal.layer]))
229 + );
230 +
231 + expect(exitCodeOf(exit)).toBe(1);
232 + expect(terminal.stdout()).toBe('');
233 + expect(terminal.stderr()).toBe(
234 + 'Invalid API key\nIf your login expired, log in again, then retry:\n> composio logout && COMPOSIO_WEB_URL=https://platform.composio.dev composio login\n'
235 + );
236 + })
237 + );
238 + }
239 + );
240 });
ts/packages/cli/test/src/effects/handle-http-error.test.ts
+30 -1
@@ -1,4 +1,5 @@
1 import {
2 + AuthenticationError as ClientAuthenticationError,
3 APIConnectionError as ClientAPIConnectionError,
4 APIConnectionTimeoutError as ClientAPIConnectionTimeoutError,
5 BadRequestError as ClientBadRequestError,
@@ -7,7 +8,7 @@ import {
8 type ComposioError,
9 } from '@composio/client/effect';
10 import { describe, expect, it } from '@effect/vitest';
10 -import { Effect } from 'effect';
11 +import { ConfigProvider, Effect } from 'effect';
12 import { handleClientApiError } from 'src/effects/handle-http-error';
13 import { ReportedFailure } from 'src/effects/report-failure';
14 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -127,6 +128,34 @@ describe('handleClientApiError', () => {
128 })
129 );
130
131 + it.effect('names the key to replace for a 401 when it comes from COMPOSIO_USER_API_KEY', () =>
132 + Effect.gen(function* () {
133 + const { ui, lines } = recordingUI();
134 + const unauthorized = new ClientAuthenticationError({
135 + message: '401 Invalid API key',
136 + method: 'GET',
137 + url,
138 + status: 401,
139 + requestId: undefined,
140 + details: { message: 'Invalid API key', code: 401, slug: 'Auth_InvalidApiKey', status: 401 },
141 + body: undefined,
142 + });
143 +
144 + const exit = yield* Effect.exit(handleClientApiError(ui, options)(unauthorized)).pipe(
145 + Effect.provideService(
146 + ConfigProvider.ConfigProvider,
147 + ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'uak_env' } })
148 + )
149 + );
150 +
151 + expect(lines).toStrictEqual([
152 + 'stderr: Invalid API key',
153 + 'stderr: If the key in COMPOSIO_USER_API_KEY is no longer valid, replace it, then retry.',
154 + ]);
155 + expect(exitCodeOf(exit)).toBe(1);
156 + })
157 + );
158 +
159 it.effect('replaces the hint with suggestions when the search finds some', () =>
160 Effect.gen(function* () {
161 const { ui, lines } = recordingUI();
ts/packages/cli/test/src/effects/rejected-user-api-key.test.ts
+162 -27
@@ -1,6 +1,11 @@
1 +import { AuthenticationError } from '@composio/client/effect';
2 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 +import * as BunPath from '@effect/platform-bun/BunPath';
4 import { describe, expect, it } from '@effect/vitest';
2 -import { ConfigProvider, Effect, Layer, Option } from 'effect';
3 -import { rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
5 +import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from 'effect';
6 +import * as tempy from 'tempy';
7 +import { rejectedUserApiKeyHint, unauthorizedHint } from 'src/effects/rejected-user-api-key';
8 +import { NodeOs } from 'src/services/node-os';
9 import { ComposioUserContext } from 'src/services/user-context';
10
11 const PRODUCTION = { base: 'https://backend.composio.dev', web: 'https://dashboard.composio.dev/' };
@@ -9,33 +14,73 @@ const STAGING = {
14 web: 'https://staging-dashboard.composio.dev/',
15 };
16
12 -/** The hint for a stored login whose resolved backend is `baseURL` with its Dashboard at `webURL`. */
13 -const hintFor = (baseURL: string, webURL: string, env: Record<string, string> = {}) =>
14 - rejectedUserApiKeyHint.pipe(
15 - Effect.provide(
16 - Layer.mergeAll(
17 - Layer.succeed(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env })),
18 - Layer.succeed(
19 - ComposioUserContext,
20 - ComposioUserContext.of({
21 - data: {
22 - apiKey: Option.some('uak_stored'),
23 - baseURL,
24 - webURL,
25 - orgId: Option.none(),
26 - projectId: Option.none(),
27 - testUserId: Option.none(),
28 - },
29 - backendMismatch: Option.none(),
30 - isLoggedIn: () => true,
31 - logout: Effect.void,
32 - login: () => Effect.void,
33 - update: () => Effect.void,
34 - })
35 - )
36 - )
17 +/** The services the hints read: `env`, and a user context with `apiKey` on `baseURL`/`webURL`. */
18 +const userContextLayer = (
19 + baseURL: string,
20 + webURL: string,
21 + env: Record<string, string> = {},
22 + apiKey: Option.Option<string> = Option.some('uak_stored')
23 +) =>
24 + Layer.mergeAll(
25 + Layer.succeed(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env })),
26 + Layer.succeed(
27 + ComposioUserContext,
28 + ComposioUserContext.of({
29 + data: {
30 + apiKey,
31 + baseURL,
32 + webURL,
33 + orgId: Option.none(),
34 + projectId: Option.none(),
35 + testUserId: Option.none(),
36 + },
37 + backendMismatch: Option.none(),
38 + isLoggedIn: () => true,
39 + logout: Effect.void,
40 + login: () => Effect.void,
41 + update: () => Effect.void,
42 + })
43 + )
44 + );
45 +
46 +/**
47 + * `userContextLayer` on `baseURL`/`webURL` plus a temporary home, where `~/.composio/agent.json`
48 + * lives, read through the real filesystem.
49 + */
50 +const agentHomeLayer = (baseURL: string, webURL: string) => {
51 + const homedir = tempy.temporaryDirectory({ prefix: 'unauthorized-hint' });
52 + return Layer.mergeAll(
53 + userContextLayer(baseURL, webURL),
54 + BunFileSystem.layer,
55 + BunPath.layer,
56 + Layer.succeed(
57 + NodeOs,
58 + NodeOs.of({ homedir, tmpdir: homedir, arch: 'arm64', platform: 'darwin' })
59 )
60 );
61 +};
62 +
63 +/** Saves an agent identity whose user API key is `userApiKey` in `~/.composio/agent.json`. */
64 +const saveAgentIdentity = (userApiKey: string) =>
65 + Effect.gen(function* () {
66 + const fs = yield* FileSystem.FileSystem;
67 + const path = yield* Path.Path;
68 + const os = yield* NodeOs;
69 + const dir = path.join(os.homedir, '.composio');
70 + yield* fs.makeDirectory(dir, { recursive: true });
71 + yield* fs.writeFileString(
72 + path.join(dir, 'agent.json'),
73 + JSON.stringify({
74 + composio_agent_key: 'ak_saved',
75 + composio: { user_api_key: userApiKey, org_id: 'org_agent' },
76 + }),
77 + { mode: 0o600 }
78 + );
79 + });
80 +
81 +/** The hint for a stored login whose resolved backend is `baseURL` with its Dashboard at `webURL`. */
82 +const hintFor = (baseURL: string, webURL: string, env: Record<string, string> = {}) =>
83 + rejectedUserApiKeyHint.pipe(Effect.provide(userContextLayer(baseURL, webURL, env)));
84
85 describe('rejectedUserApiKeyHint', () => {
86 it.effect.each([
@@ -94,3 +139,93 @@ describe('rejectedUserApiKeyHint', () => {
139 })
140 );
141 });
142 +
143 +const unauthorized = (slug: string) =>
144 + new AuthenticationError({
145 + message: '401 Unauthorized',
146 + method: 'GET',
147 + url: 'https://backend.composio.dev/api/v3.1/auth/session/info',
148 + status: 401,
149 + requestId: undefined,
150 + details: { message: 'Unauthorized', code: 401, slug, status: 401 },
151 + body: undefined,
152 + });
153 +
154 +describe('unauthorizedHint', () => {
155 + it.effect('[Given] the backend rejected the user API key [Then] it says to log in again', () =>
156 + Effect.gen(function* () {
157 + const hint = yield* unauthorizedHint(unauthorized('UserApiKey_Unauthorized')).pipe(
158 + Effect.provide(userContextLayer(PRODUCTION.base, PRODUCTION.web))
159 + );
160 + expect(hint).toEqual(
161 + Option.some('Log in again, then retry:\n> composio logout && composio login')
162 + );
163 + })
164 + );
165 +
166 + it.effect.each<{
167 + name: string;
168 + env: Record<string, string>;
169 + apiKey: Option.Option<string>;
170 + hint: Option.Option<string>;
171 + }>([
172 + {
173 + name: 'a stored login',
174 + env: {},
175 + apiKey: Option.some('uak_stored'),
176 + hint: Option.some(
177 + 'If your login expired, log in again, then retry:\n> composio logout && composio login'
178 + ),
179 + },
180 + {
181 + name: 'a key from COMPOSIO_USER_API_KEY',
182 + env: { COMPOSIO_USER_API_KEY: 'uak_env' },
183 + apiKey: Option.some('uak_env'),
184 + hint: Option.some(
185 + 'If the key in COMPOSIO_USER_API_KEY is no longer valid, replace it, then retry.'
186 + ),
187 + },
188 + { name: 'no user API key', env: {}, apiKey: Option.none(), hint: Option.none() },
189 + ])('[Given] another 401 and $name [Then] the login is only the likely cause', c =>
190 + Effect.gen(function* () {
191 + const hint = yield* unauthorizedHint(unauthorized('Auth_InvalidApiKey')).pipe(
192 + Effect.provide(userContextLayer(PRODUCTION.base, PRODUCTION.web, c.env, c.apiKey))
193 + );
194 + expect(hint).toEqual(c.hint);
195 + })
196 + );
197 +});
198 +
199 +describe('[Given] the stored login is the saved agent identity', () => {
200 + // `composio logout` would need --yes without a terminal and would delete the saved agent key.
201 + it.effect('[Then] a rejected key names reuse-only agent login and the saved key file', () =>
202 + Effect.gen(function* () {
203 + yield* saveAgentIdentity('uak_stored');
204 + expect(yield* rejectedUserApiKeyHint).toBe(
205 + 'Log in again, then retry:\n> COMPOSIO_ENVIRONMENT=staging composio agent login <composio_agent_key>\nUse the composio_agent_key from ~/.composio/agent.json.'
206 + );
207 + }).pipe(Effect.provide(agentHomeLayer(STAGING.base, STAGING.web)))
208 + );
209 +
210 + it.effect('[Then] another 401 names reuse-only agent login and the saved key file', () =>
211 + Effect.gen(function* () {
212 + yield* saveAgentIdentity('uak_stored');
213 + expect(yield* unauthorizedHint(unauthorized('Auth_InvalidApiKey'))).toEqual(
214 + Option.some(
215 + 'If your login expired, log in again, then retry:\n> composio agent login <composio_agent_key>\nUse the composio_agent_key from ~/.composio/agent.json.'
216 + )
217 + );
218 + }).pipe(Effect.provide(agentHomeLayer(PRODUCTION.base, PRODUCTION.web)))
219 + );
220 +
221 + it.effect('[Given] the saved agent owns another key [Then] it names the regular login', () =>
222 + Effect.gen(function* () {
223 + yield* saveAgentIdentity('uak_other');
224 + expect(yield* unauthorizedHint(unauthorized('Auth_InvalidApiKey'))).toEqual(
225 + Option.some(
226 + 'If your login expired, log in again, then retry:\n> composio logout && composio login'
227 + )
228 + );
229 + }).pipe(Effect.provide(agentHomeLayer(PRODUCTION.base, PRODUCTION.web)))
230 + );
231 +});