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

resolver.ts

343 lines12.2 KB

1import { msg } from "gt-i18n";
2import { translatableDetail } from "../errors/translatable.ts";
3import type {
4 AuthClientPresentationMetadata,
5 ExecutionEnvironmentDescriptor,
6} from "@t3tools/contracts";
7import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
8import * as Context from "effect/Context";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import * as HttpClient from "effect/http/HttpClient";
14​
15import {
16 appendClientConnectionParams,
17 type ClientOwnerParams,
18 readClientOwnerParams,
19} from "../authorization/remote.ts";
20import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
21import * as ClientCapabilities from "../platform/capabilities.ts";
22import {
23 BearerConnectionCredential,
24 BearerConnectionProfile,
25 type ConnectionCatalogEntry,
26 SshConnectionProfile,
27} from "./catalog.ts";
28import * as ConnectionCredentialStore from "./credentialStore.ts";
29import {
30 credentialMissingError,
31 environmentMismatchError,
32 mapRemoteEnvironmentError,
33 profileMissingError,
34} from "./errors.ts";
35import {
36 PullRequestRoutingPermissions,
37 pullRequestRoutingConnectionKey,
38} from "./pullRequestRoutingPermissions.ts";
39import type {
40 BearerConnectionTarget,
41 ConnectionTarget,
42 PreparedConnection,
43 PrimaryConnectionTarget,
44 RelayConnectionTarget,
45 SshConnectionTarget,
46} from "./model.ts";
47import { ConnectionBlockedError, type ConnectionAttemptError } from "./model.ts";
48import * as ConnectionProfileStore from "./profileStore.ts";
49import {
50 appendOrchestrationProtocol,
51 orchestrationProtocolCompatibilityError,
52} from "./compatibility.ts";
53import { credentialConnectionId } from "./routes.ts";
54import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
55​
56export class ConnectionResolver extends Context.Service<
57 ConnectionResolver,
58 {
59 readonly prepare: (
60 entry: ConnectionCatalogEntry,
61 ) => Effect.Effect<PreparedConnection, ConnectionAttemptError>;
62 /**
63 * Authorizes a socket without the orchestration protocol gate, for hosts
64 * too old to connect normally. Only update RPCs may run over it.
65 */
66 readonly prepareForUpdate: (entry: ConnectionCatalogEntry) => Effect.Effect<
67 {
68 readonly prepared: PreparedConnection;
69 readonly descriptor: ExecutionEnvironmentDescriptor;
70 },
71 ConnectionAttemptError
72 >;
73 }
74>()("@t3tools/client-runtime/connection/resolver/ConnectionResolver") {}
75​
76const isBearerProfile = Schema.is(BearerConnectionProfile);
77const isSshProfile = Schema.is(SshConnectionProfile);
78const isBearerCredential = Schema.is(BearerConnectionCredential);
79​
80function primarySocketUrl(
81 target: PrimaryConnectionTarget,
82 clientMetadata: AuthClientPresentationMetadata | undefined,
83 owners: ClientOwnerParams,
84): string {
85 const url = new URL(target.wsBaseUrl);
86 if (url.pathname === "" || url.pathname === "/") {
87 url.pathname = "/ws";
88 }
89 appendClientConnectionParams(url, clientMetadata, "direct", owners);
90 return url.toString();
92​
93const makePrimaryBroker = Effect.fn("clientRuntime.connection.broker.makePrimary")(function* () {
94 const auth = yield* ClientCapabilities.PrimaryEnvironmentAuth;
95 const presentation = yield* ClientCapabilities.ClientPresentation;
96 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
97​
98 return Effect.fn("clientRuntime.connection.broker.primary")(function* (
99 target: PrimaryConnectionTarget,
100 ) {
101 const bearerToken = yield* auth.bearerToken;
102 if (Option.isNone(bearerToken)) {
103 return {
104 environmentId: target.environmentId,
105 label: target.label,
106 httpBaseUrl: target.httpBaseUrl,
107 socketUrl: primarySocketUrl(target, presentation.metadata, yield* readClientOwnerParams),
108 httpAuthorization: null,
109 target,
110 } satisfies PreparedConnection;
111 }
112​
113 const authorized = yield* remote.authorizeBearer({
114 expectedEnvironmentId: target.environmentId,
115 httpBaseUrl: target.httpBaseUrl,
116 wsBaseUrl: target.wsBaseUrl,
117 bearerToken: bearerToken.value,
118 connectionMethod: "direct",
119 });
120 return {
121 ...authorized,
122 target,
123 } satisfies PreparedConnection;
124 });
125});
126​
127const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")(function* () {
128 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
129 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
130​
131 return Effect.fn("clientRuntime.connection.broker.bearer")(function* (
132 entry: ConnectionCatalogEntry & { readonly target: BearerConnectionTarget },
133 ) {
134 const target = entry.target;
135 const profile = yield* Effect.fromOption(entry.profile, () =>
136 profileMissingError(target.connectionId),
137 );
138 if (!isBearerProfile(profile)) {
139 return yield* new ConnectionBlockedError({
140 reason: "configuration",
141 ...translatableDetail(
142 msg`Connection profile ${{ connectionId: target.connectionId }} is not a bearer connection.`,
143 ),
144 });
145 }
146 if (profile.environmentId !== target.environmentId) {
147 return yield* environmentMismatchError({
148 expected: target.environmentId,
149 actual: profile.environmentId,
150 });
151 }
152 if (profile.authorization === "t3-connect") {
153 const authorized = yield* remote.authorizeDpop({
154 expectedEnvironmentId: target.environmentId,
155 directEndpoint: { httpBaseUrl: profile.httpBaseUrl, wsBaseUrl: profile.wsBaseUrl },
156 });
157 return { ...authorized, target } satisfies PreparedConnection;
158 }
159 const credential = yield* credentials.get(credentialConnectionId(target.connectionId)).pipe(
160 Effect.flatMap(
161 Option.match({
162 onNone: () => Effect.fail(credentialMissingError(target.connectionId)),
163 onSome: Effect.succeed,
164 }),
165 ),
166 );
167 const authorized =
168 credential._tag === "DpopConnectionCredential"
169 ? yield* remote.authorizeDirectDpop({
170 expectedEnvironmentId: target.environmentId,
171 connectionId: credentialConnectionId(target.connectionId),
172 httpBaseUrl: profile.httpBaseUrl,
173 wsBaseUrl: profile.wsBaseUrl,
174 })
175 : yield* remote.authorizeBearer({
176 expectedEnvironmentId: target.environmentId,
177 httpBaseUrl: profile.httpBaseUrl,
178 wsBaseUrl: profile.wsBaseUrl,
179 bearerToken: credential.token,
180 connectionMethod: "direct",
181 });
182 return {
183 ...authorized,
184 target,
185 } satisfies PreparedConnection;
186 });
187});
188​
189const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(function* () {
190 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
191​
192 return Effect.fnUntraced(
193 function* (target: RelayConnectionTarget) {
194 const authorized = yield* remote.authorizeDpop({
195 expectedEnvironmentId: target.environmentId,
196 });
197 return {
198 ...authorized,
199 target,
200 } satisfies PreparedConnection;
201 },
202 Effect.withSpan("clientRuntime.connection.broker.relay"),
203 withRelayClientTracing,
204 );
205});
206​
207const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(function* () {
208 const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;
209 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
210 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
211 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
212​
213 return Effect.fn("clientRuntime.connection.broker.ssh")(function* (
214 entry: ConnectionCatalogEntry & { readonly target: SshConnectionTarget },
215 ) {
216 const target = entry.target;
217 const profile = yield* Effect.fromOption(entry.profile, () =>
218 profileMissingError(target.connectionId),
219 );
220 if (!isSshProfile(profile)) {
221 return yield* new ConnectionBlockedError({
222 reason: "configuration",
223 ...translatableDetail(
224 msg`Connection profile ${{ connectionId: target.connectionId }} is not an SSH connection.`,
225 ),
226 });
227 }
228 if (profile.environmentId !== target.environmentId) {
229 return yield* environmentMismatchError({
230 expected: target.environmentId,
231 actual: profile.environmentId,
232 });
233 }
234 // Each pairing adds a session on the host, so connects reuse the saved token.
235 const saved = Option.getOrUndefined(yield* credentials.get(target.connectionId));
236 const savedToken = saved !== undefined && isBearerCredential(saved) ? saved.token : undefined;
237 const prepared = yield* ssh.prepare({
238 connectionId: target.connectionId,
239 expectedEnvironmentId: target.environmentId,
240 target: profile.target,
241 ...(savedToken === undefined ? {} : { bearerToken: savedToken }),
242 });
243 if (prepared.bearerToken !== savedToken) {
244 yield* credentials.put(
245 target.connectionId,
246 new BearerConnectionCredential({ token: prepared.bearerToken }),
247 );
248 }
249 const preparedProfile = new SshConnectionProfile({
250 connectionId: profile.connectionId,
251 environmentId: profile.environmentId,
252 label: profile.label,
253 target: prepared.bootstrap.target,
254 });
255 if (
256 pullRequestRoutingConnectionKey(entry) !==
257 pullRequestRoutingConnectionKey({ ...entry, profile: Option.some(preparedProfile) })
258 ) {
259 const permissions = yield* PullRequestRoutingPermissions;
260 yield* permissions.forget(target.environmentId);
261 }
262 yield* profiles.put(preparedProfile);
263 const authorized = yield* remote.authorizeBearer({
264 expectedEnvironmentId: target.environmentId,
265 httpBaseUrl: prepared.bootstrap.httpBaseUrl,
266 wsBaseUrl: prepared.bootstrap.wsBaseUrl,
267 bearerToken: prepared.bearerToken,
268 connectionMethod: "ssh",
269 });
270 return {
271 ...authorized,
272 target,
273 } satisfies PreparedConnection;
274 });
275});
276​
277/** @public */
278export const make = Effect.gen(function* () {
279 const primary = yield* makePrimaryBroker();
280 const bearer = yield* makeBearerBroker();
281 const relay = yield* makeRelayBroker();
282 const ssh = yield* makeSshBroker();
283 const httpClient = yield* HttpClient.HttpClient;
284​
285 const authorize = Effect.fn("clientRuntime.connection.broker.authorize")(function* (
286 entry: ConnectionCatalogEntry,
287 ) {
288 const target: ConnectionTarget = entry.target;
289 yield* Effect.annotateCurrentSpan({
290 "connection.environment.id": target.environmentId,
291 "connection.target.kind": target._tag,
292 });
293 const authorized: PreparedConnection & {
294 readonly descriptor?: ExecutionEnvironmentDescriptor;
295 } = yield* (() => {
296 switch (target._tag) {
297 case "PrimaryConnectionTarget":
298 return primary(target);
299 case "BearerConnectionTarget":
300 return bearer({ ...entry, target });
301 case "RelayConnectionTarget":
302 return relay(target);
303 case "SshConnectionTarget":
304 return ssh({ ...entry, target });
305 }
306 })();
307 const { descriptor: authorizedDescriptor, ...prepared } = authorized;
308 const descriptor =
309 authorizedDescriptor ??
310 (yield* fetchRemoteEnvironmentDescriptor({
311 httpBaseUrl: prepared.httpBaseUrl,
312 }).pipe(
313 Effect.mapError(mapRemoteEnvironmentError),
314 Effect.provideService(HttpClient.HttpClient, httpClient),
315 ));
316 if (descriptor.environmentId !== target.environmentId) {
317 return yield* environmentMismatchError({
318 expected: target.environmentId,
319 actual: descriptor.environmentId,
320 });
321 }
322 return { prepared, descriptor };
323 });
324​
325 const prepare = Effect.fn("clientRuntime.connection.broker.prepare")(function* (
326 entry: ConnectionCatalogEntry,
327 ) {
328 const { prepared, descriptor } = yield* authorize(entry);
329 const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
330 if (compatibilityError !== null) {
331 return yield* compatibilityError;
332 }
333 return {
334 ...prepared,
335 descriptor,
336 socketUrl: appendOrchestrationProtocol(prepared.socketUrl),
337 };
338 });
339​
340 return ConnectionResolver.of({ prepare, prepareForUpdate: authorize });
341});
342​
343export const layer = Layer.effect(ConnectionResolver, make);