Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

webhookRoute.ts

194 lines8.5 KB

1import { EnvironmentHttpApi } from "@t3tools/contracts";
2import * as ByteSize from "effect/ByteSize";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import * as Tracer from "effect/Tracer";
7import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";
8import type * as HttpServerRequest from "effect/http/HttpServerRequest";
9import * as HttpServerResponse from "effect/http/HttpServerResponse";
10import * as HttpTraceContext from "effect/http/HttpTraceContext";
11import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
12import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
13​
14import * as Metrics from "../observability/Metrics.ts";
15import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
16import * as Workflows from "../workflows/Workflows.ts";
17import * as RelayDeliveryProof from "./RelayDeliveryProof.ts";
18import * as ScheduledTaskService from "./ScheduledTaskService.ts";
19​
20/** The relay enforces the same cap. */
21export const WEBHOOK_MAX_BODY_BYTES = 1024 * 1024;
22​
23// The relay records this outcome header.
24const WEBHOOK_OUTCOME_HEADER = "x-t3-hook-outcome";
25​
26const json = (
27 status: number,
28 body: Record<string, string>,
29 outcome: string,
30 headers?: Record<string, string>,
31) =>
32 HttpServerResponse.jsonUnsafe(body, {
33 status,
34 headers: { ...headers, [WEBHOOK_OUTCOME_HEADER]: outcome },
35 });
36​
37export const layer = HttpApiBuilder.group(
38 EnvironmentHttpApi,
39 "webhooks",
40 Effect.fnUntraced(function* (handlers) {
41 const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
42 const relayDeliveryProof = yield* RelayDeliveryProof.RelayDeliveryProof;
43 const workflows = yield* Workflows.Workflows;
44 const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
45 /**
46 * The endpoint is raw so the signature is checked over the exact body
47 * bytes; the service checks the token and signature.
48 */
49 // Only verified relay deliveries join a trace; direct requests keep their existing context.
50 const handler = Effect.fnUntraced(function* ({
51 params,
52 request,
53 }: {
54 readonly params: { readonly hookId: string; readonly token: string };
55 readonly request: HttpServerRequest.HttpServerRequest;
56 }) {
57 // The router answers HEAD with the GET route; link checkers probe with HEAD.
58 if (request.method === "HEAD") {
59 return json(405, { error: "method_not_allowed" }, "method_not_allowed", {
60 allow: "GET, POST, PUT, PATCH",
61 });
62 }
63 const contentLength = Number(request.headers["content-length"] ?? "0");
64 if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {
65 return json(413, { error: "body_too_large" }, "body_too_large");
66 }
67 // Chunked requests carry no content-length, so the reader itself is capped.
68 const body = yield* request.arrayBuffer.pipe(
69 Effect.map((buffer) => new Uint8Array(buffer)),
70 Effect.provideService(
71 HttpIncomingMessage.MaxBodySize,
72 ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),
73 ),
74 Effect.option,
75 );
76 const tooLarge = (error: string) =>
77 Metrics.increment(Metrics.webhookDeliveriesTotal, {
78 outcome: "body_too_large",
79 source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct",
80 }).pipe(Effect.as(json(413, { error }, "body_too_large")));
81 if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable");
82 if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {
83 return yield* tooLarge("body_too_large");
84 }
85​
86 const headers: Record<string, string> = {};
87 for (const [name, value] of Object.entries(request.headers)) {
88 // Webhook senders do not use cookies, so the request a task reads carries none.
89 if (typeof value === "string" && name.toLowerCase() !== "cookie") {
90 headers[name.toLowerCase()] = value;
91 }
92 }
93 const queryIndex = request.url.indexOf("?");
94 // The relay's delivery id and receive time count only with its signed
95 // proof; the URL can also be called directly. The receive time matters
96 // for requests the relay held while we were offline.
97 const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId });
98 const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined;
99 const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined;
100​
101 // A relay delivery joins the relay's trace, and goes to the T3 Connect
102 // tracer with it. Anyone else's traceparent is never trusted.
103 const relayParent = Option.isSome(relay)
104 ? HttpTraceContext.fromHeaders(request.headers)
105 : Option.none<Tracer.ExternalSpan>();
106 if (params.hookId.startsWith(Workflows.HOOK_PREFIX)) {
107 if (ManagedPolicy.deniedBy(managedPolicy, "webhookTasks") !== undefined) {
108 return json(403, { error: "blocked_by_policy" }, "blocked_by_policy");
109 }
110 // Answered only once the run is stored, so a sender that hears nothing may send again.
111 const started = yield* workflows
112 .deliver({
113 hookId: params.hookId,
114 token: params.token,
115 request: {
116 method: request.method,
117 headers,
118 query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),
119 body: new TextDecoder().decode(body.value),
120 },
121 ...(relayDeliveryId ? { deliveryId: `relay:${relayDeliveryId}` } : {}),
122 })
123 .pipe(Effect.result);
124 if (Result.isFailure(started)) {
125 if (started.failure._tag === "WorkflowInputError") {
126 return json(
127 400,
128 { error: "invalid_request", problem: started.failure.problem },
129 "invalid",
130 );
131 }
132 if (started.failure._tag === "WorkflowHookBusyError") {
133 return json(429, { error: "rate_limited" }, "rate_limited", { "retry-after": "60" });
134 }
135 yield* Effect.logWarning("Workflow hook delivery failed", { hookId: params.hookId });
136 return json(500, { error: "internal_error" }, "error");
137 }
138 return Option.isNone(started.success)
139 ? json(404, { error: "hook_not_found" }, "not_found")
140 : json(202, { runId: started.success.value.runId }, "accepted");
141 }
142 const result = yield* scheduledTasks
143 .triggerWebhook({
144 hookId: params.hookId,
145 token: params.token,
146 method: request.method,
147 path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`,
148 query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),
149 headers,
150 body: body.value,
151 bodyText: new TextDecoder().decode(body.value),
152 ...(relayDeliveryId ? { relayDeliveryId } : {}),
153 ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}),
154 })
155 .pipe(
156 Option.isSome(relayParent)
157 ? (effect) =>
158 effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing)
159 : (effect) => effect,
160 Effect.catchCause((cause) =>
161 Effect.logWarning("Webhook delivery failed").pipe(
162 Effect.annotateLogs({ hookId: params.hookId }),
163 Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),
164 Effect.as({ _tag: "error" as const }),
165 ),
166 ),
167 );
168​
169 switch (result._tag) {
170 case "accepted":
171 return json(202, { deliveryId: result.deliveryId }, result.outcome);
172 case "not_found":
173 return json(404, { error: "hook_not_found" }, "not_found");
174 case "rejected_signature":
175 return json(401, { error: "invalid_signature" }, "rejected_signature");
176 case "disabled":
177 return json(409, { error: "hook_disabled" }, "disabled");
178 case "blocked_by_policy":
179 return json(403, { error: "blocked_by_policy" }, "blocked_by_policy");
180 case "rate_limited":
181 return json(429, { error: result.outcome }, result.outcome);
182 case "expired":
183 return json(410, { error: "delivery_too_old" }, "expired");
184 case "error":
185 return json(500, { error: "internal_error" }, "error");
186 }
187 });
188 return handlers
189 .handleRaw("webhookPost", handler)
190 .handleRaw("webhookPut", handler)
191 .handleRaw("webhookPatch", handler)
192 .handleRaw("webhookGet", handler);
193 }),
194);