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

http.test.ts

1,263 lines48.3 KB

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