feat(relay): forward webhook requests to the environment's tunnel #15086
Mergedjuliusmarmingemerged 8 commits into
t3code/webhooks-server fromrefs/pull/15086/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge changed the title
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- infra/relay/src/environments/EnvironmentLinks.ts line 364Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -324,0 +344,21 @@344+ findActiveManagedForEnvironment: Effect.fn(345+ "relay.environment_links.find_active_managed_for_environment",346+ )(function* (input) {347+ yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });348+ return yield* db349+ .select({350+ userId: relayEnvironmentLinks.userId,351+ environmentId: relayEnvironmentLinks.environmentId,352+ environmentLabel: relayEnvironmentLinks.environmentLabel,353+ environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,354+ endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,355+ endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,356+ endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,357+ createdAt: relayEnvironmentLinks.createdAt,358+ })359+ .from(relayEnvironmentLinks)360+ .where(361+ and(362+ eq(relayEnvironmentLinks.environmentId, input.environmentId),363+ isNull(relayEnvironmentLinks.revokedAt),364+ eq(relayEnvironmentLinks.endpointProviderKind, "cloudflare_tunnel"),infra/relay/src/environments/EnvironmentLinks.ts line 367OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -324,0 +347,21 @@347+ yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });348+ return yield* db349+ .select({350+ userId: relayEnvironmentLinks.userId,351+ environmentId: relayEnvironmentLinks.environmentId,352+ environmentLabel: relayEnvironmentLinks.environmentLabel,353+ environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,354+ endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,355+ endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,356+ endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,357+ createdAt: relayEnvironmentLinks.createdAt,358+ })359+ .from(relayEnvironmentLinks)360+ .where(361+ and(362+ eq(relayEnvironmentLinks.environmentId, input.environmentId),363+ isNull(relayEnvironmentLinks.revokedAt),364+ eq(relayEnvironmentLinks.endpointProviderKind, "cloudflare_tunnel"),365+ ),366+ )367+ .limit(5)@@ -283,3 +291,7 @@283291 Layer.provide(runtimeLayer),284292 );285293294+ // Fails open: a limiter outage must not drop webhooks the environment would accept.295+ const hookRateLimiterLayer = Layer.succeed(HookForwarder.HookRateLimiter, {296+ allow: (key) =>297+ hookRateLimit.limit({ key }).pipe(
- infra/relay/src/environments/EnvironmentLinks.ts lines 341 to 399Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -325,3 +377,21 @@377+ wsBaseUrl: row.endpointWsBaseUrl,378+ providerKind:379+ row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],380+ },381+ environmentPublicKey: row.environmentPublicKey,382+ linkedAt: row.createdAt,383+ })),384+ ),385+ Effect.mapError(386+ (cause) =>387+ new EnvironmentLinkEnvironmentLookupPersistenceError({388+ environmentId: input.environmentId,389+ cause,390+ }),391+ ),392+ );393+ }),394+325395 revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {326396 yield* Effect.annotateCurrentSpan({327397 "relay.environment_id": input.environmentId,infra/relay/src/hooks/HookForwarder.ts lines 56 to 62Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +38,21 @@38+const DROPPED_REQUEST_HEADER_PREFIXES = ["proxy-", "cf-", "x-forwarded-"];39+// Cloudflare answers 530 when the tunnel for a hostname has no connected origin.40+const TUNNEL_OFFLINE_STATUS = 530;41+42+export const isRelayHookPath = (url: string): boolean => url.startsWith(RELAY_HOOK_PATH_PREFIX);43+44+/** Replaces the hook token (and any query) so traces and logs never record the secret. */45+export const redactRelayHookUrl = (url: string): string => {46+ const path = url.split("?", 1)[0] ?? url;47+ const segments = path.split("/");48+ if (segments.length >= 6) {49+ segments[5] = "<redacted>";50+ }51+ return segments.join("/");52+};53+54+/**55+ * Per-environment request budget for public hook forwarding. The key is the56+ * environment id only, because the sender chooses the hook id; the environment57+ * enforces its own per-hook limits.58+ */infra/relay/src/http/Api.ts lines 228 to 272Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -229,3 +250,21 @@250+ ),251+ ).pipe(252+ Effect.provideService(HttpServerRequest.HttpServerRequest, redacted),253+ Effect.ensuring(Effect.yieldNow),254+ );255+ });256+257+// Webhook senders put shared secrets and signatures in headers such as258+// x-hub-signature-256, stripe-signature and x-gitlab-token.259+const webhookHeaderRedactionLayer = Layer.effect(260+ Headers.CurrentRedactedNames,261+ Effect.map(Headers.CurrentRedactedNames, (names) => [262+ ...names,263+ /signature/i,264+ /token/i,265+ /secret/i,266+ ]),267+);229268230269 export const traceRelayHttpRequestWith = <E, R, LayerError, LayerRequirements>(231270 httpEffect: Effect.Effect<
- infra/relay/src/hooks/HookForwarder.ts lines 66 to 66OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +46,21 @@46+ const segments = path.split("/");47+ if (segments.length >= 6) {48+ segments[5] = "<redacted>";49+ }50+ return segments.join("/");51+};52+53+/**54+ * Request budget for public hook forwarding, keyed by a hash of the full hook55+ * URL (environment, hook and token). Requests with a wrong token get their own56+ * budget, so they cannot use up a real sender's; the environment rejects them.57+ */58+const hookBudgetKey = (hook: {59+ readonly environmentId: string;60+ readonly rawHookId: string;61+ readonly rawToken: string;62+}) =>63+ Effect.promise(() =>64+ crypto.subtle.digest(65+ "SHA-256",66+ new TextEncoder().encode(`${hook.environmentId}/${hook.rawHookId}/${hook.rawToken}`),
- infra/relay/src/hooks/HookForwarder.ts lines 130 to 154Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +120,21 @@120+ };121+ } catch {122+ return null;123+ }124+}125+126+function forwardedHeaders(headers: Readonly<Record<string, string>>): Record<string, string> {127+ const result: Record<string, string> = {};128+ for (const name in headers) {129+ const lower = name.toLowerCase();130+ if (131+ DROPPED_REQUEST_HEADERS.has(lower) ||132+ DROPPED_REQUEST_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix))133+ ) {134+ continue;135+ }136+ const value = headers[name];137+ if (value !== undefined) result[lower] = value;138+ }139+ return result;140+}
- @@ -0,0 +227,21 @@227+ const declaredLength = Number(request.headers["content-length"] ?? "0");228+ if (Number.isFinite(declaredLength) && declaredLength > RELAY_HOOK_MAX_BODY_BYTES) {229+ yield* outcome("payload_too_large");230+ return errorResponse(413, "payload_too_large");231+ }232+233+ const endpoint = yield* resolveEndpoint(parsed.environmentId).pipe(234+ Effect.catch((error) =>235+ Effect.logWarning("Failed to resolve hook endpoint", {236+ environmentId: parsed.environmentId,237+ errorTag: error._tag,238+ }).pipe(Effect.as(null)),239+ ),240+ );241+ if (!endpoint) {242+ yield* outcome("not_found");243+ return hookNotFound();244+ }245+246+ const body =247+ request.method === "GET"
- infra/relay/src/hooks/HookForwarder.ts line 276OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +256,21 @@256+ return errorResponse(400, "invalid_body");257+ }258+259+ const baseUrl = endpoint.httpBaseUrl.endsWith("/")260+ ? endpoint.httpBaseUrl261+ : `${endpoint.httpBaseUrl}/`;262+ const headers = forwardedHeaders(request.headers);263+ let upstreamRequest = HttpClientRequest.make(264+ request.method as "GET" | "POST" | "PUT" | "PATCH",265+ )(`${baseUrl}api/hooks/${parsed.rawHookId}/${parsed.rawToken}${parsed.search}`, { headers });266+ if (request.method !== "GET") {267+ upstreamRequest = HttpClientRequest.bodyUint8Array(268+ upstreamRequest,269+ body.success,270+ headers["content-type"],271+ );272+ }273+274+ const upstream = yield* httpClient.execute(upstreamRequest).pipe(275+ Effect.flatMap((response) =>276+ response.arrayBuffer.pipe(
juliusmarminge merged thisb070e52
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
3230279· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.