Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as PlatformError from "effect/PlatformError";
6import * as Tracer from "effect/Tracer";
7import {
8 HttpClient,
9 HttpClientResponse,
10 HttpServerRequest,
11 type HttpClientRequest,
12} from "effect/unstable/http";
13
14import { EnvironmentId } from "@t3tools/contracts";
15import { RelayClientTracer } from "@t3tools/shared/relayTracing";
16import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
17import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
18import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
19import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
20import * as CliTokenManager from "./CliTokenManager.ts";
21import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";
22import { CLOUD_ENDPOINT_RUNTIME_CONFIG, RELAY_URL_SECRET } from "./config.ts";
23import {
24 consumeCloudReplayGuards,
25 isSupportedLinkProviderKind,
26 linkProofScopes,
27 reconcileDesiredCloudLink,
28 releaseManagedTunnelOnShutdown,
29} from "./http.ts";
30import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
31import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
32
33const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
34 new ServerSecretStore.SecretStorePersistError({
35 resource: "cloud replay guard",
36 cause: PlatformError.systemError({
37 _tag: tag,
38 module: "FileSystem",
39 method: "open",
40 pathOrDescriptor: "cloud-replay-guard.bin",
41 }),
42 });
43
44const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
45
46function makeSecretStore(
47 create: ServerSecretStore.ServerSecretStore["Service"]["create"],
48): ServerSecretStore.ServerSecretStore["Service"] {
49 return {
50 get: unusedSecretStoreOperation,
51 set: unusedSecretStoreOperation,
52 create,
53 getOrCreateRandom: unusedSecretStoreOperation,
54 remove: unusedSecretStoreOperation,
55 };
56}
57
58it("preserves messages surfaced by cloud 500 responses", () => {
59 const cause = new Error("cloud operation failed");
60
61 expect([
62 new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ cause }).message,
63 new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ cause }).message,
64 new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({}).message,
65 new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ cause }).message,
66 new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}).message,
67 new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}).message,
68 new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ cause }).message,
69 new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ cause }).message,
70 ]).toEqual([
71 "Could not verify the linked cloud account.",
72 "Could not read the linked cloud account.",
73 "Cloud linked user is not installed for this environment.",
74 "Failed to sign cloud link JWT.",
75 "Cloud mint public key is not installed for this environment.",
76 "Cloud relay issuer is not installed for this environment.",
77 "Failed to sign cloud health JWT.",
78 "Failed to sign cloud mint JWT.",
79 ]);
80});
81
82describe("consumeCloudReplayGuards", () => {
83 it.effect("reports already-created guards as replay conflicts", () =>
84 Effect.gen(function* () {
85 const consumed = yield* consumeCloudReplayGuards({
86 secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),
87 names: ["cloud-jti", "cloud-nonce"],
88 value: new Uint8Array(),
89 });
90
91 expect(consumed).toBe(false);
92 }),
93 );
94
95 it.effect("preserves replay-store availability failures", () =>
96 Effect.gen(function* () {
97 const failure = storeFailure("PermissionDenied");
98 const error = yield* Effect.flip(
99 consumeCloudReplayGuards({
100 secrets: makeSecretStore(() => Effect.fail(failure)),
101 names: ["cloud-jti", "cloud-nonce"],
102 value: new Uint8Array(),
103 }),
104 );
105
106 expect(error).toBe(failure);
107 }),
108 );
109});
110
111describe("relay request tracing", () => {
112 it.effect("does not accept an unauthenticated request trace parent", () =>
113 Effect.gen(function* () {
114 const spans: Array<Tracer.Span> = [];
115 const productTracer = Tracer.make({
116 span: (options) => {
117 const span = new Tracer.NativeSpan(options);
118 spans.push(span);
119 return span;
120 },
121 });
122 const request = HttpServerRequest.fromWeb(
123 new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
124 headers: {
125 traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
126 },
127 }),
128 );
129
130 yield* traceRelayRequest(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
131 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
132 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
133 );
134
135 expect(spans).toHaveLength(1);
136 const span = spans[0]!;
137 expect(span.traceId).not.toBe("0123456789abcdef0123456789abcdef");
138 expect(Option.isNone(span.parent)).toBe(true);
139 }),
140 );
141
142 it.effect("continues an authenticated relay trace with the product tracer", () =>
143 Effect.gen(function* () {
144 const spans: Array<Tracer.Span> = [];
145 const productTracer = Tracer.make({
146 span: (options) => {
147 const span = new Tracer.NativeSpan(options);
148 spans.push(span);
149 return span;
150 },
151 });
152 const request = HttpServerRequest.fromWeb(
153 new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
154 headers: {
155 traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
156 },
157 }),
158 );
159
160 yield* traceAuthenticatedRelayRequest(
161 Effect.void.pipe(Effect.withSpan("relay.mint.handler")),
162 ).pipe(
163 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
164 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
165 );
166
167 expect(spans).toHaveLength(1);
168 const span = spans[0]!;
169 expect(span.traceId).toBe("0123456789abcdef0123456789abcdef");
170 expect(Option.getOrUndefined(span.parent)?.spanId).toBe("0123456789abcdef");
171 }),
172 );
173});
174
175describe("reconcileDesiredCloudLink", () => {
176 it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
177 Effect.gen(function* () {
178 const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
179
180 expect(error).toMatchObject({
181 _tag: "EnvironmentHttpUnauthorizedError",
182 message: "Run `t3 connect link` to authorize this environment.",
183 });
184 }).pipe(
185 Effect.provideService(
186 ServerSecretStore.ServerSecretStore,
187 makeSecretStore(unusedSecretStoreOperation),
188 ),
189 Effect.provideService(
190 ServerEnvironment.ServerEnvironment,
191 ServerEnvironment.ServerEnvironment.of({
192 getEnvironmentId: unusedSecretStoreOperation(),
193 getDescriptor: unusedSecretStoreOperation(),
194 }),
195 ),
196 Effect.provideService(
197 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
198 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
199 applyConfig: unusedSecretStoreOperation,
200 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
201 ),
202 Effect.provideService(
203 EnvironmentAuth.EnvironmentAuth,
204 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
205 ),
206 Effect.provideService(
207 CliTokenManager.CloudCliTokenManager,
208 CliTokenManager.CloudCliTokenManager.of({
209 get: unusedSecretStoreOperation(),
210 getExisting: Effect.succeed(Option.none()),
211 hasCredential: unusedSecretStoreOperation(),
212 store: () => unusedSecretStoreOperation(),
213 clear: unusedSecretStoreOperation(),
214 }),
215 ),
216 Effect.provideService(
217 HttpClient.HttpClient,
218 HttpClient.make(() => unusedSecretStoreOperation()),
219 ),
220 Effect.provide(NodeServices.layer),
221 ),
222 );
223});
224
225describe("releaseManagedTunnelOnShutdown", () => {
226 const cliToken: CliTokenManager.PersistedToken = {
227 accessToken: "cli-access-token",
228 refreshToken: "cli-refresh-token",
229 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
230 };
231
232 function makeMemorySecretStore(initial: Iterable<readonly [string, string]> = []) {
233 const values = new Map<string, Uint8Array>(
234 Array.from(initial, ([name, value]) => [name, new TextEncoder().encode(value)] as const),
235 );
236 const store: ServerSecretStore.ServerSecretStore["Service"] = {
237 get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
238 set: (name, value) =>
239 Effect.sync(() => {
240 values.set(name, value);
241 }),
242 create: unusedSecretStoreOperation,
243 getOrCreateRandom: unusedSecretStoreOperation,
244 remove: (name) =>
245 Effect.sync(() => {
246 values.delete(name);
247 }),
248 };
249 return { store, values };
250 }
251
252 interface ReleaseHarness {
253 readonly store: ServerSecretStore.ServerSecretStore["Service"];
254 readonly applyConfigCalls: Array<unknown>;
255 readonly requests: Array<HttpClientRequest.HttpClientRequest>;
256 readonly respond?: () => Response;
257 }
258
259 const provideReleaseHarness =
260 (harness: ReleaseHarness) =>
261 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
262 effect.pipe(
263 Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),
264 Effect.provideService(
265 ServerEnvironment.ServerEnvironment,
266 ServerEnvironment.ServerEnvironment.of({
267 getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
268 getDescriptor: Effect.die("unused"),
269 }),
270 ),
271 Effect.provideService(
272 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
273 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
274 applyConfig: (config) =>
275 Effect.sync(() => {
276 harness.applyConfigCalls.push(config);
277 return {
278 status: "disabled",
279 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus;
280 }),
281 }),
282 ),
283 Effect.provideService(
284 EnvironmentAuth.EnvironmentAuth,
285 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
286 ),
287 Effect.provideService(
288 CliTokenManager.CloudCliTokenManager,
289 CliTokenManager.CloudCliTokenManager.of({
290 get: unusedSecretStoreOperation(),
291 getExisting: Effect.succeed(Option.some(cliToken)),
292 hasCredential: unusedSecretStoreOperation(),
293 store: () => unusedSecretStoreOperation(),
294 clear: unusedSecretStoreOperation(),
295 }),
296 ),
297 Effect.provideService(
298 HttpClient.HttpClient,
299 HttpClient.make((request) =>
300 Effect.sync(() => {
301 harness.requests.push(request);
302 return HttpClientResponse.fromWeb(
303 request,
304 (harness.respond ?? (() => Response.json({ ok: true })))(),
305 );
306 }),
307 ),
308 ),
309 );
310
311 // The persisted state of a CLI-managed link whose tunnel is releasable.
312 const managedLinkSecrets = [
313 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
314 [RELAY_URL_SECRET, "https://relay.example.test"],
315 [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"],
316 ] as const;
317
318 it.effect("stops the connector, releases the relay tunnel, and drops the dead token", () => {
319 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
320 const applyConfigCalls: Array<unknown> = [];
321 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
322
323 return Effect.gen(function* () {
324 const released = yield* releaseManagedTunnelOnShutdown();
325
326 expect(released).toBe(true);
327 expect(applyConfigCalls).toEqual([null]);
328 expect(requests).toHaveLength(1);
329 const request = requests[0]!;
330 expect(request.method).toBe("DELETE");
331 expect(request.url).toBe(
332 "https://relay.example.test/v1/client/environment-links/env_123/tunnel",
333 );
334 expect(request.headers.authorization).toBe("Bearer cli-access-token");
335 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
336 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
337 });
338
339 it.effect("does nothing for links without a stored managed tunnel runtime config", () => {
340 const { store } = makeMemorySecretStore();
341 const applyConfigCalls: Array<unknown> = [];
342 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
343
344 return Effect.gen(function* () {
345 const released = yield* releaseManagedTunnelOnShutdown();
346
347 expect(released).toBe(false);
348 expect(applyConfigCalls).toEqual([]);
349 expect(requests).toEqual([]);
350 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
351 });
352
353 it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => {
354 // A managed runtime config without a CLI-desired link: the environment was
355 // linked by a web/mobile client, and nothing re-provisions the tunnel on
356 // the next boot, so shutdown must not release it.
357 const { store, values } = makeMemorySecretStore([
358 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
359 [RELAY_URL_SECRET, "https://relay.example.test"],
360 ]);
361 const applyConfigCalls: Array<unknown> = [];
362 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
363
364 return Effect.gen(function* () {
365 const released = yield* releaseManagedTunnelOnShutdown();
366
367 expect(released).toBe(false);
368 expect(applyConfigCalls).toEqual([]);
369 expect(requests).toEqual([]);
370 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
371 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
372 });
373
374 it.effect("leaves the tunnel of a publish-only desired link untouched", () => {
375 const { store, values } = makeMemorySecretStore([
376 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
377 [RELAY_URL_SECRET, "https://relay.example.test"],
378 [CLOUD_CLI_DESIRED_LINK_SECRET, "publish_only"],
379 ]);
380 const applyConfigCalls: Array<unknown> = [];
381 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
382
383 return Effect.gen(function* () {
384 const released = yield* releaseManagedTunnelOnShutdown();
385
386 expect(released).toBe(false);
387 expect(applyConfigCalls).toEqual([]);
388 expect(requests).toEqual([]);
389 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
390 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
391 });
392
393 it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
394 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
395 const applyConfigCalls: Array<unknown> = [];
396 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
397 const freshConfig = new TextEncoder().encode("fresh-runtime-config");
398
399 return Effect.gen(function* () {
400 const released = yield* releaseManagedTunnelOnShutdown();
401
402 expect(released).toBe(true);
403 // The finalizer only drops the config it released; the one written by
404 // the restarted process while the DELETE was in flight stays.
405 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
406 }).pipe(
407 provideReleaseHarness({
408 store,
409 applyConfigCalls,
410 requests,
411 respond: () => {
412 // A restarted process reconciled and stored a fresh connector config
413 // while this shutdown's release request was in flight.
414 values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);
415 return Response.json({ ok: true });
416 },
417 }),
418 );
419 });
420
421 it.effect("keeps the stored connector token when the relay skipped the release", () => {
422 // ok:false means a concurrent provision owns the recorded tunnel, so the
423 // stored runtime config (possibly freshly written by that provision) must
424 // survive.
425 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
426 const applyConfigCalls: Array<unknown> = [];
427 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
428
429 return Effect.gen(function* () {
430 const released = yield* releaseManagedTunnelOnShutdown();
431
432 expect(released).toBe(false);
433 expect(requests).toHaveLength(1);
434 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
435 }).pipe(
436 provideReleaseHarness({
437 store,
438 applyConfigCalls,
439 requests,
440 respond: () => Response.json({ ok: false }),
441 }),
442 );
443 });
444
445 it.effect("keeps the stored connector token when the relay release request fails", () => {
446 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
447 const applyConfigCalls: Array<unknown> = [];
448 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
449
450 return Effect.gen(function* () {
451 const result = yield* Effect.result(releaseManagedTunnelOnShutdown());
452
453 expect(result._tag).toBe("Failure");
454 expect(requests).toHaveLength(1);
455 // The tunnel still exists, so the stored token stays valid across the
456 // restart and the next boot can bring the connector back immediately.
457 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
458 }).pipe(
459 provideReleaseHarness({
460 store,
461 applyConfigCalls,
462 requests,
463 respond: () => Response.json({ ok: false }, { status: 503 }),
464 }),
465 );
466 });
467});
468
469describe("link proof provider kinds", () => {
470 const proofRequest = (
471 providerKind: RelayLinkProofRequest["endpoint"]["providerKind"],
472 ): RelayLinkProofRequest => ({
473 challenge: "challenge",
474 relayIssuer: "https://relay.example.test",
475 endpoint: {
476 httpBaseUrl: "http://127.0.0.1:7331",
477 wsBaseUrl: "ws://127.0.0.1:7331",
478 providerKind,
479 },
480 origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 },
481 });
482
483 it("accepts managed and manual endpoints but not t3_relay", () => {
484 expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true);
485 expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true);
486 expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false);
487 });
488
489 it("only claims the managed-tunnel scope for tunnel links", () => {
490 expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([
491 "agent_activity_notifications",
492 "managed_tunnels",
493 ]);
494 expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]);
495 });
496});