crbench//

← all cases

Add response-pipeline webhook delivery job

Tier 2 easy typescript · cross-file · real merged PR from formbricks/formbricks #8095

Ground-truth defects

d1 · security · critical
The new response-pipeline webhook delivery job (process-response-pipeline-job.ts) calls validateWebhookUrl(webhook.url) and then issues a plain fetchWithTimeout(webhook.url, ...) with no pinned dispatcher/agent and no manual redirect handling. The validate-then-default-fetch sequence leaves a DNS-rebinding TOCTOU window (the URL re-resolves on the real request) and follows 30x redirects, so an attacker-controlled webhook can reach internal services and cloud metadata endpoints (SSRF). Fixed by #8095 by pinning the resolved IP via a custom dispatcher and setting redirect to manual on delivery.

The change under review

diff (truncated — full diff)
diff --git a/apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts b/apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts
new file mode 100644
index 000000000..d896651ac
--- /dev/null
+++ b/apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts
@@ -0,0 +1,791 @@
+import "server-only";
+import { PipelineTriggers, Prisma, type Webhook } from "@prisma/client";
+import { createHash } from "node:crypto";
+import { prisma } from "@formbricks/database";
+import { type JobHandler, type TResponsePipelineJobData, UnrecoverableError } from "@formbricks/jobs";
+import { logger } from "@formbricks/logger";
+import { DatabaseError } from "@formbricks/types/errors";
+import { type TUserLocale, ZUserLocale } from "@formbricks/types/user";
+import { handleConnectorPipeline } from "@/lib/connector/pipeline-handler";
+import { POSTHOG_KEY } from "@/lib/constants";
+import { generateStandardWebhookSignature } from "@/lib/crypto";
+import { getIntegrations } from "@/lib/integration/service";
+import { getResponseCountBySurveyId } from "@/lib/response/service";
+import { validateWebhookUrl } from "@/lib/utils/validate-webhook-url";
+import { queueAuditEventWithoutRequest } from "@/modules/ee/audit-logs/lib/handler";
+import { type TAuditStatus, UNKNOWN_DATA } from "@/modules/ee/audit-logs/types/audit-log";
+import { recordResponseCreatedMeterEvent } from "@/modules/ee/billing/lib/metering";
+import { sendResponseFinishedEmail } from "@/modules/email";
+import { captureSurveyResponsePostHogEvent } from "@/modules/response-pipeline/lib/posthog";
+import { resolveStorageUrlsInObject } from "@/modules/storage/utils";
+import { sendFollowUpsForResponse } from "@/modules/survey/follow-ups/lib/follow-ups";
+import { FollowUpSendError } from "@/modules/survey/follow-ups/types/follow-up";
+import { handleIntegrations } from "./handle-integrations";
+import { sendTelemetryEvents } from "./telemetry";
+
+const WEBHOOK_TIMEOUT_MS = 5_000;
+const DEFAULT_NOTIFICATION_LOCALE: TUserLocale = "en-US";
+
+const pipelineOrganizationSelect = {
+  id: true,
+  billing: {
+    select: {
+      stripeCustomerId: true,
+    },
+  },
+} satisfies Prisma.OrganizationSelect;
+
+const pipelineSurveySelect = {
+  id: true,
+  workspaceId: true,
+  name: true,
+  type: true,
+  status: true,
+  createdAt: true,
+  updatedAt: true,
+  blocks: true,
+  hiddenFields: true,
+  variables: true,
+  followUps: true,
+  autoComplete: true,
+  languages: {
+    select: {
+      default: true,
+      enabled: true,
+      language: {
+        select: {
+          id: true,
+          code: true,
+          alias: true,
+          createdAt: true,
+          updatedAt: true,
+          workspaceId: true,
+        },
+      },
+    },
+  },
+} satisfies Prisma.SurveySelect;
+
+type TPipelineOrganization = Prisma.OrganizationGetPayload<{ select: typeof pipelineOrganizationSelect }>;
+type TPipelineSurvey = Prisma.SurveyGetPayload<{ select: typeof pipelineSurveySelect }>;
+
+const getOrganizationForPipeline = async (workspaceId: string): Promise<TPipelineOrganization | null> =>
+  prisma.organization.findFirst({
+    where: {
+      workspaces: {
+        some: {
+          id: workspaceId,
+        },
+      },
+    },
+    select: pipelineOrganizationSelect,
+  });
+
+const getSurveyForPipeline = async (surveyId: string): Promise<TPipelineSurvey | null> =>
+  prisma.survey.findUnique({
+    where: {
+      id: surveyId,
+    },
+    select: pipelineSurveySelect,
+  });
+
+const getPipelineLogContext = (
+  data: TResponsePipelineJobData,
+  context: Parameters<JobHandler<TResponsePipelineJobData>>[1]
+) => ({
+  attempt: context.attempt,
+  workspaceId: data.workspaceId,
+  event: data.event,
+  jobId: context.jobId,
+  jobName: context.jobName,
+  maxAttempts: context.maxAttempts,
+  queueName: context.queueName,
+  responseId: data.response.id,
+  surveyId: data.surveyId,
+});
+
+const toError = (error: unknown, fallbackMessage: string): Error =>
+  error instanceof Error ? error : new Error(fallbackMessage);
+
+const toUserLocale = (locale: string): TUserLocale => {
+  const parsedLocale = ZUserLocale.safeParse(locale);
+  return parsedLocale.success ? parsedLocale.data : DEFAULT_NOTIFICATION_LOCALE;
+};
+
+export const isPipelinePoolExhaustionError = (error: unknown): boolean => {
+  if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2024") {
+    return true;
+  }
+
+  if (error instanceof DatabaseError || error instanceof Error) {
+    return /Timed out fetching a new connection from the connection pool|connection pool timeout/i.test(
+      error.message
+    );
+  }
+
+  return false;
+};
+
+const createWebhookMessageId = ({
+  event,
+  jobId,
+  webhookId,
+}: {
+  event: TResponsePipelineJobData["event"];
+  jobId: string;
+  webhookId: string;
+}): string => createHash("sha256").update(`${jobId}:${webhookId}:${event}`).digest("hex");
+
+const fetchWithTimeout = async (
+  url: string,
+  options: RequestInit,
+  timeoutMs: number = WEBHOOK_TIMEOUT_MS
+): Promise<Response> => {
+  const abortController = new AbortController();
+  const signal = options.signal
+    ? AbortSignal.any([options.signal, abortController.signal])
+    : abortController.signal;
+  const timeoutId = setTimeout(() => {
+    abortController.abort(new Error("Timeout"));
+  }, timeoutMs);
+
+  try {
+    return await fetch(url, {
+      ...options,
+      signal,
+    });
+  } finally {
+    clearTimeout(timeoutId);
+  }
+};
+
+const getWebhooksForPipeline = async (
+  workspaceId: string,
+  event: PipelineTriggers,
+  surveyId: string
+): Promise<Webhook[]> => {
+  return await prisma.webhook.findMany({
+    where: {
+      workspaceId,
+      triggers: { has: event },
+      OR: [{ surveyIds: { has: surveyId } }, { surveyIds: { isEmpty: true } }],
+    },
+  });
+};
+
+const createWebhookDeliveryTask = async ({
+  webhook,
+  data,
+  survey,
+  logContext,
+}: {
+  webhook: Webhook;
+  data: TResponsePipelineJobData;
+  survey: TPipelineSurvey;
+  logContext: ReturnType<typeof getPipelineLogContext>;
+}): Promise<void> => {
+  try {
+    const body = JSON.stringify({
+      webhookId: webhook.id,
+      event: data.event,
+      data: {
+        ...data.response,
+        data: resolveStorageUrlsInObject(data.response.data),
+        survey: {
+          title: survey?.name,
+          type: survey?.type,
+          status: survey?.status,
+          createdAt: survey?.createdAt,
+          updatedAt: survey?.updatedAt,
+        },
+      },
+    });
+
+    const webhookMessageId = createWebhookMessageId({
+      event: data.event,
+      jobId: logContext.jobId,
+      webhookId: webhook.id,
+    });
+    const webhookTimestamp = Math.floor(Date.now() / 1000);
+    const requestHeaders: Record<string, string> = {
+      "content-type": "application/json",
+      "webhook-id": webhookMessageId,
+      "webhook-timestamp": webhookTimestamp.toString(),
+    };
+
+    if (webhook.secret) {
+      requestHeaders["webhook-signature"] = generateStandardWebhookSignature(
+        webhookMessageId,
+        webhookTimestamp,
+        body,
+        webhook.secret
+      );
+    }
+
+    await validateWebhookUrl(webhook.url);
+    const response = await fetchWithTimeout(webhook.url, {
+      method: "POST",
+      headers: requestHeaders,
+      body,
+    });
+
+    if (!response.ok) {
+      throw new Error(`Webhook delivery failed with status ${response.status}`);
+    }
+  } catch (error) {
+    logger.error(
+      {
+        ...logContext,
+        err: error,
+        webhookId: webhook.id,
+        webhookUrl: webhook.url,
+      },
+      "Response pipeline webhook delivery failed"
+    );
+    throw error;
+  }
+};
+
+const deliverWebhooks = async ({
+  data,
+  logContext,
+  survey,
+  webhooks,
+}: {
+  data: TResponsePipelineJobData;
+  logContext: ReturnType<typeof getPipelineLogContext>;
+  survey: TPipelineSurvey;
+  webhooks: Webhook[];
+}): Promise<void> => {
+  const results = await Promise.allSettled(
+    webhooks.map((webhook) =>
+      createWebhookDeliveryTask({
+        webhook,
+        data,
+        survey,
+        logContext,
+      })
+    )
+  );
+
+  const failedResults = results.filter((result) => result.status === "rejected");
+  if (failedResults.length === 0) {
+    return;
+  }
+
+  if (logContext.attempt < logContext.maxAttempts) {
+    throw toError(failedResults[0].reason, "Response pipeline webhook delivery failed");
+  }
+
+  logger.error(
+    {
+      ...logContext,
+      failedWebhookCount: failedResults.length,
+    },
+    "Response pipeline webhook delivery exhausted retries; continuing with remaining side effects"
+  );
+};
+
+const loadResponseFinishedContext = async ({
+  data,
+  logContext,
+  workspaceId,
+}: {
+  data: TResponsePipelineJobData;
+  logContext: ReturnType<typeof getPipelineLogContext>;
+  workspaceId: string;
+}): Promise<{
+  integrations: Awaited<ReturnType<typeof getIntegrations>>;
+  responseCount: number | null;
+}> => {
+  const [integrationsResult, responseCountResult] = await Promise.allSettled([
+    getIntegrations(workspaceId),
+    getResponseCountBySurveyId(data.surveyId),
+  ]);
+
+  if (integrationsResult.status === "rejected") {
+    logger.error(
+      {
+        ...logContext,
+        err: integrationsResult.reason,
+      },
+      "Response pipeline integration lookup failed"
+    );
+  }
+
+  if (responseCountResult.status === "rejected") {
+    logger.error(
+      {
+        ...logContext,
+        err: responseCountResult.reason,
+      },
+      "Response pipeline response count lookup failed"
+    );
+  }
+
+  return {
+    integrations: integrationsResult.status === "fulfilled" ? integrationsResult.value : [],
+    responseCount: responseCountResult.status === "fulfilled" ? responseCountResult.value : null,
+  };
+};
+
+const getUsersWithNotifications = async ({
+  data,
+  logContext,
+  workspaceId,
+}: {
+  data: TResponsePipelineJobData;
+  logContext: ReturnType<typeof getPipelineLogContext>;
+  workspaceId: string;
+}): Promise<Array<{ email: string; locale: TUserLocale }>> => {
+  try {
+    const users = await prisma.user.findMany({
+      where: {
+        memberships: {
+          some: {
+            organization: {
+              workspaces: {
+                some: {
+                  id: workspaceId,
+                },
+              },
+            },
+          },
+        },
+        OR: [
+          {
+            memberships: {
+              some: {
+                role: {
+                  in: ["owner", "manager"],
+                },
+                organization: {
+                  workspaces: {
+                    some: {
+                      id: workspaceId,
+                    },
+                  },
+                },
+              },
+            },
+          },
+          {
+            teamUsers: {
+              some: {
+                team: {
+                  workspaceTeams: {
+                    some: {
+                      workspace: {
+                        id: workspaceId,
+                      },
+                    },
+                  },
+                },
+              },
+            },
+          },
+        ],
+        notificationSettings: {
+          path: ["alert", data.surveyId],
+          equals: true,
+        },
+      },
+      select: { email: true, locale: true },
+    });
+
+    return users.map((user) => ({
+      email: user.email,
+      locale: toUserLocale(user.locale),
+    }));
+  } catch (error) {
+    logger.error(
+      {
+        ...logContext,
+        err: error,
+      },
+      "Response pipeline notification recipient lookup failed"
+    );
+
+    return [];
+  }
+};
+
+const handleFollowUpsSafely = async ({
+  data,
+  logContext,
+  survey,
+}: {
+  data: TResponsePipelineJobData;
+  logContext: ReturnType<typeof getPipelineLogContext>;
+  survey: TPipelineSurvey;
+}): Promise<void> => {
+  if (!survey.followUps?.length) {
+    return;
+  }
+
+  try {
+    const followUpsResult = await sendFollowUpsForResponse(data.response.id);
+    if (!followUpsResult.ok && followUpsResult.error.code !== FollowUpSendError.FOLLOW_UP_NOT_ALLOWED) {
+      logger.error(
+        {
+          ...logContext,
+          error: followUpsResult.error,
+        },
+        "Response pipeline follow-up delivery failed"
+      );
+    }
+  } catch (error) {
+    logger.error(
+      {
+        ...logContext,
+        err: error,
+      },
+      "Response pipeline follow-up delivery failed"
+    );
+  }
+};
+
+const sendNotificationEmailsSafely = async ({
+  data,
+  logContext,
+  responseCount,
+  survey,
+  usersWithNotifications,
+  workspaceId,
+}: {
+  data: TResponsePipelineJobData;
+  logContext: ReturnType<typeof getPipelineLogContext>;
+  responseCount: number | null;
+  survey: TPipelineSurvey;
+  usersWithNotifications: Array<{ email: string; locale: TUserLocale }>;
+  workspaceId: string;
+}): Promise<void> => {
+  if (responseCount === null) {
+    if (usersWithNotifications.length > 0) {
+      logger.error(
+        {
+          ...logContext,
+          notificationRecipientCount: usersWithNotifications.length,
+        },
+        "Response pipeline notification emails skipped because the response count could not be loaded"
+      );
+    }
+
+    return;
+  }
+
+  await Promise.all(
+    usersWithNotifications.map(async (user) => {
+      try {
+        await sendResponseFinishedEmail(
+          user.email,
+          user.locale,
+          workspaceId,
+          survey,
+          data.response,
+          responseCount
+        );
+      } catch (error) {
+        logger.error(
+          {
+            ...logContext,
+            err: error,
+            userEmail: user.email,
+          },

Leaderboard for this case

easy · 7 of 9 bots fully caught it (78% solve rate) · 78% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 Cubic solved 1/1 100.0% 3 0
2 cursor solved 1/1 100.0% 1 0
3 Drape (Deep Review) solved 1/1 100.0% 4 0
4 Drape (Review) solved 1/1 100.0% 3 0
5 Mjolnir (Opus 5.5) solved 1/1 100.0% 5 0
6 Mjolnir (Sonnet 5.5) solved 1/1 100.0% 3 0
7 Claude Code (Opus 5.5) solved 1/1 100.0% 5 1
8 greptile miss 0/1 0.0% 2 0
9 qodo miss 0/1 0.0% 0 0

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✓ off by one
valid · matches d1 · impact critical
valid · impact critical
I checked the repo. There is no packages/jobs. handler.ts only exports queueAuditEventBackground and queueAuditEvent. There is no lib/connector, and response-pipeline has no posthog, handle-integrations or telemetry files. The Webhook model in schema.prisma uses environmentId, not workspaceId. So the new module can't compile against this repo. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
If any webhook fails before the last attempt, the whole job throws and every matching webhook is sent again, including the ones that already succeeded. The old route.ts caught and logged webhook failures and never retried, so this duplicate-delivery path is new. [grounded: diff] [consensus 3/3: valid=3]
invalid
The select includes blocks, hiddenFields, variables, languages and name. Those are exactly the fields that getElementResponseMapping, the email code and handleIntegrations read. No access to an omitted field was found. [invalid: contradiction] [consensus 3/5: invalid=3, uncertain=2]
uncertain
The change does replace updateSurvey with a raw prisma.survey.update. But survey/service.ts shows no cache invalidation or status-specific logic, and the finding names no concrete missed side effect for a status-only change. The claimed failure is not shown. [uncertain: no evidence quoted] [consensus 3/4: uncertain=3, valid=1]
raw comments (5)
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:229
SSRF protections regress compared with the existing pipeline route. (1) The code calls `validateWebhookUrl` and then makes a plain `fetch`, which looks up DNS again. That brings back the DNS-rebinding TOCTOU that `validateAndResolveWebhookUrl` + `createPinnedDispatcher` exist to prevent: an attacker-controlled domain can resolve to a public IP during validation and to an internal IP or cloud metadata endpoint at fetch time. (2) The fetch no longer sets `redirect: "manual"` unless DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS is set, so a validated public webhook URL can redirect to an internal address and the request will follow it.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:5
The module does not compile or run against this repo. Several imports don't exist: `@formbricks/jobs` (no packages/jobs), `@/lib/connector/pipeline-handler`, `@/modules/response-pipeline/lib/posthog`, `./handle-integrations`, `./telemetry`, and `queueAuditEventWithoutRequest` (the handler only exports `queueAuditEvent`/`queueAuditEventBackground`). The Prisma queries also use `workspaceId`, `workspaces`, and `workspaceTeams`, but the schema still uses environment/project (`environmentId`, `projects`, `projectTeams`). Every query (organization, survey, webhook, and user lookups) would fail type-checking or throw at runtime.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:269
When any one webhook fails or returns non-2xx before the last attempt, the whole job throws. The retry then sends the response again to every matching webhook, including the ones that already succeeded. One broken endpoint causes up to maxAttempts duplicate deliveries to healthy endpoints. The stable webhook-id only helps receivers that deduplicate. Non-2xx responses were not treated as failures before, so this is a new duplicate-delivery path.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:38
The survey is loaded with a narrow `pipelineSurveySelect` (no questions/endings/environment, recall data, etc.). This partial object is then passed to `sendResponseFinishedEmail`, `handleIntegrations`, and `handleConnectorPipeline`, which expect a full `TSurvey`. Code in those functions that reads omitted fields (for example, to render question headlines in emails or map columns for integrations) gets undefined at runtime and either crashes or produces wrong output.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:479
Auto-complete updates the survey with a raw `prisma.survey.update` instead of the `updateSurvey` service the route used. This skips the service-level validation and side effects (such as cache invalidation and segment/trigger handling) that run when a survey status changes.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✓ exact
valid · impact high
The new fetchWithTimeout calls fetch with no redirect option, so redirects are followed by default. validateWebhookUrl only checks the first URL. The existing pipeline route and webhook.ts both use redirect "manual" for exactly this SSRF reason, unless DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS is set. [grounded: diff] [consensus 5/5: valid=5]
valid · matches d1 · impact critical
valid · impact high
In the repo, getIntegrations(environmentId) filters integrations by environmentId. sendResponseFinishedEmail calls getOrganizationByEnvironmentId, which looks up the organization through projects.environments. The new job passes a workspaceId to both, so integrations come back empty and the email throws ResourceNotFoundError. [grounded: diff] [consensus 4/5: valid=4, uncertain=1]
raw comments (4)
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:153
<!-- cubic:v=369d0b07-569e-4b32-a461-001cf6408be9 --> <!-- cubic:review-run=0ba14e6b-4498-5a77-a54c-024cf8690899 --> <!-- metadata:{"confidence":10} --> P0: This fetch follows redirects by default, so a public webhook can redirect to a private or metadata endpoint and bypass URL validation. Set `redirect: "manual"` for untrusted webhook delivery, matching the existing pipeline route. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts, line 153: <comment>This fetch follows redirects by default, so a public webhook can redirect to a private or metadata endpoint and bypass URL validation. Set `redirect: "manual"` for untrusted webhook delivery, matching the existing pipeline route.</comment> <file context> @@ -0,0 +1,791 @@ + }, timeoutMs); + + try { + return await fetch(url, { + ...options, + signal, </file context> ``` </details>
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:225
<!-- cubic:v=36202960-28af-4d1c-9715-158ac52331c3 --> <!-- cubic:review-run=0ba14e6b-4498-5a77-a54c-024cf8690899 --> <!-- metadata:{"confidence":10} --> P0: The validator resolves DNS but this wrapper discards the validated address before `fetch` resolves the hostname again. Use `validateAndResolveWebhookUrl` with `createPinnedDispatcher` so delivery connects to the address that passed validation. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts, line 225: <comment>The validator resolves DNS but this wrapper discards the validated address before `fetch` resolves the hostname again. Use `validateAndResolveWebhookUrl` with `createPinnedDispatcher` so delivery connects to the address that passed validation.</comment> <file context> @@ -0,0 +1,791 @@ + ); + } + + await validateWebhookUrl(webhook.url); + const response = await fetchWithTimeout(webhook.url, { + method: "POST", </file context> ``` </details>
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:302
<!-- cubic:v=c0381f3c-5d02-42ad-80eb-617b9f2d547d --> <!-- cubic:review-run=0ba14e6b-4498-5a77-a54c-024cf8690899 --> <!-- metadata:{"confidence":9} --> P1: This passes a workspace ID to environment-scoped helpers, so integrations are queried with the wrong ID and notification email organization lookup fails. Pass the actual environment ID through the pipeline, or update every helper contract consistently. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts, line 302: <comment>This passes a workspace ID to environment-scoped helpers, so integrations are queried with the wrong ID and notification email organization lookup fails. Pass the actual environment ID through the pipeline, or update every helper contract consistently.</comment> <file context> @@ -0,0 +1,791 @@ + responseCount: number | null; +}> => { + const [integrationsResult, responseCountResult] = await Promise.allSettled([ + getIntegrations(workspaceId), + getResponseCountBySurveyId(data.surveyId), + ]); </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **3 issues found** across 1 file <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts"> <violation number="1" location="apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:153"> P0: This fetch follows redirects by default, so a public webhook can redirect to a private or metadata endpoint and bypass URL validation. Set `redirect: "manual"` for untrusted webhook delivery, matching the existing pipeline route.</violation> <violation number="2" location="apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:225"> P0: The validator resolves DNS but this wrapper discards the validated address before `fetch` resolves the hostname again. Use `validateAndResolveWebhookUrl` with `createPinnedDispatcher` so delivery connects to the address that passed validation.</violation> <violation number="3" location="apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:302"> P1: This passes a workspace ID to environment-scoped helpers, so integrations are queried with the wrong ID and notification email organization lookup fails. Pass the actual environment ID through the pipeline, or update every helper contract consistently.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/38/ai_pr_review_github_delivery_46478ae75380ad72ab1e915d6002f99fa06c3f2954145de65f8e1c0a2637b532?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F38)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_46478ae75380ad72ab1e915d6002f99fa06c3f2954145de65f8e1c0a2637b532:9ca1154461fff2a6bc275d305990beafaac87682:0ba14e6b-4498-5a77-a54c-024cf8690899 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✓ off by one
valid · matches d1 · impact critical
raw comments (2)
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:230
### Webhook delivery reintroduces SSRF risk **High Severity** <!-- DESCRIPTION START --> Webhook delivery calls `validateWebhookUrl` then `fetch` without pinning the validated IP or blocking redirects. DNS rebinding or a 3xx to an internal host can bypass SSRF checks and POST response data to private addresses. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: af34959f-ea17-4a4a-bc41-ff5eadef56c8 --> <!-- LOCATIONS START apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts#L224-L230 apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts#L138-L160 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts#L138-L160`](https://github.com/drape-io/crbench-cursor-2026-09/blob/2ca02989cf5cac7e70483f0062eecbf9cadfe3ba/apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts#L138-L160) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmMyM2IyZTNjLTQwZTgtNDEwMC05Y2VkLTNmMTUyNDZkYzJlZCIsImVuY3J5cHRpb25LZXkiOiJiYXhGa3VfYjJ0dE9iNnNORkdxWUVNNkxDZ2dxMG5nU2UwaXVsa3ZUVmxBIiwiYnJhbmNoIjoidDItZm9ybWJyaWNrcy04MDk1IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmMyM2IyZTNjLTQwZTgtNDEwMC05Y2VkLTNmMTUyNDZkYzJlZCIsImVuY3J5cHRpb25LZXkiOiJiYXhGa3VfYjJ0dE9iNnNORkdxWUVNNkxDZ2dxMG5nU2UwaXVsa3ZUVmxBIiwiYnJhbmNoIjoidDItZm9ybWJyaWNrcy04MDk1IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MzksImNvbW1pdFNoYSI6IjJjYTAyOTg5Y2Y1Y2FjN2U3MDQ4M2YwMDYyZWVjYmY5Y2FkZmUzYmEiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2ca02989cf5cac7e70483f0062eecbf9cadfe3ba. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTo3ZjY5NmY1OC03NDI5LTRkNTMtYTU4Ny1lMmU2OTU5MGUwY2IiLCJlbmNyeXB0aW9uS2V5IjoieUlfRXNhSjk3NXVwRzZxWEZmMDZCTHg1VGdNUnpuTkczazJRYmhsdTdnbyIsImJyYW5jaCI6InQyLWZvcm1icmlja3MtODA5NSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2ca02989cf5cac7e70483f0062eecbf9cadfe3ba. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✓ off by one
valid · impact high
The new fetchWithTimeout calls fetch without a redirect option (default 'follow'), while the existing pipeline route and webhook.ts use redirect: 'manual' gated on DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS, so validateWebhookUrl can be bypassed by redirects. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d1 · impact critical
valid · impact low
A single webhook failure throws and the job retries, which re-POSTs to every matched webhook, including ones that already succeeded. The stable webhook-id lets receivers deduplicate, but the duplicate deliveries still happen. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
Pool-exhaustion errors in the response-count, integrations and recipient lookups are caught and turned into null or [], so they never reach the job-level retry branch. The job then completes, and notifications and auto-complete are skipped permanently. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:150
**Webhook delivery follows redirects to internal hosts** `fetchWithTimeout` never sets `redirect`, so a validated webhook URL can 302 the worker to a private/internal address. The old route and `webhook.ts` use `redirect: "manual"`. Pass `redirect: DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS ? "follow" : "manual"` and treat 3xx as failure. ``` apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:139 const fetchWithTimeout = async ( apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:140 url: string, apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:141 options: RequestInit, apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:142 timeoutMs: number = WEBHOOK_TIMEOUT_MS apps/web/app/api/(internal)/pipeline/route.ts:97 // `redirect: "manual"` blocks SSRF via redirect — webhook URLs are validated against private/internal apps/web/app/api/(internal)/pipeline/route.ts:98 // ranges before delivery, but redirect targets would otherwise bypass that check. Gated on the same apps/web/app/api/(internal)/pipeline/route.ts:99 // env var as `validateWebhookUrl`: self-hosters who opted into trusting internal URLs also get the apps/web/app/api/(internal)/pipeline/route.ts:100 // pre-patch redirect-follow behavior for consistency. apps/web/app/api/(internal)/pipeline/route.ts:101 const redirectMode: RequestRedirect = DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS ? "follow" : "manual"; apps/web/app/api/(internal)/pipeline/route.ts:102 // Uses AbortSignal to actually cancel the underlying fetch when the timer fires — ```
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:225
**Webhook IP not pinned after validation (DNS rebinding)** `validateWebhookUrl` discards the resolved address and fetch resolves DNS again, so a hostname can rebind to a private IP after validation. The old route pinned it. Use `validateAndResolveWebhookUrl` and pass `createPinnedDispatcher(address)` to fetch, destroying it afterward. ``` apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:225 await validateWebhookUrl(webhook.url); apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:226 const response = await fetchWithTimeout(webhook.url, { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:227 method: "POST", apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:228 headers: requestHeaders, apps/web/lib/utils/validate-webhook-url.ts:203 /** apps/web/lib/utils/validate-webhook-url.ts:204 * Validates a webhook URL to prevent Server-Side Request Forgery (SSRF). apps/web/lib/utils/validate-webhook-url.ts:205 * Thin wrapper around {@link validateAndResolveWebhookUrl} for callers that only apps/web/lib/utils/validate-webhook-url.ts:206 * need validation (e.g. webhook create/update) and discard the resolved address. apps/web/lib/utils/validate-webhook-url.ts:207 * apps/web/lib/utils/validate-webhook-url.ts:208 * @throws {InvalidInputError} when the URL fails any validation check ```
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:279
**Healthy webhooks get the same event again** When one webhook fails before the last attempt, deliverWebhooks throws and BullMQ retries the whole job. Every retry POSTs again to webhooks that already succeeded. Track which webhooks were delivered and skip them on retry, or queue each webhook as its own job. ``` apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:261 webhooks.map((webhook) => apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:262 createWebhookDeliveryTask({ apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:263 webhook, apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:264 data, apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:278 } apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:280 logger.error( apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:744 await deliverWebhooks({ apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:745 data, apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:746 logContext, apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:747 survey, ```
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:323
**Transient DB errors permanently drop notifications and auto-complete** `loadResponseFinishedContext` and `getUsersWithNotifications` swallow every error, pool exhaustion included. The job then succeeds without a retry, so alert emails and auto-complete are skipped for good. Rethrow errors that `isPipelinePoolExhaustionError` recognises so the job retries. ``` apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:304 ]); apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:306 if (integrationsResult.status === "rejected") { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:307 logger.error( apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:308 { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:771 if (isPipelinePoolExhaustionError(error)) { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:772 logger.warn( apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:773 { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:774 ...logContext, apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:775 err: error, apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:776 }, ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✓ off by one
valid · matches d1 · impact critical
valid · impact medium
On any attempt before the last, one failed webhook makes deliverWebhooks throw. That throw happens before the responseFinished/responseCreated side effects run, so emails and integrations are delayed until a later attempt. Every retry also re-POSTs to webhooks that already succeeded. The stable webhook-id lets receivers deduplicate, but that only softens the duplicate posts and does not change the behavior. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The timeout is cleared in `finally` once fetch resolves, which happens when the headers arrive. The caller only checks response.ok and never reads or cancels the body, so the connection stays held until the body finishes or is garbage-collected. Undici's own body timeout probably keeps this from lasting forever, so the impact is low. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:170
**Webhook delivery follows redirects and skips IP pinning** The webhook fetch follows redirects by default and validates the URL separately from `fetch`. The original route used `redirect: "manual"` and a pinned dispatcher, so a redirect or DNS rebind now reaches internal services. Use `validateAndResolveWebhookUrl`, a `createPinnedDispatcher` dispatcher, and `redirect: "manual"` unless internal URLs are allowed. ``` apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:115 export const isPipelinePoolExhaustionError = (error: unknown): boolean => { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:116 if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2024") { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:117 return true; apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:118 } apps/web/app/api/(internal)/pipeline/route.ts:101 const redirectMode: RequestRedirect = DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS ? "follow" : "manual"; apps/web/app/api/(internal)/pipeline/route.ts:102 // Uses AbortSignal to actually cancel the underlying fetch when the timer fires — apps/web/app/api/(internal)/pipeline/route.ts:103 // a Promise.race would only reject the wrapper while the fetch keeps the socket apps/web/app/api/(internal)/pipeline/route.ts:104 // open, which then deadlocks dispatcher.close() (graceful drain waits for it). apps/web/app/api/(internal)/pipeline/route.ts:105 const fetchWithTimeout = ( apps/web/app/api/(internal)/pipeline/route.ts:106 url: string, ```
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:257
**One failing webhook delays emails and integrations** `deliverWebhooks` throws on any webhook failure until the last attempt, so the other side effects are skipped on earlier attempts. Each retry also re-posts to webhooks that already succeeded. Run the other side effects regardless of webhook outcome, and retry only the failed webhooks. ``` apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:246 } apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:247 }; apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:249 const deliverWebhooks = async ({ apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:250 data, apps/web/app/api/(internal)/pipeline/route.ts:303 // Await webhook and email promises with allSettled to prevent early rejection apps/web/app/api/(internal)/pipeline/route.ts:304 const results = await Promise.allSettled([...webhookPromises, ...emailPromises]); apps/web/app/api/(internal)/pipeline/route.ts:305 results.forEach((result) => { apps/web/app/api/(internal)/pipeline/route.ts:306 if (result.status === "rejected") { apps/web/app/api/(internal)/pipeline/route.ts:307 logger.error({ error: result.reason, url: request.url }, "Promise rejected"); apps/web/app/api/(internal)/pipeline/route.ts:308 } ```
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:125
**Webhook response body never consumed or cancelled** `fetchWithTimeout` clears the timeout as soon as headers arrive, and the caller never reads or cancels `response.body`. A slow or endless response body then stays open with no timeout, holding the connection. Cancel the body (`await response.body?.cancel()`) after checking `response.ok`, or keep the abort timer until the body is drained. ``` apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:115 export const isPipelinePoolExhaustionError = (error: unknown): boolean => { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:116 if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2024") { apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:117 return true; apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:118 } apps/web/app/api/(internal)/pipeline/route.ts:102 // Uses AbortSignal to actually cancel the underlying fetch when the timer fires — apps/web/app/api/(internal)/pipeline/route.ts:103 // a Promise.race would only reject the wrapper while the fetch keeps the socket apps/web/app/api/(internal)/pipeline/route.ts:104 // open, which then deadlocks dispatcher.close() (graceful drain waits for it). apps/web/app/api/(internal)/pipeline/route.ts:105 const fetchWithTimeout = ( apps/web/app/api/(internal)/pipeline/route.ts:106 url: string, apps/web/app/api/(internal)/pipeline/route.ts:107 options: RequestInit & { dispatcher?: Agent }, ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✗ —
valid · impact critical
I checked the repo: there is no packages/jobs package, apps/web/package.json does not list @formbricks/jobs, and the only file in modules/response-pipeline is this new one. So the imports of ./handle-integrations, ./telemetry and the posthog module have nothing to resolve to, and the build fails. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
A grep shows processResponsePipelineJob is only referenced in this file and in a docs page. Response producers such as apps/web/app/api/v2/client/[environmentId]/responses/route.ts still call sendToPipeline, so nothing ever runs the new handler. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:5
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> `@formbricks/jobs` is not in the workspaces, lockfile, or `apps/web/package.json`. The imported local modules `./handle-integrations`, `./telemetry`, and `@/modules/response-pipeline/lib/posthog` are also missing. Add these modules and the package dependency with this file.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:720
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> Nothing imports or registers `processResponsePipelineJob`. `apps/web/instrumentation-jobs.ts` and `enqueueResponsePipelineEvents` are absent, while response producers still call `sendToPipeline` and post to `/api/pipeline`. Register this handler and switch the producers in the same change.
PR-level
<h3>Greptile Summary</h3> Adds the worker that processes queued survey response events. It validates the survey context, sends matching webhooks, and runs event-specific work for created and finished responses. - Delivers matching webhooks with signed, timed requests. - Runs integrations, alerts, follow-ups, and survey completion for finished responses. - Records billing, analytics, and telemetry events for created responses. <h3>Confidence Score: 3/5</h3> This PR is not safe to merge because the new file does not build and its handler cannot run. Several imports have no matching package or file. No worker registers `processResponsePipelineJob`, and producers still use `/api/pipeline`. **Files Needing Attention:** `apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts` <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts | Adds a background response pipeline handler. Its imports cannot resolve, and no worker or producer calls it. | </details> <details open><summary><h3>Sequence Diagram</h3></summary> ```mermaid sequenceDiagram participant Build as Next.js build participant Handler as process-response-pipeline-job.ts participant Resolver as Module resolver participant API as Response API participant Legacy as /api/pipeline participant Worker as Background worker Build->>Handler: Type-check included source Handler->>Resolver: "Import @formbricks/jobs and local helpers" Resolver-->>Build: Modules cannot be found API->>Legacy: sendToPipeline over HTTP Legacy-->>API: Run the existing pipeline Note over Handler,Worker: No registry imports the new handler Worker--xHandler: processResponsePipelineJob is never called ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update apps/web/modules/response-pipelin..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/4aaf0df0c93b46e98c36380558bc632c5d9f16a2) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284451)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✓ off by one
valid · impact high
The new fetchWithTimeout spreads only method/headers/body/signal and never sets redirect, so fetch uses its default "follow". The existing pipeline route explicitly sets `redirect: redirectMode` (manual) to block SSRF via redirects. [grounded: diff] [consensus 3/3: valid=3]
valid · impact high
The new job validates the URL but throws away the resolved address and fetches without a pinned dispatcher. The old route used validateAndResolveWebhookUrl plus createPinnedDispatcher specifically to prevent DNS-rebinding TOCTOU. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
Any single rejected webhook throws before the last attempt, so the whole job retries. That re-POSTs webhooks that already succeeded and delays all later side effects. The old route caught and logged webhook failures without blocking anything. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d1 · impact critical
valid · impact medium
A non-2xx response now throws, and deliverWebhooks rethrows on non-final attempts. Healthy webhooks get re-sent and integrations, emails, metering and telemetry are held back until retries run out. The old route used .catch(logger.error) and carried on. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:215
[P1] Webhook delivery dropped the SSRF protection against redirects The existing pipeline route (`apps/web/app/api/(internal)/pipeline/route.ts`) sends webhooks with `redirect: DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS ? "follow" : "manual"`. Its comment says this is there because "redirect targets would otherwise bypass" the private/internal-range check. The new `fetchWithTimeout` passes only `method`/`headers`/`body`/`signal`, so `fetch` falls back to its default `redirect: "follow"`. Any webhook URL that passes `validateWebhookUrl` can answer with a 302 to an internal address such as `http://169.254.169.254/...` or `http://localhost:...`, and the worker will POST the response payload there. This brings back an SSRF hole that the old route had closed.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:215
[P1] Webhook target is not pinned to the validated IP, so DNS rebinding works again The new job calls `validateWebhookUrl(webhook.url)`, which throws away the resolved address, and then `fetch(webhook.url)` resolves DNS a second time. The old route used `validateAndResolveWebhookUrl` together with `createPinnedDispatcher(address)` and destroyed the dispatcher afterwards. It did this to close exactly this gap; its comment describes the "attacker-controlled domain can rebind to a private/internal IP after validation passed (TOCTOU SSRF)" case, and there is a dedicated `validate-webhook-url.toctou.test.ts`. A domain with a short TTL can resolve to a public IP during validation and to an internal IP at fetch time. The fix is to keep the returned address and pass a pinned `dispatcher` to `fetch`.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:281
[P2] One failing webhook makes the whole job retry, re-sending every webhook and delaying all other side effects When any single webhook rejects, including a permanent 4xx from a misconfigured customer endpoint, `deliverWebhooks` throws on every attempt before the last. The job then re-runs from the start. Webhooks that already succeeded get POSTed again on each attempt. Only the `webhook-id` header stays the same, and most receivers don't deduplicate on it. Integrations, follow-ups, notification emails, auto-complete, metering and telemetry for that response are also held back until all retries and backoff are used up. In practice, one broken webhook in a workspace means duplicate deliveries to healthy endpoints and delayed emails and integrations for every response. A fix is to retry only the webhooks that failed, or to run the other side effects without waiting on webhook success.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:236
[P1] Webhook delivery dropped the redirect and DNS-rebinding SSRF protections The existing pipeline route (`apps/web/app/api/(internal)/pipeline/route.ts`) calls `validateAndResolveWebhookUrl` and sends the request through `createPinnedDispatcher(address)`, which pins the connection to the IP that was validated. It also sets `redirect: "manual"` unless `DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS` is on. The new job calls only `validateWebhookUrl(webhook.url)` and then a plain `fetch`, which uses the default `redirect: "follow"` and resolves DNS again. Anyone who can configure a webhook can get past the private/internal IP check in two ways: point the URL at a public host that answers with a 30x to `http://169.254.169.254/...` or another internal address, or use a domain that rebinds to a private IP between validation and fetch. Either way the server POSTs response data to internal services, which reintroduces the SSRF that the existing code guards against.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:288
[P2] One failing webhook causes the other webhooks to be re-sent and delays all other side effects until retries run out A non-2xx status now throws (line 244). `deliverWebhooks` then rethrows on every attempt except the last, so one misconfigured or flaky customer endpoint (for example one that returns 404 or 500) makes the whole job retry. Each retry POSTs again to every webhook that already succeeded. For `responseFinished`, it also holds back integrations, connectors, follow-up emails, notification emails and survey auto-complete. For `responseCreated`, it holds back metering, PostHog and telemetry. All of these wait for every retry and its backoff to finish. The old route logged webhook failures and carried on, so one bad endpoint never blocked these effects. A stable `webhook-id` helps receivers drop duplicates, but the delayed billing, emails and auto-complete still affect the other features.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✓ off by one
valid · matches d1 · impact critical
valid · impact high
The fetch call in fetchWithTimeout does not set a redirect option, so it uses the default "follow", and validateWebhookUrl only checks the original URL. The existing pipeline route uses redirect "manual" (route.ts:101) precisely to block redirect-based SSRF, so this new job weakens that protection. [grounded: diff] [consensus 3/3: valid=3]
valid · impact high
The new job validates the URL and then lets fetch resolve DNS again with no pinned dispatcher. The old route used validateAndResolveWebhookUrl together with createPinnedDispatcher (route.ts:156-161), so this change reintroduces the DNS-rebinding TOCTOU gap. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:169
[P1] Webhook delivery drops redirect blocking and DNS pinning (SSRF protection) The legacy pipeline route (`apps/web/app/api/(internal)/pipeline/route.ts`) calls `validateAndResolveWebhookUrl`, pins the connection to the validated IP with `createPinnedDispatcher`, and sets `redirect: "manual"` unless `DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS` is set. This job handler instead calls `validateWebhookUrl(webhook.url)` and then a plain `fetch` with the default `redirect: "follow"` and no dispatcher. This regresses two protections whenever a user-configured webhook URL is delivered by this job. A public URL can return a 3xx redirect to an internal address, for example a cloud metadata IP or localhost, and the job will follow it. A hostname can also resolve to a public IP at validation time and rebind to a private IP at fetch time. Both reopen the SSRF paths the route already closes. The new code should use the same resolved-address, pinned-dispatcher, and manual-redirect logic as the existing route (see `route.ts` lines 97-139).
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:153
[P1] Webhook fetch follows redirects, bypassing the SSRF check `fetchWithTimeout` calls `fetch` without `redirect: "manual"`, so it uses the default `follow`. `validateWebhookUrl` only checks the original URL. A user-configured webhook that answers with a 302 to an internal address (for example cloud metadata at 169.254.169.254 or localhost services) will be followed, and the check never sees the redirect target. The route this job replaces (`apps/web/app/api/(internal)/pipeline/route.ts`) sets `redirect: "manual"` unless `DANGEROUSLY_ALLOW_WEBHOOK_INTERNAL_URLS` is on, specifically to block this. The behaviour has regressed whenever the new job handles webhooks with self-hosted defaults.
apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts:225
[P1] Webhook delivery no longer pins the validated IP, which allows DNS-rebinding SSRF The job calls `validateWebhookUrl(webhook.url)`, then `fetch` resolves DNS again on its own. A domain controlled by an attacker can return a public IP during validation and a private IP at connect time (TOCTOU). The old route used `validateAndResolveWebhookUrl` and `createPinnedDispatcher(address)` to fix the connection to the validated IP, and it destroyed the dispatcher afterwards. The new code drops that protection, so any user who can configure a webhook can reach internal services through the pipeline worker.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 critical ✗ —
raw comments (2)
PR-level
<h3>Qodo is busy working</h3> Check back in a few minutes. Qodo's code review agents are on it. <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
PR-level
<h3>PR Summary by Qodo</h3> Add resilient response pipeline job processor <code>✨ Enhancement</code> <code>🕐 40+ Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Adds a queued handler for response-created and response-finished pipeline events. >• Delivers signed webhooks with validation, timeouts, deterministic IDs, and retry-aware failure > handling. >• Isolates billing, analytics, integrations, notifications, follow-ups, and survey completion > failures. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD J["Pipeline Job"] --> C["Load Context"] --> W["Deliver Webhooks"] --> E{"Event Type"} E -->|responseFinished| F["Finished Effects"] --> X["External Systems"] E -->|responseCreated| R["Created Effects"] --> X ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Fan out side effects into dedicated jobs</b></summary> <dl> <dd> - ➕ Provides independent retry policies and failure isolation for each downstream system. - ➕ Allows separate concurrency controls for webhooks, email, integrations, billing, and telemetry. - ➕ Keeps the central processor smaller and easier to reason about. - ➖ Requires coordination, idempotency guarantees, and additional queue definitions. - ➖ Makes ordering and completion semantics more complex. - ➖ Expands the migration scope substantially. </dd> </dl> </details> >**Recommendation:** The single orchestrator is reasonable for preserving pipeline ordering and centralizing the initial queued implementation. Dedicated child jobs would offer stronger isolation and scaling, but should be considered separately after idempotency and event-completion semantics are defined. </dd> </dl> </details> <details> <summary> Files changed (1) <code> +791 / -0 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (1) <code> +791 / -0 </code></summary> <dl> <dd> <details> <summary>process-response-pipeline-job.ts<code>Implement queued response pipeline orchestration</code> <code>+791/-0</code></summary> <br/> >Implement queued response pipeline orchestration > ><pre> >• Adds a job handler that loads and validates pipeline context, delivers signed webhooks, and dispatches event-specific side effects. It introduces structured logging, database pool exhaustion detection, retry-aware webhook behavior, locale fallback, and fault isolation for integrations, notifications, follow-ups, billing, analytics, telemetry, and survey auto-completion. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/38/files#diff-6ee05c329308a0d4f0ea44e9a4d8bda54ce0d8f4ab1c03889373ade2612d6570'>apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts</a> </details> </dd> </dl> </details> </dd> </dl> </details>