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