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

environmentHttpAuth.ts

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