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

CloudLink.lifecycle.test.ts

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