@devries-cameron20 / composio-1 / commits / a8cd0e779
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): refuse a directory project from outside the logged-in org (#5363)

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/5362; split from https://github.com/ComposioHQ/composio/pull/5334 - refuses directory projects outside the saved login’s org before any request; without a stored org, checks every page of the active key’s organizations - names a refused directory project in the resource-command fallback notice and keeps the refusal, membership, pagination, and fallback regressions together - keeps the passing operations, whoami, and agent-signin suites passing; no additional known-failure conversion belongs to this behavior - 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:21 UTC a8cd0e779fa2c2bcdb7bb809c90b16769f3a12e7
6 files changed +291 -14
ts/packages/cli/AGENTS.md
+1 -1
@@ -69,7 +69,7 @@ Rules:
69 - A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`, an expected failure whose message fits the tree) or `actingUserOption` / `devActingUserOption` (for commands that also run without one; the latter takes the developer project already resolved) in `surface.ts`; both name a fallback test user on stderr. A handler never reads `--user-id` or a test user id to resolve one itself, never prints that notice, and lets `MissingActingUserError` through instead of wrapping it in its own error (its tag is the `error_name` telemetry reports). An empty consumer user id counts as none. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
70 - Logic shared across groups belongs in `src/effects/` or `src/services/`, never in another command's directory.
71 - A group registers its subcommands with `withRegisteredSubcommands` (`src/commands/registration.ts`), never `Command.withSubcommands`, so each subcommand gets its command identity.
72 -- A command that needs a logged-in user pipes `withCommandMeta({ requiresLogin: true })` on itself or on its group entry, and the selected command checks it right after it began (`assertLoggedIn` in `src/effects/require-auth.ts`). Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`. A `dev` command that reads or writes a project's resources (auth configs, connected accounts, trigger instances, logs) resolves its developer project with `resolveDeveloperResourceProject` (`surface.ts`: `--project-name`'s, else the directory's, else the backend's default developer project, read once from session info and named on stderr even off a terminal, since these commands once let the backend pick it) and sends those requests on `ComposioClientSingleton.getFor` with it (`developerProjectClient`), or passes it to the repository method that takes it: `get()` carries no org or project, so the backend would pick the project per request. A command that always required a developer project (`dev playground-execute`, `dev triggers listen`, `dev connected-accounts list` and `link`) uses `resolveSurfaceProject('developer')` or `actingUser`, which fail with `ProjectResolutionError` instead.
72 +- A command that needs a logged-in user pipes `withCommandMeta({ requiresLogin: true })` on itself or on its group entry, and the selected command checks it right after it began (`assertLoggedIn` in `src/effects/require-auth.ts`). Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`. A `dev` command that reads or writes a project's resources (auth configs, connected accounts, trigger instances, logs) resolves its developer project with `resolveDeveloperResourceProject` (`surface.ts`: `--project-name`'s, else the directory's, else the backend's default developer project, read once from session info and named on stderr even off a terminal, since these commands once let the backend pick it) and sends those requests on `ComposioClientSingleton.getFor` with it (`developerProjectClient`), or passes it to the repository method that takes it: `get()` carries no org or project, so the backend would pick the project per request. A command that always required a developer project (`dev playground-execute`, `dev triggers listen`, `dev connected-accounts list` and `link`) uses `resolveSurfaceProject('developer')` or `actingUser`, which fail with `ProjectResolutionError` instead. Neither ever sends a request to a directory project outside the logged-in org (or, with no stored org, outside the key's orgs).
73 - A group entry is recognised by its place in the tree: `<dir>/<dir>.cmd.ts` or `<dir>/root-<dir>.cmd.ts` with other `.cmd.ts` files below `<dir>/`. The same name with nothing below it (`logout/logout.cmd.ts`) is a top-level command. Every command needs a test; a group entry does not, though one with a default action (`generate`) still gets one.
74
75 Legacy shape still present while commands migrate: `<group>/commands/<group>.<name>.cmd.ts` holding flags, handler, helpers, and errors in one file, and top-level `<name>.cmd.ts` doing the same. Migrate a command to the directory shape when you touch it for more than a one-line fix, one command per PR.
ts/packages/cli/CHANGELOG.md
+2
@@ -4,6 +4,8 @@
4
5 ### Patch Changes
6
7 +- A directory developer project must belong to the stored login's org, checked before any request. With no stored org, the CLI checks every page of the active key's org list. Resource commands refuse a project outside that boundary and name why they use the default developer project instead.
8 +
9 - `composio dev` resource commands now act on the directory's developer project or `--project-name`, rather than leaving the backend to choose. Without a directory project they keep working by resolving the default developer project once from session info and naming it on stderr, including in scripts. Project lookup failures preserve their cause and recovery advice.
10
11 - A command whose stdout reader stops reading early, as in
ts/packages/cli/src/services/command-project.ts
+62 -13
@@ -10,6 +10,7 @@ import {
10 DeveloperProjectNotFoundError,
11 AmbiguousDeveloperProjectNameError,
12 getSessionInfoByUserApiKey,
13 + userKeyBelongsToOrg,
14 } from './composio-account';
15
16 export type ProjectMode = 'consumer' | 'developer';
@@ -42,6 +43,7 @@ export class ProjectResolutionError extends Data.TaggedError('services/ProjectRe
43 | 'missing_developer_project'
44 | 'project_not_found'
45 | 'ambiguous_project_name'
46 + | 'org_mismatch'
47 | 'request_failed';
48 readonly message: string;
49 readonly cause?: unknown;
@@ -81,15 +83,37 @@ const normalizeLookupError = <E>(error: E): ProjectResolutionError | E => {
83 };
84
85 /** Why the working directory's developer project cannot serve a command. */
84 -type DirectoryProjectRefusal = { readonly reason: 'missing_developer_project' };
86 +type DirectoryProjectRefusal =
87 + | { readonly reason: 'missing_developer_project' }
88 + | {
89 + readonly reason: 'org_mismatch';
90 + readonly directoryOrgId: string;
91 + readonly storedOrgId: Option.Option<string>;
92 + };
93
86 -const refusalError = (_refusal: DirectoryProjectRefusal): ProjectResolutionError =>
87 - new ProjectResolutionError({
88 - reason: 'missing_developer_project',
89 - message: 'No developer project configured for this directory. Run `composio dev init`.',
90 - });
94 +const refusalError = (refusal: DirectoryProjectRefusal): ProjectResolutionError =>
95 + refusal.reason === 'missing_developer_project'
96 + ? new ProjectResolutionError({
97 + reason: 'missing_developer_project',
98 + message: 'No developer project configured for this directory. Run `composio dev init`.',
99 + })
100 + : new ProjectResolutionError({
101 + reason: 'org_mismatch',
102 + message: Option.match(refusal.storedOrgId, {
103 + onSome: storedOrgId =>
104 + `This directory is set up for a developer project in org "${refusal.directoryOrgId}", not in the org you are logged in to ("${storedOrgId}"). Run \`composio orgs switch\` to use that org, \`composio dev init\` to set this directory up in yours, or pass --project-name.`,
105 + onNone: () =>
106 + `This directory is set up for a developer project in org "${refusal.directoryOrgId}", which your API key cannot access. Run \`composio dev init\` to set it up in one of your orgs, or pass --project-name.`,
107 + }),
108 + });
109
92 -/** The developer project configured for the working directory. */
110 +/**
111 + * The developer project the working directory is set up for, or why it cannot be used. A cloned
112 + * repository's `.composio/` must not send the user's requests, and the credentials some of them
113 + * carry, to a project its author chose, so the project must be in the org the user is logged in
114 + * to. Without a stored org, as with a key from `COMPOSIO_USER_API_KEY`, it must be in an org the
115 + * key belongs to.
116 + */
117 const localDeveloperProject = (params: {
118 projectContext: ProjectContext['Service'];
119 apiKey: string;
@@ -101,6 +125,17 @@ const localDeveloperProject = (params: {
125 return Result.fail<DirectoryProjectRefusal>({ reason: 'missing_developer_project' });
126 }
127 const { orgId, projectId, projectName } = localProject.value;
128 + const allowed = yield* Option.match(params.storedOrgId, {
129 + onSome: storedOrgId => Effect.succeed(storedOrgId === orgId),
130 + onNone: () => userKeyBelongsToOrg({ apiKey: params.apiKey, orgId }),
131 + });
132 + if (!allowed) {
133 + return Result.fail<DirectoryProjectRefusal>({
134 + reason: 'org_mismatch',
135 + directoryOrgId: orgId,
136 + storedOrgId: params.storedOrgId,
137 + });
138 + }
139 return Result.succeed({
140 orgId,
141 projectId,
@@ -117,12 +152,25 @@ const resolveLocalDeveloperProject = (params: Parameters<typeof localDeveloperPr
152 );
153
154 /** What is wrong with the directory's developer project, as the start of a sentence. */
120 -const refusalSummary = (_refusal: DirectoryProjectRefusal): string =>
121 - 'No developer project is set up for this directory';
155 +const refusalSummary = (refusal: DirectoryProjectRefusal): string =>
156 + refusal.reason === 'missing_developer_project'
157 + ? 'No developer project is set up for this directory'
158 + : Option.match(refusal.storedOrgId, {
159 + onSome: storedOrgId =>
160 + `This directory's developer project is in org "${refusal.directoryOrgId}", not the org you are logged in to ("${storedOrgId}")`,
161 + onNone: () =>
162 + `This directory's developer project is in org "${refusal.directoryOrgId}", which your API key cannot access`,
163 + });
164
123 -/** The command that lets the directory's developer project serve the next run. */
124 -const refusalRemedy = (_refusal: DirectoryProjectRefusal): string =>
125 - 'Run `composio dev init` to choose one, or pass --project-name.';
165 +/** The command that lets the directory's own developer project serve the next run. */
166 +const refusalRemedy = (refusal: DirectoryProjectRefusal): string =>
167 + refusal.reason === 'missing_developer_project'
168 + ? 'Run `composio dev init` to choose one, or pass --project-name.'
169 + : Option.match(refusal.storedOrgId, {
170 + onSome: () =>
171 + "Run `composio orgs switch` to use the directory's org, or `composio dev init` to set this directory up in yours.",
172 + onNone: () => 'Run `composio dev init` to set this directory up in one of your orgs.',
173 + });
174
175 /** The stderr notice naming the default developer project a command uses instead. */
176 const defaultProjectNotice = (
@@ -236,7 +284,8 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
284 * (whose failures stay failures), else the directory's, else the backend's default developer
285 * project (`defaultDeveloperProject`). `notice` says, for stderr, why the default stands in and
286 * which project it is; it is none when the command uses the project it was given. The default
239 - * never stands in for a `--project-name` that cannot be resolved.
287 + * never stands in for a `--project-name` that cannot be resolved, and no request ever names a
288 + * directory project that fails the org check.
289 */
290 export const resolveDeveloperProjectOrDefault = (params: { projectName?: string }) =>
291 Effect.gen(function* () {
ts/packages/cli/src/services/composio-account.ts
+29
@@ -89,6 +89,35 @@ export const listOrganizations = (params: {
89 };
90 });
91
92 +/**
93 + * Whether the user key belongs to `orgId`, reading every page of its org list. A missing org
94 + * is only known after the last page.
95 + */
96 +export const userKeyBelongsToOrg = (params: {
97 + apiKey: string;
98 + orgId: string;
99 +}): Effect.Effect<boolean, ClientError, ComposioClientSingleton> =>
100 + Effect.gen(function* () {
101 + const clientSingleton = yield* ComposioClientSingleton;
102 + const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
103 + const fromPage = (cursor: string | undefined): Effect.Effect<boolean, ClientError> =>
104 + client.org
105 + .list(
106 + { limit: 100, ...(cursor === undefined ? {} : { cursor }) },
107 + { ...idempotent, ...validated }
108 + )
109 + .pipe(
110 + Effect.flatMap(page =>
111 + page.organizations.some(organization => organization.id === params.orgId)
112 + ? Effect.succeed(true)
113 + : page.next_cursor
114 + ? fromPage(page.next_cursor)
115 + : Effect.succeed(false)
116 + )
117 + );
118 + return yield* fromPage(undefined);
119 + });
120 +
121 /**
122 * Lists projects for a specific organization.
123 *
ts/packages/cli/test/src/commands/auth-configs/list/auth-configs.list.cmd.test.ts
+37
@@ -1,5 +1,6 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 +import { ComposioUserContext } from 'src/services/user-context';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
6 import type { AuthConfigItem } from 'src/models/auth-configs';
@@ -242,4 +243,40 @@ describe('CLI: composio dev auth-configs list acts on the developer project', ()
243 })
244 );
245 });
246 +
247 + layer(
248 + TestLive({
249 + ...inProject,
250 + authConfigsData,
251 + accountData: defaultDeveloperProjectAccountData(),
252 + })
253 + )(it => {
254 + it.effect(
255 + '[Given] a directory set up for a project in another org [Then] never names it, using the default project',
256 + () =>
257 + Effect.gen(function* () {
258 + const userContext = yield* ComposioUserContext;
259 + yield* userContext.login('test_api_key', 'org_mine');
260 + const terminal = redirectedTerminalUI();
261 + const { exitCode, calls } = yield* runRecordingRepositoryScopes(
262 + ['dev', 'auth-configs', 'list'],
263 + terminal.layer
264 + );
265 +
266 + expect(exitCode).toBe(0);
267 + expect(terminal.stderr()).toContain(
268 + 'Warning: This directory\'s developer project is in org "org_test", not the org you are logged in to ("org_mine"); using "newest-project" (proj_newest)'
269 + );
270 + expect(calls).toEqual([
271 + {
272 + method: 'listAuthConfigs',
273 + scope: expect.objectContaining({
274 + orgId: 'org_mine',
275 + projectId: DEFAULT_PROJECT_SCOPE.projectId,
276 + }),
277 + },
278 + ]);
279 + })
280 + );
281 + });
282 });
ts/packages/cli/test/src/services/command-project.test.ts
+160
@@ -95,6 +95,20 @@ const localProject = (orgId: string) =>
95 })
96 );
97
98 +const orgList = (ids: ReadonlyArray<string>, nextCursor: string | null = null) =>
99 + jsonResponse({
100 + organizations: ids.map(id => ({
101 + id,
102 + name: id,
103 + created_at: '2024-01-01T00:00:00.000Z',
104 + updated_at: '2024-01-01T00:00:00.000Z',
105 + })),
106 + next_cursor: nextCursor,
107 + total_pages: 1,
108 + current_page: 1,
109 + total_items: ids.length,
110 + });
111 +
112 describe('resolveCommandProject', () => {
113 afterEach(() => {
114 vi.restoreAllMocks();
@@ -127,6 +141,72 @@ describe('resolveCommandProject', () => {
141 }).pipe(Effect.provide(testLayer))
142 );
143
144 + it.effect('refuses a directory project outside the logged-in org without a request', () =>
145 + Effect.gen(function* () {
146 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
147 +
148 + const error = yield* resolveCommandProject({ mode: 'developer' }).pipe(Effect.flip);
149 +
150 + expect(error).toMatchObject({ reason: 'org_mismatch' });
151 + expect(error.message).toContain('"org_other"');
152 + expect(error.message).toContain('composio orgs switch');
153 + expect(fetchSpy).not.toHaveBeenCalled();
154 + }).pipe(
155 + Effect.provide(
156 + Layer.mergeAll(singleton, userContext(Option.some('org_1')), localProject('org_other'))
157 + )
158 + )
159 + );
160 +
161 + it.effect('resolves a directory project in the logged-in org without a request', () =>
162 + Effect.gen(function* () {
163 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
164 + const project = yield* resolveCommandProject({ mode: 'developer' });
165 + expect(fetchSpy).not.toHaveBeenCalled();
166 +
167 + expect(project).toMatchObject({
168 + orgId: 'org_1',
169 + projectId: 'pr_local',
170 + source: 'developer-local-config',
171 + });
172 + }).pipe(
173 + Effect.provide(
174 + Layer.mergeAll(singleton, userContext(Option.some('org_1')), localProject('org_1'))
175 + )
176 + )
177 + );
178 +
179 + it.effect(
180 + 'checks a directory project against every page of the key orgs when none is stored',
181 + () =>
182 + Effect.gen(function* () {
183 + const fetchSpy = vi
184 + .spyOn(globalThis, 'fetch')
185 + .mockResolvedValueOnce(orgList(['org_a'], 'cursor_2'))
186 + .mockResolvedValueOnce(orgList(['org_2']));
187 +
188 + const project = yield* resolveCommandProject({ mode: 'developer' });
189 +
190 + expect(project).toMatchObject({ orgId: 'org_2', projectId: 'pr_local' });
191 + expect(fetchSpy).toHaveBeenCalledTimes(2);
192 + }).pipe(
193 + Effect.provide(Layer.mergeAll(singleton, userContext(Option.none()), localProject('org_2')))
194 + )
195 + );
196 +
197 + it.effect('refuses a directory project from another org when no org is stored', () =>
198 + Effect.gen(function* () {
199 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(orgList(['org_mine']));
200 +
201 + const error = yield* resolveCommandProject({ mode: 'developer' }).pipe(Effect.flip);
202 +
203 + expect(error).toMatchObject({ reason: 'org_mismatch' });
204 + expect(error.message).toContain('cannot access');
205 + }).pipe(
206 + Effect.provide(Layer.mergeAll(singleton, userContext(Option.none()), localProject('org_2')))
207 + )
208 + );
209 +
210 it.effect('turns an unknown project name into project_not_found with the remedy', () =>
211 Effect.gen(function* () {
212 vi.spyOn(globalThis, 'fetch').mockResolvedValue(projectsPage(['Other']));
@@ -296,6 +376,66 @@ describe('resolveDeveloperProjectOrDefault', () => {
376 }).pipe(Effect.provide(Layer.mergeAll(singleton, userContext(Option.none()), noLocalProject)))
377 );
378
379 + it.effect(
380 + 'ignores a directory project outside the logged-in org and names it in the notice',
381 + () =>
382 + Effect.gen(function* () {
383 + const fetchSpy = vi
384 + .spyOn(globalThis, 'fetch')
385 + .mockResolvedValue(defaultProjectInfo('org_1'));
386 +
387 + const { project, notice } = yield* resolveDeveloperProjectOrDefault({});
388 +
389 + expect(project).toMatchObject({
390 + orgId: 'org_1',
391 + projectId: 'pr_newest',
392 + source: 'developer-default',
393 + });
394 + expect(notice).toEqual(
395 + Option.some(
396 + 'This directory\'s developer project is in org "org_other", not the org you are logged in to ("org_1"); using "Newest App" (pr_newest), the newest developer project in the org you are logged in to, instead. Run `composio orgs switch` to use the directory\'s org, or `composio dev init` to set this directory up in yours.'
397 + )
398 + );
399 + // No request ever names the directory's project.
400 + expect(fetchSpy).toHaveBeenCalledTimes(1);
401 + expect(requestOf(fetchSpy.mock.calls[0]).headers.get('x-org-id')).toBe('org_1');
402 + }).pipe(
403 + Effect.provide(
404 + Layer.mergeAll(singleton, userContext(Option.some('org_1')), localProject('org_other'))
405 + )
406 + )
407 + );
408 +
409 + it.effect(
410 + 'ignores a directory project in an org the key cannot access when no org is stored',
411 + () =>
412 + Effect.gen(function* () {
413 + const fetchSpy = vi
414 + .spyOn(globalThis, 'fetch')
415 + .mockResolvedValueOnce(orgList(['org_mine']))
416 + .mockResolvedValueOnce(defaultProjectInfo('org_mine'));
417 +
418 + const { project, notice } = yield* resolveDeveloperProjectOrDefault({});
419 +
420 + expect(project).toMatchObject({
421 + orgId: 'org_mine',
422 + projectId: 'pr_newest',
423 + source: 'developer-default',
424 + });
425 + expect(notice).toEqual(
426 + Option.some(
427 + 'This directory\'s developer project is in org "org_2", which your API key cannot access; using "Newest App" (pr_newest), the newest developer project in the org you joined most recently, instead. Run `composio dev init` to set this directory up in one of your orgs.'
428 + )
429 + );
430 + expect(fetchSpy).toHaveBeenCalledTimes(2);
431 + const sessionRequest = requestOf(fetchSpy.mock.calls[1]);
432 + expect(sessionRequest.path).toBe(SESSION_INFO_PATH);
433 + expect(sessionRequest.headers.has('x-org-id')).toBe(false);
434 + }).pipe(
435 + Effect.provide(Layer.mergeAll(singleton, userContext(Option.none()), localProject('org_2')))
436 + )
437 + );
438 +
439 it.effect.each([
440 {
441 given: 'session info without a project',
@@ -326,6 +466,26 @@ describe('resolveDeveloperProjectOrDefault', () => {
466 }).pipe(Effect.provide(testLayer))
467 );
468
469 + it.effect('names the ignored directory project when no default can be found either', () =>
470 + Effect.gen(function* () {
471 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
472 + jsonResponse({ ...makeSessionInfo(), project: null })
473 + );
474 +
475 + const error = yield* resolveDeveloperProjectOrDefault({}).pipe(Effect.flip);
476 +
477 + expect(error).toMatchObject({
478 + reason: 'missing_developer_project',
479 + message:
480 + 'This directory\'s developer project is in org "org_other", not the org you are logged in to ("org_1"), and no developer project was found in your org to use instead. Run `composio dev init` to set one up.',
481 + });
482 + }).pipe(
483 + Effect.provide(
484 + Layer.mergeAll(singleton, userContext(Option.some('org_1')), localProject('org_other'))
485 + )
486 + )
487 + );
488 +
489 it.effect.each([
490 { status: 401, message: 'Invalid API key' },
491 { status: 403, message: 'Access denied' },