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