The best way to control Claude Code, Codex and more from any computer or phone

main
ts 269 lines 10.4 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as certificateAuthorities from "@distilled.cloud/cloudflare/certificate-authorities";
7 import * as mtls from "@distilled.cloud/cloudflare/mtls-certificates";
8 import * as Provider from "alchemy/Provider";
9 import * as Effect from "effect/Effect";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import { testName } from "../../names.ts";
13 import { CA_CERT_1, CA_CERT_2 } from "./fixtures/certs.ts";
14 const { test } = Test.make({ providers: Cloudflare.providers() });
15
16 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
17
18 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
19
20 const resolveZoneId = Effect.gen(function* () {
21 const { accountId } = yield* yield* CloudflareEnvironment;
22 const zone = yield* findZoneByName({ accountId, name: zoneName });
23 if (!zone) {
24 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
25 }
26 return zone.id;
27 });
28
29 // The scoped API token the test harness mints propagates eventually-
30 // consistently across Cloudflare's edge — a fresh token intermittently 403s
31 // with "Unable to authenticate request". Ride out the blips on the test's
32 // own out-of-band calls by retrying the typed `Forbidden` error (part of
33 // each operation's error union via distilled patches). Bounded:
34 // 6 retries of 500ms exponential backoff = max ~31.5s.
35 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
36
37 const getHostnames = (zoneId: string, mtlsCertificateId?: string) =>
38 certificateAuthorities.getHostnameAssociation({ zoneId, mtlsCertificateId }).pipe(
39 Effect.map((r) => [...(r.hostnames ?? [])].sort()),
40 Effect.retry({
41 while: (e) => e._tag === "Forbidden",
42 schedule: forbiddenRetrySchedule,
43 times: 6,
44 }),
45 );
46
47 // Normalize the keyed association to a known (empty) baseline so each run
48 // starts from the same cloud state regardless of what a previous (possibly
49 // interrupted) run left behind.
50 const clearAssociation = (zoneId: string, mtlsCertificateId?: string) =>
51 certificateAuthorities.putHostnameAssociation({ zoneId, mtlsCertificateId, hostnames: [] }).pipe(
52 Effect.retry({
53 while: (e) => e._tag === "Forbidden",
54 schedule: forbiddenRetrySchedule,
55 times: 6,
56 }),
57 );
58
59 // PUT→GET on the association is eventually consistent at the edge — poll
60 // with a typed, bounded retry until the observed set matches.
61 const waitForHostnames = (
62 zoneId: string,
63 expected: ReadonlyArray<string>,
64 mtlsCertificateId?: string,
65 ) =>
66 getHostnames(zoneId, mtlsCertificateId).pipe(
67 Effect.flatMap((observed) =>
68 observed.length === expected.length && observed.every((h, i) => h === [...expected].sort()[i])
69 ? Effect.succeed(observed)
70 : Effect.fail({ _tag: "HostnamesNotConverged", observed } as const),
71 ),
72 Effect.retry({
73 while: (e) => e._tag === "HostnamesNotConverged",
74 // Bounded: 25 polls x 3s = max ~75s. PUT→GET convergence at the edge
75 // runs well past the earlier ~30s under full-suite parallel load (the
76 // API is being throttled, which stretches the propagation window).
77 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(25)]),
78 }),
79 );
80
81 const waitForCertDelete = (accountId: string, mtlsCertificateId: string) =>
82 mtls.getMtlsCertificate({ accountId, mtlsCertificateId }).pipe(
83 Effect.flatMap((cert) =>
84 cert.id === mtlsCertificateId
85 ? Effect.fail({ _tag: "CertificateNotDeleted" } as const)
86 : Effect.void,
87 ),
88 Effect.catchTag("CertificateNotFound", () => Effect.void),
89 Effect.retry({
90 while: (e) => e._tag === "CertificateNotDeleted",
91 // Bounded: 30 polls x 3s = max ~90s of waiting. The CA certificate
92 // delete only completes once the hostname-association clear (issued
93 // first by destroy) has propagated, and under full-suite load that
94 // combined window was observed to exceed the previous ~30s budget.
95 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(30)]),
96 }),
97 );
98
99 describe.sequential(
100 "HostnameAssociation",
101 {
102 tags: [
103 "provider:cloudflare",
104 "provider:cloudflare:certificateauthorities",
105 "provider:cloudflare:zone",
106 "live",
107 ],
108 },
109 () => {
110 test.provider(
111 "pins Managed CA hostnames, updates in place, and clears on destroy",
112 (stack) =>
113 Effect.gen(function* () {
114 const zoneId = yield* resolveZoneId;
115
116 yield* stack.destroy();
117 // Known baseline: no Managed CA hostname associations.
118 yield* clearAssociation(zoneId);
119
120 const created = yield* stack.deploy(
121 Cloudflare.CertificateAuthorities.HostnameAssociation("ManagedCaHosts", {
122 zoneId,
123 hostnames: [`${testName("mtls")}.${zoneName}`],
124 }),
125 );
126
127 expect(created.zoneId).toEqual(zoneId);
128 expect(created.mtlsCertificateId).toBeUndefined();
129 expect(created.hostnames).toEqual([`${testName("mtls")}.${zoneName}`]);
130
131 yield* waitForHostnames(zoneId, [`${testName("mtls")}.${zoneName}`]);
132
133 // In-place update — hostnames are the mutable aspect of the singleton.
134 const updated = yield* stack.deploy(
135 Cloudflare.CertificateAuthorities.HostnameAssociation("ManagedCaHosts", {
136 zoneId,
137 hostnames: [`${testName("mtls2")}.${zoneName}`, `${testName("mtls")}.${zoneName}`],
138 }),
139 );
140
141 expect([...updated.hostnames].sort()).toEqual([
142 `${testName("mtls")}.${zoneName}`,
143 `${testName("mtls2")}.${zoneName}`,
144 ]);
145
146 yield* waitForHostnames(zoneId, [
147 `${testName("mtls")}.${zoneName}`,
148 `${testName("mtls2")}.${zoneName}`,
149 ]);
150
151 yield* stack.destroy();
152
153 // Destroy cleared the association (PUT of an empty hostname list).
154 yield* waitForHostnames(zoneId, []);
155 }).pipe(logLevel),
156 // Three sequential edge-convergence waits (create, update, clear), each up
157 // to ~75s under throttled full-suite load, exceed the 120s default.
158 { timeout: 300_000 },
159 );
160
161 test.provider(
162 "associates hostnames with an uploaded CA and destroys before the cert",
163 (stack) =>
164 Effect.gen(function* () {
165 const { accountId } = yield* yield* CloudflareEnvironment;
166 const zoneId = yield* resolveZoneId;
167
168 yield* stack.destroy();
169
170 const { cert, assoc } = yield* stack.deploy(
171 Effect.gen(function* () {
172 const cert = yield* Cloudflare.MtlsCertificate.MtlsCertificate("CertAuthCa", {
173 ca: true,
174 certificates: CA_CERT_1,
175 });
176 const assoc = yield* Cloudflare.CertificateAuthorities.HostnameAssociation(
177 "CaHosts",
178 {
179 zoneId,
180 mtlsCertificateId: cert.mtlsCertificateId,
181 hostnames: [`${testName("mtls-ca")}.${zoneName}`],
182 },
183 );
184 return { cert, assoc };
185 }),
186 );
187
188 expect(cert.mtlsCertificateId).toBeDefined();
189 expect(assoc.mtlsCertificateId).toEqual(cert.mtlsCertificateId);
190 expect(assoc.hostnames).toEqual([`${testName("mtls-ca")}.${zoneName}`]);
191
192 yield* waitForHostnames(
193 zoneId,
194 [`${testName("mtls-ca")}.${zoneName}`],
195 cert.mtlsCertificateId,
196 );
197
198 // Destroy must clear the association before deleting the certificate —
199 // Cloudflare refuses to delete a CA that hostnames still reference.
200 yield* stack.destroy();
201
202 yield* waitForCertDelete(accountId, cert.mtlsCertificateId);
203 }).pipe(logLevel),
204 { tags: ["provider:cloudflare:mtlscertificate"] },
205 );
206
207 test.provider(
208 "changing the certificate key replaces the association",
209 (stack) =>
210 Effect.gen(function* () {
211 const { accountId } = yield* yield* CloudflareEnvironment;
212 const zoneId = yield* resolveZoneId;
213
214 yield* stack.destroy();
215 yield* clearAssociation(zoneId);
216
217 const first = yield* stack.deploy(
218 Effect.gen(function* () {
219 const assoc = yield* Cloudflare.CertificateAuthorities.HostnameAssociation(
220 "ReplaceHosts",
221 { zoneId, hostnames: [`${testName("mtls-replace")}.${zoneName}`] },
222 );
223 return { assoc };
224 }),
225 );
226
227 expect(first.assoc.mtlsCertificateId).toBeUndefined();
228 yield* waitForHostnames(zoneId, [`${testName("mtls-replace")}.${zoneName}`]);
229
230 // mtlsCertificateId keys the association — switching from the Managed
231 // CA to an uploaded CA is a replacement: the new keyed association is
232 // created and the old Managed CA list is cleared as the old instance
233 // deletes.
234 const second = yield* stack.deploy(
235 Effect.gen(function* () {
236 const cert = yield* Cloudflare.MtlsCertificate.MtlsCertificate("ReplaceCa", {
237 ca: true,
238 certificates: CA_CERT_2,
239 });
240 const assoc = yield* Cloudflare.CertificateAuthorities.HostnameAssociation(
241 "ReplaceHosts",
242 {
243 zoneId,
244 mtlsCertificateId: cert.mtlsCertificateId,
245 hostnames: [`${testName("mtls-replace")}.${zoneName}`],
246 },
247 );
248 return { cert, assoc };
249 }),
250 );
251
252 expect(second.assoc.mtlsCertificateId).toEqual(second.cert.mtlsCertificateId);
253
254 yield* waitForHostnames(
255 zoneId,
256 [`${testName("mtls-replace")}.${zoneName}`],
257 second.cert.mtlsCertificateId,
258 );
259 // The old Managed CA association was cleared by the replacement.
260 yield* waitForHostnames(zoneId, []);
261
262 yield* stack.destroy();
263
264 yield* waitForCertDelete(accountId, second.cert.mtlsCertificateId);
265 }).pipe(logLevel),
266 { tags: ["provider:cloudflare:mtlscertificate"] },
267 );
268 },
269 );