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

service.ts

536 lines20.2 KB

1import {
2 type ClientConnectionMethod,
3 EnvironmentId,
4 type ExecutionEnvironmentDescriptor,
5} from "@t3tools/contracts";
6import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
7import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
8import {
9 exchangeRemoteDpopAccessToken,
10 type RemoteEnvironmentAuthError,
11 resolveRemoteDpopWebSocketConnectionUrl,
12 resolveRemoteWebSocketConnectionUrl,
13} from "./remote.ts";
14import {
15 environmentMismatchError,
16 mapManagedRelayError,
17 mapRemoteDpopEnvironmentError,
18 mapRemoteEnvironmentError,
19} from "../connection/errors.ts";
20import {
21 ConnectionBlockedError,
22 ConnectionTransientError,
23 type ConnectionAttemptError,
24} from "../connection/model.ts";
25import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
26import { environmentEndpointUrl } from "../environment/endpoint.ts";
27import * as ClientCapabilities from "../platform/capabilities.ts";
28import * as ManagedRelay from "../relay/managedRelay.ts";
29import * as TokenStore from "./tokenStore.ts";
30import * as Clock from "effect/Clock";
31import * as Context from "effect/Context";
32import * as Effect from "effect/Effect";
33import * as Fiber from "effect/Fiber";
34import * as Layer from "effect/Layer";
35import * as Option from "effect/Option";
36import * as Result from "effect/Result";
37import * as Scope from "effect/Scope";
38import * as Semaphore from "effect/Semaphore";
39import * as HttpClient from "effect/http/HttpClient";
40​
41import {
42 DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,
43 type PreparedHttpAuthorization,
44} from "../connection/model.ts";
45​
46export interface AuthorizedRemoteEnvironment {
47 readonly environmentId: EnvironmentId;
48 readonly label: string;
49 readonly httpBaseUrl: string;
50 readonly socketUrl: string;
51 readonly httpAuthorization: PreparedHttpAuthorization;
52 readonly descriptor?: ExecutionEnvironmentDescriptor;
54​
55export interface AuthorizedRemoteHttpEnvironment {
56 readonly environmentId: EnvironmentId;
57 readonly label: string;
58 readonly httpBaseUrl: string;
59 readonly httpAuthorization: Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>;
61​
62export class RemoteEnvironmentAuthorization extends Context.Service<
63 RemoteEnvironmentAuthorization,
64 {
65 readonly authorizeBearer: (input: {
66 readonly expectedEnvironmentId: EnvironmentId;
67 readonly httpBaseUrl: string;
68 readonly wsBaseUrl: string;
69 readonly bearerToken: string;
70 readonly connectionMethod: ClientConnectionMethod;
71 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
72 readonly authorizeDpop: (input: {
73 readonly expectedEnvironmentId: EnvironmentId;
74 /**
75 * The access token is not bound to an origin, and each proof is minted
76 * for the URL it signs, so a token from the relay also works on the
77 * environment's LAN or tailnet address.
78 */
79 readonly directEndpoint?: { readonly httpBaseUrl: string; readonly wsBaseUrl: string };
80 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
81 readonly authorizeDpopHttp: (input: {
82 readonly expectedEnvironmentId: EnvironmentId;
83 readonly rejectedAccessToken?: string;
84 }) => Effect.Effect<AuthorizedRemoteHttpEnvironment, ConnectionAttemptError>;
85 }
86>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
87​
88const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
89const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000;
90​
91function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
92 return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
93 ? error
94 : mapRemoteDpopEnvironmentError(error);
96​
97const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (
98 httpBaseUrl: string,
99 connectionMethod: ClientConnectionMethod,
100) {
101 return yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
102 Effect.mapError((error) => mapRemoteEnvironmentError(error, connectionMethod)),
103 );
104});
105​
106export const make = Effect.gen(function* () {
107 const serviceScope = yield* Scope.Scope;
108 const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
109 const relay = yield* ManagedRelay.ManagedRelayClient;
110 const cloudSession = yield* ClientCapabilities.CloudSession;
111 const deviceIdentity = yield* ClientCapabilities.RelayDeviceIdentity;
112 const presentation = yield* ClientCapabilities.ClientPresentation;
113 const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
114 const httpClient = yield* HttpClient.HttpClient;
115 const tokenLock = yield* Semaphore.make(1);
116 const tokenOwners = new Map<
117 EnvironmentId,
118 { readonly accessToken: string; readonly identity: ClientCapabilities.CloudSessionIdentity }
119 >();
120 const pendingTokens = new Map<
121 EnvironmentId,
122 {
123 readonly id: object;
124 readonly identity: ClientCapabilities.CloudSessionIdentity;
125 readonly thumbprint: string;
126 readonly token: Effect.Effect<TokenStore.RemoteDpopAccessToken, ConnectionAttemptError>;
127 }
128 >();
129​
130 /**
131 * A saved LAN address can belong to another machine on a different network.
132 */
133 const verifyDirectEndpoint = Effect.fn("clientRuntime.connection.remote.verifyDirectEndpoint")(
134 function* (input: {
135 readonly expectedEnvironmentId: EnvironmentId;
136 readonly httpBaseUrl: string;
137 readonly connectionMethod: ClientConnectionMethod;
138 }) {
139 const descriptor = yield* fetchDescriptor(input.httpBaseUrl, input.connectionMethod).pipe(
140 Effect.provideService(HttpClient.HttpClient, httpClient),
141 );
142 if (descriptor.environmentId !== input.expectedEnvironmentId) {
143 return yield* environmentMismatchError({
144 expected: input.expectedEnvironmentId,
145 actual: descriptor.environmentId,
146 });
147 }
148 return descriptor;
149 },
150 );
151​
152 const authorizeBearer = Effect.fn("clientRuntime.connection.remote.authorizeBearer")(
153 function* (input: {
154 readonly expectedEnvironmentId: Parameters<
155 RemoteEnvironmentAuthorization["Service"]["authorizeBearer"]
156 >[0]["expectedEnvironmentId"];
157 readonly httpBaseUrl: string;
158 readonly wsBaseUrl: string;
159 readonly bearerToken: string;
160 readonly connectionMethod: ClientConnectionMethod;
161 }) {
162 const descriptor = yield* verifyDirectEndpoint(input);
163 const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
164 wsBaseUrl: input.wsBaseUrl,
165 httpBaseUrl: input.httpBaseUrl,
166 bearerToken: input.bearerToken,
167 clientMetadata: presentation.metadata,
168 connectionMethod: input.connectionMethod,
169 }).pipe(
170 Effect.mapError(mapRemoteEnvironmentError),
171 Effect.provideService(HttpClient.HttpClient, httpClient),
172 );
173 return {
174 environmentId: descriptor.environmentId,
175 label: descriptor.label,
176 httpBaseUrl: input.httpBaseUrl,
177 socketUrl,
178 descriptor,
179 httpAuthorization: {
180 _tag: "Bearer" as const,
181 token: input.bearerToken,
182 },
183 };
184 },
185 );
186​
187 const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")(
188 function* (
189 token: TokenStore.RemoteDpopAccessToken,
190 timeoutMs?: number,
191 endpoint: { readonly httpBaseUrl: string; readonly wsBaseUrl: string } = token.endpoint,
192 ) {
193 return yield* resolveRemoteDpopWebSocketConnectionUrl({
194 wsBaseUrl: endpoint.wsBaseUrl,
195 httpBaseUrl: endpoint.httpBaseUrl,
196 accessToken: token.accessToken,
197 createProof: (proof) =>
198 signer.createProof(proof).pipe(
199 Effect.mapError(
200 () =>
201 new ConnectionBlockedError({
202 reason: "configuration",
203 detail: "Could not create the websocket authorization proof.",
204 }),
205 ),
206 ),
207 clientMetadata: presentation.metadata,
208 connectionMethod: "relay",
209 ...(timeoutMs === undefined ? {} : { timeoutMs }),
210 });
211 },
212 Effect.provideService(HttpClient.HttpClient, httpClient),
213 );
214​
215 const sessionChanged = () =>
216 new ConnectionBlockedError({
217 reason: "authentication",
218 detail: "Your cloud sign-in changed. Sign in again to authorize the environment.",
219 });
220​
221 // A missing identity before the attempt captures one means the cloud session
222 // is still loading, not a sign-out. Only a captured identity that goes away
223 // or changes is evidence of one.
224 const sessionPending = () =>
225 new ConnectionTransientError({
226 reason: "session-pending",
227 detail: "Waiting for the T3 Connect sign-in to load.",
228 });
229​
230 const assertSession = Effect.fnUntraced(function* (
231 identity: ClientCapabilities.CloudSessionIdentity,
232 ) {
233 const current = yield* cloudSession.identity;
234 if (Option.isNone(current) || current.value !== identity) {
235 return yield* sessionChanged();
236 }
237 });
238​
239 // Called under tokenLock so a late rejection cannot remove a newer credential.
240 const removeRejectedToken = Effect.fnUntraced(function* (
241 environmentId: EnvironmentId,
242 accessToken: string,
243 ) {
244 const cached = yield* tokenStore.get(environmentId);
245 if (Option.isSome(cached) && cached.value.accessToken === accessToken) {
246 yield* tokenStore.remove(environmentId);
247 tokenOwners.delete(environmentId);
248 }
249 });
250​
251 const obtainBootstrap = Effect.fn("relay.connection.bootstrap.obtain")(function* (
252 environmentId: EnvironmentId,
253 identity: ClientCapabilities.CloudSessionIdentity,
254 ) {
255 yield* assertSession(identity);
256 const clerkToken = yield* cloudSession.clerkToken.pipe(
257 Effect.withSpan("relay.connection.cloudSessionToken.resolve"),
258 );
259 const deviceId = yield* deviceIdentity.deviceId.pipe(
260 Effect.withSpan("relay.connection.deviceIdentity.resolve"),
261 );
262 yield* assertSession(identity);
263 const connected = yield* relay
264 .connectEnvironment({
265 clerkToken,
266 scopes: [RelayEnvironmentConnectScope],
267 environmentId,
268 ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
269 })
270 .pipe(Effect.mapError(mapManagedRelayError));
271 if (connected.environmentId !== environmentId) {
272 return yield* environmentMismatchError({
273 expected: environmentId,
274 actual: connected.environmentId,
275 });
276 }
277 yield* assertSession(identity);
278 return connected;
279 });
280​
281 const exchangeDpopToken = Effect.fn("clientRuntime.connection.remote.exchangeDpopToken")(
282 function* (
283 environmentId: EnvironmentId,
284 thumbprint: string,
285 identity: ClientCapabilities.CloudSessionIdentity,
286 ) {
287 const bootstrap = yield* obtainBootstrap(environmentId, identity);
288 const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl, "relay").pipe(
289 Effect.provideService(HttpClient.HttpClient, httpClient),
290 Effect.withSpan("environment.authorization.descriptor"),
291 );
292 if (descriptor.environmentId !== environmentId) {
293 return yield* environmentMismatchError({
294 expected: environmentId,
295 actual: descriptor.environmentId,
296 });
297 }
298 const bootstrapProof = yield* signer
299 .createProof({
300 method: "POST",
301 url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
302 })
303 .pipe(
304 Effect.mapError(
305 () =>
306 new ConnectionBlockedError({
307 reason: "configuration",
308 detail: "Could not create the environment authorization proof.",
309 }),
310 ),
311 );
312 yield* assertSession(identity);
313 const access = yield* exchangeRemoteDpopAccessToken({
314 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
315 credential: bootstrap.credential,
316 dpopProof: bootstrapProof,
317 clientMetadata: presentation.metadata,
318 }).pipe(
319 Effect.mapError(mapRemoteDpopEnvironmentError),
320 Effect.provideService(HttpClient.HttpClient, httpClient),
321 Effect.withSpan("environment.authorization.accessToken.exchange"),
322 );
323 const issuedAt = yield* Clock.currentTimeMillis;
324 return new TokenStore.RemoteDpopAccessToken({
325 environmentId: descriptor.environmentId,
326 accountId: identity.accountId,
327 label: descriptor.label,
328 endpoint: bootstrap.endpoint,
329 accessToken: access.access_token,
330 expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
331 dpopThumbprint: thumbprint,
332 });
333 },
334 );
335​
336 const getDpopToken = Effect.fn("clientRuntime.connection.remote.getDpopToken")(function* (
337 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0],
338 ) {
339 const session = yield* cloudSession.identity;
340 if (Option.isNone(session)) {
341 return yield* sessionPending();
342 }
343 const identity = session.value;
344 const thumbprint = yield* signer.thumbprint.pipe(
345 Effect.mapError(
346 () =>
347 new ConnectionBlockedError({
348 reason: "configuration",
349 detail: "Could not load the environment authorization key.",
350 }),
351 ),
352 Effect.withSpan("environment.authorization.dpopKey.resolve"),
353 );
354 const selected = yield* tokenLock.withPermits(1)(
355 Effect.gen(function* () {
356 yield* assertSession(identity);
357 const now = yield* Clock.currentTimeMillis;
358 const cached = yield* tokenStore
359 .get(input.expectedEnvironmentId)
360 .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
361 const owner = tokenOwners.get(input.expectedEnvironmentId);
362 if (
363 Option.isSome(cached) &&
364 cached.value.environmentId === input.expectedEnvironmentId &&
365 cached.value.accountId === identity.accountId &&
366 cached.value.dpopThumbprint === thumbprint &&
367 cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS &&
368 cached.value.accessToken !== input.rejectedAccessToken &&
369 (owner?.accessToken !== cached.value.accessToken || owner.identity === identity)
370 ) {
371 tokenOwners.set(input.expectedEnvironmentId, {
372 accessToken: cached.value.accessToken,
373 identity,
374 });
375 return { token: Effect.succeed(cached.value), fromCache: true };
376 }
377 if (input.rejectedAccessToken !== undefined) {
378 yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken);
379 }
380 const pending = pendingTokens.get(input.expectedEnvironmentId);
381 if (pending?.identity === identity && pending.thumbprint === thumbprint) {
382 return { token: pending.token, fromCache: false };
383 }
384​
385 const id = {};
386 const fiber = yield* exchangeDpopToken(
387 input.expectedEnvironmentId,
388 thumbprint,
389 identity,
390 ).pipe(
391 Effect.flatMap((token) =>
392 tokenLock.withPermits(1)(
393 Effect.gen(function* () {
394 yield* assertSession(identity);
395 yield* tokenStore
396 .put(token)
397 .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
398 const current = yield* cloudSession.identity;
399 if (Option.isNone(current) || current.value !== identity) {
400 yield* removeRejectedToken(input.expectedEnvironmentId, token.accessToken);
401 return yield* sessionChanged();
402 }
403 tokenOwners.set(input.expectedEnvironmentId, {
404 accessToken: token.accessToken,
405 identity,
406 });
407 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
408 pendingTokens.delete(input.expectedEnvironmentId);
409 }
410 return token;
411 }),
412 ),
413 ),
414 Effect.timeoutOrElse({
415 duration: DPOP_AUTHORIZATION_TIMEOUT_MS,
416 orElse: () =>
417 Effect.fail(
418 new ConnectionTransientError({
419 reason: "timeout",
420 detail: "Timed out renewing the environment credential.",
421 }),
422 ),
423 }),
424 Effect.ensuring(
425 tokenLock.withPermits(1)(
426 Effect.sync(() => {
427 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
428 pendingTokens.delete(input.expectedEnvironmentId);
429 }
430 }),
431 ),
432 ),
433 // One caller's timeout must not cancel renewal for other HTTP requests.
434 Effect.forkIn(serviceScope),
435 );
436 const token = Fiber.join(fiber);
437 pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, token });
438 return { token, fromCache: false };
439 }),
440 );
441 yield* Effect.annotateCurrentSpan({
442 "connection.remote_token_cache": selected.fromCache ? "hit" : "miss",
443 });
444 const token = yield* selected.token;
445 yield* assertSession(identity);
446 return { token, fromCache: selected.fromCache, identity };
447 });
448​
449 const httpAuthorization = (
450 token: TokenStore.RemoteDpopAccessToken,
451 httpBaseUrl = token.endpoint.httpBaseUrl,
452 ): AuthorizedRemoteHttpEnvironment => ({
453 environmentId: token.environmentId,
454 label: token.label,
455 httpBaseUrl,
456 httpAuthorization: {
457 _tag: "Dpop",
458 accessToken: token.accessToken,
459 expiresAtEpochMs: token.expiresAtEpochMs,
460 },
461 });
462​
463 const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(function* (
464 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
465 ) {
466 const endpoint = input.directEndpoint;
467 const descriptor =
468 endpoint === undefined
469 ? undefined
470 : yield* verifyDirectEndpoint({
471 expectedEnvironmentId: input.expectedEnvironmentId,
472 httpBaseUrl: endpoint.httpBaseUrl,
473 connectionMethod: "direct",
474 });
475 const authorized = (token: TokenStore.RemoteDpopAccessToken, socketUrl: string) => ({
476 ...httpAuthorization(token, endpoint?.httpBaseUrl),
477 socketUrl,
478 ...(descriptor === undefined ? {} : { descriptor }),
479 });
480 let selected = yield* getDpopToken(input);
481 if (selected.fromCache) {
482 const cachedSocket = yield* createDpopSocketUrl(
483 selected.token,
484 CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
485 endpoint,
486 ).pipe(Effect.result);
487 if (Result.isSuccess(cachedSocket)) {
488 yield* assertSession(selected.identity);
489 return authorized(selected.token, cachedSocket.success);
490 }
491 if (cachedSocket.failure._tag === "ConnectionBlockedError") {
492 return yield* mapDpopSocketError(cachedSocket.failure);
493 }
494 // An unreachable direct address says nothing about the token, so keep
495 // it for the T3 Connect route rather than forcing a relay round trip.
496 if (endpoint !== undefined && cachedSocket.failure._tag !== "EnvironmentAuthInvalidError") {
497 return yield* mapDpopSocketError(cachedSocket.failure);
498 }
499 yield* assertSession(selected.identity);
500 selected = yield* getDpopToken({
501 ...input,
502 rejectedAccessToken: selected.token.accessToken,
503 });
504 }
505 const socket = yield* createDpopSocketUrl(selected.token, undefined, endpoint).pipe(
506 Effect.result,
507 );
508 if (Result.isFailure(socket)) {
509 if (endpoint === undefined || socket.failure._tag === "ConnectionBlockedError") {
510 yield* tokenLock.withPermits(1)(
511 removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken),
512 );
513 }
514 return yield* mapDpopSocketError(socket.failure);
515 }
516 yield* assertSession(selected.identity);
517 return authorized(selected.token, socket.success);
518 });
519​
520 return RemoteEnvironmentAuthorization.of({
521 authorizeBearer,
522 authorizeDpop: Effect.fn("environment.authorization")(function (input) {
523 return authorizeDpop(input);
524 }),
525 // The relay tracer must wrap span creation, not just the token request.
526 authorizeDpopHttp: Effect.fnUntraced(function* (input) {
527 return yield* getDpopToken(input).pipe(
528 Effect.map(({ token }) => httpAuthorization(token)),
529 Effect.withSpan("environment.authorization.http"),
530 withRelayClientTracing,
531 );
532 }),
533 });
534});
535​
536export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);