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

environmentHttpAuth.ts

269 lines9.7 KB

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