Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CloudLink.lifecycle.test.ts

1,051 lines39.7 KB

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