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

CloudLink.lifecycle.test.ts

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