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

CloudLink.lifecycle.test.ts

1,123 lines42.2 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { describe, expect, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as PlatformError from "effect/PlatformError";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } from "effect/http";
13import * as NetAddress from "effect/net/NetAddress";
14​
15import { EnvironmentId } from "@t3tools/contracts";
16import * as EnvironmentKeys from "./environmentKeys.ts";
17import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
18import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
19import * as ServerConfigModule from "../config.ts";
20import { writeServiceState } from "../serviceLauncher.ts";
21import {
22 SERVICE_LAUNCHER_PROTOCOL,
23 SERVICE_STATE_FILE,
24 SERVICE_STOP_MARKER_FILE,
25 type ServiceUpdateRecord,
26} from "./serviceProtocol.ts";
27import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
28import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
29import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
30import * as CliTokenManager from "./CliTokenManager.ts";
31import { RelayManagedEndpointRecoveryRegistrationRequest } from "@t3tools/contracts/relay";
32import {
33 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
34 CLOUD_ENDPOINT_RUNTIME_CONFIG,
35 CLOUD_LINK_REVOKED,
36 CLOUD_LINKED_USER_ID,
37 decodeRuntimeConfig,
38 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
39 RELAY_ISSUER_SECRET,
40 RELAY_URL_SECRET,
41} from "./config.ts";
42import * as CloudLink from "./CloudLink.ts";
43import * as ConnectReachability from "./ConnectReachability.ts";
44import { consumeCloudReplayGuards } from "./CloudLink.ts";
45import { pendingServiceUpdateExists } from "./updateHandoff.ts";
46import { managedTunnelStartupAction } from "./managedTunnelStartup.ts";
47import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
48import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
49​
50const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
51 new ServerSecretStore.SecretStorePersistError({
52 resource: "cloud replay guard",
53 cause: PlatformError.systemError({
54 _tag: tag,
55 module: "FileSystem",
56 method: "open",
57 pathOrDescriptor: "cloud-replay-guard.bin",
58 }),
59 });
60​
61const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
62​
63const idleAwarenessRelay = AgentAwarenessRelay.AgentAwarenessRelay.of({
64 publishThread: () => Effect.void,
65 drain: Effect.void,
66 requestCatchUp: () => Effect.void,
67 start: () => Effect.void,
68});
69​
70const idleHttpServer = HttpServer.HttpServer.of({
71 address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
72 serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
73});
74​
75const decodeManagedTunnelRecoveryRegistration = Schema.decodeUnknownEffect(
76 Schema.fromJsonString(RelayManagedEndpointRecoveryRegistrationRequest),
77);
78​
79function makeSecretStore(
80 create: ServerSecretStore.ServerSecretStore["Service"]["create"],
81): ServerSecretStore.ServerSecretStore["Service"] {
82 return {
83 get: unusedSecretStoreOperation,
84 set: unusedSecretStoreOperation,
85 create,
86 getOrCreateRandom: unusedSecretStoreOperation,
87 remove: unusedSecretStoreOperation,
88 };
90​
91describe("consumeCloudReplayGuards", () => {
92 it.effect("reports already-created guards as replay conflicts", () =>
93 Effect.gen(function* () {
94 const consumed = yield* consumeCloudReplayGuards({
95 secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),
96 names: ["cloud-jti", "cloud-nonce"],
97 value: new Uint8Array(),
98 });
99​
100 expect(consumed).toBe(false);
101 }),
102 );
103});
104​
105describe("releaseManagedTunnelOnShutdown", () => {
106 const cliToken: CliTokenManager.PersistedToken = {
107 accessToken: "cli-access-token",
108 refreshToken: "cli-refresh-token",
109 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
110 };
111​
112 function makeMemorySecretStore(initial: Iterable<readonly [string, string]> = []) {
113 const values = new Map<string, Uint8Array>(
114 Array.from(initial, ([name, value]) => [name, new TextEncoder().encode(value)] as const),
115 );
116 const store: ServerSecretStore.ServerSecretStore["Service"] = {
117 get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
118 set: (name, value) =>
119 Effect.sync(() => {
120 values.set(name, value);
121 }),
122 create: (name, value) =>
123 Effect.sync(() => {
124 values.set(name, value);
125 }),
126 getOrCreateRandom: unusedSecretStoreOperation,
127 remove: (name) =>
128 Effect.sync(() => {
129 values.delete(name);
130 }),
131 };
132 return { store, values };
133 }
134​
135 interface ReleaseHarness {
136 readonly store: ServerSecretStore.ServerSecretStore["Service"];
137 readonly applyConfigCalls: Array<unknown>;
138 readonly requests: Array<HttpClientRequest.HttpClientRequest>;
139 readonly onRequest?: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<void>;
140 readonly respond?: () => Response;
141 readonly address?: HttpServer.HttpServer["Service"]["address"];
142 readonly respondEffect?: Effect.Effect<Response>;
143 readonly getExisting?: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
144 readonly latestReachability?: ConnectReachability.ConnectReachability["Service"]["latest"];
145 readonly connector?: ManagedEndpointRuntime.ConnectorFacts;
146 }
147​
148 const writeLauncherState = (update: ServiceUpdateRecord) =>
149 Effect.gen(function* () {
150 const path = yield* Path.Path;
151 const config = yield* ServerConfigModule.ServerConfig;
152 const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
153 yield* Effect.promise(() =>
154 writeServiceState(statePath, {
155 protocol: SERVICE_LAUNCHER_PROTOCOL,
156 activeVersion: "0.0.30",
157 update,
158 }),
159 );
160 });
161​
162 const provideReleaseHarness =
163 (harness: ReleaseHarness) =>
164 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
165 effect.pipe(
166 Effect.provide(
167 CloudLink.layer.pipe(
168 Layer.provide(EnvironmentKeys.layer),
169 Layer.provide(ManagedPolicy.layerTest()),
170 ),
171 ),
172 Effect.provideService(
173 ConnectReachability.ConnectReachability,
174 ConnectReachability.ConnectReachability.of({
175 check: Effect.die("unused"),
176 latest: harness.latestReachability ?? Effect.succeedNone,
177 }),
178 ),
179 Effect.provideService(HttpServer.HttpServer, {
180 ...idleHttpServer,
181 address: harness.address ?? idleHttpServer.address,
182 }),
183 Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),
184 Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),
185 Effect.provideService(
186 ServerEnvironment.ServerEnvironment,
187 ServerEnvironment.ServerEnvironment.of({
188 getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
189 getDescriptor: Effect.die("unused"),
190 }),
191 ),
192 Effect.provideService(
193 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
194 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
195 applyConfig: (config) =>
196 Effect.sync(() => {
197 harness.applyConfigCalls.push(config);
198 return config === null
199 ? ({
200 status: "disabled",
201 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus)
202 : ({
203 status: "running",
204 providerKind: "cloudflare_tunnel",
205 pid: 123,
206 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus);
207 }),
208 recoveryRequests: Stream.empty,
209 requestRecovery: () => Effect.void,
210 restartConnector: () => Effect.succeed(false),
211 tunnelConnected: Stream.empty,
212 inspectConnector: Effect.succeed(harness.connector ?? null),
213 readinessChanged: Stream.empty,
214 withLinkStateLock: (effect) => effect,
215 }),
216 ),
217 Effect.provideService(
218 EnvironmentAuth.EnvironmentAuth,
219 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
220 ),
221 Effect.provideService(
222 CliTokenManager.CloudCliTokenManager,
223 CliTokenManager.CloudCliTokenManager.of({
224 get: unusedSecretStoreOperation(),
225 getExisting: harness.getExisting ?? Effect.succeedSome(cliToken),
226 hasCredential: unusedSecretStoreOperation(),
227 store: () => unusedSecretStoreOperation(),
228 clear: unusedSecretStoreOperation(),
229 }),
230 ),
231 Effect.provideService(
232 HttpClient.HttpClient,
233 HttpClient.make((request) =>
234 Effect.sync(() => {
235 harness.requests.push(request);
236 }).pipe(
237 Effect.andThen(harness.onRequest?.(request) ?? Effect.void),
238 Effect.andThen(
239 harness.respondEffect ??
240 Effect.sync(() => (harness.respond ?? (() => Response.json({ ok: true })))()),
241 ),
242 Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
243 ),
244 ),
245 ),
246​
247 Effect.provide(
248 ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
249 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
250 ),
251 ),
252 Effect.scoped,
253 );
254​
255 const managedLinkSecrets = [
256 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
257 [CLOUD_ENDPOINT_CONFIRMED_ORIGIN, "confirmed-origin"],
258 [RELAY_URL_SECRET, "https://relay.example.test"],
259 [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"],
260 ] as const;
261​
262 it.effect("does not recreate a link that was unlinked while startup registration retried", () => {
263 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
264 const applyConfigCalls: Array<unknown> = [];
265 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
266​
267 return Effect.gen(function* () {
268 const link = yield* CloudLink.CloudLink;
269​
270 values.delete(CLOUD_CLI_DESIRED_LINK_SECRET);
271​
272 expect(yield* link.reconcileDesiredLinkIfStillDesired("http://127.0.0.1:3773")).toBeNull();
273 expect(requests).toEqual([]);
274 expect(applyConfigCalls).toEqual([]);
275 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
276 });
277​
278 it.effect("stops the connector, releases the relay tunnel, and drops the dead token", () => {
279 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
280 const applyConfigCalls: Array<unknown> = [];
281 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
282​
283 return Effect.gen(function* () {
284 const link = yield* CloudLink.CloudLink;
285 const released = yield* link.releaseManagedTunnelOnShutdown();
286​
287 expect(released).toBe(true);
288 expect(applyConfigCalls).toEqual([null]);
289 expect(requests).toHaveLength(1);
290 const request = requests[0]!;
291 expect(request.method).toBe("DELETE");
292 expect(request.url).toBe(
293 "https://relay.example.test/v1/client/environment-links/env_123/tunnel",
294 );
295 expect(request.headers.authorization).toBe("Bearer cli-access-token");
296 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
297 expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false);
298 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
299 });
300​
301 it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => {
302 const { store, values } = makeMemorySecretStore([
303 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
304 [RELAY_URL_SECRET, "https://relay.example.test"],
305 ]);
306 const applyConfigCalls: Array<unknown> = [];
307 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
308​
309 return Effect.gen(function* () {
310 const link = yield* CloudLink.CloudLink;
311 const released = yield* link.releaseManagedTunnelOnShutdown();
312​
313 expect(released).toBe(false);
314 expect(applyConfigCalls).toEqual([]);
315 expect(requests).toEqual([]);
316 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
317 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
318 });
319​
320 it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
321 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
322 const applyConfigCalls: Array<unknown> = [];
323 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
324​
325 return Effect.gen(function* () {
326 const link = yield* CloudLink.CloudLink;
327 yield* writeLauncherState({
328 id: "update-1",
329 fromVersion: "0.0.30",
330 targetVersion: "0.0.31",
331 dbPath: "/tmp/state.sqlite",
332 status: "pending",
333 });
334​
335 const released = yield* link.releaseManagedTunnelOnShutdown();
336​
337 expect(released).toBe(false);
338 expect(applyConfigCalls).toEqual([]);
339 expect(requests).toEqual([]);
340 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
341 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
342 });
343​
344 it.effect("still releases a pending update when the launcher is stopping", () => {
345 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
346 const applyConfigCalls: Array<unknown> = [];
347 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
348​
349 return Effect.gen(function* () {
350 const link = yield* CloudLink.CloudLink;
351 yield* writeLauncherState({
352 id: "update-1",
353 fromVersion: "0.0.30",
354 targetVersion: "0.0.31",
355 dbPath: "/tmp/state.sqlite",
356 status: "pending",
357 });
358 const fs = yield* FileSystem.FileSystem;
359 const path = yield* Path.Path;
360 const config = yield* ServerConfigModule.ServerConfig;
361 yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
362​
363 expect(yield* pendingServiceUpdateExists).toBe(true);
364 const released = yield* link.releaseManagedTunnelOnShutdown();
365​
366 expect(released).toBe(true);
367 expect(requests).toHaveLength(1);
368 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
369 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
370 });
371​
372 // regression: 808d6853555 keep the managed tunnel across remote update restarts
373 it.effect("still releases when the recorded update already settled", () => {
374 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
375 const applyConfigCalls: Array<unknown> = [];
376 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
377​
378 return Effect.gen(function* () {
379 const link = yield* CloudLink.CloudLink;
380 yield* writeLauncherState({
381 id: "update-1",
382 fromVersion: "0.0.30",
383 targetVersion: "0.0.31",
384 status: "committed",
385 });
386​
387 const released = yield* link.releaseManagedTunnelOnShutdown();
388​
389 expect(released).toBe(true);
390 expect(requests).toHaveLength(1);
391 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
392 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
393 });
394​
395 it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
396 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
397 const applyConfigCalls: Array<unknown> = [];
398 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
399 const freshConfig = new TextEncoder().encode("fresh-runtime-config");
400​
401 return Effect.gen(function* () {
402 const link = yield* CloudLink.CloudLink;
403 const released = yield* link.releaseManagedTunnelOnShutdown();
404​
405 expect(released).toBe(true);
406​
407 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
408 }).pipe(
409 provideReleaseHarness({
410 store,
411 applyConfigCalls,
412 requests,
413 respond: () => {
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 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
423 const applyConfigCalls: Array<unknown> = [];
424 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
425​
426 return Effect.gen(function* () {
427 const link = yield* CloudLink.CloudLink;
428 const released = yield* link.releaseManagedTunnelOnShutdown();
429​
430 expect(released).toBe(false);
431 expect(requests).toHaveLength(1);
432 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
433 }).pipe(
434 provideReleaseHarness({
435 store,
436 applyConfigCalls,
437 requests,
438 respond: () => Response.json({ ok: false }),
439 }),
440 );
441 });
442​
443 it.effect("registers an existing tunnel and starts the confirmed connector", () => {
444 const { store } = makeMemorySecretStore([
445 [
446 CLOUD_ENDPOINT_RUNTIME_CONFIG,
447 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
448 ],
449 [RELAY_URL_SECRET, "https://relay.example.test"],
450 [CLOUD_LINKED_USER_ID, "user-123"],
451 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
452 ]);
453 const applyConfigCalls: Array<unknown> = [];
454 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
455​
456 return Effect.gen(function* () {
457 const link = yield* CloudLink.CloudLink;
458 expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toMatchObject({
459 status: "ready",
460 });
461 expect(requests).toHaveLength(1);
462 expect(requests[0]?.method).toBe("POST");
463 expect(requests[0]?.url).toBe(
464 "https://relay.example.test/v1/environments/env_123/tunnel/recovery",
465 );
466 expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
467 const body = requests[0]?.body;
468 expect(body?._tag).toBe("Uint8Array");
469 if (body?._tag === "Uint8Array") {
470 expect(
471 yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)),
472 ).toMatchObject({
473 cloudUserId: "user-123",
474 tunnelId: "existing-tunnel",
475 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
476 });
477 }
478 expect(applyConfigCalls).toHaveLength(1);
479 }).pipe(
480 provideReleaseHarness({
481 store,
482 applyConfigCalls,
483 requests,
484 respond: () => Response.json({ status: "ready" }),
485 }),
486 );
487 });
488​
489 it.effect("registers and starts a managed tunnel at the bound IPv6 loopback address", () => {
490 const { store } = makeMemorySecretStore();
491 const config = {
492 providerKind: "cloudflare_tunnel" as const,
493 connectorToken: "existing-token",
494 tunnelId: "existing-tunnel",
495 };
496 const applyConfigCalls: Array<unknown> = [];
497 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
498​
499 return Effect.gen(function* () {
500 const link = yield* CloudLink.CloudLink;
501 expect(
502 yield* link.applyRelayConfig({
503 relayUrl: "https://relay.example.test",
504 cloudUserId: "user-123",
505 environmentCredential: "environment-credential",
506 cloudMintPublicKey:
507 "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----",
508 endpointRuntime: config,
509 }),
510 ).toMatchObject({ ok: true, endpointRuntimeStatus: { status: "running" } });
511 expect(requests).toHaveLength(1);
512 const body = requests[0]!.body;
513 if (body._tag !== "Uint8Array") throw new Error("Expected a JSON recovery request");
514 expect(
515 yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)),
516 ).toMatchObject({
517 origin: { localHttpHost: "[::1]", localHttpPort: 4884 },
518 });
519 expect(applyConfigCalls).toEqual([null, config]);
520 }).pipe(
521 provideReleaseHarness({
522 store,
523 applyConfigCalls,
524 requests,
525 address: NetAddress.inetAddressFromIpStringUnsafe("::1", 4884),
526 respond: () => Response.json({ status: "ready" }),
527 }),
528 );
529 });
530​
531 it.effect("marks a link the relay rejects as revoked without dropping or replacing it", () => {
532 const { store, values } = makeMemorySecretStore([
533 [
534 CLOUD_ENDPOINT_RUNTIME_CONFIG,
535 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
536 ],
537 [RELAY_URL_SECRET, "https://relay.example.test"],
538 [CLOUD_LINKED_USER_ID, "user-123"],
539 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
540 [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"],
541 ]);
542 const applyConfigCalls: Array<unknown> = [];
543 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
544​
545 return Effect.gen(function* () {
546 const link = yield* CloudLink.CloudLink;
547 expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toEqual({
548 status: "revoked",
549 });
550 expect((yield* link.linkState()).linkRevoked).toBe(true);
551​
552 expect(requests).toHaveLength(1);
553 expect(applyConfigCalls).toEqual([]);
554 expect(values.has(RELAY_ENVIRONMENT_CREDENTIAL_SECRET)).toBe(true);
555 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
556 }).pipe(
557 provideReleaseHarness({
558 store,
559 applyConfigCalls,
560 requests,
561 respond: () =>
562 Response.json(
563 {
564 _tag: "RelayAuthInvalidError",
565 code: "auth_invalid",
566 reason: "not_authorized",
567 traceId: "trace-revoked",
568 },
569 { status: 401 },
570 ),
571 }),
572 );
573 });
574​
575 it.effect("does not mark a link that was replaced while its rejection was in flight", () => {
576 const { store, values } = makeMemorySecretStore([
577 [
578 CLOUD_ENDPOINT_RUNTIME_CONFIG,
579 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
580 ],
581 [RELAY_URL_SECRET, "https://relay.example.test"],
582 [CLOUD_LINKED_USER_ID, "user-123"],
583 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "old-credential"],
584 ]);
585​
586 return Effect.gen(function* () {
587 const link = yield* CloudLink.CloudLink;
588 expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toEqual({
589 status: "superseded",
590 });
591 expect(values.has(CLOUD_LINK_REVOKED)).toBe(false);
592 }).pipe(
593 provideReleaseHarness({
594 store,
595 applyConfigCalls: [],
596 requests: [],
597 respond: () => {
598 values.set(
599 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
600 new TextEncoder().encode("replacement-credential"),
601 );
602 return Response.json(
603 {
604 _tag: "RelayAuthInvalidError",
605 code: "auth_invalid",
606 reason: "not_authorized",
607 traceId: "trace-stale",
608 },
609 { status: 401 },
610 );
611 },
612 }),
613 );
614 });
615​
616 it.effect("clears the revoked mark when the environment is linked again", () => {
617 const { store } = makeMemorySecretStore([
618 [RELAY_URL_SECRET, "https://relay.example.test"],
619 [CLOUD_LINKED_USER_ID, "user-123"],
620 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "revoked-credential"],
621 [CLOUD_LINK_REVOKED, "true"],
622 ]);
623 const cloudMintPublicKey =
624 "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----";
625​
626 return Effect.gen(function* () {
627 const link = yield* CloudLink.CloudLink;
628 expect((yield* link.linkState()).linkRevoked).toBe(true);
629 yield* link.applyRelayConfig({
630 relayUrl: "https://relay.example.test",
631 cloudUserId: "user-123",
632 environmentCredential: "fresh-credential",
633 cloudMintPublicKey,
634 endpointRuntime: null,
635 });
636 expect(yield* link.linkState()).toMatchObject({ linked: true, linkRevoked: false });
637 }).pipe(provideReleaseHarness({ store, applyConfigCalls: [], requests: [] }));
638 });
639​
640 it.effect(
641 "starts a connector with a marker for the current origin without contacting relay",
642 () => {
643 const configJson =
644 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}';
645 const config = {
646 providerKind: "cloudflare_tunnel" as const,
647 connectorToken: "existing-token",
648 tunnelId: "existing-tunnel",
649 };
650 const { store } = makeMemorySecretStore([
651 [CLOUD_ENDPOINT_RUNTIME_CONFIG, configJson],
652 [
653 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
654 `{"config":${configJson},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}`,
655 ],
656 ]);
657 const applyConfigCalls: Array<unknown> = [];
658 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
659​
660 return Effect.gen(function* () {
661 const link = yield* CloudLink.CloudLink;
662 expect(yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773")).toBe(true);
663 expect(applyConfigCalls).toEqual([config]);
664 expect(requests).toEqual([]);
665 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
666 },
667 );
668​
669 it.effect.each([
670 { name: "missing", marker: undefined, origin: "http://127.0.0.1:3773" },
671 {
672 name: "stale",
673 marker:
674 '{"config":{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}',
675 origin: "http://127.0.0.1:4884",
676 },
677 ])("does not start a connector with a $name origin marker", ({ marker, origin }) => {
678 const entries: Array<readonly [string, string]> = [
679 [
680 CLOUD_ENDPOINT_RUNTIME_CONFIG,
681 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
682 ],
683 ];
684 if (marker !== undefined) entries.push([CLOUD_ENDPOINT_CONFIRMED_ORIGIN, marker]);
685 const { store } = makeMemorySecretStore(entries);
686 const applyConfigCalls: Array<unknown> = [];
687 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
688​
689 return Effect.gen(function* () {
690 const link = yield* CloudLink.CloudLink;
691 expect(yield* link.startManagedTunnelIfOriginConfirmed(origin)).toBe(false);
692 expect(applyConfigCalls).toEqual([]);
693 expect(requests).toEqual([]);
694 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
695 });
696​
697 // regression: #9386 remove tunnels after hosts go offline
698 it.effect(
699 "starts the stored connector without a marker when confirmation is not required",
700 () => {
701 const config = {
702 providerKind: "cloudflare_tunnel" as const,
703 connectorToken: "existing-token",
704 tunnelId: "existing-tunnel",
705 };
706 const { store } = makeMemorySecretStore([
707 [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(config)],
708 ]);
709 const applyConfigCalls: Array<unknown> = [];
710 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
711​
712 return Effect.gen(function* () {
713 const link = yield* CloudLink.CloudLink;
714 expect(
715 yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773", {
716 requireConfirmedOrigin: false,
717 }),
718 ).toBe(true);
719 expect(applyConfigCalls).toEqual([config]);
720 expect(requests).toEqual([]);
721 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
722 },
723 );
724​
725 it.effect.each(["replaced", "removed"] as const)(
726 "does not activate a tunnel when its runtime config is %s during registration",
727 (mutation) => {
728 const originalConfig =
729 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}';
730 const { store, values } = makeMemorySecretStore([
731 [CLOUD_ENDPOINT_RUNTIME_CONFIG, originalConfig],
732 [RELAY_URL_SECRET, "https://relay.example.test"],
733 [CLOUD_LINKED_USER_ID, "user-123"],
734 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
735 ]);
736 const applyConfigCalls: Array<unknown> = [];
737 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
738​
739 return Effect.gen(function* () {
740 const link = yield* CloudLink.CloudLink;
741 expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toEqual({
742 status: "superseded",
743 });
744 expect(applyConfigCalls).toEqual([]);
745 expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false);
746 }).pipe(
747 provideReleaseHarness({
748 store,
749 applyConfigCalls,
750 requests,
751 respond: () => {
752 if (mutation === "replaced") {
753 values.set(
754 CLOUD_ENDPOINT_RUNTIME_CONFIG,
755 new TextEncoder().encode(
756 '{"providerKind":"cloudflare_tunnel","connectorToken":"fresh-token","tunnelId":"fresh-tunnel"}',
757 ),
758 );
759 } else {
760 values.delete(CLOUD_ENDPOINT_RUNTIME_CONFIG);
761 }
762 return Response.json({ status: "ready" });
763 },
764 }),
765 );
766 },
767 );
768​
769 it.effect("requests startup recovery for a legacy config without a recorded tunnel ID", () => {
770 const { store } = makeMemorySecretStore([
771 [
772 CLOUD_ENDPOINT_RUNTIME_CONFIG,
773 '{"providerKind":"cloudflare_tunnel","connectorToken":"token"}',
774 ],
775 [RELAY_URL_SECRET, "https://relay.example.test"],
776 [CLOUD_LINKED_USER_ID, "user-123"],
777 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
778 ]);
779 const applyConfigCalls: Array<unknown> = [];
780 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
781​
782 return Effect.gen(function* () {
783 const link = yield* CloudLink.CloudLink;
784 const registration = yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773");
785 expect(registration).toEqual({
786 status: "recovery_required",
787 config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
788 });
789 expect(
790 managedTunnelStartupAction({
791 wantsCliLink: false,
792 registration,
793 }),
794 ).toEqual({
795 action: "request_recovery",
796 config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
797 });
798 expect(requests).toEqual([]);
799 expect(applyConfigCalls).toEqual([]);
800 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
801 });
802​
803 it.effect("recovers a web-linked tunnel and clears its revoked mark", () => {
804 const oldConfig =
805 '{"providerKind":"cloudflare_tunnel","connectorToken":"old-token","tunnelId":"old-tunnel"}';
806 const nextConfig = {
807 providerKind: "cloudflare_tunnel",
808 connectorToken: "new-token",
809 tunnelId: "new-tunnel",
810 } as const;
811 const { store, values } = makeMemorySecretStore([
812 [CLOUD_ENDPOINT_RUNTIME_CONFIG, oldConfig],
813 [RELAY_URL_SECRET, "https://relay.example.test"],
814 [CLOUD_LINKED_USER_ID, "user-123"],
815 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
816 [CLOUD_LINK_REVOKED, "true"],
817 ]);
818 const applyConfigCalls: Array<unknown> = [];
819 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
820​
821 return Effect.gen(function* () {
822 const link = yield* CloudLink.CloudLink;
823 expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(true);
824 expect(requests).toHaveLength(1);
825 expect(requests[0]?.method).toBe("POST");
826 expect(requests[0]?.url).toBe("https://relay.example.test/v1/environments/env_123/tunnel");
827 expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
828 expect(applyConfigCalls).toEqual([nextConfig]);
829 expect(
830 Option.getOrNull(
831 decodeRuntimeConfig(new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG))),
832 ),
833 ).toEqual(nextConfig);
834 expect(values.has(CLOUD_LINK_REVOKED)).toBe(false);
835 }).pipe(
836 provideReleaseHarness({
837 store,
838 applyConfigCalls,
839 requests,
840 respond: () =>
841 Response.json({
842 endpoint: {
843 httpBaseUrl: "https://environment.example.test/",
844 wsBaseUrl: "wss://environment.example.test/ws",
845 providerKind: "cloudflare_tunnel",
846 },
847 endpointRuntime: nextConfig,
848 }),
849 }),
850 );
851 });
852​
853 it.effect("does not recover an environment without a managed tunnel credential", () => {
854 const { store } = makeMemorySecretStore([
855 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
856 [RELAY_URL_SECRET, "https://relay.example.test"],
857 ]);
858 const applyConfigCalls: Array<unknown> = [];
859 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
860​
861 return Effect.gen(function* () {
862 const link = yield* CloudLink.CloudLink;
863 expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(false);
864 expect(applyConfigCalls).toEqual([]);
865 expect(requests).toEqual([]);
866 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
867 });
868​
869 it.effect("ignores recovery requests for a tunnel that has already been replaced", () => {
870 const { store } = makeMemorySecretStore([
871 [
872 CLOUD_ENDPOINT_RUNTIME_CONFIG,
873 '{"providerKind":"cloudflare_tunnel","connectorToken":"current-token","tunnelId":"current-tunnel"}',
874 ],
875 [RELAY_URL_SECRET, "https://relay.example.test"],
876 [CLOUD_LINKED_USER_ID, "user-123"],
877 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
878 ]);
879 const applyConfigCalls: Array<unknown> = [];
880 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
881​
882 return Effect.gen(function* () {
883 const link = yield* CloudLink.CloudLink;
884 expect(
885 yield* link.recoverManagedTunnel("http://127.0.0.1:3773", {
886 providerKind: "cloudflare_tunnel",
887 connectorToken: "old-token",
888 tunnelId: "old-tunnel",
889 }),
890 ).toBe(false);
891 expect(requests).toEqual([]);
892 expect(applyConfigCalls).toEqual([]);
893 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
894 });
895​
896 it.effect.each([
897 {
898 status: 401,
899 body: {
900 _tag: "RelayAuthInvalidError",
901 code: "auth_invalid",
902 reason: "invalid_bearer",
903 traceId: "trace-revoked",
904 },
905 rejection: "unauthorized",
906 },
907 { status: 403, body: {}, rejection: "forbidden" },
908 { status: 409, body: {}, rejection: "rejected" },
909 ])("preserves a permanent $status relay recovery failure", ({ status, body, rejection }) => {
910 const { store } = makeMemorySecretStore([
911 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
912 [RELAY_URL_SECRET, "https://relay.example.test"],
913 [CLOUD_LINKED_USER_ID, "user-123"],
914 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
915 ]);
916 const applyConfigCalls: Array<unknown> = [];
917 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
918​
919 return Effect.gen(function* () {
920 const link = yield* CloudLink.CloudLink;
921 const error = yield* Effect.flip(link.recoverManagedTunnel("http://127.0.0.1:3773"));
922​
923 expect(error).toMatchObject({ _tag: "RelayRequestError", rejection });
924 expect(CloudLink.shouldRetryCloudLink(error)).toBe(false);
925 expect(requests).toHaveLength(1);
926 expect(applyConfigCalls).toEqual([]);
927 }).pipe(
928 provideReleaseHarness({
929 store,
930 applyConfigCalls,
931 requests,
932 respond: () => Response.json(body, { status }),
933 }),
934 );
935 });
936​
937 it.effect("retries a relay link proof rejected as expired", () => {
938 const { store } = makeMemorySecretStore([
939 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
940 [RELAY_URL_SECRET, "https://relay.example.test"],
941 [CLOUD_LINKED_USER_ID, "user-123"],
942 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
943 ]);
944 const applyConfigCalls: Array<unknown> = [];
945 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
946​
947 return Effect.gen(function* () {
948 const link = yield* CloudLink.CloudLink;
949 const error = yield* Effect.flip(link.recoverManagedTunnel("http://127.0.0.1:3773"));
950​
951 expect(error).toMatchObject({ _tag: "RelayRequestError", rejection: "unavailable" });
952 expect(error.message).toContain("Trace ID: trace-expired");
953 expect(CloudLink.shouldRetryCloudLink(error)).toBe(true);
954 }).pipe(
955 provideReleaseHarness({
956 store,
957 applyConfigCalls,
958 requests,
959 respond: () =>
960 Response.json(
961 {
962 _tag: "RelayEnvironmentLinkProofExpiredError",
963 code: "environment_link_proof_expired",
964 traceId: "trace-expired",
965 },
966 { status: 401 },
967 ),
968 }),
969 );
970 });
971​
972 it.effect("keeps a tunnel configuration replaced during recovery", () => {
973 const { store, values } = makeMemorySecretStore([
974 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
975 [RELAY_URL_SECRET, "https://relay.example.test"],
976 [CLOUD_LINKED_USER_ID, "user-123"],
977 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
978 ]);
979 const applyConfigCalls: Array<unknown> = [];
980 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
981 const freshConfig = new TextEncoder().encode("fresh-config");
982​
983 return Effect.gen(function* () {
984 const link = yield* CloudLink.CloudLink;
985 expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(false);
986 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
987 expect(applyConfigCalls).toEqual([]);
988 }).pipe(
989 provideReleaseHarness({
990 store,
991 applyConfigCalls,
992 requests,
993 respond: () => {
994 values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);
995 return Response.json({
996 endpoint: {
997 httpBaseUrl: "https://environment.example.test/",
998 wsBaseUrl: "wss://environment.example.test/ws",
999 providerKind: "cloudflare_tunnel",
1000 },
1001 endpointRuntime: {
1002 providerKind: "cloudflare_tunnel",
1003 connectorToken: "replacement-token",
1004 },
1005 });
1006 },
1007 }),
1008 );
1009 });
1010​
1011 it.effect("does not report a managed tunnel after a relay config write fails part-way", () => {
1012 const { store, values } = makeMemorySecretStore([
1013 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "managed-config"],
1014 [CLOUD_ENDPOINT_CONFIRMED_ORIGIN, "confirmed-origin"],
1015 [RELAY_URL_SECRET, "https://relay.example.test"],
1016 [CLOUD_LINKED_USER_ID, "user-123"],
1017 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "old-credential"],
1018 ]);
1019 const failingStore: ServerSecretStore.ServerSecretStore["Service"] = {
1020 ...store,
1021 set: (name, value) =>
1022 name === RELAY_ISSUER_SECRET
1023 ? Effect.fail(
1024 new ServerSecretStore.SecretStorePersistError({
1025 resource: name,
1026 cause: PlatformError.systemError({
1027 _tag: "PermissionDenied",
1028 module: "FileSystem",
1029 method: "rename",
1030 pathOrDescriptor: `${name}.bin`,
1031 }),
1032 }),
1034 : store.set(name, value),
1035 };
1036 const applyConfigCalls: Array<unknown> = [];
1037 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1038 const cloudMintPublicKey =
1039 "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAMY09Vo5CzEA6aEkhB/0h27t4Qs71SHS1fTSI4K0KvZQ=\n-----END PUBLIC KEY-----\n";
1040​
1041 return Effect.gen(function* () {
1042 const link = yield* CloudLink.CloudLink;
1043 const error = yield* Effect.flip(
1044 link.applyRelayConfig({
1045 relayUrl: "https://relay.example.test",
1046 cloudUserId: "user-123",
1047 environmentCredential: "new-credential",
1048 cloudMintPublicKey,
1049 endpointRuntime: null,
1050 }),
1051 );
1052​
1053 expect(error._tag).toBe("CloudLinkInternalError");
1054 expect(yield* link.linkState()).toMatchObject({
1055 linked: true,
1056 cloudUserId: "user-123",
1057 managedTunnelActive: false,
1058 });
1059 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
1060 }).pipe(provideReleaseHarness({ store: failingStore, applyConfigCalls, requests }));
1061 });
1062​
1063 it.effect("does not report a not-linked check once the managed tunnel config is stored", () => {
1064 const { store } = makeMemorySecretStore(managedLinkSecrets);
1065 const notLinked = ConnectReachability.classifyReachability(
1067 managedTunnelConfigured: false,
1068 connector: null,
1069 endpoint: null,
1070 edgeReachable: null,
1071 exitNode: null,
1072 },
1073 "2026-10-29T00:00:00.000Z",
1074 );
1075​
1076 return Effect.gen(function* () {
1077 const state = yield* (yield* CloudLink.CloudLink).linkState();
1078​
1079 expect(state.managedTunnelActive).toBe(true);
1080 expect(state.reachability?.status === "unreachable" && state.reachability.cause).not.toBe(
1081 "not_linked",
1082 );
1083 // The address shows before any check passes.
1084 expect(state.tunnelHostname).toBe("prod-abc.t3coderelay.com");
1085 }).pipe(
1086 provideReleaseHarness({
1087 store,
1088 applyConfigCalls: [],
1089 requests: [],
1090 latestReachability: Effect.succeedSome(notLinked),
1091 connector: {
1092 pid: 123,
1093 readyConnections: 0,
1094 hostname: "prod-abc.t3coderelay.com",
1095 protocol: null,
1096 },
1097 }),
1098 );
1099 });
1100​
1101 it.effect("reports a check that ran after the managed tunnel config was stored", () => {
1102 const { store } = makeMemorySecretStore(managedLinkSecrets);
1103 const reachable = {
1104 status: "reachable" as const,
1105 checkedAt: "2026-10-29T00:00:00.000Z",
1106 readyConnections: 4,
1107 protocol: "quic",
1108 };
1109​
1110 return Effect.gen(function* () {
1111 const state = yield* (yield* CloudLink.CloudLink).linkState();
1112​
1113 expect(state.reachability).toEqual(reachable);
1114 }).pipe(
1115 provideReleaseHarness({
1116 store,
1117 applyConfigCalls: [],
1118 requests: [],
1119 latestReachability: Effect.succeedSome(reachable),
1120 }),
1121 );
1122 });
1123});