Skip to content

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

9.6 KB
Raw Blame
import { afterEach, describe, expect, it, vi } from '@effect/vitest';
import * as os from 'node:os';
import * as path from 'node:path';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import * as FileSystem from '@effect/platform/FileSystem';
import * as Path from '@effect/platform/Path';
import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
import * as BunPath from '@effect/platform-bun/BunPath';
import { Effect, Layer } from 'effect';
import { Composio as RawComposioClient } from '@composio/client';
import {
  ComposioBlockedInternalUrlError,
  ComposioSensitiveFilePathBlockedError,
  MAX_URL_UPLOAD_SIZE_BYTES,
} from '@composio/core';
import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';

// Schema with a single `file_uploadable` attachment field — mirrors tools like
// GMAIL_SEND_EMAIL whose attachment is uploaded from a local path.
const inputSchema = {
  type: 'object',
  properties: {
    attachment: { file_uploadable: true, type: 'string' },
  },
};

const makeClient = (createPresignedURL = vi.fn()) =>
  Object.assign(new RawComposioClient({ apiKey: 'test' }), {
    files: { createPresignedURL },
  });

describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
  afterEach(() => {
    vi.unstubAllGlobals();
    vi.restoreAllMocks();
  });

  it('ignores malformed composition branches without hiding valid schemas', () => {
    expect(
      schemaHasFileUploadable({
        anyOf: ['not-a-schema', null, { file_uploadable: true }],
      })
    ).toBe(true);
    expect(schemaHasFileUploadable({ anyOf: ['not-a-schema', null] })).toBe(false);
  });

  it.effect('refuses to read/upload a path under a sensitive directory (~/.ssh/id_rsa)', () =>
    Effect.gen(function* () {
      const fsApi = yield* FileSystem.FileSystem;
      const pathApi = yield* Path.Path;
      const createPresignedURL = vi.fn();
      const client = makeClient(createPresignedURL);

      yield* Effect.promise(() =>
        expect(
          uploadToolInputFiles({
            fs: fsApi,
            path: pathApi,
            toolSlug: 'GMAIL_SEND_EMAIL',
            arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
            inputSchema,
            client,
          })
        ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError)
      );

      // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.
      expect(createPresignedURL).not.toHaveBeenCalled();
    }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
  );

  it.effect(
    'surfaces CLI-appropriate remediation, not the SDK-only opt-out, in the block error',
    () =>
      Effect.gen(function* () {
        const fsApi = yield* FileSystem.FileSystem;
        const pathApi = yield* Path.Path;
        const client = makeClient(vi.fn());

        // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the
        // error must not point users at that non-existent knob (issue #3763 review #2/#3).
        yield* Effect.promise(() =>
          expect(
            uploadToolInputFiles({
              fs: fsApi,
              path: pathApi,
              toolSlug: 'GMAIL_SEND_EMAIL',
              arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
              inputSchema,
              client,
            })
          ).rejects.toThrowError(/has no opt-out/i)
        );

        yield* Effect.promise(() =>
          expect(
            uploadToolInputFiles({
              fs: fsApi,
              path: pathApi,
              toolSlug: 'GMAIL_SEND_EMAIL',
              arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
              inputSchema,
              client,
            })
          ).rejects.not.toThrowError(/sensitiveFileUploadProtection/)
        );
      }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
  );

  it.effect('refuses credential-like basenames (.env) even outside a sensitive directory', () =>
    Effect.gen(function* () {
      const fsApi = yield* FileSystem.FileSystem;
      const pathApi = yield* Path.Path;
      const createPresignedURL = vi.fn();
      const client = makeClient(createPresignedURL);

      yield* Effect.promise(() =>
        expect(
          uploadToolInputFiles({
            fs: fsApi,
            path: pathApi,
            toolSlug: 'GMAIL_SEND_EMAIL',
            arguments_: { attachment: path.join(os.tmpdir(), '.env') },
            inputSchema,
            client,
          })
        ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError)
      );
      expect(createPresignedURL).not.toHaveBeenCalled();
    }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
  );

  it.effect('still uploads a normal (non-sensitive) local file', () => {
    const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
    const file = path.join(root, 'document.pdf');
    writeFileSync(file, 'hello');

    const createPresignedURL = vi.fn(async () => ({
      new_presigned_url: 'https://1.1.1.1/put',
      key: 's3key-123',
    }));
    const client = makeClient(createPresignedURL);
    vi.stubGlobal(
      'fetch',
      vi.fn(async () => ({ ok: true, statusText: 'OK' }))
    );

    return Effect.gen(function* () {
      const fsApi = yield* FileSystem.FileSystem;
      const pathApi = yield* Path.Path;
      const result = yield* Effect.promise(() =>
        uploadToolInputFiles({
          fs: fsApi,
          path: pathApi,
          toolSlug: 'GMAIL_SEND_EMAIL',
          arguments_: { attachment: file },
          inputSchema,
          client,
        })
      );

      expect(createPresignedURL).toHaveBeenCalledTimes(1);
      expect(createPresignedURL).toHaveBeenCalledWith(
        expect.objectContaining({ md5: '5d41402abc4b2a76b9719d911017c592' })
      );
      expect(result.attachment).toMatchObject({ s3key: 's3key-123', name: 'document.pdf' });
    }).pipe(
      Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
      Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
    );
  });
});

describe('uploadToolInputFiles — URL SSRF boundary', () => {
  afterEach(() => {
    vi.unstubAllGlobals();
    vi.restoreAllMocks();
  });

  it.effect('rejects an unsafe source before requesting an upload destination', () =>
    Effect.gen(function* () {
      const fsApi = yield* FileSystem.FileSystem;
      const pathApi = yield* Path.Path;
      const createPresignedURL = vi.fn();
      const client = makeClient(createPresignedURL);
      const sourceUrl = 'http://169.254.169.254/latest/meta-data/credentials';

      yield* Effect.promise(() =>
        expect(
          uploadToolInputFiles({
            fs: fsApi,
            path: pathApi,
            toolSlug: 'GMAIL_SEND_EMAIL',
            arguments_: { attachment: sourceUrl },
            inputSchema,
            client,
          })
        ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
      );

      expect(createPresignedURL).not.toHaveBeenCalled();
    }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
  );

  it.effect('rejects an unsafe presigned destination before sending file bytes', () => {
    const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
    const file = path.join(root, 'document.pdf');
    writeFileSync(file, 'hello');
    const fetchSpy = vi.spyOn(globalThis, 'fetch');
    const createPresignedURL = vi.fn(async () => ({
      new_presigned_url: 'http://127.0.0.1:8080/upload',
      key: 's3key-123',
    }));

    return Effect.gen(function* () {
      const fsApi = yield* FileSystem.FileSystem;
      const pathApi = yield* Path.Path;

      yield* Effect.promise(() =>
        expect(
          uploadToolInputFiles({
            fs: fsApi,
            path: pathApi,
            toolSlug: 'GMAIL_SEND_EMAIL',
            arguments_: { attachment: file },
            inputSchema,
            client: makeClient(createPresignedURL),
          })
        ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
      );

      expect(createPresignedURL).toHaveBeenCalledOnce();
      expect(fetchSpy).not.toHaveBeenCalled();
    }).pipe(
      Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
      Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
    );
  });
});

describe('uploadToolInputFiles — URL download size cap', () => {
  afterEach(() => {
    vi.unstubAllGlobals();
    vi.restoreAllMocks();
  });

  it.effect('rejects a remote file that declares a body above the cap before buffering it', () => {
    const createPresignedURL = vi.fn();
    const client = makeClient(createPresignedURL);
    const oversized = String(MAX_URL_UPLOAD_SIZE_BYTES + 1);
    vi.stubGlobal(
      'fetch',
      vi.fn(
        async () =>
          new Response('not the real body', {
            status: 200,
            headers: { 'content-length': oversized, 'content-type': 'application/octet-stream' },
          })
      )
    );

    return Effect.gen(function* () {
      const fsApi = yield* FileSystem.FileSystem;
      const pathApi = yield* Path.Path;

      yield* Effect.promise(() =>
        expect(
          uploadToolInputFiles({
            fs: fsApi,
            path: pathApi,
            toolSlug: 'GMAIL_SEND_EMAIL',
            arguments_: { attachment: 'https://1.1.1.1/large.bin' },
            inputSchema,
            client,
          })
        ).rejects.toThrow(/exceeds maximum allowed size/)
      );

      expect(createPresignedURL).not.toHaveBeenCalled();
    }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)));
  });
});