Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import {
4 ORCHESTRATION_PROTOCOL_HEADER,
5 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
6} from "@t3tools/contracts";
7import * as Result from "effect/Result";
8import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
9import { FetchHttpClient, type HttpMethod } from "effect/http";
10
11import type { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
12import type { PreparedConnection, PreparedHttpAuthorization } from "../connection/model.ts";
13import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
14import {
15 executeEnvironmentHttpRequest,
16 makeEnvironmentHttpApiGroupClient,
17 makeEnvironmentHttpApiUrlBuilder,
18 RemoteEnvironmentAuthFetchError,
19 RemoteEnvironmentAuthTimeoutError,
20 type RemoteEnvironmentRequestError,
21} from "../rpc/http.ts";
22
23export interface EnvironmentHttpAuthHeaders {
24 readonly authorization?: string;
25 readonly dpop?: string;
26}
27
28export function withOrchestrationProtocolHeader(
29 headers: EnvironmentHttpAuthHeaders,
30): EnvironmentHttpAuthHeaders & {
31 readonly [ORCHESTRATION_PROTOCOL_HEADER]: typeof ORCHESTRATION_PROTOCOL_VERSION_TEXT;
32} {
33 return {
34 ...headers,
35 [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT,
36 };
37}
38
39/**
40 * Cookie-authenticated environments need credentialed mode for cross-origin fetches; bearer/DPoP uses headers.
41 * `FetchHttpClient` reads `RequestInit` from the fiber context per request.
42 */
43const withEnvironmentCredentials = <A, E, R>(
44 authorization: PreparedHttpAuthorization | null,
45 request: Effect.Effect<A, E, R>,
46): Effect.Effect<A, E, R> =>
47 authorization === null
48 ? request.pipe(Effect.provideService(FetchHttpClient.RequestInit, { credentials: "include" }))
49 : request;
50
51const buildEnvironmentAuthHeaders = Effect.fn("environmentHttpAuth.buildEnvironmentAuthHeaders")(
52 function* (
53 authorization: PreparedHttpAuthorization | null,
54 method: HttpMethod.HttpMethod,
55 url: string,
56 signer: Option.Option<ManagedRelayDpopSigner["Service"]>,
57 ): Effect.fn.Return<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> {
58 if (authorization === null) {
59 return {};
60 }
61 if (authorization._tag === "Bearer") {
62 return { authorization: `Bearer ${authorization.token}` };
63 }
64 if (Option.isNone(signer)) {
65 return yield* new RemoteEnvironmentAuthFetchError({
66 message: "No DPoP signer is available to authorize the environment request.",
67 cause: authorization._tag,
68 });
69 }
70 const proof = yield* signer.value
71 .createProof({ method, url, accessToken: authorization.accessToken })
72 .pipe(
73 Effect.mapError(
74 (cause) =>
75 new RemoteEnvironmentAuthFetchError({
76 message: "Could not create the environment request authorization proof.",
77 cause,
78 }),
79 ),
80 );
81 return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof };
82 },
83);
84
85/**
86 * A DPoP request is T3 Connect work, so its span starts an exported trace that
87 * the environment continues; its local caller's span would leave that trace
88 * without a root.
89 */
90export const executeAuthenticatedEnvironmentHttpRequest = <
91 Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1],
92 A,
93 E,
94 R,
95>(
96 input: Parameters<typeof executeEnvironmentRequest<Group, A, E, R>>[0],
97) =>
98 input.prepared.httpAuthorization?._tag === "Dpop"
99 ? executeEnvironmentRequest(input).pipe(
100 Effect.withSpan(ENVIRONMENT_REQUEST_SPAN, { root: true }),
101 withRelayClientTracing,
102 )
103 : executeEnvironmentRequest(input).pipe(Effect.withSpan(ENVIRONMENT_REQUEST_SPAN));
104
105const ENVIRONMENT_REQUEST_SPAN = "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest";
106
107const executeEnvironmentRequest = Effect.fnUntraced(function* <
108 Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1],
109 A,
110 E,
111 R,
112>(input: {
113 readonly prepared: PreparedConnection;
114 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
115 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
116 readonly method: HttpMethod.HttpMethod;
117 /**
118 * The URL to sign, from the group's contract URL builder. It encodes path
119 * params exactly like the request client, so the DPoP proof matches the
120 * URL actually sent.
121 */
122 readonly url: (urls: ReturnType<typeof makeEnvironmentHttpApiUrlBuilder>[Group]) => string;
123 readonly timeoutMs: number;
124 readonly group: Group;
125 readonly request: (input: {
126 readonly client: Effect.Success<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>>;
127 readonly headers: EnvironmentHttpAuthHeaders;
128 }) => Effect.Effect<A, E, R>;
129 /** Some endpoints report rejected credentials in a successful response. */
130 readonly isUnauthorizedResponse?: (response: NoInfer<A>) => boolean;
131}): Effect.fn.Return<
132 A,
133 RemoteEnvironmentRequestError,
134 Effect.Services<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>> | R
135> {
136 let httpBaseUrl = input.prepared.httpBaseUrl;
137 const requestUrlFor = (baseUrl: string) =>
138 input.url(makeEnvironmentHttpApiUrlBuilder(baseUrl)[input.group]);
139 return yield* Effect.gen(function* () {
140 let rejectedAccessToken: string | undefined;
141 for (;;) {
142 let authorization = input.prepared.httpAuthorization;
143 if (authorization?._tag === "Dpop") {
144 const remote = input.remoteAuthorization;
145 if (remote === undefined || Option.isNone(remote)) {
146 return yield* new RemoteEnvironmentAuthFetchError({
147 message: "No relay authorization service is available for the environment request.",
148 cause: input.prepared.target._tag,
149 });
150 }
151 const current = yield* remote.value
152 .authorizeDpopHttp({
153 expectedEnvironmentId: input.prepared.environmentId,
154 ...(rejectedAccessToken === undefined ? {} : { rejectedAccessToken }),
155 })
156 .pipe(
157 Effect.mapError(
158 (cause) =>
159 new RemoteEnvironmentAuthFetchError({
160 message: "Could not authorize the environment request.",
161 cause,
162 }),
163 ),
164 );
165 // A learned direct route keeps its own origin; only the token renews.
166 if (input.prepared.target._tag === "RelayConnectionTarget") {
167 httpBaseUrl = current.httpBaseUrl;
168 }
169 authorization = current.httpAuthorization;
170 }
171
172 const requestUrl = requestUrlFor(httpBaseUrl);
173 const client = yield* makeEnvironmentHttpApiGroupClient(httpBaseUrl, input.group);
174 const headers = yield* buildEnvironmentAuthHeaders(
175 authorization,
176 input.method,
177 requestUrl,
178 input.signer,
179 );
180 const result = yield* executeEnvironmentHttpRequest(
181 requestUrl,
182 input.timeoutMs,
183 withEnvironmentCredentials(authorization, input.request({ client, headers })),
184 ).pipe(Effect.result);
185
186 if (Result.isFailure(result)) {
187 if (
188 authorization?._tag === "Dpop" &&
189 rejectedAccessToken === undefined &&
190 result.failure._tag === "EnvironmentAuthInvalidError" &&
191 result.failure.reason === "invalid_credential"
192 ) {
193 rejectedAccessToken = authorization.accessToken;
194 continue;
195 }
196 return yield* result.failure;
197 }
198
199 if (
200 authorization?._tag === "Dpop" &&
201 input.isUnauthorizedResponse?.(result.success) === true
202 ) {
203 if (rejectedAccessToken === undefined) {
204 rejectedAccessToken = authorization.accessToken;
205 continue;
206 }
207 return yield* new RemoteEnvironmentAuthFetchError({
208 message: "The environment rejected the renewed session authorization.",
209 cause: result.success,
210 });
211 }
212 return result.success;
213 }
214 }).pipe(
215 Effect.timeoutOrElse({
216 duration: input.timeoutMs,
217 orElse: () =>
218 Effect.fail(
219 new RemoteEnvironmentAuthTimeoutError(requestUrlFor(httpBaseUrl), input.timeoutMs),
220 ),
221 }),
222 );
223});