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