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

service.ts

560 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 * 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 scopes: presentation.scopes,
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* sessionChanged();
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 // A rejected token falls through and is replaced like on the tunnel.
523 if (endpoint !== undefined && cachedSocket.failure._tag !== "EnvironmentAuthInvalidError") {
524 return yield* mapDpopSocketError(cachedSocket.failure);
525 }
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 // A direct address that refuses the socket says nothing about the token.
536 if (endpoint === undefined || socket.failure._tag === "ConnectionBlockedError") {
537 yield* tokenLock.withPermits(1)(
538 removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken),
539 );
540 }
541 return yield* mapDpopSocketError(socket.failure);
542 }
543 yield* assertSession(selected.identity);
544 return authorized(selected.token, socket.success);
545 });
546​
547 return RemoteEnvironmentAuthorization.of({
548 authorizeBearer,
549 authorizeDpop: (input) =>
550 authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),
551 authorizeDpopHttp: (input) =>
552 getDpopToken(input).pipe(
553 Effect.map(({ token }) => httpAuthorization(token)),
554 Effect.withSpan("environment.authorization.http"),
555 withRelayClientTracing,
556 ),
557 });
558});
559​
560export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);