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

HookForwarder.ts

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