Open History to see the last commit
1import { msg } from "gt-i18n";
2import { translatableMessage } from "../errors/translatable.ts";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import {
6 ORCHESTRATION_PROTOCOL_HEADER,
7 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
8} from "@t3tools/contracts";
9import * as Result from "effect/Result";
10import * as SubscriptionRef from "effect/SubscriptionRef";
11import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
12import { FetchHttpClient, HttpClientError, type HttpMethod } from "effect/http";
13
14import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
15import type { PreparedConnection, PreparedHttpAuthorization } from "../connection/model.ts";
16import * as EnvironmentRegistry from "../connection/registry.ts";
17import * as EnvironmentSupervisor from "../connection/supervisor.ts";
18import * as ManagedRelay from "../relay/managedRelay.ts";
19import {
20 executeEnvironmentHttpRequest,
21 makeEnvironmentHttpApiGroupClient,
22 makeEnvironmentHttpApiUrlBuilder,
23 RemoteEnvironmentAuthFetchError,
24 RemoteEnvironmentAuthTimeoutError,
25 type RemoteEnvironmentRequestError,
26} from "../rpc/http.ts";
27
28export interface EnvironmentHttpAuthHeaders {
29 readonly authorization?: string;
30 readonly dpop?: string;
31}
32
33export function withOrchestrationProtocolHeader(
34 headers: EnvironmentHttpAuthHeaders,
35): EnvironmentHttpAuthHeaders & {
36 readonly [ORCHESTRATION_PROTOCOL_HEADER]: typeof ORCHESTRATION_PROTOCOL_VERSION_TEXT;
37} {
38 return {
39 ...headers,
40 [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT,
41 };
42}
43
44/**
45 * Cookie-authenticated environments need credentialed mode for cross-origin fetches; bearer/DPoP uses headers.
46 * `FetchHttpClient` reads `RequestInit` from the fiber context per request.
47 */
48const withEnvironmentRequestInit = <A, E, R>(
49 authorization: PreparedHttpAuthorization | null,
50 requestInit: RequestInit | undefined,
51 request: Effect.Effect<A, E, R>,
52): Effect.Effect<A, E, R> => {
53 if (authorization !== null && requestInit === undefined) return request;
54 return request.pipe(
55 Effect.provideService(FetchHttpClient.RequestInit, {
56 ...requestInit,
57 ...(authorization === null ? { credentials: "include" as const } : {}),
58 }),
59 );
60};
61
62const buildEnvironmentAuthHeaders = Effect.fn("environmentHttpAuth.buildEnvironmentAuthHeaders")(
63 function* (
64 authorization: PreparedHttpAuthorization | null,
65 method: HttpMethod.HttpMethod,
66 url: string,
67 signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>,
68 ): Effect.fn.Return<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> {
69 if (authorization === null) {
70 return {};
71 }
72 if (authorization._tag === "Bearer") {
73 return { authorization: `Bearer ${authorization.token}` };
74 }
75 if (Option.isNone(signer)) {
76 return yield* new RemoteEnvironmentAuthFetchError({
77 ...translatableMessage(
78 msg("No DPoP signer is available to authorize the environment request."),
79 ),
80 cause: authorization._tag,
81 });
82 }
83 const proof = yield* signer.value
84 .createProof({ method, url, accessToken: authorization.accessToken })
85 .pipe(
86 Effect.mapError(
87 (cause) =>
88 new RemoteEnvironmentAuthFetchError({
89 ...translatableMessage(
90 msg("Could not create the environment request authorization proof."),
91 ),
92 cause,
93 }),
94 ),
95 );
96 return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof };
97 },
98);
99
100/**
101 * A DPoP request is T3 Connect work, so its span starts an exported trace that
102 * the environment continues; its local caller's span would leave that trace
103 * without a root.
104 */
105export const executeAuthenticatedEnvironmentHttpRequest = <
106 Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1],
107 A,
108 E,
109 R,
110>(
111 input: Parameters<typeof executeEnvironmentRequest<Group, A, E, R>>[0],
112) =>
113 input.prepared.httpAuthorization?._tag === "Dpop"
114 ? executeEnvironmentRequest(input).pipe(
115 Effect.withSpan(ENVIRONMENT_REQUEST_SPAN, { root: true }),
116 withRelayClientTracing,
117 )
118 : executeEnvironmentRequest(input).pipe(Effect.withSpan(ENVIRONMENT_REQUEST_SPAN));
119
120const HTTP_ORIGIN_REPORT_TIMEOUT_MS = 5_000;
121
122function isHttpOriginTransportFailure(error: RemoteEnvironmentRequestError): boolean {
123 return (
124 error._tag === "RemoteEnvironmentAuthTimeoutError" ||
125 (error._tag === "RemoteEnvironmentAuthFetchError" &&
126 HttpClientError.isHttpClientError(error.cause) &&
127 error.cause.reason._tag === "TransportError")
128 );
129}
130
131/** Sends the request with this client's own credentials on the supervised environment. */
132export const executeConnectedEnvironmentHttpRequest = Effect.fn(
133 "clientRuntime.state.executeConnectedEnvironmentHttpRequest",
134)(function* <Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1], A, E, R>(
135 input: Omit<
136 Parameters<typeof executeEnvironmentRequest<Group, A, E, R>>[0],
137 "prepared" | "signer" | "remoteAuthorization"
138 >,
139) {
140 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
141 const prepared = yield* SubscriptionRef.get(supervisor.prepared);
142 if (Option.isNone(prepared)) {
143 return yield* new RemoteEnvironmentAuthFetchError({
144 ...translatableMessage(msg("The environment is not connected.")),
145 cause: supervisor.target._tag,
146 });
147 }
148 return yield* executeAuthenticatedEnvironmentHttpRequest({
149 ...input,
150 prepared: prepared.value,
151 signer: yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner),
152 remoteAuthorization: yield* Effect.serviceOption(
153 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
154 ),
155 });
156});
157
158const ENVIRONMENT_REQUEST_SPAN = "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest";
159
160const executeEnvironmentRequest = Effect.fnUntraced(function* <
161 Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1],
162 A,
163 E,
164 R,
165>(input: {
166 readonly prepared: Pick<
167 PreparedConnection,
168 "environmentId" | "httpBaseUrl" | "httpAuthorization" | "target"
169 >;
170 readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
171 readonly remoteAuthorization?: Option.Option<
172 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
173 >;
174 readonly method: HttpMethod.HttpMethod;
175 /**
176 * The URL to sign, from the group's contract URL builder. It encodes path
177 * params exactly like the request client, so the DPoP proof matches the
178 * URL actually sent.
179 */
180 readonly url: (urls: ReturnType<typeof makeEnvironmentHttpApiUrlBuilder>[Group]) => string;
181 readonly timeoutMs: number;
182 /** Extra fetch options, such as refusing redirects for credentialed audio uploads. */
183 readonly requestInit?: RequestInit;
184 readonly group: Group;
185 readonly request: (input: {
186 readonly client: Effect.Success<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>>;
187 readonly headers: EnvironmentHttpAuthHeaders;
188 }) => Effect.Effect<A, E, R>;
189 /** Some endpoints report rejected credentials in a successful response. */
190 readonly isUnauthorizedResponse?: (response: NoInfer<A>) => boolean;
191}): Effect.fn.Return<
192 A,
193 RemoteEnvironmentRequestError,
194 Effect.Services<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>> | R
195> {
196 const supervisor = yield* Effect.serviceOption(EnvironmentSupervisor.EnvironmentSupervisor);
197 const registry = yield* Effect.serviceOption(EnvironmentRegistry.EnvironmentRegistry);
198 const reportHttpOriginTransportFailure = (failedOrigin: string) => {
199 const checkForSupervisor = (
200 candidate: EnvironmentSupervisor.EnvironmentSupervisor["Service"],
201 ) =>
202 candidate.target.environmentId === input.prepared.environmentId &&
203 candidate.checkHttpOrigin !== undefined
204 ? SubscriptionRef.get(candidate.prepared).pipe(
205 Effect.flatMap((current) =>
206 Option.isSome(current) && current.value.httpBaseUrl === failedOrigin
207 ? candidate.checkHttpOrigin!
208 : Effect.void,
209 ),
210 )
211 : Effect.void;
212 if (
213 Option.isSome(supervisor) &&
214 supervisor.value.target.environmentId === input.prepared.environmentId
215 ) {
216 return checkForSupervisor(supervisor.value);
217 }
218 if (Option.isSome(registry) && typeof registry.value.run === "function") {
219 return Effect.forkDetach(
220 registry.value
221 .run(
222 input.prepared.environmentId,
223 EnvironmentSupervisor.EnvironmentSupervisor.pipe(Effect.flatMap(checkForSupervisor)),
224 )
225 .pipe(Effect.timeoutOption(HTTP_ORIGIN_REPORT_TIMEOUT_MS), Effect.ignore),
226 { startImmediately: true },
227 ).pipe(Effect.asVoid);
228 }
229 return Effect.void;
230 };
231
232 let httpBaseUrl = input.prepared.httpBaseUrl;
233 let requestInFlight = false;
234 const requestUrlFor = (baseUrl: string) =>
235 input.url(makeEnvironmentHttpApiUrlBuilder(baseUrl)[input.group]);
236 return yield* Effect.gen(function* () {
237 let rejectedAccessToken: string | undefined;
238 for (;;) {
239 let authorization = input.prepared.httpAuthorization;
240 if (authorization?._tag === "Dpop") {
241 const remote = input.remoteAuthorization;
242 if (remote === undefined || Option.isNone(remote)) {
243 return yield* new RemoteEnvironmentAuthFetchError({
244 ...translatableMessage(
245 msg("No relay authorization service is available for the environment request."),
246 ),
247 cause: input.prepared.target._tag,
248 });
249 }
250 const authFetchError = (cause: unknown) =>
251 new RemoteEnvironmentAuthFetchError({
252 ...translatableMessage(msg("Could not authorize the environment request.")),
253 cause,
254 });
255 const direct = authorization.directConnection;
256 if (direct !== undefined) {
257 authorization = yield* remote.value
258 .authorizeDirectDpopHttp(direct, rejectedAccessToken)
259 .pipe(Effect.mapError(authFetchError));
260 } else {
261 const current = yield* remote.value
262 .authorizeDpopHttp({
263 expectedEnvironmentId: input.prepared.environmentId,
264 ...(rejectedAccessToken === undefined ? {} : { rejectedAccessToken }),
265 })
266 .pipe(Effect.mapError(authFetchError));
267 // A learned direct route keeps its own origin; only the token renews.
268 if (input.prepared.target._tag === "RelayConnectionTarget") {
269 httpBaseUrl = current.httpBaseUrl;
270 }
271 authorization = current.httpAuthorization;
272 }
273 }
274
275 const requestUrl = requestUrlFor(httpBaseUrl);
276 const client = yield* makeEnvironmentHttpApiGroupClient(httpBaseUrl, input.group);
277 const headers = yield* buildEnvironmentAuthHeaders(
278 authorization,
279 input.method,
280 requestUrl,
281 input.signer,
282 );
283 requestInFlight = true;
284 const result = yield* executeEnvironmentHttpRequest(
285 requestUrl,
286 input.timeoutMs,
287 withEnvironmentRequestInit(
288 authorization,
289 input.requestInit,
290 input.request({ client, headers }),
291 ),
292 ).pipe(Effect.result);
293 requestInFlight = false;
294
295 if (Result.isFailure(result)) {
296 if (
297 authorization?._tag === "Dpop" &&
298 rejectedAccessToken === undefined &&
299 result.failure._tag === "EnvironmentAuthInvalidError" &&
300 result.failure.reason === "invalid_credential"
301 ) {
302 rejectedAccessToken = authorization.accessToken;
303 continue;
304 }
305 if (isHttpOriginTransportFailure(result.failure)) {
306 yield* reportHttpOriginTransportFailure(httpBaseUrl);
307 }
308 return yield* result.failure;
309 }
310
311 if (
312 authorization?._tag === "Dpop" &&
313 input.isUnauthorizedResponse?.(result.success) === true
314 ) {
315 if (rejectedAccessToken === undefined) {
316 rejectedAccessToken = authorization.accessToken;
317 continue;
318 }
319 return yield* new RemoteEnvironmentAuthFetchError({
320 ...translatableMessage(
321 msg("The environment rejected the renewed session authorization."),
322 ),
323 cause: result.success,
324 });
325 }
326 return result.success;
327 }
328 }).pipe(
329 Effect.timeoutOrElse({
330 duration: input.timeoutMs,
331 orElse: () =>
332 (requestInFlight ? reportHttpOriginTransportFailure(httpBaseUrl) : Effect.void).pipe(
333 Effect.andThen(
334 Effect.fail(
335 new RemoteEnvironmentAuthTimeoutError({
336 requestUrl: requestUrlFor(httpBaseUrl),
337 timeoutMs: input.timeoutMs,
338 }),
339 ),
340 ),
341 ),
342 }),
343 );
344});