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

resolver.ts

332 lines11.7 KB

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