Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as PlatformError from "effect/PlatformError";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14import * as Tracer from "effect/Tracer";
15import * as Stream from "effect/Stream";
16import {
17 HttpClient,
18 HttpClientResponse,
19 HttpServerRequest,
20 type HttpClientRequest,
21} from "effect/unstable/http";
22
23import { DESKTOP_UPDATE_RESTART_MARKER_FILE, EnvironmentId } from "@t3tools/contracts";
24import { RelayClientTracer } from "@t3tools/shared/relayTracing";
25import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
26import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
27import * as ServerConfigModule from "../config.ts";
28import { writeServiceState } from "../serviceLauncher.ts";
29import {
30 SERVICE_LAUNCHER_PROTOCOL,
31 SERVICE_STATE_FILE,
32 SERVICE_STOP_MARKER_FILE,
33 type ServiceUpdateRecord,
34} from "./serviceProtocol.ts";
35import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
36import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
37import * as CliTokenManager from "./CliTokenManager.ts";
38import {
39 RelayManagedEndpointRecoveryRegistrationRequest,
40 type RelayLinkProofRequest,
41} from "@t3tools/contracts/relay";
42import {
43 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
44 CLOUD_ENDPOINT_RUNTIME_CONFIG,
45 CLOUD_LINKED_USER_ID,
46 decodeConfirmedOrigin,
47 decodeRuntimeConfig,
48 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
49 RELAY_URL_SECRET,
50} from "./config.ts";
51import {
52 consumeCloudReplayGuards,
53 isSupportedLinkProviderKind,
54 linkProofScopes,
55 pendingServiceUpdateExists,
56 parseManagedEndpointLocalOrigin,
57 reconcileDesiredCloudLink,
58 reconcileDesiredCloudLinkIfStillDesired,
59 recoverManagedCloudTunnel,
60 registerManagedCloudTunnelRecovery,
61 releaseManagedTunnelOnShutdown,
62 startManagedCloudTunnelIfOriginConfirmed,
63} from "./http.ts";
64import {
65 managedTunnelStartupAction,
66 retryManagedTunnelRegistration,
67} from "./managedTunnelStartup.ts";
68import { shouldRetryCloudLink } from "./relayResponse.ts";
69import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
70import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
71
72const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
73 new ServerSecretStore.SecretStorePersistError({
74 resource: "cloud replay guard",
75 cause: PlatformError.systemError({
76 _tag: tag,
77 module: "FileSystem",
78 method: "open",
79 pathOrDescriptor: "cloud-replay-guard.bin",
80 }),
81 });
82
83const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
84const decodeManagedTunnelRecoveryRegistration = Schema.decodeUnknownEffect(
85 Schema.fromJsonString(RelayManagedEndpointRecoveryRegistrationRequest),
86);
87
88function makeSecretStore(
89 create: ServerSecretStore.ServerSecretStore["Service"]["create"],
90): ServerSecretStore.ServerSecretStore["Service"] {
91 return {
92 get: unusedSecretStoreOperation,
93 set: unusedSecretStoreOperation,
94 create,
95 getOrCreateRandom: unusedSecretStoreOperation,
96 remove: unusedSecretStoreOperation,
97 };
98}
99
100it("preserves messages surfaced by cloud 500 responses", () => {
101 const cause = new Error("cloud operation failed");
102
103 expect([
104 new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ cause }).message,
105 new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ cause }).message,
106 new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({}).message,
107 new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ cause }).message,
108 new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}).message,
109 new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}).message,
110 new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ cause }).message,
111 new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ cause }).message,
112 ]).toEqual([
113 "Could not verify the linked cloud account.",
114 "Could not read the linked cloud account.",
115 "Cloud linked user is not installed for this environment.",
116 "Failed to sign cloud link JWT.",
117 "Cloud mint public key is not installed for this environment.",
118 "Cloud relay issuer is not installed for this environment.",
119 "Failed to sign cloud health JWT.",
120 "Failed to sign cloud mint JWT.",
121 ]);
122});
123
124describe("consumeCloudReplayGuards", () => {
125 it.effect("reports already-created guards as replay conflicts", () =>
126 Effect.gen(function* () {
127 const consumed = yield* consumeCloudReplayGuards({
128 secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),
129 names: ["cloud-jti", "cloud-nonce"],
130 value: new Uint8Array(),
131 });
132
133 expect(consumed).toBe(false);
134 }),
135 );
136
137 it.effect("preserves replay-store availability failures", () =>
138 Effect.gen(function* () {
139 const failure = storeFailure("PermissionDenied");
140 const error = yield* Effect.flip(
141 consumeCloudReplayGuards({
142 secrets: makeSecretStore(() => Effect.fail(failure)),
143 names: ["cloud-jti", "cloud-nonce"],
144 value: new Uint8Array(),
145 }),
146 );
147
148 expect(error).toBe(failure);
149 }),
150 );
151});
152
153describe("relay request tracing", () => {
154 it.effect("does not accept an unauthenticated request trace parent", () =>
155 Effect.gen(function* () {
156 const spans: Array<Tracer.Span> = [];
157 const productTracer = Tracer.make({
158 span: (options) => {
159 const span = new Tracer.NativeSpan(options);
160 spans.push(span);
161 return span;
162 },
163 });
164 const request = HttpServerRequest.fromWeb(
165 new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
166 headers: {
167 traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
168 },
169 }),
170 );
171
172 yield* traceRelayRequest(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
173 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
174 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
175 );
176
177 expect(spans).toHaveLength(1);
178 const span = spans[0]!;
179 expect(span.traceId).not.toBe("0123456789abcdef0123456789abcdef");
180 expect(Option.isNone(span.parent)).toBe(true);
181 }),
182 );
183
184 it.effect("continues an authenticated relay trace with the product tracer", () =>
185 Effect.gen(function* () {
186 const spans: Array<Tracer.Span> = [];
187 const productTracer = Tracer.make({
188 span: (options) => {
189 const span = new Tracer.NativeSpan(options);
190 spans.push(span);
191 return span;
192 },
193 });
194 const request = HttpServerRequest.fromWeb(
195 new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
196 headers: {
197 traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
198 },
199 }),
200 );
201
202 yield* traceAuthenticatedRelayRequest(
203 Effect.void.pipe(Effect.withSpan("relay.mint.handler")),
204 ).pipe(
205 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
206 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
207 );
208
209 expect(spans).toHaveLength(1);
210 const span = spans[0]!;
211 expect(span.traceId).toBe("0123456789abcdef0123456789abcdef");
212 expect(Option.getOrUndefined(span.parent)?.spanId).toBe("0123456789abcdef");
213 }),
214 );
215});
216
217describe("reconcileDesiredCloudLink", () => {
218 it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
219 Effect.gen(function* () {
220 const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
221
222 expect(error).toMatchObject({
223 _tag: "EnvironmentHttpUnauthorizedError",
224 message: "Run `t3 connect link` to authorize this environment.",
225 });
226 }).pipe(
227 Effect.provideService(
228 ServerSecretStore.ServerSecretStore,
229 makeSecretStore(unusedSecretStoreOperation),
230 ),
231 Effect.provideService(
232 ServerEnvironment.ServerEnvironment,
233 ServerEnvironment.ServerEnvironment.of({
234 getEnvironmentId: unusedSecretStoreOperation(),
235 getDescriptor: unusedSecretStoreOperation(),
236 }),
237 ),
238 Effect.provideService(
239 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
240 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
241 applyConfig: unusedSecretStoreOperation,
242 recoveryRequests: Stream.empty,
243 requestRecovery: () => Effect.void,
244 withLinkStateLock: (effect) => effect,
245 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
246 ),
247 Effect.provideService(
248 EnvironmentAuth.EnvironmentAuth,
249 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
250 ),
251 Effect.provideService(
252 CliTokenManager.CloudCliTokenManager,
253 CliTokenManager.CloudCliTokenManager.of({
254 get: unusedSecretStoreOperation(),
255 getExisting: Effect.succeedNone,
256 hasCredential: unusedSecretStoreOperation(),
257 store: () => unusedSecretStoreOperation(),
258 clear: unusedSecretStoreOperation(),
259 }),
260 ),
261 Effect.provideService(
262 HttpClient.HttpClient,
263 HttpClient.make(() => unusedSecretStoreOperation()),
264 ),
265 Effect.provide(NodeServices.layer),
266 ),
267 );
268});
269
270describe("parseManagedEndpointLocalOrigin", () => {
271 it.each([
272 {
273 input: "http://127.0.0.1:80",
274 httpBaseUrl: "http://127.0.0.1",
275 wsBaseUrl: "ws://127.0.0.1",
276 port: 80,
277 },
278 {
279 input: "https://127.0.0.1:443",
280 httpBaseUrl: "https://127.0.0.1",
281 wsBaseUrl: "wss://127.0.0.1",
282 port: 443,
283 },
284 ])("accepts an explicit default port in $input", ({ input, httpBaseUrl, wsBaseUrl, port }) => {
285 expect(parseManagedEndpointLocalOrigin(input)).toEqual({
286 httpBaseUrl,
287 wsBaseUrl,
288 origin: { localHttpHost: "127.0.0.1", localHttpPort: port },
289 });
290 });
291
292 it.each([
293 "ftp://127.0.0.1:3773",
294 "http://user:password@127.0.0.1:3773",
295 "http://127.0.0.1:3773/api",
296 "http://127.0.0.1:3773?mode=test",
297 "http://127.0.0.1:3773#fragment",
298 ])("rejects non-origin URL %s", (input) => {
299 expect(() => parseManagedEndpointLocalOrigin(input)).toThrow("Invalid local origin");
300 });
301});
302
303describe("releaseManagedTunnelOnShutdown", () => {
304 const cliToken: CliTokenManager.PersistedToken = {
305 accessToken: "cli-access-token",
306 refreshToken: "cli-refresh-token",
307 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
308 };
309
310 function makeMemorySecretStore(initial: Iterable<readonly [string, string]> = []) {
311 const values = new Map<string, Uint8Array>(
312 Array.from(initial, ([name, value]) => [name, new TextEncoder().encode(value)] as const),
313 );
314 const store: ServerSecretStore.ServerSecretStore["Service"] = {
315 get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
316 set: (name, value) =>
317 Effect.sync(() => {
318 values.set(name, value);
319 }),
320 create: (name, value) =>
321 Effect.sync(() => {
322 values.set(name, value);
323 }),
324 getOrCreateRandom: unusedSecretStoreOperation,
325 remove: (name) =>
326 Effect.sync(() => {
327 values.delete(name);
328 }),
329 };
330 return { store, values };
331 }
332
333 interface ReleaseHarness {
334 readonly store: ServerSecretStore.ServerSecretStore["Service"];
335 readonly applyConfigCalls: Array<unknown>;
336 readonly requests: Array<HttpClientRequest.HttpClientRequest>;
337 readonly onRequest?: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<void>;
338 readonly respond?: () => Response;
339 readonly respondEffect?: Effect.Effect<Response>;
340 }
341
342 // Writes the launcher's durable state file into this test's baseDir with
343 // the launcher's own writer; the release reads it to detect an in-flight
344 // update handoff.
345 const writeLauncherState = (update: ServiceUpdateRecord) =>
346 Effect.gen(function* () {
347 const path = yield* Path.Path;
348 const config = yield* ServerConfigModule.ServerConfig;
349 const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
350 yield* Effect.promise(() =>
351 writeServiceState(statePath, {
352 protocol: SERVICE_LAUNCHER_PROTOCOL,
353 activeVersion: "0.0.30",
354 update,
355 }),
356 );
357 });
358
359 // Writes the marker the desktop app leaves just before it stops its backend
360 // to install an update, and returns when it was written.
361 const writeDesktopUpdateRestartMarker = Effect.gen(function* () {
362 const fs = yield* FileSystem.FileSystem;
363 const path = yield* Path.Path;
364 const config = yield* ServerConfigModule.ServerConfig;
365 const runtimeDir = path.join(config.baseDir, "runtime");
366 const markerPath = path.join(runtimeDir, DESKTOP_UPDATE_RESTART_MARKER_FILE);
367 yield* fs.makeDirectory(runtimeDir, { recursive: true });
368 yield* fs.writeFileString(markerPath, "");
369 const { mtime } = yield* fs.stat(markerPath);
370 return Option.getOrThrow(mtime).getTime();
371 });
372
373 const provideReleaseHarness =
374 (harness: ReleaseHarness) =>
375 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
376 effect.pipe(
377 Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),
378 Effect.provideService(
379 ServerEnvironment.ServerEnvironment,
380 ServerEnvironment.ServerEnvironment.of({
381 getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
382 getDescriptor: Effect.die("unused"),
383 }),
384 ),
385 Effect.provideService(
386 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
387 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
388 applyConfig: (config) =>
389 Effect.sync(() => {
390 harness.applyConfigCalls.push(config);
391 return config === null
392 ? ({
393 status: "disabled",
394 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus)
395 : ({
396 status: "running",
397 providerKind: "cloudflare_tunnel",
398 pid: 123,
399 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus);
400 }),
401 recoveryRequests: Stream.empty,
402 requestRecovery: () => Effect.void,
403 withLinkStateLock: (effect) => effect,
404 }),
405 ),
406 Effect.provideService(
407 EnvironmentAuth.EnvironmentAuth,
408 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
409 ),
410 Effect.provideService(
411 CliTokenManager.CloudCliTokenManager,
412 CliTokenManager.CloudCliTokenManager.of({
413 get: unusedSecretStoreOperation(),
414 getExisting: Effect.succeedSome(cliToken),
415 hasCredential: unusedSecretStoreOperation(),
416 store: () => unusedSecretStoreOperation(),
417 clear: unusedSecretStoreOperation(),
418 }),
419 ),
420 Effect.provideService(
421 HttpClient.HttpClient,
422 HttpClient.make((request) =>
423 Effect.sync(() => {
424 harness.requests.push(request);
425 }).pipe(
426 Effect.andThen(harness.onRequest?.(request) ?? Effect.void),
427 Effect.andThen(
428 harness.respondEffect ??
429 Effect.sync(() => (harness.respond ?? (() => Response.json({ ok: true })))()),
430 ),
431 Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
432 ),
433 ),
434 ),
435 // The release consults the launcher state file under the configured
436 // baseDir, so every harness run gets a scoped temp baseDir.
437 Effect.provide(
438 ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
439 Layer.provideMerge(NodeServices.layer),
440 ),
441 ),
442 Effect.scoped,
443 );
444
445 // The persisted state of a CLI-managed link whose tunnel is releasable.
446 const managedLinkSecrets = [
447 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
448 [CLOUD_ENDPOINT_CONFIRMED_ORIGIN, "confirmed-origin"],
449 [RELAY_URL_SECRET, "https://relay.example.test"],
450 [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"],
451 ] as const;
452
453 it.effect("does not recreate a link that was unlinked while startup registration retried", () => {
454 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
455 const applyConfigCalls: Array<unknown> = [];
456 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
457
458 return Effect.gen(function* () {
459 // Registration started while this marker existed. Unlink removes it
460 // before startup receives the relay's final not_linked response.
461 values.delete(CLOUD_CLI_DESIRED_LINK_SECRET);
462
463 expect(yield* reconcileDesiredCloudLinkIfStillDesired("http://127.0.0.1:3773")).toBeNull();
464 expect(requests).toEqual([]);
465 expect(applyConfigCalls).toEqual([]);
466 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
467 });
468
469 it.effect("stops the connector, releases the relay tunnel, and drops the dead token", () => {
470 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
471 const applyConfigCalls: Array<unknown> = [];
472 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
473
474 return Effect.gen(function* () {
475 const released = yield* releaseManagedTunnelOnShutdown();
476
477 expect(released).toBe(true);
478 expect(applyConfigCalls).toEqual([null]);
479 expect(requests).toHaveLength(1);
480 const request = requests[0]!;
481 expect(request.method).toBe("DELETE");
482 expect(request.url).toBe(
483 "https://relay.example.test/v1/client/environment-links/env_123/tunnel",
484 );
485 expect(request.headers.authorization).toBe("Bearer cli-access-token");
486 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
487 expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false);
488 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
489 });
490
491 it.effect("does nothing for links without a stored managed tunnel runtime config", () => {
492 const { store } = makeMemorySecretStore();
493 const applyConfigCalls: Array<unknown> = [];
494 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
495
496 return Effect.gen(function* () {
497 const released = yield* releaseManagedTunnelOnShutdown();
498
499 expect(released).toBe(false);
500 expect(applyConfigCalls).toEqual([]);
501 expect(requests).toEqual([]);
502 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
503 });
504
505 it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => {
506 // A managed runtime config without a CLI-desired link: the environment was
507 // linked by a web/mobile client, and nothing re-provisions the tunnel on
508 // the next boot, so shutdown must not release it.
509 const { store, values } = makeMemorySecretStore([
510 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
511 [RELAY_URL_SECRET, "https://relay.example.test"],
512 ]);
513 const applyConfigCalls: Array<unknown> = [];
514 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
515
516 return Effect.gen(function* () {
517 const released = yield* releaseManagedTunnelOnShutdown();
518
519 expect(released).toBe(false);
520 expect(applyConfigCalls).toEqual([]);
521 expect(requests).toEqual([]);
522 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
523 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
524 });
525
526 it.effect("leaves the tunnel of a publish-only desired link untouched", () => {
527 const { store, values } = makeMemorySecretStore([
528 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
529 [RELAY_URL_SECRET, "https://relay.example.test"],
530 [CLOUD_CLI_DESIRED_LINK_SECRET, "publish_only"],
531 ]);
532 const applyConfigCalls: Array<unknown> = [];
533 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
534
535 return Effect.gen(function* () {
536 const released = yield* releaseManagedTunnelOnShutdown();
537
538 expect(released).toBe(false);
539 expect(applyConfigCalls).toEqual([]);
540 expect(requests).toEqual([]);
541 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
542 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
543 });
544
545 it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
546 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
547 const applyConfigCalls: Array<unknown> = [];
548 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
549
550 return Effect.gen(function* () {
551 yield* writeLauncherState({
552 id: "update-1",
553 fromVersion: "0.0.30",
554 targetVersion: "0.0.31",
555 dbPath: "/tmp/state.sqlite",
556 status: "pending",
557 });
558
559 const released = yield* releaseManagedTunnelOnShutdown();
560
561 // The launcher restarts a server immediately, so the tunnel is not
562 // orphaned; keeping it avoids the hostname route re-propagation that
563 // dominates update downtime. The stored config must survive so the
564 // next boot respawns the connector against the same tunnel.
565 expect(released).toBe(false);
566 expect(applyConfigCalls).toEqual([]);
567 expect(requests).toEqual([]);
568 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
569 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
570 });
571
572 it.effect("keeps the tunnel once when the desktop app restarts it for an update", () => {
573 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
574 const applyConfigCalls: Array<unknown> = [];
575 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
576
577 return Effect.gen(function* () {
578 yield* TestClock.setTime(yield* writeDesktopUpdateRestartMarker);
579
580 expect(yield* releaseManagedTunnelOnShutdown()).toBe(false);
581 expect(requests).toEqual([]);
582 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
583
584 // The shutdown consumed the marker, so a later quit releases the tunnel.
585 expect(yield* releaseManagedTunnelOnShutdown()).toBe(true);
586 expect(requests).toHaveLength(1);
587 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
588 });
589
590 it.effect("releases the tunnel when the desktop update marker is stale", () => {
591 const { store } = makeMemorySecretStore(managedLinkSecrets);
592 const applyConfigCalls: Array<unknown> = [];
593 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
594
595 return Effect.gen(function* () {
596 const writtenAt = yield* writeDesktopUpdateRestartMarker;
597 yield* TestClock.setTime(writtenAt + Duration.toMillis(Duration.minutes(2)));
598
599 expect(yield* releaseManagedTunnelOnShutdown()).toBe(true);
600 expect(requests).toHaveLength(1);
601 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
602 });
603
604 it.effect("still releases a pending update when the launcher is stopping", () => {
605 // `t3 service uninstall` or `systemctl stop` during the pending window:
606 // the launcher writes its stop marker before signalling the child, so no
607 // replacement server is coming and the tunnel must not be kept.
608 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
609 const applyConfigCalls: Array<unknown> = [];
610 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
611
612 return Effect.gen(function* () {
613 yield* writeLauncherState({
614 id: "update-1",
615 fromVersion: "0.0.30",
616 targetVersion: "0.0.31",
617 dbPath: "/tmp/state.sqlite",
618 status: "pending",
619 });
620 const fs = yield* FileSystem.FileSystem;
621 const path = yield* Path.Path;
622 const config = yield* ServerConfigModule.ServerConfig;
623 yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
624
625 expect(yield* pendingServiceUpdateExists).toBe(true);
626 const released = yield* releaseManagedTunnelOnShutdown();
627
628 expect(released).toBe(true);
629 expect(requests).toHaveLength(1);
630 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
631 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
632 });
633
634 it.effect("still releases when the recorded update already settled", () => {
635 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
636 const applyConfigCalls: Array<unknown> = [];
637 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
638
639 return Effect.gen(function* () {
640 yield* writeLauncherState({
641 id: "update-1",
642 fromVersion: "0.0.30",
643 targetVersion: "0.0.31",
644 status: "committed",
645 });
646
647 const released = yield* releaseManagedTunnelOnShutdown();
648
649 expect(released).toBe(true);
650 expect(requests).toHaveLength(1);
651 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
652 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
653 });
654
655 it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
656 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
657 const applyConfigCalls: Array<unknown> = [];
658 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
659 const freshConfig = new TextEncoder().encode("fresh-runtime-config");
660
661 return Effect.gen(function* () {
662 const released = yield* releaseManagedTunnelOnShutdown();
663
664 expect(released).toBe(true);
665 // The finalizer only drops the config it released; the one written by
666 // the restarted process while the DELETE was in flight stays.
667 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
668 }).pipe(
669 provideReleaseHarness({
670 store,
671 applyConfigCalls,
672 requests,
673 respond: () => {
674 // A restarted process reconciled and stored a fresh connector config
675 // while this shutdown's release request was in flight.
676 values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);
677 return Response.json({ ok: true });
678 },
679 }),
680 );
681 });
682
683 it.effect("keeps the stored connector token when the relay skipped the release", () => {
684 // ok:false means a concurrent provision owns the recorded tunnel, so the
685 // stored runtime config (possibly freshly written by that provision) must
686 // survive.
687 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
688 const applyConfigCalls: Array<unknown> = [];
689 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
690
691 return Effect.gen(function* () {
692 const released = yield* releaseManagedTunnelOnShutdown();
693
694 expect(released).toBe(false);
695 expect(requests).toHaveLength(1);
696 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
697 }).pipe(
698 provideReleaseHarness({
699 store,
700 applyConfigCalls,
701 requests,
702 respond: () => Response.json({ ok: false }),
703 }),
704 );
705 });
706
707 it.effect("keeps the stored connector token when the relay release request fails", () => {
708 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
709 const applyConfigCalls: Array<unknown> = [];
710 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
711
712 return Effect.gen(function* () {
713 const result = yield* Effect.result(releaseManagedTunnelOnShutdown());
714
715 expect(result._tag).toBe("Failure");
716 expect(requests).toHaveLength(1);
717 // The tunnel still exists, so the stored token stays valid across the
718 // restart and the next boot can bring the connector back immediately.
719 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
720 }).pipe(
721 provideReleaseHarness({
722 store,
723 applyConfigCalls,
724 requests,
725 respond: () => Response.json({ ok: false }, { status: 503 }),
726 }),
727 );
728 });
729
730 it.effect("registers an existing tunnel and starts the confirmed connector", () => {
731 const { store } = makeMemorySecretStore([
732 [
733 CLOUD_ENDPOINT_RUNTIME_CONFIG,
734 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
735 ],
736 [RELAY_URL_SECRET, "https://relay.example.test"],
737 [CLOUD_LINKED_USER_ID, "user-123"],
738 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
739 ]);
740 const applyConfigCalls: Array<unknown> = [];
741 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
742
743 return Effect.gen(function* () {
744 expect(yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773")).toMatchObject({
745 status: "ready",
746 });
747 expect(requests).toHaveLength(1);
748 expect(requests[0]?.method).toBe("POST");
749 expect(requests[0]?.url).toBe(
750 "https://relay.example.test/v1/environments/env_123/tunnel/recovery",
751 );
752 expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
753 const body = requests[0]?.body;
754 expect(body?._tag).toBe("Uint8Array");
755 if (body?._tag === "Uint8Array") {
756 expect(
757 yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)),
758 ).toMatchObject({
759 cloudUserId: "user-123",
760 tunnelId: "existing-tunnel",
761 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
762 });
763 }
764 expect(applyConfigCalls).toHaveLength(1);
765 }).pipe(
766 provideReleaseHarness({
767 store,
768 applyConfigCalls,
769 requests,
770 respond: () => Response.json({ status: "ready" }),
771 }),
772 );
773 });
774
775 it.effect("reconciles a changed port after a relay outage outlasts the startup fallback", () => {
776 const config = {
777 providerKind: "cloudflare_tunnel" as const,
778 connectorToken: "existing-token",
779 tunnelId: "existing-tunnel",
780 };
781 const { store } = makeMemorySecretStore([
782 [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(config)],
783 [
784 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
785 JSON.stringify({
786 config,
787 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
788 }),
789 ],
790 [RELAY_URL_SECRET, "https://relay.example.test"],
791 [CLOUD_LINKED_USER_ID, "user-123"],
792 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
793 ]);
794 const applyConfigCalls: Array<unknown> = [];
795 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
796 let relayAvailable = false;
797 const localOrigin = "http://127.0.0.1:4884";
798
799 return Effect.gen(function* () {
800 const fallbackStarted = yield* Deferred.make<void>();
801 const firstFailure = yield* Deferred.make<void>();
802 expect(yield* startManagedCloudTunnelIfOriginConfirmed(localOrigin)).toBe(false);
803 const registration = yield* Effect.forkChild(
804 retryManagedTunnelRegistration(
805 registerManagedCloudTunnelRecovery(localOrigin).pipe(
806 Effect.tapError(() => Deferred.succeed(firstFailure, undefined)),
807 ),
808 shouldRetryCloudLink,
809 startManagedCloudTunnelIfOriginConfirmed(localOrigin, {
810 requireConfirmedOrigin: false,
811 }).pipe(
812 Effect.orDie,
813 Effect.tap((started) => {
814 expect(started).toBe(true);
815 return Deferred.succeed(fallbackStarted, undefined);
816 }),
817 Effect.asVoid,
818 ),
819 ),
820 { startImmediately: true },
821 );
822 yield* Deferred.await(firstFailure);
823 yield* TestClock.adjust("15 minutes");
824 yield* Effect.raceFirst(
825 Deferred.await(fallbackStarted),
826 Fiber.join(registration).pipe(
827 Effect.andThen(Effect.die("Registration ended before starting the fallback")),
828 ),
829 );
830 expect(applyConfigCalls).toEqual([config]);
831 const attemptsBeforeRecovery = requests.length;
832
833 relayAvailable = true;
834 yield* TestClock.adjust("1 minute");
835 expect(yield* Fiber.join(registration)).toMatchObject({ status: "ready" });
836 expect(requests.length).toBeGreaterThan(attemptsBeforeRecovery);
837 const marker = yield* store.get(CLOUD_ENDPOINT_CONFIRMED_ORIGIN);
838 expect(Option.isSome(marker)).toBe(true);
839 if (Option.isSome(marker)) {
840 expect(
841 Option.getOrThrow(decodeConfirmedOrigin(new TextDecoder().decode(marker.value))),
842 ).toEqual({
843 config,
844 origin: { localHttpHost: "127.0.0.1", localHttpPort: 4884 },
845 });
846 }
847 }).pipe(
848 provideReleaseHarness({
849 store,
850 applyConfigCalls,
851 requests,
852 respond: () =>
853 relayAvailable
854 ? Response.json({ status: "ready" })
855 : Response.json({ message: "relay unavailable" }, { status: 503 }),
856 }),
857 );
858 });
859
860 it.effect(
861 "starts a connector with a marker for the current origin without contacting relay",
862 () => {
863 const configJson =
864 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}';
865 const config = {
866 providerKind: "cloudflare_tunnel" as const,
867 connectorToken: "existing-token",
868 tunnelId: "existing-tunnel",
869 };
870 const { store } = makeMemorySecretStore([
871 [CLOUD_ENDPOINT_RUNTIME_CONFIG, configJson],
872 [
873 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
874 `{"config":${configJson},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}`,
875 ],
876 ]);
877 const applyConfigCalls: Array<unknown> = [];
878 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
879
880 return Effect.gen(function* () {
881 expect(yield* startManagedCloudTunnelIfOriginConfirmed("http://127.0.0.1:3773")).toBe(true);
882 expect(applyConfigCalls).toEqual([config]);
883 expect(requests).toEqual([]);
884 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
885 },
886 );
887
888 it.effect.each([
889 { name: "missing", marker: undefined, origin: "http://127.0.0.1:3773" },
890 {
891 name: "stale",
892 marker:
893 '{"config":{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}',
894 origin: "http://127.0.0.1:4884",
895 },
896 ])("does not start a connector with a $name origin marker", ({ marker, origin }) => {
897 const entries: Array<readonly [string, string]> = [
898 [
899 CLOUD_ENDPOINT_RUNTIME_CONFIG,
900 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
901 ],
902 ];
903 if (marker !== undefined) entries.push([CLOUD_ENDPOINT_CONFIRMED_ORIGIN, marker]);
904 const { store } = makeMemorySecretStore(entries);
905 const applyConfigCalls: Array<unknown> = [];
906 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
907
908 return Effect.gen(function* () {
909 expect(yield* startManagedCloudTunnelIfOriginConfirmed(origin)).toBe(false);
910 expect(applyConfigCalls).toEqual([]);
911 expect(requests).toEqual([]);
912 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
913 });
914
915 it.effect(
916 "starts the stored connector without a marker when confirmation is not required",
917 () => {
918 const config = {
919 providerKind: "cloudflare_tunnel" as const,
920 connectorToken: "existing-token",
921 tunnelId: "existing-tunnel",
922 };
923 const { store } = makeMemorySecretStore([
924 [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(config)],
925 ]);
926 const applyConfigCalls: Array<unknown> = [];
927 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
928
929 return Effect.gen(function* () {
930 expect(
931 yield* startManagedCloudTunnelIfOriginConfirmed("http://127.0.0.1:3773", {
932 requireConfirmedOrigin: false,
933 }),
934 ).toBe(true);
935 expect(applyConfigCalls).toEqual([config]);
936 expect(requests).toEqual([]);
937 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
938 },
939 );
940
941 it.effect.each(["replaced", "removed"] as const)(
942 "does not activate a tunnel when its runtime config is %s during registration",
943 (mutation) => {
944 const originalConfig =
945 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}';
946 const { store, values } = makeMemorySecretStore([
947 [CLOUD_ENDPOINT_RUNTIME_CONFIG, originalConfig],
948 [RELAY_URL_SECRET, "https://relay.example.test"],
949 [CLOUD_LINKED_USER_ID, "user-123"],
950 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
951 ]);
952 const applyConfigCalls: Array<unknown> = [];
953 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
954
955 return Effect.gen(function* () {
956 expect(yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773")).toEqual({
957 status: "superseded",
958 });
959 expect(applyConfigCalls).toEqual([]);
960 expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false);
961 }).pipe(
962 provideReleaseHarness({
963 store,
964 applyConfigCalls,
965 requests,
966 respond: () => {
967 if (mutation === "replaced") {
968 values.set(
969 CLOUD_ENDPOINT_RUNTIME_CONFIG,
970 new TextEncoder().encode(
971 '{"providerKind":"cloudflare_tunnel","connectorToken":"fresh-token","tunnelId":"fresh-tunnel"}',
972 ),
973 );
974 } else {
975 values.delete(CLOUD_ENDPOINT_RUNTIME_CONFIG);
976 }
977 return Response.json({ status: "ready" });
978 },
979 }),
980 );
981 },
982 );
983
984 it.effect("requests startup recovery for a legacy config without a recorded tunnel ID", () => {
985 const { store } = makeMemorySecretStore([
986 [
987 CLOUD_ENDPOINT_RUNTIME_CONFIG,
988 '{"providerKind":"cloudflare_tunnel","connectorToken":"token"}',
989 ],
990 [RELAY_URL_SECRET, "https://relay.example.test"],
991 [CLOUD_LINKED_USER_ID, "user-123"],
992 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
993 ]);
994 const applyConfigCalls: Array<unknown> = [];
995 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
996
997 return Effect.gen(function* () {
998 const registration = yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773");
999 expect(registration).toEqual({
1000 status: "recovery_required",
1001 config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
1002 });
1003 expect(
1004 managedTunnelStartupAction({
1005 wantsCliLink: false,
1006 registration,
1007 }),
1008 ).toEqual({
1009 action: "request_recovery",
1010 config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
1011 });
1012 expect(requests).toEqual([]);
1013 expect(applyConfigCalls).toEqual([]);
1014 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
1015 });
1016
1017 it.effect("recovers a web-linked tunnel with its environment credential", () => {
1018 const oldConfig =
1019 '{"providerKind":"cloudflare_tunnel","connectorToken":"old-token","tunnelId":"old-tunnel"}';
1020 const nextConfig = {
1021 providerKind: "cloudflare_tunnel",
1022 connectorToken: "new-token",
1023 tunnelId: "new-tunnel",
1024 } as const;
1025 const { store, values } = makeMemorySecretStore([
1026 [CLOUD_ENDPOINT_RUNTIME_CONFIG, oldConfig],
1027 [RELAY_URL_SECRET, "https://relay.example.test"],
1028 [CLOUD_LINKED_USER_ID, "user-123"],
1029 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1030 ]);
1031 const applyConfigCalls: Array<unknown> = [];
1032 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1033
1034 return Effect.gen(function* () {
1035 expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(true);
1036 expect(requests).toHaveLength(1);
1037 expect(requests[0]?.method).toBe("POST");
1038 expect(requests[0]?.url).toBe("https://relay.example.test/v1/environments/env_123/tunnel");
1039 expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
1040 expect(applyConfigCalls).toEqual([nextConfig]);
1041 expect(
1042 Option.getOrNull(
1043 decodeRuntimeConfig(new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG))),
1044 ),
1045 ).toEqual(nextConfig);
1046 }).pipe(
1047 provideReleaseHarness({
1048 store,
1049 applyConfigCalls,
1050 requests,
1051 respond: () =>
1052 Response.json({
1053 endpoint: {
1054 httpBaseUrl: "https://environment.example.test/",
1055 wsBaseUrl: "wss://environment.example.test/ws",
1056 providerKind: "cloudflare_tunnel",
1057 },
1058 endpointRuntime: nextConfig,
1059 }),
1060 }),
1061 );
1062 });
1063
1064 it.effect("allows managed tunnel provisioning to take longer than ten seconds", () =>
1065 Effect.gen(function* () {
1066 const oldConfig =
1067 '{"providerKind":"cloudflare_tunnel","connectorToken":"old-token","tunnelId":"old-tunnel"}';
1068 const nextConfig = {
1069 providerKind: "cloudflare_tunnel" as const,
1070 connectorToken: "new-token",
1071 tunnelId: "new-tunnel",
1072 };
1073 const { store } = makeMemorySecretStore([
1074 [CLOUD_ENDPOINT_RUNTIME_CONFIG, oldConfig],
1075 [RELAY_URL_SECRET, "https://relay.example.test"],
1076 [CLOUD_LINKED_USER_ID, "user-123"],
1077 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1078 ]);
1079 const applyConfigCalls: Array<unknown> = [];
1080 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1081 const requestStarted = yield* Deferred.make<void>();
1082 const response = yield* Deferred.make<Response>();
1083 const recovery = yield* recoverManagedCloudTunnel("http://127.0.0.1:3773").pipe(
1084 provideReleaseHarness({
1085 store,
1086 applyConfigCalls,
1087 requests,
1088 onRequest: () => Deferred.succeed(requestStarted, undefined),
1089 respondEffect: Deferred.await(response),
1090 }),
1091 Effect.forkChild({ startImmediately: true }),
1092 );
1093
1094 yield* Deferred.await(requestStarted);
1095 expect(requests).toHaveLength(1);
1096 yield* TestClock.adjust("11 seconds");
1097 yield* Effect.yieldNow;
1098 yield* Deferred.succeed(
1099 response,
1100 Response.json({
1101 endpoint: {
1102 httpBaseUrl: "https://environment.example.test/",
1103 wsBaseUrl: "wss://environment.example.test/ws",
1104 providerKind: "cloudflare_tunnel",
1105 },
1106 endpointRuntime: nextConfig,
1107 }),
1108 );
1109
1110 expect(yield* Fiber.join(recovery)).toBe(true);
1111 expect(requests).toHaveLength(1);
1112 expect(applyConfigCalls).toEqual([nextConfig]);
1113 }),
1114 );
1115
1116 it.effect("does not recover an environment without a managed tunnel credential", () => {
1117 const { store } = makeMemorySecretStore([
1118 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1119 [RELAY_URL_SECRET, "https://relay.example.test"],
1120 ]);
1121 const applyConfigCalls: Array<unknown> = [];
1122 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1123
1124 return Effect.gen(function* () {
1125 expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(false);
1126 expect(applyConfigCalls).toEqual([]);
1127 expect(requests).toEqual([]);
1128 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
1129 });
1130
1131 it.effect("ignores recovery requests for a tunnel that has already been replaced", () => {
1132 const { store } = makeMemorySecretStore([
1133 [
1134 CLOUD_ENDPOINT_RUNTIME_CONFIG,
1135 '{"providerKind":"cloudflare_tunnel","connectorToken":"current-token","tunnelId":"current-tunnel"}',
1136 ],
1137 [RELAY_URL_SECRET, "https://relay.example.test"],
1138 [CLOUD_LINKED_USER_ID, "user-123"],
1139 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1140 ]);
1141 const applyConfigCalls: Array<unknown> = [];
1142 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1143
1144 return Effect.gen(function* () {
1145 expect(
1146 yield* recoverManagedCloudTunnel("http://127.0.0.1:3773", {
1147 providerKind: "cloudflare_tunnel",
1148 connectorToken: "old-token",
1149 tunnelId: "old-tunnel",
1150 }),
1151 ).toBe(false);
1152 expect(requests).toEqual([]);
1153 expect(applyConfigCalls).toEqual([]);
1154 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
1155 });
1156
1157 it.effect.each([
1158 { status: 401, errorTag: "EnvironmentHttpUnauthorizedError" },
1159 { status: 403, errorTag: "EnvironmentHttpForbiddenError" },
1160 { status: 409, errorTag: "EnvironmentHttpBadRequestError" },
1161 ])("preserves a permanent $status relay recovery failure", ({ status, errorTag }) => {
1162 const { store } = makeMemorySecretStore([
1163 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1164 [RELAY_URL_SECRET, "https://relay.example.test"],
1165 [CLOUD_LINKED_USER_ID, "user-123"],
1166 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1167 ]);
1168 const applyConfigCalls: Array<unknown> = [];
1169 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1170
1171 return Effect.gen(function* () {
1172 const error = yield* Effect.flip(recoverManagedCloudTunnel("http://127.0.0.1:3773"));
1173
1174 expect(error._tag).toBe(errorTag);
1175 expect(requests).toHaveLength(1);
1176 expect(applyConfigCalls).toEqual([]);
1177 }).pipe(
1178 provideReleaseHarness({
1179 store,
1180 applyConfigCalls,
1181 requests,
1182 respond: () => Response.json({}, { status }),
1183 }),
1184 );
1185 });
1186
1187 it.effect("keeps a tunnel configuration replaced during recovery", () => {
1188 const { store, values } = makeMemorySecretStore([
1189 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1190 [RELAY_URL_SECRET, "https://relay.example.test"],
1191 [CLOUD_LINKED_USER_ID, "user-123"],
1192 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1193 ]);
1194 const applyConfigCalls: Array<unknown> = [];
1195 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1196 const freshConfig = new TextEncoder().encode("fresh-config");
1197
1198 return Effect.gen(function* () {
1199 expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(false);
1200 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
1201 expect(applyConfigCalls).toEqual([]);
1202 }).pipe(
1203 provideReleaseHarness({
1204 store,
1205 applyConfigCalls,
1206 requests,
1207 respond: () => {
1208 values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);
1209 return Response.json({
1210 endpoint: {
1211 httpBaseUrl: "https://environment.example.test/",
1212 wsBaseUrl: "wss://environment.example.test/ws",
1213 providerKind: "cloudflare_tunnel",
1214 },
1215 endpointRuntime: {
1216 providerKind: "cloudflare_tunnel",
1217 connectorToken: "replacement-token",
1218 },
1219 });
1220 },
1221 }),
1222 );
1223 });
1224});
1225
1226describe("link proof provider kinds", () => {
1227 const proofRequest = (
1228 providerKind: RelayLinkProofRequest["endpoint"]["providerKind"],
1229 ): RelayLinkProofRequest => ({
1230 challenge: "challenge",
1231 relayIssuer: "https://relay.example.test",
1232 endpoint: {
1233 httpBaseUrl: "http://127.0.0.1:7331",
1234 wsBaseUrl: "ws://127.0.0.1:7331",
1235 providerKind,
1236 },
1237 origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 },
1238 });
1239
1240 it("accepts managed and manual endpoints but not t3_relay", () => {
1241 expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true);
1242 expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true);
1243 expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false);
1244 });
1245
1246 it("only claims the managed-tunnel scope for tunnel links", () => {
1247 expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([
1248 "agent_activity_notifications",
1249 "managed_tunnels",
1250 ]);
1251 expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]);
1252 });
1253});