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

http.test.ts

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