Skip to content

The open alternative to Salesforce, designed for AI.

6.8 KB
Raw Blame
import { beforeEach, describe, expect, it, vi } from 'vitest';

import {
  SLACK_ENTITY_DETAILS_UNIVERSAL_IDENTIFIER,
  SLACK_ASSISTANT_REQUEST_UNIVERSAL_IDENTIFIER,
  SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
  SLACK_LINK_UNFURL_UNIVERSAL_IDENTIFIER,
} from 'src/constants/universal-identifiers';
import { slackEventsResolverHandler } from 'src/logic-functions/slack-events-resolver';
import { type SlackEventsRequestBody } from 'src/logic-functions/types/slack-events-request-body.type';
import { Response } from 'twenty-sdk/logic-function';

const {
  getSlackWebhookSecretMock,
  verifySignatureMock,
  resolveWorkspaceMock,
  findClaimedWorkspaceMock,
} = vi.hoisted(() => ({
  getSlackWebhookSecretMock: vi.fn(),
  verifySignatureMock: vi.fn(),
  resolveWorkspaceMock: vi.fn(),
  findClaimedWorkspaceMock: vi.fn(),
}));

vi.mock('src/logic-functions/utils/get-slack-webhook-secret', () => ({
  getSlackWebhookSecret: getSlackWebhookSecretMock,
}));

vi.mock('src/logic-functions/utils/verify-slack-request-signature', () => ({
  verifySlackRequestSignature: verifySignatureMock,
}));

vi.mock('src/logic-functions/utils/resolve-target-workspace-id', () => ({
  resolveTargetWorkspaceId: resolveWorkspaceMock,
}));

vi.mock('src/logic-functions/utils/find-claimed-workspace-id', () => ({
  findClaimedWorkspaceId: findClaimedWorkspaceMock,
}));

const buildRoutePayload = (body: SlackEventsRequestBody) => ({
  body,
  rawBody: JSON.stringify(body),
  headers: {
    'x-slack-signature': 'v0=signature',
    'x-slack-request-timestamp': '1700000000',
  },
  queryStringParameters: {},
  pathParameters: {},
  isBase64Encoded: false,
  requestContext: { http: { method: 'POST', path: '/' } },
  userWorkspaceId: null,
});

describe('slackEventsResolverHandler', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    getSlackWebhookSecretMock.mockReturnValue({
      success: true,
      secret: 'secret',
    });
    verifySignatureMock.mockReturnValue(true);
  });

  it('should route app_uninstalled to the install-revoked function in the claiming workspace', async () => {
    findClaimedWorkspaceMock.mockResolvedValue('workspace-1');

    const body: SlackEventsRequestBody = {
      type: 'event_callback',
      team_id: 'T123',
      event: { type: 'app_uninstalled' },
    };

    const result = await slackEventsResolverHandler(buildRoutePayload(body));

    expect(result).toEqual({
      workspaceId: 'workspace-1',
      targetLogicFunctionUniversalIdentifier:
        SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
      payload: body,
    });
  });

  it('should route tokens_revoked to the install-revoked function', async () => {
    findClaimedWorkspaceMock.mockResolvedValue('workspace-1');

    const result = await slackEventsResolverHandler(
      buildRoutePayload({
        type: 'event_callback',
        team_id: 'T123',
        event: { type: 'tokens_revoked', tokens: { bot: ['B123'] } },
      }),
    );

    expect(result).toMatchObject({
      targetLogicFunctionUniversalIdentifier:
        SLACK_INSTALL_REVOKED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
    });
  });

  it('should ack a removal event for an unclaimed team instead of erroring into a retry', async () => {
    findClaimedWorkspaceMock.mockResolvedValue(null);

    const result = await slackEventsResolverHandler(
      buildRoutePayload({
        type: 'event_callback',
        team_id: 'T123',
        event: { type: 'tokens_revoked', tokens: { bot: ['B123'] } },
      }),
    );

    expect(result).toBeInstanceOf(Response);
    expect((result as Response).body).toEqual({
      ok: true,
      skipped: 'No workspace claims this Slack team',
    });
  });

  it('should keep a removal event retryable when the claim lookup fails', async () => {
    findClaimedWorkspaceMock.mockRejectedValue(new Error('kv unavailable'));

    await expect(
      slackEventsResolverHandler(
        buildRoutePayload({
          type: 'event_callback',
          team_id: 'T123',
          event: { type: 'app_uninstalled' },
        }),
      ),
    ).rejects.toThrow('kv unavailable');
  });

  it('should throw on a removal event with no team_id', async () => {
    await expect(
      slackEventsResolverHandler(
        buildRoutePayload({
          type: 'event_callback',
          event: { type: 'app_uninstalled' },
        }),
      ),
    ).rejects.toThrow('no team_id');
    expect(findClaimedWorkspaceMock).not.toHaveBeenCalled();
  });

  it('should keep failing loudly when a message event targets an unclaimed team', async () => {
    resolveWorkspaceMock.mockRejectedValue(
      new Error('No workspace has claimed Slack team T123'),
    );

    await expect(
      slackEventsResolverHandler(
        buildRoutePayload({
          type: 'event_callback',
          team_id: 'T123',
          event: { type: 'message', channel_type: 'im' },
        }),
      ),
    ).rejects.toThrow('No workspace has claimed Slack team T123');
  });

  it('should route link_shared to the link unfurl function', async () => {
    resolveWorkspaceMock.mockResolvedValue('workspace-1');

    const body: SlackEventsRequestBody = {
      type: 'event_callback',
      team_id: 'T123',
      event: {
        type: 'link_shared',
        channel: 'C123',
        message_ts: '1700000000.000100',
        user: 'U123',
        links: [{ url: 'https://crm.example.com/object/person/uuid' }],
      },
    };

    const result = await slackEventsResolverHandler(buildRoutePayload(body));

    expect(result).toEqual({
      workspaceId: 'workspace-1',
      targetLogicFunctionUniversalIdentifier:
        SLACK_LINK_UNFURL_UNIVERSAL_IDENTIFIER,
      payload: body,
    });
  });

  it('should route entity_details_requested to the entity details function', async () => {
    resolveWorkspaceMock.mockResolvedValue('workspace-1');

    const body: SlackEventsRequestBody = {
      type: 'event_callback',
      team_id: 'T123',
      event: {
        type: 'entity_details_requested',
        user: 'U123',
        trigger_id: 'trigger-1',
        external_ref: { id: 'uuid', type: 'person' },
      },
    };

    const result = await slackEventsResolverHandler(buildRoutePayload(body));

    expect(result).toEqual({
      workspaceId: 'workspace-1',
      targetLogicFunctionUniversalIdentifier:
        SLACK_ENTITY_DETAILS_UNIVERSAL_IDENTIFIER,
      payload: body,
    });
  });

  it('should route other events unchanged', async () => {
    resolveWorkspaceMock.mockResolvedValue('workspace-1');

    const result = await slackEventsResolverHandler(
      buildRoutePayload({
        type: 'event_callback',
        team_id: 'T123',
        event: { type: 'message', channel_type: 'im' },
      }),
    );

    expect(result).toMatchObject({
      targetLogicFunctionUniversalIdentifier:
        SLACK_ASSISTANT_REQUEST_UNIVERSAL_IDENTIFIER,
    });
    expect(findClaimedWorkspaceMock).not.toHaveBeenCalled();
  });
});