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

next
ts 134 lines 5.78 KB
Raw
1 import { describe, expect, test } from 'bun:test';
2 import { ConfigProvider, Console, Effect } from 'effect';
3 import { NpmCli, publishNpm, type Distribution } from '../scripts/sdk-release/registry';
4 import { CommandError, sha256Hex } from '../scripts/sdk-release/runtime';
5 import { batch } from './sdk-release-controller-fixture';
6 import { runRelease, type Fetch } from './sdk-release-harness';
7
8 const ID_TOKEN_REQUEST_URL = 'https://token.actions.example.test/oidc?api-version=2.0';
9 const ID_TOKEN_REQUEST_TOKEN = 'actions-request-secret';
10 const ID_TOKEN = 'eyJhbGciOiJSUzI1NiJ9.eyJyZXBvc2l0b3J5IjoiQ29tcG9zaW9IUS9jb21wb3NpbyJ9.c2ln';
11 const NPM_TOKEN = `npm_${'x'.repeat(36)}`;
12 const EXCHANGE = 'https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/';
13 const REFUSAL = 'OIDC token exchange error - package not found';
14
15 const tarball = async (name: string, file: string): Promise<Distribution> => {
16 const bytes = new TextEncoder().encode(`original ${file}`);
17 return {
18 language: 'typescript',
19 name,
20 version: '1.0.1',
21 file,
22 bytes,
23 sha256: await runRelease(sha256Hex(bytes)),
24 };
25 };
26 const core = await tarball('@composio/core', 'composio-core-1.0.1.tgz');
27 const openai = await tarball('@composio/openai', 'composio-openai-1.0.1.tgz');
28
29 interface Sent {
30 readonly method: string;
31 readonly url: string;
32 readonly authorization: string | null;
33 }
34
35 /** GitHub's ID-token endpoint, npm's exchange endpoint, and a registry that serves neither tarball yet. */
36 const fakeRegistry = (refused: ReadonlySet<string>) => {
37 const sent: Sent[] = [];
38 const fetch: Fetch = async (input, init) => {
39 const url = String(input);
40 const method = init?.method ?? 'GET';
41 sent.push({ method, url, authorization: new Headers(init?.headers).get('authorization') });
42 if (url.startsWith('https://token.actions.example.test/'))
43 return new Response(JSON.stringify({ value: ID_TOKEN }));
44 if (url.startsWith(EXCHANGE))
45 return refused.has(decodeURIComponent(url.slice(EXCHANGE.length)))
46 ? new Response(JSON.stringify({ message: REFUSAL }), { status: 404 })
47 : new Response(JSON.stringify({ token: NPM_TOKEN }));
48 if (url.endsWith('/latest')) return new Response(JSON.stringify({ version: '1.0.0' }));
49 if (url.startsWith('https://registry.npmjs.org/')) return new Response('{}', { status: 404 });
50 throw new Error(`Unexpected request ${method} ${url}`);
51 };
52 return { sent, fetch };
53 };
54
55 const withActionsEnv = (env: Record<string, string>) =>
56 Effect.provideService(ConfigProvider.ConfigProvider, ConfigProvider.fromUnknown(env));
57
58 const actionsEnv = {
59 ACTIONS_ID_TOKEN_REQUEST_URL: ID_TOKEN_REQUEST_URL,
60 ACTIONS_ID_TOKEN_REQUEST_TOKEN: ID_TOKEN_REQUEST_TOKEN,
61 };
62
63 /** Runs `publishNpm` against fakes and returns what it printed, the npm commands, and the failure. */
64 const publish = async (files: Distribution[], fetch: Fetch, env: Record<string, string>) => {
65 const printed: string[] = [];
66 const commands: string[][] = [];
67 const capture = (...args: ReadonlyArray<unknown>) => printed.push(args.map(String).join(' '));
68 const console: Console.Console = Object.assign(Object.create(globalThis.console), {
69 log: capture,
70 info: capture,
71 warn: capture,
72 error: capture,
73 });
74 const failure = await runRelease(
75 publishNpm('.', batch, files).pipe(
76 withActionsEnv(env),
77 Effect.provideService(NpmCli, {
78 run: args => {
79 commands.push([...args]);
80 // Stops the run right after the first upload; later steps have their own tests.
81 return Effect.fail(new CommandError({ message: 'stopped after publish', exitCode: 1 }));
82 },
83 }),
84 Effect.provideService(Console.Console, console),
85 Effect.flip
86 ),
87 fetch
88 );
89 const message = failure instanceof Error ? failure.message : String(failure);
90 return { output: [...printed, message].join('\n'), message, commands };
91 };
92
93 const expectNoTokens = (output: string) => {
94 expect(output).not.toContain('eyJ');
95 expect(output).not.toContain('npm_');
96 expect(output).not.toContain(ID_TOKEN_REQUEST_TOKEN);
97 };
98
99 describe('npm trusted-publishing login preflight', () => {
100 test('a refused exchange for one package fails before any upload and names that package and npm’s reason', async () => {
101 const registry = fakeRegistry(new Set(['@composio/openai']));
102 const result = await publish([core, openai], registry.fetch, actionsEnv);
103 expect(result.commands).toEqual([]);
104 expect(result.message).toContain(`@composio/openai (404): ${REFUSAL}`);
105 expect(result.message).not.toContain('@composio/core (');
106 expect(result.output).toContain('@composio/core');
107 expectNoTokens(result.output);
108 });
109
110 test('accepted exchanges let publishing proceed without printing either token', async () => {
111 const registry = fakeRegistry(new Set());
112 const result = await publish([core, openai], registry.fetch, actionsEnv);
113 expect(result.commands[0]?.slice(0, 1)).toEqual(['publish']);
114 expect(result.message).toContain('stopped after publish');
115 expectNoTokens(result.output);
116 expect(registry.sent.slice(0, 3)).toEqual([
117 {
118 method: 'GET',
119 url: `${ID_TOKEN_REQUEST_URL}&audience=npm%3Aregistry.npmjs.org`,
120 authorization: `Bearer ${ID_TOKEN_REQUEST_TOKEN}`,
121 },
122 { method: 'POST', url: `${EXCHANGE}@composio%2fcore`, authorization: `Bearer ${ID_TOKEN}` },
123 { method: 'POST', url: `${EXCHANGE}@composio%2fopenai`, authorization: `Bearer ${ID_TOKEN}` },
124 ]);
125 });
126
127 test('without the GitHub ID-token request env the preflight names the missing id-token permission', async () => {
128 const registry = fakeRegistry(new Set());
129 const result = await publish([core], registry.fetch, {});
130 expect(result.message).toContain('id-token permission missing');
131 expect(result.commands).toEqual([]);
132 expect(registry.sent).toEqual([]);
133 });
134 });