Repository navigation
Expand file tree
/
Copy pathservice.ts
More file actions
890 lines (857 loc) · 35.1 KB
/
Copy pathservice.ts
File metadata and controls
890 lines (857 loc) · 35.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
import { msg } from "gt-i18n";
import { translatableDetail } from "../errors/translatable.ts";
import {
AuthAccessTokenType,
connectDeviceVerificationCode,
type ClientConnectionMethod,
EnvironmentId,
type ExecutionEnvironmentDescriptor,
} from "@t3tools/contracts";
import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import {
exchangeRemoteDpopAccessToken,
issueRemoteLanCredential,
type RemoteEnvironmentAuthError,
resolveRemoteDpopWebSocketConnectionUrl,
resolveRemoteWebSocketConnectionUrl,
} from "./remote.ts";
import {
credentialMissingError,
environmentMismatchError,
mapManagedRelayError,
mapRemoteDpopEnvironmentError,
mapRemoteEnvironmentError,
} from "../connection/errors.ts";
import { DpopConnectionCredential } from "../connection/catalog.ts";
import * as ConnectionCredentialStore from "../connection/credentialStore.ts";
import {
ConnectionBlockedError,
ConnectionTransientError,
type ConnectionAttemptError,
type DirectDpopConnection,
} from "../connection/model.ts";
import { isNearbyAddress } from "../connection/routes.ts";
import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import * as ClientCapabilities from "../platform/capabilities.ts";
import * as ManagedRelay from "../relay/managedRelay.ts";
import * as TokenStore from "./tokenStore.ts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/http/HttpClient";
import {
DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,
type PreparedHttpAuthorization,
} from "../connection/model.ts";
export interface AuthorizedRemoteEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly httpBaseUrl: string;
readonly socketUrl: string;
readonly httpAuthorization: PreparedHttpAuthorization;
readonly descriptor?: ExecutionEnvironmentDescriptor;
}
export interface AuthorizedRemoteHttpEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly httpBaseUrl: string;
readonly httpAuthorization: Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>;
}
export class RemoteEnvironmentAuthorization extends Context.Service<
RemoteEnvironmentAuthorization,
{
readonly authorizeBearer: (input: {
readonly expectedEnvironmentId: EnvironmentId;
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly bearerToken: string;
readonly connectionMethod: ClientConnectionMethod;
}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
readonly authorizeDpop: (input: {
readonly expectedEnvironmentId: EnvironmentId;
/**
* The access token is not bound to an origin, and each proof is minted
* for the URL it signs, so a token from the relay also works on the
* environment's LAN or tailnet address.
*/
readonly directEndpoint?: { readonly httpBaseUrl: string; readonly wsBaseUrl: string };
}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
readonly authorizeLanDpop: (input: {
readonly expectedEnvironmentId: EnvironmentId;
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly accessToken: string;
}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
readonly mintLanCredential: (input: {
readonly httpBaseUrl: string;
readonly bearerToken: string;
}) => Effect.Effect<string, ConnectionAttemptError>;
/** A saved address paired with this device's DPoP key, which renews with the host itself. */
readonly authorizeDirectDpop: (input: {
readonly expectedEnvironmentId: EnvironmentId;
readonly connectionId: string;
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
readonly authorizeDirectDpopHttp: (
connection: DirectDpopConnection,
rejectedAccessToken?: string,
) => Effect.Effect<
Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>,
ConnectionAttemptError
>;
readonly authorizeDpopHttp: (input: {
readonly expectedEnvironmentId: EnvironmentId;
readonly rejectedAccessToken?: string;
}) => Effect.Effect<AuthorizedRemoteHttpEnvironment, ConnectionAttemptError>;
/**
* Lets the next direct authorization of this address skip its own descriptor
* read. Kept only where the address reaches the same machine on every network.
*/
readonly rememberCheckedDescriptor: (
httpBaseUrl: string,
descriptor: Option.Option<ExecutionEnvironmentDescriptor>,
keepsItsHost: boolean,
) => Effect.Effect<void>;
/**
* Renews a live socket's token before it expires, so the server moves the
* socket to the new session instead of closing it. Runs until interrupted.
*/
readonly renewDpopBeforeExpiry: (input: {
readonly expectedEnvironmentId: EnvironmentId;
readonly expiresAtEpochMs: number;
readonly directConnection?: DirectDpopConnection;
}) => Effect.Effect<void, ConnectionAttemptError>;
}
>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000;
const CHECKED_DESCRIPTOR_TTL_NANOS = 5_000_000_000n;
// A loopback or LAN host answers well inside this, so a dead one frees its attempt sooner.
const NEARBY_DESCRIPTOR_TIMEOUT_MS = 3_000;
/** A token with the descriptor its mint read. A cached token has none. */
interface IssuedDpopToken {
readonly token: TokenStore.RemoteDpopAccessToken;
readonly descriptor?: ExecutionEnvironmentDescriptor;
}
function mapDpopSocketError(
error: RemoteEnvironmentAuthError | ConnectionAttemptError,
connectionMethod: ClientConnectionMethod = "relay",
) {
return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
? error
: mapRemoteDpopEnvironmentError(error, connectionMethod);
}
function approvalPendingError(hostLabel: string, thumbprint: string, traceId: string) {
const verificationCode = connectDeviceVerificationCode(thumbprint);
return new ConnectionTransientError({
reason: "approval-pending",
...translatableDetail(
msg("Approve this device on {host}. It shows code {verificationCode}.", {
host: hostLabel,
verificationCode,
}),
),
verificationCode,
traceId,
hop: "server",
via: "relay",
failureCause: "approval_pending",
});
}
const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (
httpBaseUrl: string,
connectionMethod: ClientConnectionMethod,
timeoutMs?: number,
) {
return yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl,
...(timeoutMs === undefined ? {} : { timeoutMs }),
}).pipe(Effect.mapError((error) => mapRemoteEnvironmentError(error, connectionMethod)));
});
export const make = Effect.gen(function* () {
const serviceScope = yield* Scope.Scope;
const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
const relay = yield* ManagedRelay.ManagedRelayClient;
const cloudSession = yield* ClientCapabilities.CloudSession;
const deviceIdentity = yield* ClientCapabilities.RelayDeviceIdentity;
const presentation = yield* ClientCapabilities.ClientPresentation;
const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
const httpClient = yield* HttpClient.HttpClient;
const tokenLock = yield* Semaphore.make(1);
const directTokenLocks = yield* KeyedLock.make<string>();
const tokenOwners = new Map<
EnvironmentId,
{ readonly accessToken: string; readonly identity: ClientCapabilities.CloudSessionIdentity }
>();
const pendingTokens = new Map<
EnvironmentId,
{
readonly id: object;
readonly identity: ClientCapabilities.CloudSessionIdentity;
readonly thumbprint: string;
readonly issued: Effect.Effect<IssuedDpopToken, ConnectionAttemptError>;
}
>();
// A route or host check hands its descriptor to the connect it leads to, once,
// so the connect skips a round trip. Only over HTTPS or loopback: any other
// plain http address can belong to another machine after a network change.
const checkedDescriptors = new Map<
string,
{ readonly descriptor: ExecutionEnvironmentDescriptor; readonly at: bigint }
>();
/**
* A saved LAN address can belong to another machine on a different network.
*/
const verifyDirectEndpoint = Effect.fn("clientRuntime.connection.remote.verifyDirectEndpoint")(
function* (input: {
readonly expectedEnvironmentId: EnvironmentId;
readonly httpBaseUrl: string;
readonly connectionMethod: ClientConnectionMethod;
}) {
const checked = checkedDescriptors.get(input.httpBaseUrl);
checkedDescriptors.delete(input.httpBaseUrl);
// A remembered mismatch still reads again, so a host that answers for the
// right environment a moment later is not blocked.
const descriptor =
checked !== undefined &&
checked.descriptor.environmentId === input.expectedEnvironmentId &&
(yield* Clock.monotonicTimeNanos) - checked.at <= CHECKED_DESCRIPTOR_TTL_NANOS
? checked.descriptor
: yield* fetchDescriptor(
input.httpBaseUrl,
input.connectionMethod,
// An SSH forward listens on loopback but reaches a remote host.
input.connectionMethod === "direct" && isNearbyAddress(input.httpBaseUrl)
? NEARBY_DESCRIPTOR_TIMEOUT_MS
: undefined,
).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
if (descriptor.environmentId !== input.expectedEnvironmentId) {
return yield* environmentMismatchError({
expected: input.expectedEnvironmentId,
actual: descriptor.environmentId,
});
}
return descriptor;
},
);
const authorizeBearer = Effect.fn("clientRuntime.connection.remote.authorizeBearer")(
function* (input: {
readonly expectedEnvironmentId: Parameters<
RemoteEnvironmentAuthorization["Service"]["authorizeBearer"]
>[0]["expectedEnvironmentId"];
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly bearerToken: string;
readonly connectionMethod: ClientConnectionMethod;
}) {
const descriptor = yield* verifyDirectEndpoint(input);
const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: input.wsBaseUrl,
httpBaseUrl: input.httpBaseUrl,
bearerToken: input.bearerToken,
clientMetadata: presentation.metadata,
connectionMethod: input.connectionMethod,
}).pipe(
Effect.mapError(mapRemoteEnvironmentError),
Effect.provideService(HttpClient.HttpClient, httpClient),
);
return {
environmentId: descriptor.environmentId,
label: descriptor.label,
httpBaseUrl: input.httpBaseUrl,
socketUrl,
descriptor,
httpAuthorization: {
_tag: "Bearer" as const,
token: input.bearerToken,
},
};
},
);
const createSocketProof = (proof: ManagedRelay.ManagedRelayDpopProofInput) =>
signer.createProof(proof).pipe(
Effect.mapError(
() =>
new ConnectionBlockedError({
reason: "configuration",
...translatableDetail(msg("Could not create the websocket authorization proof.")),
}),
),
);
const authorizeLanDpop = Effect.fn("clientRuntime.connection.remote.authorizeLanDpop")(function* (
input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeLanDpop"]>[0],
) {
const descriptor = yield* verifyDirectEndpoint({
expectedEnvironmentId: input.expectedEnvironmentId,
httpBaseUrl: input.httpBaseUrl,
connectionMethod: "direct",
});
const socketUrl = yield* resolveRemoteDpopWebSocketConnectionUrl({
wsBaseUrl: input.wsBaseUrl,
httpBaseUrl: input.httpBaseUrl,
accessToken: input.accessToken,
createProof: createSocketProof,
clientMetadata: presentation.metadata,
connectionMethod: "direct",
}).pipe(
Effect.mapError((error) => mapDpopSocketError(error, "direct")),
Effect.provideService(HttpClient.HttpClient, httpClient),
);
return {
environmentId: descriptor.environmentId,
label: descriptor.label,
httpBaseUrl: input.httpBaseUrl,
socketUrl,
descriptor,
httpAuthorization: { _tag: "LanDpop" as const, accessToken: input.accessToken },
};
});
const mintLanCredential = Effect.fn("clientRuntime.connection.remote.mintLanCredential")(
function* (
input: Parameters<RemoteEnvironmentAuthorization["Service"]["mintLanCredential"]>[0],
) {
const dpopProof = yield* signer
.createProof({
method: "POST",
url: environmentEndpointUrl(input.httpBaseUrl, "/api/auth/lan-credential"),
})
.pipe(
Effect.mapError(
() =>
new ConnectionBlockedError({
reason: "configuration",
detail: "Could not create the LAN credential proof.",
}),
),
);
const issued = yield* issueRemoteLanCredential({ ...input, dpopProof }).pipe(
Effect.mapError((error) => mapDpopSocketError(error, "direct")),
Effect.provideService(HttpClient.HttpClient, httpClient),
);
return issued.access_token;
},
);
const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")(
function* (
token: TokenStore.RemoteDpopAccessToken,
timeoutMs?: number,
endpoint: { readonly httpBaseUrl: string; readonly wsBaseUrl: string } = token.endpoint,
) {
return yield* resolveRemoteDpopWebSocketConnectionUrl({
wsBaseUrl: endpoint.wsBaseUrl,
httpBaseUrl: endpoint.httpBaseUrl,
accessToken: token.accessToken,
createProof: createSocketProof,
clientMetadata: presentation.metadata,
connectionMethod: "relay",
...(timeoutMs === undefined ? {} : { timeoutMs }),
});
},
Effect.provideService(HttpClient.HttpClient, httpClient),
);
const sessionChanged = () =>
new ConnectionBlockedError({
reason: "authentication",
...translatableDetail(
msg("Your cloud sign-in changed. Sign in again to authorize the environment."),
),
});
// A missing identity before the attempt captures one means the cloud session
// is still loading, not a sign-out. Only a captured identity that goes away
// or changes is evidence of one.
const sessionPending = () =>
new ConnectionTransientError({
reason: "session-pending",
...translatableDetail(msg("Waiting for the T3 Connect sign-in to load.")),
});
const assertSession = Effect.fnUntraced(function* (
identity: ClientCapabilities.CloudSessionIdentity,
) {
const current = yield* cloudSession.identity;
if (Option.isNone(current) || current.value !== identity) {
return yield* sessionChanged();
}
});
// Called under tokenLock so a late rejection cannot remove a newer credential.
const removeRejectedToken = Effect.fnUntraced(function* (
environmentId: EnvironmentId,
accessToken: string,
) {
const cached = yield* tokenStore.get(environmentId);
if (Option.isSome(cached) && cached.value.accessToken === accessToken) {
yield* tokenStore.remove(environmentId);
tokenOwners.delete(environmentId);
}
});
const obtainBootstrap = Effect.fn("relay.connection.bootstrap.obtain")(function* (
environmentId: EnvironmentId,
identity: ClientCapabilities.CloudSessionIdentity,
) {
yield* assertSession(identity);
const clerkToken = yield* cloudSession.clerkToken.pipe(
Effect.withSpan("relay.connection.cloudSessionToken.resolve"),
);
const deviceId = yield* deviceIdentity.deviceId.pipe(
Effect.withSpan("relay.connection.deviceIdentity.resolve"),
);
yield* assertSession(identity);
const connected = yield* relay
.connectEnvironment({
clerkToken,
scopes: [RelayEnvironmentConnectScope],
environmentId,
...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
})
.pipe(Effect.mapError(mapManagedRelayError));
if (connected.environmentId !== environmentId) {
return yield* environmentMismatchError({
expected: environmentId,
actual: connected.environmentId,
});
}
yield* assertSession(identity);
return connected;
});
const exchangeDpopToken = Effect.fn("clientRuntime.connection.remote.exchangeDpopToken")(
function* (
environmentId: EnvironmentId,
thumbprint: string,
identity: ClientCapabilities.CloudSessionIdentity,
) {
const bootstrap = yield* obtainBootstrap(environmentId, identity);
const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl, "relay").pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.withSpan("environment.authorization.descriptor"),
);
if (descriptor.environmentId !== environmentId) {
return yield* environmentMismatchError({
expected: environmentId,
actual: descriptor.environmentId,
});
}
const bootstrapProof = yield* signer
.createProof({
method: "POST",
url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
})
.pipe(
Effect.mapError(
() =>
new ConnectionBlockedError({
reason: "configuration",
...translatableDetail(msg("Could not create the environment authorization proof.")),
}),
),
);
yield* assertSession(identity);
const access = yield* exchangeRemoteDpopAccessToken({
httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
credential: bootstrap.credential,
dpopProof: bootstrapProof,
clientMetadata: presentation.metadata,
}).pipe(
Effect.mapError((error) =>
error._tag === "EnvironmentConnectApprovalPendingError"
? approvalPendingError(descriptor.label, thumbprint, error.traceId)
: mapRemoteDpopEnvironmentError(error),
),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.withSpan("environment.authorization.accessToken.exchange"),
);
const issuedAt = yield* Clock.currentTimeMillis;
const token = new TokenStore.RemoteDpopAccessToken({
environmentId: descriptor.environmentId,
accountId: identity.accountId,
label: descriptor.label,
endpoint: bootstrap.endpoint,
accessToken: access.access_token,
expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
dpopThumbprint: thumbprint,
});
return { token, descriptor } satisfies IssuedDpopToken;
},
);
const getDpopToken = Effect.fn("clientRuntime.connection.remote.getDpopToken")(function* (
input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0],
) {
const session = yield* cloudSession.identity;
if (Option.isNone(session)) {
return yield* sessionPending();
}
const identity = session.value;
const thumbprint = yield* signer.thumbprint.pipe(
Effect.mapError(
() =>
new ConnectionBlockedError({
reason: "configuration",
...translatableDetail(msg("Could not load the environment authorization key.")),
}),
),
Effect.withSpan("environment.authorization.dpopKey.resolve"),
);
const selected = yield* tokenLock.withPermits(1)(
Effect.gen(function* () {
yield* assertSession(identity);
const now = yield* Clock.currentTimeMillis;
const cached = yield* tokenStore
.get(input.expectedEnvironmentId)
.pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
const owner = tokenOwners.get(input.expectedEnvironmentId);
if (
Option.isSome(cached) &&
cached.value.environmentId === input.expectedEnvironmentId &&
cached.value.accountId === identity.accountId &&
cached.value.dpopThumbprint === thumbprint &&
cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS &&
cached.value.accessToken !== input.rejectedAccessToken &&
(owner?.accessToken !== cached.value.accessToken || owner.identity === identity)
) {
tokenOwners.set(input.expectedEnvironmentId, {
accessToken: cached.value.accessToken,
identity,
});
return {
issued: Effect.succeed<IssuedDpopToken>({ token: cached.value }),
fromCache: true,
};
}
if (input.rejectedAccessToken !== undefined) {
yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken);
}
const pending = pendingTokens.get(input.expectedEnvironmentId);
if (pending?.identity === identity && pending.thumbprint === thumbprint) {
return { issued: pending.issued, fromCache: false };
}
const id = {};
const fiber = yield* exchangeDpopToken(
input.expectedEnvironmentId,
thumbprint,
identity,
).pipe(
Effect.flatMap((issued) =>
tokenLock.withPermits(1)(
Effect.gen(function* () {
const { token } = issued;
yield* assertSession(identity);
yield* tokenStore
.put(token)
.pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
const current = yield* cloudSession.identity;
if (Option.isNone(current) || current.value !== identity) {
yield* removeRejectedToken(input.expectedEnvironmentId, token.accessToken);
return yield* sessionChanged();
}
tokenOwners.set(input.expectedEnvironmentId, {
accessToken: token.accessToken,
identity,
});
if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
pendingTokens.delete(input.expectedEnvironmentId);
}
return issued;
}),
),
),
Effect.timeoutOrElse({
duration: DPOP_AUTHORIZATION_TIMEOUT_MS,
orElse: () =>
Effect.fail(
new ConnectionTransientError({
reason: "timeout",
...translatableDetail(msg("Timed out renewing the environment credential.")),
}),
),
}),
Effect.ensuring(
tokenLock.withPermits(1)(
Effect.sync(() => {
if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
pendingTokens.delete(input.expectedEnvironmentId);
}
}),
),
),
// One caller's timeout must not cancel renewal for other HTTP requests.
Effect.forkIn(serviceScope),
);
const issued = Fiber.join(fiber);
pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, issued });
return { issued, fromCache: false };
}),
);
yield* Effect.annotateCurrentSpan({
"connection.remote_token_cache": selected.fromCache ? "hit" : "miss",
});
const issued = yield* selected.issued;
yield* assertSession(identity);
return { ...issued, fromCache: selected.fromCache, identity };
});
const proofError = (detail: string) => () =>
new ConnectionBlockedError({ reason: "configuration", ...translatableDetail(detail) });
// Requests for the same credential share a renewal without waiting on other hosts.
const directDpopToken = Effect.fn("clientRuntime.connection.remote.directDpopToken")(function* (
connection: DirectDpopConnection,
rejectedAccessToken?: string,
) {
return yield* directTokenLocks.withLock(
connection.connectionId,
Effect.gen(function* () {
const stored = yield* credentials.get(connection.connectionId);
if (Option.isNone(stored) || stored.value._tag !== "DpopConnectionCredential") {
return yield* credentialMissingError(connection.connectionId);
}
const current = stored.value;
const now = yield* Clock.currentTimeMillis;
if (
current.accessToken !== rejectedAccessToken &&
current.expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS > now
) {
return current;
}
const proof = yield* signer
.createProof({
method: "POST",
url: environmentEndpointUrl(connection.httpBaseUrl, "/oauth/token"),
})
.pipe(
Effect.mapError(
proofError(msg("Could not create the environment authorization proof.")),
),
);
const access = yield* exchangeRemoteDpopAccessToken({
httpBaseUrl: connection.httpBaseUrl,
credential: current.accessToken,
credentialType: AuthAccessTokenType,
dpopProof: proof,
}).pipe(
Effect.mapError((error) => mapRemoteDpopEnvironmentError(error, "direct")),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.withSpan("environment.authorization.directRenewal"),
);
const renewed = new DpopConnectionCredential({
accessToken: access.access_token,
expiresAtEpochMs: (yield* Clock.currentTimeMillis) + access.expires_in * 1_000,
});
yield* credentials.put(connection.connectionId, renewed);
return renewed;
}),
);
});
const directHttpAuthorization = (
connection: DirectDpopConnection,
credential: DpopConnectionCredential,
) =>
({
_tag: "Dpop",
accessToken: credential.accessToken,
expiresAtEpochMs: credential.expiresAtEpochMs,
directConnection: connection,
}) as const;
const authorizeDirectDpop = Effect.fn("clientRuntime.connection.remote.authorizeDirectDpop")(
function* (
input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDirectDpop"]>[0],
) {
const descriptor = yield* verifyDirectEndpoint({
expectedEnvironmentId: input.expectedEnvironmentId,
httpBaseUrl: input.httpBaseUrl,
connectionMethod: "direct",
});
const connection = { connectionId: input.connectionId, httpBaseUrl: input.httpBaseUrl };
const openSocket = (credential: DpopConnectionCredential) =>
resolveRemoteDpopWebSocketConnectionUrl({
wsBaseUrl: input.wsBaseUrl,
httpBaseUrl: input.httpBaseUrl,
accessToken: credential.accessToken,
createProof: (proof) =>
signer
.createProof(proof)
.pipe(
Effect.mapError(
proofError(msg("Could not create the websocket authorization proof.")),
),
),
clientMetadata: presentation.metadata,
connectionMethod: "direct",
}).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.result);
let credential = yield* directDpopToken(connection);
let socket = yield* openSocket(credential);
// A token the host refuses before its expiry, such as after a clock jump, renews once.
if (Result.isFailure(socket) && socket.failure._tag === "EnvironmentAuthInvalidError") {
credential = yield* directDpopToken(connection, credential.accessToken);
socket = yield* openSocket(credential);
}
if (Result.isFailure(socket)) {
const failure = socket.failure;
return yield* failure._tag === "ConnectionBlockedError"
? failure
: mapRemoteDpopEnvironmentError(failure, "direct");
}
return {
environmentId: descriptor.environmentId,
label: descriptor.label,
httpBaseUrl: input.httpBaseUrl,
socketUrl: socket.success,
descriptor,
httpAuthorization: directHttpAuthorization(connection, credential),
};
},
);
const httpAuthorization = (
token: TokenStore.RemoteDpopAccessToken,
httpBaseUrl = token.endpoint.httpBaseUrl,
): AuthorizedRemoteHttpEnvironment => ({
environmentId: token.environmentId,
label: token.label,
httpBaseUrl,
httpAuthorization: {
_tag: "Dpop",
accessToken: token.accessToken,
expiresAtEpochMs: token.expiresAtEpochMs,
},
});
const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(function* (
input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
) {
const endpoint = input.directEndpoint;
const directDescriptor =
endpoint === undefined
? undefined
: yield* verifyDirectEndpoint({
expectedEnvironmentId: input.expectedEnvironmentId,
httpBaseUrl: endpoint.httpBaseUrl,
connectionMethod: "direct",
});
const authorized = (
token: TokenStore.RemoteDpopAccessToken,
socketUrl: string,
descriptor: ExecutionEnvironmentDescriptor,
) => ({ ...httpAuthorization(token, endpoint?.httpBaseUrl), socketUrl, descriptor });
// A cached token comes without a descriptor. That read needs no ticket, so
// it runs beside the ticket request, and a failed ticket abandons it.
const openSocket = Effect.fnUntraced(function* (issued: IssuedDpopToken, timeoutMs?: number) {
const socket = createDpopSocketUrl(issued.token, timeoutMs, endpoint).pipe(Effect.result);
const known = directDescriptor ?? issued.descriptor;
if (known !== undefined) {
return Result.map(yield* socket, (socketUrl) => authorized(issued.token, socketUrl, known));
}
const reading = yield* fetchDescriptor(issued.token.endpoint.httpBaseUrl, "relay").pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.forkChild,
);
const opened = yield* socket;
if (Result.isFailure(opened)) {
yield* Fiber.interrupt(reading);
return Result.fail(opened.failure);
}
return Result.succeed(authorized(issued.token, opened.success, yield* Fiber.join(reading)));
});
let selected = yield* getDpopToken(input);
if (selected.fromCache) {
const cachedSocket = yield* openSocket(selected, CACHED_ENDPOINT_SOCKET_TIMEOUT_MS);
if (Result.isSuccess(cachedSocket)) {
yield* assertSession(selected.identity);
return cachedSocket.success;
}
if (cachedSocket.failure._tag === "ConnectionBlockedError") {
return yield* mapDpopSocketError(cachedSocket.failure);
}
// An unreachable direct address says nothing about the token, so keep
// it for the T3 Connect route rather than forcing a relay round trip.
if (endpoint !== undefined && cachedSocket.failure._tag !== "EnvironmentAuthInvalidError") {
return yield* mapDpopSocketError(cachedSocket.failure);
}
yield* assertSession(selected.identity);
selected = yield* getDpopToken({
...input,
rejectedAccessToken: selected.token.accessToken,
});
}
const socket = yield* openSocket(selected);
if (Result.isFailure(socket)) {
if (endpoint === undefined || socket.failure._tag === "ConnectionBlockedError") {
yield* tokenLock.withPermits(1)(
removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken),
);
}
return yield* mapDpopSocketError(socket.failure);
}
yield* assertSession(selected.identity);
return socket.success;
});
return RemoteEnvironmentAuthorization.of({
authorizeBearer,
authorizeLanDpop,
mintLanCredential,
// Untraced: it runs on every route and host check.
rememberCheckedDescriptor: Effect.fnUntraced(function* (httpBaseUrl, descriptor, keepsItsHost) {
if (Option.isNone(descriptor) || !keepsItsHost) {
checkedDescriptors.delete(httpBaseUrl);
return;
}
checkedDescriptors.set(httpBaseUrl, {
descriptor: descriptor.value,
at: yield* Clock.monotonicTimeNanos,
});
}),
authorizeDpop: Effect.fn("environment.authorization")(function (input) {
return authorizeDpop(input);
}),
authorizeDirectDpop,
authorizeDirectDpopHttp: Effect.fn("environment.authorization.directHttp")(
function* (connection, rejectedAccessToken) {
const credential = yield* directDpopToken(connection, rejectedAccessToken);
return directHttpAuthorization(connection, credential);
},
),
// The relay tracer must wrap span creation, not just the token request.
authorizeDpopHttp: Effect.fnUntraced(function* (input) {
return yield* getDpopToken(input).pipe(
Effect.map(({ token }) => httpAuthorization(token)),
Effect.withSpan("environment.authorization.http"),
withRelayClientTracing,
);
}),
// Untraced: a span here would stay open for the socket's lifetime. Each renewal has its own.
renewDpopBeforeExpiry: Effect.fnUntraced(function* (input) {
const direct = input.directConnection;
let expiresAtEpochMs = input.expiresAtEpochMs;
let now = yield* Clock.currentTimeMillis;
// Past expiry the server has closed a T3 Connect socket. A direct socket stays open for
// its session's whole renewal window, so it keeps retrying until a blocked credential.
while (direct !== undefined || now < expiresAtEpochMs) {
// getDpopToken reuses a cached token until it is within the skew of expiry.
// The floor spaces out retries and keeps a wall-clock jump from spinning.
const floor = now < expiresAtEpochMs ? 5_000 : DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS;
yield* Effect.sleep(
Math.max(floor, expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - now),
);
const renewed = yield* (
direct === undefined
? getDpopToken({ expectedEnvironmentId: input.expectedEnvironmentId }).pipe(
Effect.map(({ token }) => token.expiresAtEpochMs),
)
: directDpopToken(direct).pipe(Effect.map((credential) => credential.expiresAtEpochMs))
).pipe(
Effect.withSpan("environment.authorization.renewSocket"),
withRelayClientTracing,
// A relay blip retries until expiry; a blocked credential ends the loop.
Effect.catchTags({ ConnectionTransientError: () => Effect.succeed(expiresAtEpochMs) }),
);
expiresAtEpochMs = Math.max(expiresAtEpochMs, renewed);
now = yield* Clock.currentTimeMillis;
}
}),
});
});
export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);