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