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