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

service.ts

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