feat: add Cloudflare URL Scanner for malicious URL detection (#26387)

* feat: add Cloudflare URL Scanner integration for malicious URL detection

- Add MALICIOUS_URL_IN_WORKFLOW to LockReason enum
- Add URL_SCANNING_ENABLED constant for feature flag
- Create urlScanner.ts utility for Cloudflare Radar URL Scanner API
- Create scanWorkflowUrls task for async URL scanning with polling
- Integrate URL scanning into scanWorkflowBody task
- Add URL scanning for event type redirect URLs
- Lock user accounts when malicious URLs are detected
- Fix pre-existing lint issues (parseInt radix, optional chaining)

Co-Authored-By: [email protected] <[email protected]>

* fix: address biome lint warnings and TypeScript iterator errors

- Wrap iterators with Array.from() to fix TS2802 errors
- Add biome-ignore comments for process.env usage
- Extract helper functions to reduce function length
- Move exports to end of file per useExportsLast rule
- Remove problematic imports that cause TypeScript errors

Co-Authored-By: [email protected] <[email protected]>

* fix: address cubic-dev-ai review comments for URL scanning

- Fix P0: Re-fetch workflow steps before scheduling notifications to use actual verifiedAt values from database instead of overriding with new Date()
- Fix P1: Mark workflow step as verified in submitWorkflowStepForUrlScanning when URL scanning is disabled or no URLs found
- Fix P1: Add whitelistWorkflows parameter to submitUrlForUrlScanning for consistency
- Fix P2: Preserve URL context in error results in urlScanner.ts scanUrls function

Co-Authored-By: [email protected] <[email protected]>

* fix: add select clause to Prisma query for workflow steps

Address cubic-dev-ai P2 comment: Use select to fetch only the required
fields (id, action, sendTo, emailSubject, reminderBody, template, sender,
verifiedAt) instead of fetching all columns from workflowStep table.

Co-Authored-By: [email protected] <[email protected]>

* fix: add select clause to Prisma query in scanWorkflowBody.ts

Address cubic-dev-ai P2 review comment: Use select to fetch only the
required fields (id, action, sendTo, emailSubject, reminderBody,
template, sender, verifiedAt) instead of fetching all columns.

Co-Authored-By: [email protected] <[email protected]>

* test: add unit tests for URL scanning functionality

- Add tests for urlScanner.ts (extractUrlsFromHtml, isUrlScanningEnabled)
- Add tests for scanWorkflowUrls.ts (happy/unhappy paths for URL scanning task)
- Add tests for scanWorkflowBody.ts (happy/unhappy paths for workflow body scanning)

Tests cover:
- URL extraction from HTML content
- URL normalization and deduplication
- Handling of malicious URLs and user locking
- Fail-open behavior for API errors
- Whitelisted user handling
- Iffy spam detection integration

Co-Authored-By: [email protected] <[email protected]>

* test: remove incomplete test that provides no value

Removed the 'should mark all steps as verified when neither Iffy nor URL scanning is enabled' test as it used vi.doMock() which doesn't work after module import, had no assertions, and gave false confidence in test coverage.

Co-Authored-By: [email protected] <[email protected]>

* refactor: use Cloudflare bulk scanning endpoint to reduce API quota usage

- Added submitUrlsForBulkScanning function that uses /urlscanner/v2/bulk endpoint
- Updated scanUrls to use bulk submission instead of individual URL submissions
- Bulk endpoint accepts up to 100 URLs per request, batching is handled automatically
- Reduces API quota usage as suggested by keithwillcode

Co-Authored-By: [email protected] <[email protected]>

* Update packages/features/tasker/tasks/scanWorkflowUrls.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix: address cubic-dev-ai review comments

- P1: Sanitize URLs before logging to prevent exposing sensitive query parameters
- P2: Extract handleUrlScanningForStep helper function to reduce code duplication
- P2: Use vi.stubGlobal for fetch mock in tests for proper cleanup

Co-Authored-By: [email protected] <[email protected]>

* fix: address volnei review comments on PR #26387

- Move vi.unstubAllGlobals() to afterEach hook in iffyScanBody tests
- Restore updateMany optimization when URL scanning is disabled

Co-Authored-By: [email protected] <[email protected]>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Volnei Munhoz <[email protected]>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-01-21 12:28:57 -03:00
1 parent a03722fd7f
commit cfb1db45b2
11 files changed
+1959 -23

No files matched your search

+1
View File
@@ -25,6 +25,7 @@ type TaskPayloads = {
createCRMEvent: z.infer<typeof import("./tasks/crm/schema").createCRMEventSchema>;
sendWorkflowEmails: z.infer<typeof import("./tasks/sendWorkflowEmails").ZSendWorkflowEmailsSchema>;
scanWorkflowBody: z.infer<typeof import("./tasks/scanWorkflowBody").scanWorkflowBodySchema>;
scanWorkflowUrls: z.infer<typeof import("./tasks/scanWorkflowUrls").scanWorkflowUrlsSchema>;
sendAnalyticsEvent: z.infer<typeof import("./tasks/analytics/schema").sendAnalyticsEventSchema>;
executeAIPhoneCall: {
workflowReminderId: number;
+1
View File
@@ -27,6 +27,7 @@ const tasks: Record<TaskTypes, () => Promise<TaskHandler>> = {
createCRMEvent: () => import("./crm/createCRMEvent").then((module) => module.createCRMEvent),
sendWorkflowEmails: () => import("./sendWorkflowEmails").then((module) => module.sendWorkflowEmails),
scanWorkflowBody: () => import("./scanWorkflowBody").then((module) => module.scanWorkflowBody),
scanWorkflowUrls: () => import("./scanWorkflowUrls").then((module) => module.scanWorkflowUrls),
sendAnalyticsEvent: () =>
import("./analytics/sendAnalyticsEvent").then((module) => module.sendAnalyticsEvent),
executeAIPhoneCall: () => import("./executeAIPhoneCall").then((module) => module.executeAIPhoneCall),
@@ -4,11 +4,14 @@ import { getTemplateBodyForAction } from "@calcom/features/ee/workflows/lib/acti
import compareReminderBodyToTemplate from "@calcom/features/ee/workflows/lib/compareReminderBodyToTemplate";
import { scheduleWorkflowNotifications } from "@calcom/features/ee/workflows/lib/scheduleWorkflowNotifications";
import { Task } from "@calcom/features/tasker/repository";
import { URL_SCANNING_ENABLED } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import prisma from "@calcom/prisma";
import { submitWorkflowStepForUrlScanning } from "./scanWorkflowUrls";
export const scanWorkflowBodySchema = z.object({
userId: z.number(),
// deprecated: use workflowStepId instead
@@ -19,6 +22,29 @@ export const scanWorkflowBodySchema = z.object({
const log = logger.getSubLogger({ prefix: ["[tasker] scanWorkflowBody"] });
/**
* Helper function to handle URL scanning or verification for a workflow step.
* Extracts the duplicated logic from both Iffy-enabled and Iffy-disabled paths.
*/
async function handleUrlScanningForStep(
workflowStep: { id: number; reminderBody: string | null; workflow: { user: { whitelistWorkflows: boolean } | null } },
userId: number
): Promise<void> {
if (URL_SCANNING_ENABLED && workflowStep.reminderBody) {
await submitWorkflowStepForUrlScanning(
workflowStep.id,
workflowStep.reminderBody,
userId,
workflowStep.workflow.user?.whitelistWorkflows ?? false
);
} else {
await prisma.workflowStep.update({
where: { id: workflowStep.id },
data: { verifiedAt: new Date() },
});
}
}
export async function scanWorkflowBody(payload: string) {
const { workflowStepIds, userId, createdAt, workflowStepId } = scanWorkflowBodySchema.parse(
JSON.parse(payload)
@@ -118,31 +144,32 @@ export async function scanWorkflowBody(payload: string) {
log.warn(`For whitelisted user, workflow step ${workflowStep.id} marked as spam`);
}
await prisma.workflowStep.update({
// Handle URL scanning or mark as verified
await handleUrlScanningForStep(workflowStep, userId);
}
}
if (!process.env.IFFY_API_KEY) {
log.info("IFFY_API_KEY not set, skipping Iffy spam scan");
if (!URL_SCANNING_ENABLED) {
await prisma.workflowStep.updateMany({
where: {
id: workflowStep.id,
id: {
in: stepIdsToScan,
},
},
data: {
verifiedAt: new Date(),
},
});
} else {
for (const workflowStep of workflowSteps) {
await handleUrlScanningForStep(workflowStep, userId);
}
}
}
if (!process.env.IFFY_API_KEY) {
log.info("IFFY_API_KEY not set, skipping scan");
await prisma.workflowStep.updateMany({
where: {
id: {
in: stepIdsToScan,
},
},
data: {
verifiedAt: new Date(),
},
});
}
const workflow = await prisma.workflow.findFirst({
where: {
steps: {
@@ -166,13 +193,28 @@ export async function scanWorkflowBody(payload: string) {
const isOrg = !!workflow?.team?.isOrganization;
const updatedWorkflowSteps = await prisma.workflowStep.findMany({
where: {
id: {
in: stepIdsToScan,
},
},
select: {
id: true,
action: true,
sendTo: true,
emailSubject: true,
reminderBody: true,
template: true,
sender: true,
verifiedAt: true,
},
});
await scheduleWorkflowNotifications({
activeOn: workflow.activeOn.map((activeOn) => activeOn.eventTypeId) ?? [],
isOrg,
workflowSteps: workflowSteps.map((step) => ({
...step,
verifiedAt: new Date(),
})),
workflowSteps: updatedWorkflowSteps,
time: workflow.time,
timeUnit: workflow.timeUnit,
trigger: workflow.trigger,
@@ -0,0 +1,277 @@
import z from "zod";
import { LockReason, lockUser } from "@calcom/features/ee/api-keys/lib/autoLock";
import {
extractUrlsFromHtml,
getScanResult,
isUrlScanningEnabled,
submitUrlForScanning,
} from "@calcom/features/ee/workflows/lib/urlScanner";
import tasker from "@calcom/features/tasker";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
export const scanWorkflowUrlsSchema = z.object({
userId: z.number(),
workflowStepId: z.number().optional(),
eventTypeId: z.number().optional(),
// URLs to scan (extracted from workflow body or event type redirect URL)
urls: z.array(z.string()).optional(),
// Scan IDs from Cloudflare (for polling results)
pendingScans: z
.array(
z.object({
url: z.string(),
scanId: z.string(),
})
)
.optional(),
// Number of poll attempts made
pollAttempts: z.number().optional(),
createdAt: z.string().optional(),
whitelistWorkflows: z.boolean().optional(),
});
const log = logger.getSubLogger({ prefix: ["[tasker] scanWorkflowUrls"] });
/**
* Sanitizes a URL for logging by removing query parameters that may contain sensitive data.
*/
function sanitizeUrlForLogging(url: string): string {
try {
const parsed = new URL(url);
// biome-ignore lint/nursery/noTernary: Simple ternary for conditional suffix
return `${parsed.protocol}//${parsed.host}${parsed.pathname}${parsed.search ? "[query_params_redacted]" : ""}`;
} catch {
return "[invalid_url]";
}
}
const MAX_POLL_ATTEMPTS = 10;
const POLL_DELAY_MS = 15000; // 15 seconds
export async function scanWorkflowUrls(payload: string) {
const parsed = scanWorkflowUrlsSchema.parse(JSON.parse(payload));
const {
userId,
workflowStepId,
eventTypeId,
urls,
pendingScans,
pollAttempts = 0,
whitelistWorkflows,
} = parsed;
if (!isUrlScanningEnabled()) {
log.info("URL scanning is not enabled, skipping");
// Mark workflow step as verified if this was for a workflow
if (workflowStepId) {
await markWorkflowStepVerified(workflowStepId);
}
return;
}
// Phase 1: Submit URLs for scanning
if (urls && urls.length > 0 && !pendingScans) {
log.info(`Submitting ${urls.length} URLs for scanning`, { userId, workflowStepId, eventTypeId });
const newPendingScans: Array<{ url: string; scanId: string }> = [];
const failedUrls: string[] = [];
for (const url of urls) {
const result = await submitUrlForScanning(url);
if ("error" in result) {
log.error(`Failed to submit URL for scanning: ${result.error}`, { url: sanitizeUrlForLogging(url) });
failedUrls.push(url);
} else {
newPendingScans.push({ url, scanId: result.scanId });
}
}
if (newPendingScans.length === 0) {
// All submissions failed, mark as verified (fail-open for submission errors)
log.warn("All URL submissions failed, marking as verified", { userId, workflowStepId, eventTypeId });
if (workflowStepId) {
await markWorkflowStepVerified(workflowStepId);
}
return;
}
// Schedule follow-up task to poll for results
const scheduledAt = new Date(Date.now() + POLL_DELAY_MS);
await tasker.create(
"scanWorkflowUrls",
{
userId,
workflowStepId,
eventTypeId,
pendingScans: newPendingScans,
pollAttempts: 0,
whitelistWorkflows,
},
{ scheduledAt }
);
return;
}
// Phase 2: Poll for scan results
if (pendingScans && pendingScans.length > 0) {
if (pollAttempts >= MAX_POLL_ATTEMPTS) {
log.warn("Max poll attempts reached, marking as verified", {
userId,
workflowStepId,
eventTypeId,
pendingScans,
});
// Fail-open: mark as verified if we can't get results
if (workflowStepId) {
await markWorkflowStepVerified(workflowStepId);
}
return;
}
const stillPending: Array<{ url: string; scanId: string }> = [];
const maliciousUrls: string[] = [];
for (const { url, scanId } of pendingScans) {
const result = await getScanResult(scanId);
if (result === null) {
// Still pending
stillPending.push({ url, scanId });
} else if (result.status === "error") {
log.error(`Error getting scan result: ${result.error}`, { url: sanitizeUrlForLogging(url), scanId });
// Don't add to stillPending, treat as non-malicious (fail-open for errors)
} else if (result.malicious) {
maliciousUrls.push(url);
log.warn(`Malicious URL detected`, {
url: sanitizeUrlForLogging(url),
scanId,
categories: result.categories,
userId,
workflowStepId,
eventTypeId,
});
}
}
// If malicious URLs found, lock the user (unless whitelisted)
if (maliciousUrls.length > 0) {
if (whitelistWorkflows) {
log.warn(`Skipping lock for whitelisted user with malicious URLs`, {
userId,
maliciousUrlCount: maliciousUrls.length,
workflowStepId,
eventTypeId,
});
} else {
log.warn(`Locking user due to malicious URLs`, {
userId,
maliciousUrlCount: maliciousUrls.length,
workflowStepId,
eventTypeId,
});
await lockUser("userId", String(userId), LockReason.MALICIOUS_URL_IN_WORKFLOW);
}
// Don't mark as verified - the workflow step should not be sent
return;
}
// If still pending, schedule another poll
if (stillPending.length > 0) {
const scheduledAt = new Date(Date.now() + POLL_DELAY_MS);
await tasker.create(
"scanWorkflowUrls",
{
userId,
workflowStepId,
eventTypeId,
pendingScans: stillPending,
pollAttempts: pollAttempts + 1,
whitelistWorkflows,
},
{ scheduledAt }
);
return;
}
// All scans completed and no malicious URLs found
log.info("All URL scans completed, no malicious URLs found", { userId, workflowStepId, eventTypeId });
if (workflowStepId) {
await markWorkflowStepVerified(workflowStepId);
}
}
}
async function markWorkflowStepVerified(workflowStepId: number) {
await prisma.workflowStep.update({
where: { id: workflowStepId },
data: { verifiedAt: new Date() },
});
log.info(`Marked workflow step as verified`, { workflowStepId });
}
/**
* Helper function to extract URLs from workflow step body and submit for scanning.
* Called from scanWorkflowBody task or directly from workflow update handler.
*/
export async function submitWorkflowStepForUrlScanning(
workflowStepId: number,
reminderBody: string,
userId: number,
whitelistWorkflows?: boolean
): Promise<void> {
if (!isUrlScanningEnabled()) {
// URL scanning is disabled, mark as verified since there's nothing to scan
await markWorkflowStepVerified(workflowStepId);
return;
}
const urls = extractUrlsFromHtml(reminderBody);
if (urls.length === 0) {
// No URLs found, mark as verified since there's nothing to scan
log.info("No URLs found in workflow step body, marking as verified", { workflowStepId });
await markWorkflowStepVerified(workflowStepId);
return;
}
log.info(`Found ${urls.length} URLs in workflow step body, submitting for scanning`, {
workflowStepId,
urlCount: urls.length,
});
await tasker.create("scanWorkflowUrls", {
userId,
workflowStepId,
urls,
whitelistWorkflows,
});
}
/**
* Helper function to scan a single URL (e.g., event type redirect URL).
*/
export async function submitUrlForUrlScanning(
url: string,
userId: number,
eventTypeId: number,
whitelistWorkflows?: boolean
): Promise<void> {
if (!isUrlScanningEnabled()) {
return;
}
log.info(`Submitting event type redirect URL for scanning`, {
url: sanitizeUrlForLogging(url),
userId,
eventTypeId,
});
await tasker.create("scanWorkflowUrls", {
userId,
eventTypeId,
urls: [url],
whitelistWorkflows,
});
}
@@ -0,0 +1,505 @@
import process from "node:process";
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
import { WorkflowActions, WorkflowTemplates, WorkflowTriggerEvents, TimeUnit } from "@calcom/prisma/enums";
import { scanWorkflowBody, iffyScanBody } from "../scanWorkflowBody";
// Mock the submitWorkflowStepForUrlScanning function
vi.mock("../scanWorkflowUrls", () => ({
submitWorkflowStepForUrlScanning: vi.fn().mockResolvedValue(undefined),
}));
// Mock the scheduleWorkflowNotifications function
vi.mock("@calcom/features/ee/workflows/lib/scheduleWorkflowNotifications", () => ({
scheduleWorkflowNotifications: vi.fn().mockResolvedValue(undefined),
}));
// Mock the Task repository
vi.mock("@calcom/features/tasker/repository", () => ({
Task: {
hasNewerScanTaskForStepId: vi.fn().mockResolvedValue(false),
},
}));
// Mock the actionHelperFunctions
vi.mock("@calcom/features/ee/workflows/lib/actionHelperFunctions", () => ({
getTemplateBodyForAction: vi.fn().mockReturnValue("Default template body"),
}));
// Mock the compareReminderBodyToTemplate
vi.mock("@calcom/features/ee/workflows/lib/compareReminderBodyToTemplate", () => ({
default: vi.fn().mockReturnValue(false),
}));
// Mock the i18n
vi.mock("@calcom/lib/server/i18n", () => ({
getTranslation: vi.fn().mockResolvedValue((key: string) => key),
}));
// Mock the timeFormat
vi.mock("@calcom/lib/timeFormat", () => ({
getTimeFormatStringFromUserTimeFormat: vi.fn().mockReturnValue("h:mma"),
}));
// Mock the constants
vi.mock("@calcom/lib/constants", async () => {
const actual = (await vi.importActual("@calcom/lib/constants")) as typeof import("@calcom/lib/constants");
return {
...actual,
URL_SCANNING_ENABLED: true,
};
});
// Import mocked modules for assertions
import { submitWorkflowStepForUrlScanning } from "../scanWorkflowUrls";
import { scheduleWorkflowNotifications } from "@calcom/features/ee/workflows/lib/scheduleWorkflowNotifications";
import { Task } from "@calcom/features/tasker/repository";
import compareReminderBodyToTemplate from "@calcom/features/ee/workflows/lib/compareReminderBodyToTemplate";
describe("scanWorkflowBody", () => {
beforeEach(() => {
vi.clearAllMocks();
// Reset environment variables
delete process.env.IFFY_API_KEY;
});
describe("happy paths", () => {
test("should process workflow step and submit for URL scanning when IFFY is not configured", async () => {
// Create test data in prismock
const user = await prismock.user.create({
data: {
id: 1,
email: "[email protected]",
locale: "en",
timeFormat: 12,
whitelistWorkflows: false,
},
});
const workflow = await prismock.workflow.create({
data: {
id: 1,
name: "Test Workflow",
userId: user.id,
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
time: 1,
timeUnit: TimeUnit.HOUR,
},
});
await prismock.workflowStep.create({
data: {
id: 200,
stepNumber: 1,
action: WorkflowActions.EMAIL_HOST,
template: WorkflowTemplates.REMINDER,
workflowId: workflow.id,
reminderBody: '<p>Hello <a href="https://example.com">click here</a></p>',
},
});
const eventType = await prismock.eventType.create({
data: {
id: 1,
title: "Test Event",
slug: "test-event",
length: 30,
userId: user.id,
},
});
await prismock.workflowsOnEventTypes.create({
data: {
workflowId: workflow.id,
eventTypeId: eventType.id,
},
});
const payload = JSON.stringify({
userId: 1,
workflowStepId: 200,
});
await scanWorkflowBody(payload);
// Should submit for URL scanning
expect(submitWorkflowStepForUrlScanning).toHaveBeenCalledWith(
200,
'<p>Hello <a href="https://example.com">click here</a></p>',
1,
false
);
// Should schedule workflow notifications
expect(scheduleWorkflowNotifications).toHaveBeenCalled();
});
test("should mark workflow step as verified when no reminder body", async () => {
// Set IFFY_API_KEY to test the Iffy path
process.env.IFFY_API_KEY = "test-api-key";
const user = await prismock.user.create({
data: {
id: 2,
email: "[email protected]",
locale: "en",
timeFormat: 12,
whitelistWorkflows: false,
},
});
const workflow = await prismock.workflow.create({
data: {
id: 2,
name: "Test Workflow 2",
userId: user.id,
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
time: 1,
timeUnit: TimeUnit.HOUR,
},
});
await prismock.workflowStep.create({
data: {
id: 201,
stepNumber: 1,
action: WorkflowActions.EMAIL_HOST,
template: WorkflowTemplates.REMINDER,
workflowId: workflow.id,
reminderBody: null, // No reminder body
},
});
const eventType = await prismock.eventType.create({
data: {
id: 2,
title: "Test Event 2",
slug: "test-event-2",
length: 30,
userId: user.id,
},
});
await prismock.workflowsOnEventTypes.create({
data: {
workflowId: workflow.id,
eventTypeId: eventType.id,
},
});
const payload = JSON.stringify({
userId: 2,
workflowStepId: 201,
});
await scanWorkflowBody(payload);
// Should mark as verified
const updatedStep = await prismock.workflowStep.findUnique({
where: { id: 201 },
});
expect(updatedStep?.verifiedAt).toBeTruthy();
});
test("should mark workflow step as verified when body matches template", async () => {
process.env.IFFY_API_KEY = "test-api-key";
vi.mocked(compareReminderBodyToTemplate).mockReturnValueOnce(true);
const user = await prismock.user.create({
data: {
id: 3,
email: "[email protected]",
locale: "en",
timeFormat: 12,
whitelistWorkflows: false,
},
});
const workflow = await prismock.workflow.create({
data: {
id: 3,
name: "Test Workflow 3",
userId: user.id,
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
time: 1,
timeUnit: TimeUnit.HOUR,
},
});
await prismock.workflowStep.create({
data: {
id: 202,
stepNumber: 1,
action: WorkflowActions.EMAIL_HOST,
template: WorkflowTemplates.REMINDER,
workflowId: workflow.id,
reminderBody: "Default template body",
},
});
const eventType = await prismock.eventType.create({
data: {
id: 3,
title: "Test Event 3",
slug: "test-event-3",
length: 30,
userId: user.id,
},
});
await prismock.workflowsOnEventTypes.create({
data: {
workflowId: workflow.id,
eventTypeId: eventType.id,
},
});
const payload = JSON.stringify({
userId: 3,
workflowStepId: 202,
});
await scanWorkflowBody(payload);
// Should mark as verified since body matches template
const updatedStep = await prismock.workflowStep.findUnique({
where: { id: 202 },
});
expect(updatedStep?.verifiedAt).toBeTruthy();
});
test("should skip processing when newer task exists", async () => {
vi.mocked(Task.hasNewerScanTaskForStepId).mockResolvedValueOnce(true);
const payload = JSON.stringify({
userId: 1,
workflowStepId: 999,
createdAt: new Date().toISOString(),
});
await scanWorkflowBody(payload);
// Should not submit for URL scanning
expect(submitWorkflowStepForUrlScanning).not.toHaveBeenCalled();
});
test("should handle deprecated workflowStepIds array", async () => {
const user = await prismock.user.create({
data: {
id: 4,
email: "[email protected]",
locale: "en",
timeFormat: 12,
whitelistWorkflows: false,
},
});
const workflow = await prismock.workflow.create({
data: {
id: 4,
name: "Test Workflow 4",
userId: user.id,
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
time: 1,
timeUnit: TimeUnit.HOUR,
},
});
await prismock.workflowStep.create({
data: {
id: 203,
stepNumber: 1,
action: WorkflowActions.EMAIL_HOST,
template: WorkflowTemplates.REMINDER,
workflowId: workflow.id,
reminderBody: '<p>Hello <a href="https://test.com">link</a></p>',
},
});
const eventType = await prismock.eventType.create({
data: {
id: 4,
title: "Test Event 4",
slug: "test-event-4",
length: 30,
userId: user.id,
},
});
await prismock.workflowsOnEventTypes.create({
data: {
workflowId: workflow.id,
eventTypeId: eventType.id,
},
});
const payload = JSON.stringify({
userId: 4,
workflowStepIds: [203], // Using deprecated array format
});
await scanWorkflowBody(payload);
// Should submit for URL scanning
expect(submitWorkflowStepForUrlScanning).toHaveBeenCalled();
});
});
describe("unhappy paths", () => {
test("should return early when no step IDs provided", async () => {
const payload = JSON.stringify({
userId: 1,
});
await scanWorkflowBody(payload);
// Should not submit for URL scanning
expect(submitWorkflowStepForUrlScanning).not.toHaveBeenCalled();
expect(scheduleWorkflowNotifications).not.toHaveBeenCalled();
});
test("should return early when workflow not found after processing steps", async () => {
// This test verifies that the function returns early when the workflow
// associated with the step IDs is not found (after the initial step processing)
// Note: In practice, this scenario is rare since workflow steps are always
// associated with a workflow, but the code handles it gracefully by logging
// a warning and returning early.
const payload = JSON.stringify({
userId: 5,
workflowStepIds: [999], // Non-existent step IDs
});
// Should not throw - the function returns early when no steps are found
await expect(scanWorkflowBody(payload)).resolves.not.toThrow();
// Should not schedule notifications since no workflow was found
expect(scheduleWorkflowNotifications).not.toHaveBeenCalled();
});
test("should pass whitelistWorkflows flag when user is whitelisted", async () => {
const user = await prismock.user.create({
data: {
id: 6,
email: "[email protected]",
locale: "en",
timeFormat: 12,
whitelistWorkflows: true, // Whitelisted user
},
});
const workflow = await prismock.workflow.create({
data: {
id: 6,
name: "Test Workflow 6",
userId: user.id,
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
time: 1,
timeUnit: TimeUnit.HOUR,
},
});
await prismock.workflowStep.create({
data: {
id: 205,
stepNumber: 1,
action: WorkflowActions.EMAIL_HOST,
template: WorkflowTemplates.REMINDER,
workflowId: workflow.id,
reminderBody: '<p>Hello <a href="https://example.com">link</a></p>',
},
});
const eventType = await prismock.eventType.create({
data: {
id: 6,
title: "Test Event 6",
slug: "test-event-6",
length: 30,
userId: user.id,
},
});
await prismock.workflowsOnEventTypes.create({
data: {
workflowId: workflow.id,
eventTypeId: eventType.id,
},
});
const payload = JSON.stringify({
userId: 6,
workflowStepId: 205,
});
await scanWorkflowBody(payload);
// Should pass whitelistWorkflows=true
expect(submitWorkflowStepForUrlScanning).toHaveBeenCalledWith(
205,
expect.any(String),
6,
true
);
});
});
describe("iffyScanBody", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
test("should return flagged status from Iffy API", async () => {
const mockFetch = vi.fn().mockResolvedValue({
json: () => Promise.resolve({ flagged: true }),
});
vi.stubGlobal("fetch", mockFetch);
process.env.IFFY_API_KEY = "test-api-key";
const result = await iffyScanBody("spam content", 100);
expect(result).toBe(true);
expect(mockFetch).toHaveBeenCalledWith(
"https://api.iffy.com/api/v1/moderate",
expect.objectContaining({
method: "POST",
headers: expect.objectContaining({
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
}),
body: expect.stringContaining("spam content"),
})
);
});
test("should return false when content is not flagged", async () => {
const mockFetch = vi.fn().mockResolvedValue({
json: () => Promise.resolve({ flagged: false }),
});
vi.stubGlobal("fetch", mockFetch);
process.env.IFFY_API_KEY = "test-api-key";
const result = await iffyScanBody("normal content", 100);
expect(result).toBe(false);
});
test("should handle API errors gracefully", async () => {
const mockFetch = vi.fn().mockRejectedValue(new Error("API error"));
vi.stubGlobal("fetch", mockFetch);
process.env.IFFY_API_KEY = "test-api-key";
const result = await iffyScanBody("content", 100);
// Should return undefined on error (fail-open)
expect(result).toBeUndefined();
});
});
});
@@ -0,0 +1,478 @@
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import { describe, expect, test, vi, beforeEach } from "vitest";
import tasker from "@calcom/features/tasker";
import {
scanWorkflowUrls,
submitWorkflowStepForUrlScanning,
submitUrlForUrlScanning,
} from "../scanWorkflowUrls";
// Mock the urlScanner module
vi.mock("@calcom/features/ee/workflows/lib/urlScanner", () => ({
extractUrlsFromHtml: vi.fn((html: string) => {
// Simple mock implementation
const urls: string[] = [];
const hrefRegex = /href=["']([^"']+)["']/gi;
for (const match of Array.from(html.matchAll(hrefRegex))) {
const url = match[1];
if (url.startsWith("http://") || url.startsWith("https://")) {
urls.push(url);
}
}
return urls;
}),
submitUrlForScanning: vi.fn().mockResolvedValue({ scanId: "mock-scan-id" }),
getScanResult: vi.fn().mockResolvedValue({
url: "https://example.com",
scanId: "mock-scan-id",
status: "completed",
malicious: false,
categories: [],
}),
isUrlScanningEnabled: vi.fn().mockReturnValue(true),
}));
// Mock the tasker
vi.mock("@calcom/features/tasker", () => ({
default: {
create: vi.fn().mockResolvedValue(undefined),
},
}));
// Mock the autoLock module
vi.mock("@calcom/features/ee/api-keys/lib/autoLock", () => ({
LockReason: {
MALICIOUS_URL_IN_WORKFLOW: "MALICIOUS_URL_IN_WORKFLOW",
},
lockUser: vi.fn().mockResolvedValue(undefined),
}));
// Import mocked modules for assertions
import * as urlScanner from "@calcom/features/ee/workflows/lib/urlScanner";
import { lockUser } from "@calcom/features/ee/api-keys/lib/autoLock";
describe("scanWorkflowUrls", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("scanWorkflowUrls task handler", () => {
describe("happy paths", () => {
test("should skip scanning when URL scanning is disabled", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValueOnce(false);
// Create a workflow step in prismock first
await prismock.workflowStep.create({
data: {
id: 100,
stepNumber: 1,
action: "EMAIL_HOST",
template: "REMINDER",
workflowId: 1,
},
});
const payload = JSON.stringify({
userId: 1,
workflowStepId: 100,
urls: ["https://example.com"],
});
await scanWorkflowUrls(payload);
// Should mark workflow step as verified
const workflowStep = await prismock.workflowStep.findUnique({
where: { id: 100 },
});
expect(workflowStep?.verifiedAt).toBeTruthy();
expect(urlScanner.submitUrlForScanning).not.toHaveBeenCalled();
});
test("should submit URLs for scanning in phase 1", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.submitUrlForScanning).mockResolvedValue({ scanId: "scan-123" });
const payload = JSON.stringify({
userId: 1,
workflowStepId: 100,
urls: ["https://example.com", "https://another.com"],
});
await scanWorkflowUrls(payload);
expect(urlScanner.submitUrlForScanning).toHaveBeenCalledTimes(2);
expect(urlScanner.submitUrlForScanning).toHaveBeenCalledWith("https://example.com");
expect(urlScanner.submitUrlForScanning).toHaveBeenCalledWith("https://another.com");
// Should schedule follow-up task
expect(tasker.create).toHaveBeenCalledWith(
"scanWorkflowUrls",
expect.objectContaining({
userId: 1,
workflowStepId: 100,
pendingScans: expect.arrayContaining([
expect.objectContaining({ url: "https://example.com", scanId: "scan-123" }),
]),
pollAttempts: 0,
}),
expect.objectContaining({ scheduledAt: expect.any(Date) })
);
});
test("should poll for scan results in phase 2 and mark as verified when clean", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.getScanResult).mockResolvedValue({
url: "https://example.com",
scanId: "scan-123",
status: "completed",
malicious: false,
categories: [],
});
// Create a workflow step in prismock
await prismock.workflowStep.create({
data: {
id: 100,
stepNumber: 1,
action: "EMAIL_HOST",
template: "REMINDER",
workflowId: 1,
},
});
const payload = JSON.stringify({
userId: 1,
workflowStepId: 100,
pendingScans: [{ url: "https://example.com", scanId: "scan-123" }],
pollAttempts: 0,
});
await scanWorkflowUrls(payload);
expect(urlScanner.getScanResult).toHaveBeenCalledWith("scan-123");
// Should mark workflow step as verified
const workflowStep = await prismock.workflowStep.findUnique({
where: { id: 100 },
});
expect(workflowStep?.verifiedAt).toBeTruthy();
});
});
describe("unhappy paths", () => {
test("should lock user when malicious URL is detected", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.getScanResult).mockResolvedValue({
url: "https://malicious.com",
scanId: "scan-123",
status: "completed",
malicious: true,
categories: ["phishing"],
});
const payload = JSON.stringify({
userId: 1,
workflowStepId: 100,
pendingScans: [{ url: "https://malicious.com", scanId: "scan-123" }],
pollAttempts: 0,
});
await scanWorkflowUrls(payload);
expect(lockUser).toHaveBeenCalledWith("userId", "1", "MALICIOUS_URL_IN_WORKFLOW");
});
test("should not lock whitelisted user when malicious URL is detected", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.getScanResult).mockResolvedValue({
url: "https://malicious.com",
scanId: "scan-123",
status: "completed",
malicious: true,
categories: ["phishing"],
});
const payload = JSON.stringify({
userId: 1,
workflowStepId: 100,
pendingScans: [{ url: "https://malicious.com", scanId: "scan-123" }],
pollAttempts: 0,
whitelistWorkflows: true,
});
await scanWorkflowUrls(payload);
expect(lockUser).not.toHaveBeenCalled();
});
test("should mark as verified when max poll attempts reached (fail-open)", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
// Create a workflow step in prismock
await prismock.workflowStep.create({
data: {
id: 101,
stepNumber: 1,
action: "EMAIL_HOST",
template: "REMINDER",
workflowId: 1,
},
});
const payload = JSON.stringify({
userId: 1,
workflowStepId: 101,
pendingScans: [{ url: "https://example.com", scanId: "scan-123" }],
pollAttempts: 10, // MAX_POLL_ATTEMPTS
});
await scanWorkflowUrls(payload);
// Should mark workflow step as verified (fail-open)
const workflowStep = await prismock.workflowStep.findUnique({
where: { id: 101 },
});
expect(workflowStep?.verifiedAt).toBeTruthy();
});
test("should mark as verified when all URL submissions fail (fail-open)", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.submitUrlForScanning).mockResolvedValue({ error: "API error" });
// Create a workflow step in prismock
await prismock.workflowStep.create({
data: {
id: 102,
stepNumber: 1,
action: "EMAIL_HOST",
template: "REMINDER",
workflowId: 1,
},
});
const payload = JSON.stringify({
userId: 1,
workflowStepId: 102,
urls: ["https://example.com"],
});
await scanWorkflowUrls(payload);
// Should mark workflow step as verified (fail-open)
const workflowStep = await prismock.workflowStep.findUnique({
where: { id: 102 },
});
expect(workflowStep?.verifiedAt).toBeTruthy();
});
test("should schedule another poll when scan is still pending", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.getScanResult).mockResolvedValue(null); // Still pending
const payload = JSON.stringify({
userId: 1,
workflowStepId: 100,
pendingScans: [{ url: "https://example.com", scanId: "scan-123" }],
pollAttempts: 0,
});
await scanWorkflowUrls(payload);
// Should schedule another poll
expect(tasker.create).toHaveBeenCalledWith(
"scanWorkflowUrls",
expect.objectContaining({
userId: 1,
workflowStepId: 100,
pendingScans: [{ url: "https://example.com", scanId: "scan-123" }],
pollAttempts: 1,
}),
expect.objectContaining({ scheduledAt: expect.any(Date) })
);
});
test("should treat scan errors as non-malicious (fail-open)", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.getScanResult).mockResolvedValue({
url: "https://example.com",
scanId: "scan-123",
status: "error",
error: "Scan failed",
});
// Create a workflow step in prismock
await prismock.workflowStep.create({
data: {
id: 103,
stepNumber: 1,
action: "EMAIL_HOST",
template: "REMINDER",
workflowId: 1,
},
});
const payload = JSON.stringify({
userId: 1,
workflowStepId: 103,
pendingScans: [{ url: "https://example.com", scanId: "scan-123" }],
pollAttempts: 0,
});
await scanWorkflowUrls(payload);
// Should mark workflow step as verified (fail-open for errors)
const workflowStep = await prismock.workflowStep.findUnique({
where: { id: 103 },
});
expect(workflowStep?.verifiedAt).toBeTruthy();
});
});
});
describe("submitWorkflowStepForUrlScanning", () => {
describe("happy paths", () => {
test("should create task when URLs are found in reminder body", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.extractUrlsFromHtml).mockReturnValue(["https://example.com"]);
await submitWorkflowStepForUrlScanning(
100,
'<a href="https://example.com">Link</a>',
1,
false
);
expect(tasker.create).toHaveBeenCalledWith(
"scanWorkflowUrls",
expect.objectContaining({
userId: 1,
workflowStepId: 100,
urls: ["https://example.com"],
whitelistWorkflows: false,
})
);
});
test("should pass whitelistWorkflows parameter", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.extractUrlsFromHtml).mockReturnValue(["https://example.com"]);
await submitWorkflowStepForUrlScanning(
100,
'<a href="https://example.com">Link</a>',
1,
true
);
expect(tasker.create).toHaveBeenCalledWith(
"scanWorkflowUrls",
expect.objectContaining({
whitelistWorkflows: true,
})
);
});
});
describe("unhappy paths", () => {
test("should mark as verified when URL scanning is disabled", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(false);
// Create a workflow step in prismock
await prismock.workflowStep.create({
data: {
id: 104,
stepNumber: 1,
action: "EMAIL_HOST",
template: "REMINDER",
workflowId: 1,
},
});
await submitWorkflowStepForUrlScanning(
104,
'<a href="https://example.com">Link</a>',
1,
false
);
// Should mark workflow step as verified
const workflowStep = await prismock.workflowStep.findUnique({
where: { id: 104 },
});
expect(workflowStep?.verifiedAt).toBeTruthy();
expect(tasker.create).not.toHaveBeenCalled();
});
test("should mark as verified when no URLs are found", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
vi.mocked(urlScanner.extractUrlsFromHtml).mockReturnValue([]);
// Create a workflow step in prismock
await prismock.workflowStep.create({
data: {
id: 105,
stepNumber: 1,
action: "EMAIL_HOST",
template: "REMINDER",
workflowId: 1,
},
});
await submitWorkflowStepForUrlScanning(105, "<p>No links here</p>", 1, false);
// Should mark workflow step as verified
const workflowStep = await prismock.workflowStep.findUnique({
where: { id: 105 },
});
expect(workflowStep?.verifiedAt).toBeTruthy();
expect(tasker.create).not.toHaveBeenCalled();
});
});
});
describe("submitUrlForUrlScanning", () => {
describe("happy paths", () => {
test("should create task for event type redirect URL", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
await submitUrlForUrlScanning("https://redirect.com", 1, 50, false);
expect(tasker.create).toHaveBeenCalledWith(
"scanWorkflowUrls",
expect.objectContaining({
userId: 1,
eventTypeId: 50,
urls: ["https://redirect.com"],
whitelistWorkflows: false,
})
);
});
test("should pass whitelistWorkflows parameter", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(true);
await submitUrlForUrlScanning("https://redirect.com", 1, 50, true);
expect(tasker.create).toHaveBeenCalledWith(
"scanWorkflowUrls",
expect.objectContaining({
whitelistWorkflows: true,
})
);
});
});
describe("unhappy paths", () => {
test("should skip when URL scanning is disabled", async () => {
vi.mocked(urlScanner.isUrlScanningEnabled).mockReturnValue(false);
await submitUrlForUrlScanning("https://redirect.com", 1, 50, false);
expect(tasker.create).not.toHaveBeenCalled();
});
});
});
});