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

environmentHttpAuth.ts

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