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

HookForwarder.ts

428 lines15.0 KB

1import * as Clock from "effect/Clock";
2import * as Context from "effect/Context";
3import * as Crypto from "effect/Crypto";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Redacted from "effect/Redacted";
9import * as Result from "effect/Result";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import * as HttpClient from "effect/http/HttpClient";
13import type * as HttpServerRequest from "effect/http/HttpServerRequest";
14import * as HttpServerResponse from "effect/http/HttpServerResponse";
15import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
16import { EnvironmentId } from "@t3tools/contracts";
17import { RelayApi, type RelayHookDeliveryProofPayload } from "@t3tools/contracts/relay";
18import {
19 normalizeRelayIssuer,
20 RELAY_HOOK_DELIVERY_HEADER,
21 RELAY_HOOK_DELIVERY_TYP,
22 signRelayJwt,
23} from "@t3tools/shared/relayJwt";
24​
25import * as RelayConfiguration from "../Config.ts";
26import { MANAGED_ENDPOINT_KEY_PATTERN } from "../deploymentConfig.ts";
27import * as HeldHooks from "./HeldHooks.ts";
28import * as HookInbox from "./HookInbox.ts";
29import { sendUpstream, TUNNEL_OFFLINE_STATUS } from "./upstream.ts";
30​
31const RELAY_HOOK_PATH_PREFIX = "/v1/hooks/";
32export const RELAY_HOOK_MAX_BODY_BYTES = 1_048_576;
33export const RELAY_HOOK_RATE_LIMIT = { limit: 60, periodSeconds: 60 } as const;
34/** URL budgets alone are bypassable by minting URLs; cap each endpoint too. */
35export const RELAY_HOOK_ENDPOINT_RATE_LIMIT = { limit: 600, periodSeconds: 60 } as const;
36/** No tunnel origin (530) or local server unavailable (502/503/504) means the environment did not take the request. */
37const ENVIRONMENT_UNREACHABLE_STATUSES: ReadonlySet<number> = new Set([
38 502,
39 503,
40 504,
41 TUNNEL_OFFLINE_STATUS,
42]);
43​
44const DROPPED_REQUEST_HEADERS = new Set([
45 "host",
46 "connection",
47 "keep-alive",
48 "transfer-encoding",
49 "te",
50 "upgrade",
51 "content-length",
52 "cookie",
53 "x-real-ip",
54 // Only the relay may set this; a sender could otherwise collide delivery ids.
55 "x-t3-relay-delivery-id",
56 "x-t3-relay-received-at",
57 RELAY_HOOK_DELIVERY_HEADER,
58 // The environment trusts trace context only from the relay, which sets its own.
59 "traceparent",
60 "tracestate",
61 "b3",
62]);
63const DROPPED_REQUEST_HEADER_PREFIXES = ["proxy-", "cf-", "x-forwarded-", "x-b3-"];
64​
65export const isRelayHookPath = (url: string): boolean => url.startsWith(RELAY_HOOK_PATH_PREFIX);
66​
67export const redactRelayHookUrl = (url: string): string => {
68 const path = url.split("?", 1)[0] ?? url;
69 const segments = path.split("/");
70 if (segments.length >= 6) {
71 segments[5] = "redacted";
72 }
73 return segments.join("/");
74};
75​
76/** Budget decoded tokens so equivalent spellings share limits and wrong tokens cannot exhaust a real sender's budget. */
77const hookBudgetKey = (hook: {
78 readonly endpointKey: string;
79 readonly hookId: string;
80 readonly token: string;
81}) =>
82 Effect.promise(() =>
83 crypto.subtle.digest(
84 "SHA-256",
85 // Length-prefixed, so no segment contents can make two keys collide.
86 new TextEncoder().encode(
87 [hook.endpointKey, hook.hookId, hook.token]
88 .map((part) => `${part.length}:${part}`)
89 .join(""),
90 ),
91 ),
92 ).pipe(
93 Effect.map((digest) =>
94 Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""),
95 ),
96 );
97​
98export class HookRateLimiter extends Context.Service<
99 HookRateLimiter,
100 {
101 readonly allowHook: (key: string) => Effect.Effect<boolean>;
102 readonly allowEndpoint: (endpointKey: string) => Effect.Effect<boolean>;
103 }
104>()("t3code-relay/hooks/HookForwarder/HookRateLimiter") {}
105​
106export class HookForwarder extends Context.Service<
107 HookForwarder,
108 {
109 readonly handle: (
110 request: HttpServerRequest.HttpServerRequest,
111 ) => Effect.Effect<HttpServerResponse.HttpServerResponse>;
112 }
113>()("t3code-relay/hooks/HookForwarder") {}
114​
115class HookBodyTooLarge extends Schema.TaggedError<HookBodyTooLarge>()("HookBodyTooLarge", {}) {}
116​
117const errorResponse = (status: number, error: string, headers?: Record<string, string>) =>
118 HttpServerResponse.jsonUnsafe({ error }, { status, ...(headers ? { headers } : {}) });
119​
120const hookNotFound = () => errorResponse(404, "hook_not_found");
121​
122/** Longer than the inbox holds a request, so a held delivery's proof still verifies. */
123const DELIVERY_PROOF_LIFETIME_SECONDS = 25 * 60 * 60;
124​
125// HEAD reaches GET routing but must be refused.
126const FORWARDED_METHODS = new Set(["GET", "POST", "PUT", "PATCH"]);
127​
128// Environment responses use the relay origin; never let their bodies render or run there.
129const SANDBOXED_RESPONSE_HEADERS = {
130 "x-content-type-options": "nosniff",
131 "content-security-policy": "sandbox; default-src 'none'",
132} as const;
133​
134function parseHookPath(url: string) {
135 const queryIndex = url.indexOf("?");
136 const path = queryIndex === -1 ? url : url.slice(0, queryIndex);
137 const search = queryIndex === -1 ? "" : url.slice(queryIndex);
138 const segments = path.split("/");
139 if (segments.length !== 6) return null;
140 const [, , , endpointKey, rawHookId, rawToken] = segments;
141 if (!endpointKey || !MANAGED_ENDPOINT_KEY_PATTERN.test(endpointKey) || !rawHookId || !rawToken) {
142 return null;
143 }
144 try {
145 return {
146 endpointKey,
147 hookId: decodeURIComponent(rawHookId),
148 token: decodeURIComponent(rawToken),
149 // Forward the encoded segments byte-for-byte; the environment decodes them.
150 rawHookId,
151 rawToken,
152 search,
153 };
154 } catch {
155 return null;
156 }
158​
159function forwardedHeaders(headers: Readonly<Record<string, string>>): Record<string, string> {
160 const result: Record<string, string> = {};
161 // Headers the sender names in Connection are hop-by-hop too (RFC 9110 7.6.1).
162 const connectionValue =
163 Object.entries(headers).find(([name]) => name.toLowerCase() === "connection")?.[1] ?? "";
164 const nominated = new Set(
165 connectionValue
166 .split(",")
167 .map((name) => name.trim().toLowerCase())
168 .filter(Boolean),
169 );
170 for (const name in headers) {
171 const lower = name.toLowerCase();
172 if (
173 DROPPED_REQUEST_HEADERS.has(lower) ||
174 nominated.has(lower) ||
175 DROPPED_REQUEST_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix))
176 ) {
177 continue;
178 }
179 const value = headers[name];
180 if (value !== undefined) result[lower] = value;
181 }
182 return result;
184​
185const hasNoBody = (request: HttpServerRequest.HttpServerRequest) =>
186 request.source instanceof Request && request.source.body === null;
187​
188const readCappedBody = (request: HttpServerRequest.HttpServerRequest) =>
189 Effect.suspend(() => {
190 if (hasNoBody(request)) {
191 return Effect.succeed(new Uint8Array(0));
192 }
193 const chunks: Array<Uint8Array> = [];
194 let total = 0;
195 return request.stream.pipe(
196 Stream.runForEach((chunk) => {
197 total += chunk.length;
198 if (total > RELAY_HOOK_MAX_BODY_BYTES) {
199 return Effect.fail(new HookBodyTooLarge());
200 }
201 chunks.push(chunk);
202 return Effect.void;
203 }),
204 Effect.map(() => {
205 const body = new Uint8Array(total);
206 let offset = 0;
207 for (const chunk of chunks) {
208 body.set(chunk, offset);
209 offset += chunk.length;
210 }
211 return body;
212 }),
213 );
214 });
215​
216const make = Effect.gen(function* () {
217 const heldHooks = yield* HeldHooks.HeldHooks;
218 const settings = yield* RelayConfiguration.RelayConfiguration;
219 const httpClient = yield* HttpClient.HttpClient;
220 const rateLimiter = yield* HookRateLimiter;
221 const inbox = yield* HookInbox.HookInbox;
222 const crypto = yield* Crypto.Crypto;
223​
224 const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")(
225 function* (input: {
226 readonly environmentId: string;
227 readonly deliveryId: string;
228 readonly receivedAt: string;
229 readonly hookId: string;
230 readonly jti: string;
231 }) {
232 const now = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
233 return yield* signRelayJwt({
234 privateKey: Redacted.value(settings.cloudMintPrivateKey),
235 typ: RELAY_HOOK_DELIVERY_TYP,
236 payload: {
237 iss: normalizeRelayIssuer(settings.relayIssuer),
238 aud: `t3-env:${input.environmentId}`,
239 sub: input.environmentId,
240 jti: input.jti,
241 iat: now,
242 exp: now + DELIVERY_PROOF_LIFETIME_SECONDS,
243 environmentId: EnvironmentId.make(input.environmentId),
244 deliveryId: input.deliveryId,
245 receivedAt: input.receivedAt,
246 hookId: input.hookId,
247 } satisfies RelayHookDeliveryProofPayload,
248 });
249 },
250 (effect, _input) => effect.pipe(Effect.orDie),
251 );
252​
253 const handle = Effect.fn("relay.hooks.forward")(function* (
254 request: HttpServerRequest.HttpServerRequest,
255 ) {
256 const outcome = (value: string) => Effect.annotateCurrentSpan({ "relay.hook.outcome": value });
257 if (!FORWARDED_METHODS.has(request.method)) {
258 yield* outcome("method_not_allowed");
259 return errorResponse(405, "method_not_allowed", { allow: "GET, POST, PUT, PATCH" });
260 }
261 const receivedAt = DateTime.formatIso(yield* DateTime.now);
262 const parsed = parseHookPath(request.url);
263 if (!parsed) {
264 yield* outcome("invalid_path");
265 return hookNotFound();
266 }
267 yield* Effect.annotateCurrentSpan({
268 "relay.hook.endpoint_key": parsed.endpointKey,
269 "relay.hook_id": parsed.hookId,
270 });
271 const endpointAllowed = yield* rateLimiter.allowEndpoint(parsed.endpointKey);
272 const hookAllowed =
273 endpointAllowed && (yield* rateLimiter.allowHook(yield* hookBudgetKey(parsed)));
274 if (!endpointAllowed || !hookAllowed) {
275 yield* Effect.annotateCurrentSpan({
276 "relay.hook.rate_limit": endpointAllowed ? "hook" : "endpoint",
277 });
278 yield* outcome("rate_limited");
279 return errorResponse(429, "rate_limited", {
280 "retry-after": String(RELAY_HOOK_RATE_LIMIT.periodSeconds),
281 });
282 }
283 const declaredLength = Number(request.headers["content-length"] ?? "0");
284 if (Number.isFinite(declaredLength) && declaredLength > RELAY_HOOK_MAX_BODY_BYTES) {
285 yield* outcome("payload_too_large");
286 return errorResponse(413, "payload_too_large");
287 }
288​
289 const endpoint = yield* heldHooks.resolveEndpoint(parsed.endpointKey).pipe(
290 Effect.catch((error) =>
291 Effect.logWarning("Failed to resolve hook endpoint", {
292 endpointKey: parsed.endpointKey,
293 errorTag: error._tag,
294 }).pipe(Effect.as(null)),
295 ),
296 );
297 if (!endpoint) {
298 yield* outcome("not_found");
299 return hookNotFound();
300 }
301 yield* Effect.annotateCurrentSpan({
302 "relay.environment_id": endpoint.environmentId,
303 "relay.hook.hold_while_offline": endpoint.holdWhileOffline,
304 });
305​
306 const body =
307 request.method === "GET"
308 ? Result.succeed(new Uint8Array(0))
309 : yield* readCappedBody(request).pipe(Effect.result);
310 if (Result.isFailure(body)) {
311 if (body.failure._tag === "HookBodyTooLarge") {
312 yield* outcome("payload_too_large");
313 return errorResponse(413, "payload_too_large");
314 }
315 yield* outcome("invalid_body");
316 return errorResponse(400, "invalid_body");
317 }
318​
319 // Reuse one delivery ID so inbox retries cannot rerun requests that reached the environment before timeout.
320 yield* Effect.annotateCurrentSpan({ "relay.hook.body_bytes": body.success.byteLength });
321 const deliveryId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
322 // Sign once before storing held requests so the inbox needs no signing key.
323 const proof = yield* signDeliveryProof({
324 environmentId: endpoint.environmentId,
325 deliveryId,
326 receivedAt,
327 hookId: parsed.hookId,
328 jti: yield* crypto.randomUUIDv4().pipe(Effect.orDie),
329 });
330 const hook = {
331 id: deliveryId,
332 receivedAt,
333 method: request.method,
334 rawHookId: parsed.rawHookId,
335 rawToken: parsed.rawToken,
336 hookKey: parsed.hookId,
337 query: parsed.search.replace(/^\?/, ""),
338 headers: { ...forwardedHeaders(request.headers), [RELAY_HOOK_DELIVERY_HEADER]: proof },
339 body: body.success,
340 };
341 // Keep offline outcomes on the enclosing relay.hooks.forward span.
342 const holdOrFail = Effect.fnUntraced(function* (status: 503 | 504, error: string) {
343 if (!endpoint.holdWhileOffline) {
344 yield* outcome(error);
345 return errorResponse(status, error);
346 }
347 const stored = yield* inbox
348 .hold({
349 endpointKey: parsed.endpointKey,
350 baseUrl: endpoint.httpBaseUrl,
351 hook,
352 })
353 .pipe(
354 Effect.catch((cause) =>
355 Effect.logWarning("Could not hold webhook request", {
356 environmentId: endpoint.environmentId,
357 errorTag: cause._tag,
358 }).pipe(Effect.as(null)),
359 ),
360 );
361 if (stored === null) {
362 yield* outcome(error);
363 return errorResponse(status, error);
364 }
365 if (!stored) {
366 yield* outcome("inbox_full");
367 return errorResponse(503, "inbox_full");
368 }
369 yield* outcome("held");
370 return HttpServerResponse.jsonUnsafe({ queued: true }, { status: 202 });
371 });
372​
373 const upstream = yield* sendUpstream(endpoint.httpBaseUrl, hook).pipe(
374 Effect.provideService(HttpClient.HttpClient, httpClient),
375 Effect.result,
376 );
377 if (Result.isFailure(upstream)) {
378 yield* Effect.annotateCurrentSpan({ "relay.hook.upstream_error": upstream.failure._tag });
379 return yield* holdOrFail(503, "environment_unavailable");
380 }
381 if (Option.isNone(upstream.success)) {
382 return yield* holdOrFail(504, "environment_timeout");
383 }
384 const response = upstream.success.value;
385 if (ENVIRONMENT_UNREACHABLE_STATUSES.has(response.status)) {
386 yield* Effect.annotateCurrentSpan({ "relay.hook.upstream_status": response.status });
387 return yield* holdOrFail(503, "environment_unavailable");
388 }
389 yield* Effect.annotateCurrentSpan({
390 "relay.hook.outcome": "forwarded",
391 "relay.hook.upstream_status": response.status,
392 ...(response.outcome === undefined
393 ? {}
394 : { "relay.hook.upstream_outcome": response.outcome }),
395 });
396 const headers = {
397 ...SANDBOXED_RESPONSE_HEADERS,
398 ...(response.contentType ? { "content-type": response.contentType } : {}),
399 };
400 if (response.body.length === 0) {
401 return HttpServerResponse.empty({ status: response.status, headers });
402 }
403 return HttpServerResponse.uint8Array(response.body, {
404 status: response.status,
405 headers,
406 ...(response.contentType ? { contentType: response.contentType } : {}),
407 });
408 });
409​
410 return HookForwarder.of({ handle });
411});
412​
413export const layer = Layer.effect(HookForwarder, make);
414​
415export const layerApi = HttpApiBuilder.group(
416 RelayApi,
417 "hooks",
418 Effect.fnUntraced(function* (handlers) {
419 const forwarder = yield* HookForwarder;
420 const forward = ({ request }: { readonly request: HttpServerRequest.HttpServerRequest }) =>
421 forwarder.handle(request);
422 return handlers
423 .handleRaw("forwardPost", forward)
424 .handleRaw("forwardPut", forward)
425 .handleRaw("forwardPatch", forward)
426 .handleRaw("forwardGet", forward);
427 }),
428);