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

service.ts

320 lines11.9 KB

1import {
2 type ClientConnectionMethod,
3 EnvironmentId,
4 type ExecutionEnvironmentDescriptor,
5} from "@t3tools/contracts";
6import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
7import {
8 exchangeRemoteDpopAccessToken,
9 type RemoteEnvironmentAuthError,
10 resolveRemoteDpopWebSocketConnectionUrl,
11 resolveRemoteWebSocketConnectionUrl,
12} from "./remote.ts";
13import {
14 environmentMismatchError,
15 mapRemoteDpopEnvironmentError,
16 mapRemoteEnvironmentError,
17} from "../connection/errors.ts";
18import { ConnectionBlockedError, type ConnectionAttemptError } from "../connection/model.ts";
19import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
20import { environmentEndpointUrl } from "../environment/endpoint.ts";
21import * as ClientCapabilities from "../platform/capabilities.ts";
22import * as ManagedRelay from "../relay/managedRelay.ts";
23import * as TokenStore from "./tokenStore.ts";
24import * as Clock from "effect/Clock";
25import * as Context from "effect/Context";
26import * as Effect from "effect/Effect";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
29import * as Ref from "effect/Ref";
30import * as Result from "effect/Result";
31import * as HttpClient from "effect/unstable/http/HttpClient";
32​
33import type { PreparedHttpAuthorization } from "../connection/model.ts";
34​
35export interface RelayEnvironmentAuthorization {
36 readonly environmentId: EnvironmentId;
37 readonly endpoint: RelayManagedEndpoint;
38 readonly credential: string;
40​
41export interface AuthorizedRemoteEnvironment {
42 readonly environmentId: EnvironmentId;
43 readonly label: string;
44 readonly httpBaseUrl: string;
45 readonly socketUrl: string;
46 readonly httpAuthorization: PreparedHttpAuthorization;
48​
49export class RemoteEnvironmentAuthorization extends Context.Service<
50 RemoteEnvironmentAuthorization,
51 {
52 readonly authorizeBearer: (input: {
53 readonly expectedEnvironmentId: EnvironmentId;
54 readonly httpBaseUrl: string;
55 readonly wsBaseUrl: string;
56 readonly bearerToken: string;
57 readonly connectionMethod: ClientConnectionMethod;
58 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
59 readonly authorizeDpop: (input: {
60 readonly expectedEnvironmentId: EnvironmentId;
61 readonly obtainBootstrap: Effect.Effect<
62 RelayEnvironmentAuthorization,
63 ConnectionAttemptError
64 >;
65 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
66 }
67>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
68​
69const TOKEN_EXPIRY_SAFETY_MARGIN_MS = 60_000;
70const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
71const BEARER_DESCRIPTOR_CACHE_TTL_MS = 10_000;
72​
73function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
74 return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
75 ? error
76 : mapRemoteDpopEnvironmentError(error);
78​
79const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (
80 httpBaseUrl: string,
81) {
82 return yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
83 Effect.mapError(mapRemoteEnvironmentError),
84 );
85});
86​
87export const make = Effect.gen(function* () {
88 const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
89 const presentation = yield* ClientCapabilities.ClientPresentation;
90 const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
91 const httpClient = yield* HttpClient.HttpClient;
92 const bearerDescriptors = yield* Ref.make<
93 ReadonlyMap<
94 EnvironmentId,
95 {
96 readonly httpBaseUrl: string;
97 readonly descriptor: ExecutionEnvironmentDescriptor;
98 readonly validatedAtEpochMs: number;
99 }
100 >
101 >(new Map());
102​
103 const authorizeBearer = Effect.fn("clientRuntime.connection.remote.authorizeBearer")(
104 function* (input: {
105 readonly expectedEnvironmentId: Parameters<
106 RemoteEnvironmentAuthorization["Service"]["authorizeBearer"]
107 >[0]["expectedEnvironmentId"];
108 readonly httpBaseUrl: string;
109 readonly wsBaseUrl: string;
110 readonly bearerToken: string;
111 readonly connectionMethod: ClientConnectionMethod;
112 }) {
113 const now = yield* Clock.currentTimeMillis;
114 const cachedDescriptor = (yield* Ref.get(bearerDescriptors)).get(input.expectedEnvironmentId);
115 const canReuseDescriptor =
116 cachedDescriptor?.httpBaseUrl === input.httpBaseUrl &&
117 cachedDescriptor.validatedAtEpochMs + BEARER_DESCRIPTOR_CACHE_TTL_MS > now;
118 const descriptor = canReuseDescriptor
119 ? cachedDescriptor.descriptor
120 : yield* fetchDescriptor(input.httpBaseUrl).pipe(
121 Effect.provideService(HttpClient.HttpClient, httpClient),
122 );
123 if (descriptor.environmentId !== input.expectedEnvironmentId) {
124 return yield* environmentMismatchError({
125 expected: input.expectedEnvironmentId,
126 actual: descriptor.environmentId,
127 });
128 }
129 if (!canReuseDescriptor) {
130 yield* Ref.update(bearerDescriptors, (current) => {
131 const next = new Map(current);
132 next.set(input.expectedEnvironmentId, {
133 httpBaseUrl: input.httpBaseUrl,
134 descriptor,
135 validatedAtEpochMs: now,
136 });
137 return next;
138 });
139 }
140 const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
141 wsBaseUrl: input.wsBaseUrl,
142 httpBaseUrl: input.httpBaseUrl,
143 bearerToken: input.bearerToken,
144 clientMetadata: presentation.metadata,
145 connectionMethod: input.connectionMethod,
146 }).pipe(
147 Effect.mapError(mapRemoteEnvironmentError),
148 Effect.provideService(HttpClient.HttpClient, httpClient),
149 );
150 return {
151 environmentId: descriptor.environmentId,
152 label: descriptor.label,
153 httpBaseUrl: input.httpBaseUrl,
154 socketUrl,
155 httpAuthorization: {
156 _tag: "Bearer" as const,
157 token: input.bearerToken,
158 },
159 };
160 },
161 );
162​
163 const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")(
164 function* (token: TokenStore.RemoteDpopAccessToken, timeoutMs?: number) {
165 const ticketProof = yield* signer
166 .createProof({
167 method: "POST",
168 url: environmentEndpointUrl(token.endpoint.httpBaseUrl, "/api/auth/websocket-ticket"),
169 accessToken: token.accessToken,
170 })
171 .pipe(
172 Effect.mapError(
173 () =>
174 new ConnectionBlockedError({
175 reason: "configuration",
176 detail: "Could not create the websocket authorization proof.",
177 }),
178 ),
179 );
180 return yield* resolveRemoteDpopWebSocketConnectionUrl({
181 wsBaseUrl: token.endpoint.wsBaseUrl,
182 httpBaseUrl: token.endpoint.httpBaseUrl,
183 accessToken: token.accessToken,
184 dpopProof: ticketProof,
185 clientMetadata: presentation.metadata,
186 connectionMethod: "relay",
187 ...(timeoutMs === undefined ? {} : { timeoutMs }),
188 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
189 },
190 );
191​
192 const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(
193 function* (input: {
194 readonly expectedEnvironmentId: Parameters<
195 RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]
196 >[0]["expectedEnvironmentId"];
197 readonly obtainBootstrap: Parameters<
198 RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]
199 >[0]["obtainBootstrap"];
200 }) {
201 const thumbprint = yield* signer.thumbprint.pipe(
202 Effect.mapError(
203 () =>
204 new ConnectionBlockedError({
205 reason: "configuration",
206 detail: "Could not load the environment authorization key.",
207 }),
208 ),
209 Effect.withSpan("environment.authorization.dpopKey.resolve"),
210 );
211 const now = yield* Clock.currentTimeMillis;
212 const cached = yield* tokenStore
213 .get(input.expectedEnvironmentId)
214 .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
215 if (
216 Option.isSome(cached) &&
217 cached.value.environmentId === input.expectedEnvironmentId &&
218 cached.value.dpopThumbprint === thumbprint &&
219 cached.value.expiresAtEpochMs > now + TOKEN_EXPIRY_SAFETY_MARGIN_MS
220 ) {
221 yield* Effect.annotateCurrentSpan({
222 "connection.remote_token_cache": "hit",
223 });
224 const cachedSocket = yield* createDpopSocketUrl(
225 cached.value,
226 CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
227 ).pipe(Effect.result);
228 if (Result.isSuccess(cachedSocket)) {
229 return {
230 environmentId: cached.value.environmentId,
231 label: cached.value.label,
232 httpBaseUrl: cached.value.endpoint.httpBaseUrl,
233 socketUrl: cachedSocket.success,
234 httpAuthorization: {
235 _tag: "Dpop" as const,
236 accessToken: cached.value.accessToken,
237 },
238 };
239 }
240 if (cachedSocket.failure._tag === "ConnectionBlockedError") {
241 return yield* mapDpopSocketError(cachedSocket.failure);
242 }
243 yield* tokenStore
244 .remove(input.expectedEnvironmentId)
245 .pipe(Effect.withSpan("environment.authorization.accessToken.remove"));
246 }
247​
248 yield* Effect.annotateCurrentSpan({
249 "connection.remote_token_cache": "miss",
250 });
251 const bootstrap = yield* input.obtainBootstrap;
252 const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl).pipe(
253 Effect.provideService(HttpClient.HttpClient, httpClient),
254 Effect.withSpan("environment.authorization.descriptor"),
255 );
256 if (descriptor.environmentId !== input.expectedEnvironmentId) {
257 return yield* environmentMismatchError({
258 expected: input.expectedEnvironmentId,
259 actual: descriptor.environmentId,
260 });
261 }
262 const bootstrapProof = yield* signer
263 .createProof({
264 method: "POST",
265 url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
266 })
267 .pipe(
268 Effect.mapError(
269 () =>
270 new ConnectionBlockedError({
271 reason: "configuration",
272 detail: "Could not create the environment authorization proof.",
273 }),
274 ),
275 );
276 const access = yield* exchangeRemoteDpopAccessToken({
277 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
278 credential: bootstrap.credential,
279 dpopProof: bootstrapProof,
280 scopes: presentation.scopes,
281 clientMetadata: presentation.metadata,
282 }).pipe(
283 Effect.mapError(mapRemoteDpopEnvironmentError),
284 Effect.provideService(HttpClient.HttpClient, httpClient),
285 Effect.withSpan("environment.authorization.accessToken.exchange"),
286 );
287 const issuedAt = yield* Clock.currentTimeMillis;
288 const token = new TokenStore.RemoteDpopAccessToken({
289 environmentId: descriptor.environmentId,
290 label: descriptor.label,
291 endpoint: bootstrap.endpoint,
292 accessToken: access.access_token,
293 expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
294 dpopThumbprint: thumbprint,
295 });
296 const socketUrl = yield* createDpopSocketUrl(token).pipe(Effect.mapError(mapDpopSocketError));
297 yield* tokenStore
298 .put(token)
299 .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
300 return {
301 environmentId: descriptor.environmentId,
302 label: descriptor.label,
303 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
304 socketUrl,
305 httpAuthorization: {
306 _tag: "Dpop" as const,
307 accessToken: token.accessToken,
308 },
309 };
310 },
311 );
312​
313 return RemoteEnvironmentAuthorization.of({
314 authorizeBearer,
315 authorizeDpop: (input) =>
316 authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),
317 });
318});
319​
320export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);