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