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

service.ts

562 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 return yield* resolveRemoteDpopWebSocketConnectionUrl({
222 wsBaseUrl: endpoint.wsBaseUrl,
223 httpBaseUrl: endpoint.httpBaseUrl,
224 accessToken: token.accessToken,
225 createProof: (proof) =>
226 signer.createProof(proof).pipe(
227 Effect.mapError(
228 () =>
229 new ConnectionBlockedError({
230 reason: "configuration",
231 detail: "Could not create the websocket authorization proof.",
232 }),
233 ),
234 ),
235 clientMetadata: presentation.metadata,
236 connectionMethod: "relay",
237 ...(timeoutMs === undefined ? {} : { timeoutMs }),
238 });
239 },
240 Effect.provideService(HttpClient.HttpClient, httpClient),
241 );
242​
243 const sessionChanged = () =>
244 new ConnectionBlockedError({
245 reason: "authentication",
246 detail: "Your cloud sign-in changed. Sign in again to authorize the environment.",
247 });
248​
249 // A missing identity before the attempt captures one means the cloud session
250 // is still loading, not a sign-out. Only a captured identity that goes away
251 // or changes is evidence of one.
252 const sessionPending = () =>
253 new ConnectionTransientError({
254 reason: "session-pending",
255 detail: "Waiting for the T3 Connect sign-in to load.",
256 });
257​
258 const assertSession = Effect.fnUntraced(function* (
259 identity: ClientCapabilities.CloudSessionIdentity,
260 ) {
261 const current = yield* cloudSession.identity;
262 if (Option.isNone(current) || current.value !== identity) {
263 return yield* sessionChanged();
264 }
265 });
266​
267 // Called under tokenLock so a late rejection cannot remove a newer credential.
268 const removeRejectedToken = Effect.fnUntraced(function* (
269 environmentId: EnvironmentId,
270 accessToken: string,
271 ) {
272 const cached = yield* tokenStore.get(environmentId);
273 if (Option.isSome(cached) && cached.value.accessToken === accessToken) {
274 yield* tokenStore.remove(environmentId);
275 tokenOwners.delete(environmentId);
276 }
277 });
278​
279 const obtainBootstrap = Effect.fn("relay.connection.bootstrap.obtain")(function* (
280 environmentId: EnvironmentId,
281 identity: ClientCapabilities.CloudSessionIdentity,
282 ) {
283 yield* assertSession(identity);
284 const clerkToken = yield* cloudSession.clerkToken.pipe(
285 Effect.withSpan("relay.connection.cloudSessionToken.resolve"),
286 );
287 const deviceId = yield* deviceIdentity.deviceId.pipe(
288 Effect.withSpan("relay.connection.deviceIdentity.resolve"),
289 );
290 yield* assertSession(identity);
291 const connected = yield* relay
292 .connectEnvironment({
293 clerkToken,
294 scopes: [RelayEnvironmentConnectScope],
295 environmentId,
296 ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
297 })
298 .pipe(Effect.mapError(mapManagedRelayError));
299 if (connected.environmentId !== environmentId) {
300 return yield* environmentMismatchError({
301 expected: environmentId,
302 actual: connected.environmentId,
303 });
304 }
305 yield* assertSession(identity);
306 return connected;
307 });
308​
309 const exchangeDpopToken = Effect.fn("clientRuntime.connection.remote.exchangeDpopToken")(
310 function* (
311 environmentId: EnvironmentId,
312 thumbprint: string,
313 identity: ClientCapabilities.CloudSessionIdentity,
314 ) {
315 const bootstrap = yield* obtainBootstrap(environmentId, identity);
316 const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl, "relay").pipe(
317 Effect.provideService(HttpClient.HttpClient, httpClient),
318 Effect.withSpan("environment.authorization.descriptor"),
319 );
320 if (descriptor.environmentId !== environmentId) {
321 return yield* environmentMismatchError({
322 expected: environmentId,
323 actual: descriptor.environmentId,
324 });
325 }
326 const bootstrapProof = yield* signer
327 .createProof({
328 method: "POST",
329 url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
330 })
331 .pipe(
332 Effect.mapError(
333 () =>
334 new ConnectionBlockedError({
335 reason: "configuration",
336 detail: "Could not create the environment authorization proof.",
337 }),
338 ),
339 );
340 yield* assertSession(identity);
341 const access = yield* exchangeRemoteDpopAccessToken({
342 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
343 credential: bootstrap.credential,
344 dpopProof: bootstrapProof,
345 clientMetadata: presentation.metadata,
346 }).pipe(
347 Effect.mapError(mapRemoteDpopEnvironmentError),
348 Effect.provideService(HttpClient.HttpClient, httpClient),
349 Effect.withSpan("environment.authorization.accessToken.exchange"),
350 );
351 const issuedAt = yield* Clock.currentTimeMillis;
352 return new TokenStore.RemoteDpopAccessToken({
353 environmentId: descriptor.environmentId,
354 accountId: identity.accountId,
355 label: descriptor.label,
356 endpoint: bootstrap.endpoint,
357 accessToken: access.access_token,
358 expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
359 dpopThumbprint: thumbprint,
360 });
361 },
362 );
363​
364 const getDpopToken = Effect.fn("clientRuntime.connection.remote.getDpopToken")(function* (
365 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0],
366 ) {
367 const session = yield* cloudSession.identity;
368 if (Option.isNone(session)) {
369 return yield* sessionPending();
370 }
371 const identity = session.value;
372 const thumbprint = yield* signer.thumbprint.pipe(
373 Effect.mapError(
374 () =>
375 new ConnectionBlockedError({
376 reason: "configuration",
377 detail: "Could not load the environment authorization key.",
378 }),
379 ),
380 Effect.withSpan("environment.authorization.dpopKey.resolve"),
381 );
382 const selected = yield* tokenLock.withPermits(1)(
383 Effect.gen(function* () {
384 yield* assertSession(identity);
385 const now = yield* Clock.currentTimeMillis;
386 const cached = yield* tokenStore
387 .get(input.expectedEnvironmentId)
388 .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
389 const owner = tokenOwners.get(input.expectedEnvironmentId);
390 if (
391 Option.isSome(cached) &&
392 cached.value.environmentId === input.expectedEnvironmentId &&
393 cached.value.accountId === identity.accountId &&
394 cached.value.dpopThumbprint === thumbprint &&
395 cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS &&
396 cached.value.accessToken !== input.rejectedAccessToken &&
397 (owner?.accessToken !== cached.value.accessToken || owner.identity === identity)
398 ) {
399 tokenOwners.set(input.expectedEnvironmentId, {
400 accessToken: cached.value.accessToken,
401 identity,
402 });
403 return { token: Effect.succeed(cached.value), fromCache: true };
404 }
405 if (input.rejectedAccessToken !== undefined) {
406 yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken);
407 }
408 const pending = pendingTokens.get(input.expectedEnvironmentId);
409 if (pending?.identity === identity && pending.thumbprint === thumbprint) {
410 return { token: pending.token, fromCache: false };
411 }
412​
413 const id = {};
414 const fiber = yield* exchangeDpopToken(
415 input.expectedEnvironmentId,
416 thumbprint,
417 identity,
418 ).pipe(
419 Effect.flatMap((token) =>
420 tokenLock.withPermits(1)(
421 Effect.gen(function* () {
422 yield* assertSession(identity);
423 yield* tokenStore
424 .put(token)
425 .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
426 const current = yield* cloudSession.identity;
427 if (Option.isNone(current) || current.value !== identity) {
428 yield* removeRejectedToken(input.expectedEnvironmentId, token.accessToken);
429 return yield* sessionChanged();
430 }
431 tokenOwners.set(input.expectedEnvironmentId, {
432 accessToken: token.accessToken,
433 identity,
434 });
435 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
436 pendingTokens.delete(input.expectedEnvironmentId);
437 }
438 return token;
439 }),
440 ),
441 ),
442 Effect.timeoutOrElse({
443 duration: DPOP_AUTHORIZATION_TIMEOUT_MS,
444 orElse: () =>
445 Effect.fail(
446 new ConnectionTransientError({
447 reason: "timeout",
448 detail: "Timed out renewing the environment credential.",
449 }),
450 ),
451 }),
452 Effect.ensuring(
453 tokenLock.withPermits(1)(
454 Effect.sync(() => {
455 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
456 pendingTokens.delete(input.expectedEnvironmentId);
457 }
458 }),
459 ),
460 ),
461 // One caller's timeout must not cancel renewal for other HTTP requests.
462 Effect.forkIn(serviceScope),
463 );
464 const token = Fiber.join(fiber);
465 pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, token });
466 return { token, fromCache: false };
467 }),
468 );
469 yield* Effect.annotateCurrentSpan({
470 "connection.remote_token_cache": selected.fromCache ? "hit" : "miss",
471 });
472 const token = yield* selected.token;
473 yield* assertSession(identity);
474 return { token, fromCache: selected.fromCache, identity };
475 });
476​
477 const httpAuthorization = (
478 token: TokenStore.RemoteDpopAccessToken,
479 httpBaseUrl = token.endpoint.httpBaseUrl,
480 ): AuthorizedRemoteHttpEnvironment => ({
481 environmentId: token.environmentId,
482 label: token.label,
483 httpBaseUrl,
484 httpAuthorization: {
485 _tag: "Dpop",
486 accessToken: token.accessToken,
487 expiresAtEpochMs: token.expiresAtEpochMs,
488 },
489 });
490​
491 const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(function* (
492 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
493 ) {
494 const endpoint = input.directEndpoint;
495 if (endpoint !== undefined) {
496 yield* verifyDirectEndpoint({
497 expectedEnvironmentId: input.expectedEnvironmentId,
498 httpBaseUrl: endpoint.httpBaseUrl,
499 connectionMethod: "direct",
500 });
501 }
502 const authorized = (token: TokenStore.RemoteDpopAccessToken, socketUrl: string) => ({
503 ...httpAuthorization(token, endpoint?.httpBaseUrl),
504 socketUrl,
505 });
506 let selected = yield* getDpopToken(input);
507 if (selected.fromCache) {
508 const cachedSocket = yield* createDpopSocketUrl(
509 selected.token,
510 CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
511 endpoint,
512 ).pipe(Effect.result);
513 if (Result.isSuccess(cachedSocket)) {
514 yield* assertSession(selected.identity);
515 return authorized(selected.token, cachedSocket.success);
516 }
517 if (cachedSocket.failure._tag === "ConnectionBlockedError") {
518 return yield* mapDpopSocketError(cachedSocket.failure);
519 }
520 // An unreachable direct address says nothing about the token, so keep
521 // it for the T3 Connect route rather than forcing a relay round trip.
522 if (endpoint !== undefined && cachedSocket.failure._tag !== "EnvironmentAuthInvalidError") {
523 return yield* mapDpopSocketError(cachedSocket.failure);
524 }
525 yield* assertSession(selected.identity);
526 selected = yield* getDpopToken({
527 ...input,
528 rejectedAccessToken: selected.token.accessToken,
529 });
530 }
531 const socket = yield* createDpopSocketUrl(selected.token, undefined, endpoint).pipe(
532 Effect.result,
533 );
534 if (Result.isFailure(socket)) {
535 if (endpoint === undefined || socket.failure._tag === "ConnectionBlockedError") {
536 yield* tokenLock.withPermits(1)(
537 removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken),
538 );
539 }
540 return yield* mapDpopSocketError(socket.failure);
541 }
542 yield* assertSession(selected.identity);
543 return authorized(selected.token, socket.success);
544 });
545​
546 return RemoteEnvironmentAuthorization.of({
547 authorizeBearer,
548 authorizeDpop: Effect.fn("environment.authorization")(function (input) {
549 return authorizeDpop(input);
550 }),
551 // The relay tracer must wrap span creation, not just the token request.
552 authorizeDpopHttp: Effect.fnUntraced(function* (input) {
553 return yield* getDpopToken(input).pipe(
554 Effect.map(({ token }) => httpAuthorization(token)),
555 Effect.withSpan("environment.authorization.http"),
556 withRelayClientTracing,
557 );
558 }),
559 });
560});
561​
562export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);