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

CloudLink.lifecycle.test.ts

1,384 lines52.5 KB

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