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

service.ts

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