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